chore(storage): bound build retention, caches and test resources

Track build ownership, qualified pins and bounded cache/log lifecycles. Move Vite fixtures to a job-owned server helper and preserve private outputs outside Git.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:09:58 +03:00
parent 55f64f195b
commit 70ef3f9f1c
119 changed files with 3128 additions and 331 deletions
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Run a local Python check with disposable job-owned caches.
Only this invocation's scratch is removed, after its process group has ended.
Existing caches, source, dependencies and results are outside this lifecycle.
"""
import argparse
import os
import signal
import subprocess
import tempfile
import time
from contextlib import suppress
from pathlib import Path
from k1link.cache_budget import cache_publication
def stop_group(process):
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
return
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
process.poll()
try:
os.killpg(process.pid, 0)
except ProcessLookupError:
return
time.sleep(0.05)
with suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=5)
def run(tool, arguments, *, root=None):
root = root or Path(__file__).resolve().parents[1]
parent = root / ".runtime/python-checks"
ancestor = parent
while not ancestor.exists():
ancestor = ancestor.parent
if ancestor.resolve() != ancestor:
raise ValueError("Check scratch ancestor must be canonical")
parent.mkdir(parents=True, exist_ok=True, mode=0o700)
if parent.resolve() != parent:
raise ValueError("Check scratch must be canonical")
with cache_publication(parent, 64 * 1024**2, limit=512 * 1024**2, max_files=50000):
if sum(p.is_dir() for p in parent.iterdir()) >= 4:
raise ValueError("Four active or unreconciled check directories; new check refused")
owned = tempfile.TemporaryDirectory(prefix=tool + "-", dir=parent)
with owned as scratch:
env = dict(
os.environ,
PYTHONDONTWRITEBYTECODE="1",
RUFF_NO_CACHE="true",
MYPY_CACHE_DIR=str(Path(scratch) / "mypy"),
TMPDIR=scratch,
)
command = [str(root / ".venv/bin/python"), "-m", tool]
if tool == "pytest":
command += ["-p", "no:cacheprovider", "--basetemp", str(Path(scratch) / "pytest")]
if tool == "ruff":
command += ["check", "--no-cache"]
process = subprocess.Popen(
[*command, *arguments], cwd=root, env=env, start_new_session=True
)
try:
return process.wait()
finally:
stop_group(process)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("tool", choices=["pytest", "mypy", "ruff"])
parser.add_argument("arguments", nargs=argparse.REMAINDER)
args = parser.parse_args()
return run(args.tool, args.arguments)
if __name__ == "__main__":
raise SystemExit(main())
+93 -34
View File
@@ -4,6 +4,7 @@
No remote command, NAS configuration, provider credential or cache is changed.
The user LaunchAgent reconnects independently of the Core process.
"""
from __future__ import annotations
import argparse
@@ -19,6 +20,8 @@ import tempfile
import time
from pathlib import Path
from k1link.launchd_logs import bounded_launchd_output
LABEL = "com.nodedc.mission-core.map-gateway-link"
PORT = 18103
@@ -26,21 +29,47 @@ PORT = 18103
def payload(target: str, runtime: Path) -> bytes:
if not re.fullmatch(r"[a-zA-Z0-9_][a-zA-Z0-9_.-]*@[a-zA-Z0-9][a-zA-Z0-9.-]*", target):
raise ValueError("SSH target must be an explicit user@host")
return plistlib.dumps({
"Label": LABEL,
"ProgramArguments": [
"/usr/bin/ssh", "-N", "-T", "-o", "BatchMode=yes",
"-o", "StrictHostKeyChecking=yes", "-o", "ExitOnForwardFailure=yes",
"-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15",
"-o", "ServerAliveCountMax=3", "-o", "PermitLocalCommand=no",
"-o", "ForwardAgent=no", "-o", "ForwardX11=no",
"-L", f"127.0.0.1:{PORT}:127.0.0.1:{PORT}", target,
],
"RunAtLoad": True, "KeepAlive": True, "ThrottleInterval": 30,
"ExitTimeOut": 10,
"StandardOutPath": str(runtime / "stdout.log"),
"StandardErrorPath": str(runtime / "stderr.log"),
}, sort_keys=True)
return plistlib.dumps(
bounded_launchd_output(
{
"Label": LABEL,
"ProgramArguments": [
"/usr/bin/ssh",
"-N",
"-T",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ConnectTimeout=10",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-o",
"PermitLocalCommand=no",
"-o",
"ForwardAgent=no",
"-o",
"ForwardX11=no",
"-L",
f"127.0.0.1:{PORT}:127.0.0.1:{PORT}",
target,
],
"RunAtLoad": True,
"KeepAlive": True,
"ThrottleInterval": 30,
"ExitTimeOut": 10,
"StandardOutPath": str(runtime / "stdout.log"),
"StandardErrorPath": str(runtime / "stderr.log"),
},
Path(__file__).resolve().parents[1],
),
sort_keys=True,
)
def digest(value: bytes | None) -> str:
@@ -50,9 +79,13 @@ def digest(value: bytes | None) -> str:
def health() -> bool:
connection = http.client.HTTPConnection("127.0.0.1", PORT, timeout=2)
try:
connection.request("GET", "/healthz", headers={
"x-nodedc-user-id": "mission-core-loopback-operator",
})
connection.request(
"GET",
"/healthz",
headers={
"x-nodedc-user-id": "mission-core-loopback-operator",
},
)
response = connection.getresponse()
raw = response.read(65537)
if response.status != 200 or len(raw) > 65536:
@@ -66,18 +99,29 @@ def health() -> bool:
def loaded() -> bool:
return subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"],
capture_output=True, timeout=5, check=False).returncode == 0
return (
subprocess.run(
["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"],
capture_output=True,
timeout=5,
check=False,
).returncode
== 0
)
def unload() -> None:
subprocess.run(["launchctl", "bootout", f"gui/{os.getuid()}/{LABEL}"],
capture_output=True, timeout=20, check=False)
subprocess.run(
["launchctl", "bootout", f"gui/{os.getuid()}/{LABEL}"],
capture_output=True,
timeout=20,
check=False,
)
deadline = time.monotonic() + 20
while loaded():
if time.monotonic() > deadline:
raise RuntimeError("Map Gateway link did not finish unloading")
time.sleep(.2)
time.sleep(0.2)
def write_atomic(path: Path, value: bytes) -> None:
@@ -112,15 +156,22 @@ def main() -> None:
if previous is not None and plistlib.loads(previous).get("Label") != LABEL:
raise ValueError("Refusing a foreign LaunchAgent")
desired = payload(args.target, runtime)
plan = {"label": LABEL, "agent_path": str(agent), "target": args.target,
"local_bind": f"127.0.0.1:{PORT}", "remote_bind": f"127.0.0.1:{PORT}",
"current_sha256": digest(previous), "desired_sha256": digest(desired),
"remote_mutation": False}
plan = {
"label": LABEL,
"agent_path": str(agent),
"target": args.target,
"local_bind": f"127.0.0.1:{PORT}",
"remote_bind": f"127.0.0.1:{PORT}",
"current_sha256": digest(previous),
"desired_sha256": digest(desired),
"remote_mutation": False,
}
if args.action == "plan":
print(json.dumps(plan, indent=2))
return
if (args.expected_current_sha256 != digest(previous)
or args.expected_desired_sha256 != digest(desired)):
if args.expected_current_sha256 != digest(previous) or args.expected_desired_sha256 != digest(
desired
):
raise ValueError("Map Gateway link plan changed before apply")
was_loaded = loaded()
if previous == desired and was_loaded and health():
@@ -137,20 +188,28 @@ def main() -> None:
if was_loaded:
unload()
write_atomic(agent, desired)
subprocess.run(["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)],
capture_output=True, timeout=20, check=True)
subprocess.run(
["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)],
capture_output=True,
timeout=20,
check=True,
)
deadline = time.monotonic() + 40
while not health():
if time.monotonic() > deadline:
raise RuntimeError("Map Gateway link did not pass health acceptance")
time.sleep(.5)
time.sleep(0.5)
except BaseException:
unload()
if previous is not None:
write_atomic(agent, previous)
if was_loaded:
subprocess.run(["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)],
capture_output=True, timeout=20, check=True)
subprocess.run(
["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)],
capture_output=True,
timeout=20,
check=True,
)
else:
agent.unlink(missing_ok=True)
raise
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Hash-gated bounded journals for existing, explicitly owned local LaunchAgents.
Only stdout/stderr ownership changes. Arguments, environment, schedules, SSH
trust and forwarding endpoints stay byte-for-byte equivalent after unwrapping.
Previous declarations and journals are preserved for rollback and diagnosis.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import plistlib
import subprocess
import time
from pathlib import Path
from manage_mission_core_launch_agent import _reload_launch_agent, _wait_for_health, _write_atomic
from migrate_worker_tunnel_logs import reload_agent
from k1link.launchd_logs import bounded_launchd_output, service_command, service_log_path
LABELS = {
"core": "com.nodedc.mission-core.local",
"observatory": "com.nodedc.observatory-worker-tunnel.local",
"gaussian": "com.nodedc.gaussian-pipeline-tunnel.local",
"telemetry-startup": "com.nodedc.telemetry-startup.local",
"telemetry-tunnel": "com.nodedc.telemetry-tunnel.local",
"map": "com.nodedc.mission-core.map-gateway-link",
}
def digest(data):
return hashlib.sha256(data).hexdigest()
def plan(root, name, *, home=None):
home = home or Path.home()
root = root.resolve(strict=True)
label = LABELS[name]
agent = home / "Library/LaunchAgents" / f"{label}.plist"
if agent.is_symlink() or not agent.is_file():
raise ValueError("Missing or unsafe existing LaunchAgent")
before = agent.read_bytes()
document = plistlib.loads(before)
if document.get("Label") != label:
raise ValueError("Foreign LaunchAgent")
command = service_command(document)
if name == "core":
if document.get("WorkingDirectory") != str(root) or command[-2:] != ["k1link", "serve"]:
raise ValueError("Unexpected canonical Core declaration")
elif name == "telemetry-startup":
if str(root / "scripts/manage_telemetry_startup.py") not in command:
raise ValueError("Unexpected startup owner")
elif command[0] != "/usr/bin/ssh":
raise ValueError("Unexpected tunnel command")
desired = bounded_launchd_output(document, root)
assert service_command(desired) == command
for key in set(document) | set(desired):
if key not in {"ProgramArguments", "StandardOutPath", "StandardErrorPath"} and document.get(
key
) != desired.get(key):
raise ValueError("Service policy changed")
payload = plistlib.dumps(desired, sort_keys=True)
result = {
"schema": "missioncore.runtime-log-policy/v1",
"name": name,
"label": label,
"root": str(root),
"agent": str(agent),
"before_sha256": digest(before),
"desired_sha256": digest(payload),
"changed": before != payload,
"journal": str(service_log_path(desired)),
"max_bytes": 8388608,
"backups": 4,
"commands_and_environment_preserved": True,
}
return result, before, payload
def accept(name, label):
if name == "core":
if not _wait_for_health(45):
raise RuntimeError("Core health failed")
return {"operational": True}
target = f"gui/{os.getuid()}/{label}"
previous = None
stable = 0
for _ in range(15):
result = subprocess.run(
["launchctl", "print", target], capture_output=True, text=True, timeout=5
)
state = result.stdout
if name == "telemetry-startup" and "last exit code = 0" in state:
return {"last_exit_code": 0}
pid = next(
(line.strip() for line in state.splitlines() if line.strip().startswith("pid = ")), None
)
stable = stable + 1 if pid and pid == previous and "state = running" in state else 0
if stable >= 5:
return {"stable_process": pid}
previous = pid
time.sleep(1)
raise RuntimeError("LaunchAgent did not reach a stable accepted state")
def apply(expected):
current, before, payload = plan(Path(expected["root"]), expected["name"])
if current != expected:
raise ValueError("Stale log policy plan")
if not current["changed"]:
return {**current, "applied": False}
path = Path(current["agent"])
root = Path(current["root"])
backup = (
root
/ ".runtime/storage-maintenance/log-policy"
/ current["label"]
/ f"{current['before_sha256']}.plist"
)
if backup.exists() and backup.read_bytes() != before:
raise ValueError("Rollback identity collision")
if not backup.exists():
_write_atomic(backup, before)
_write_atomic(path, payload)
try:
if current["name"] == "core":
_reload_launch_agent(path)
else:
reload_agent(path, current["label"])
proof = accept(current["name"], current["label"])
except BaseException:
_write_atomic(path, before)
if current["name"] == "core":
_reload_launch_agent(path)
else:
reload_agent(path, current["label"])
accept(current["name"], current["label"])
raise
receipt = {
**current,
"applied": True,
"backup": str(backup),
"accepted": proof,
"utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
_write_atomic(backup.with_suffix(".receipt.json"), json.dumps(receipt, indent=2).encode())
return receipt
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("action", choices=["plan", "apply"])
p.add_argument("name", choices=LABELS)
p.add_argument("--plan", type=Path)
a = p.parse_args()
if a.action == "plan":
value = plan(Path(__file__).resolve().parents[1], a.name)[0]
else:
if not a.plan:
p.error("apply requires --plan")
expected = json.loads(a.plan.read_text())
if expected["name"] != a.name:
p.error("plan owner does not match")
value = apply(expected)
print(json.dumps(value, indent=2))
if __name__ == "__main__":
main()
+3 -1
View File
@@ -21,7 +21,7 @@ from pathlib import Path
from manage_mission_core_launch_agent import _wait_for_health, _write_atomic
from migrate_worker_tunnel_logs import reload_agent
from k1link.launchd_logs import launchd_log_path, prepare_launchd_log
from k1link.launchd_logs import bounded_launchd_output, launchd_log_path, prepare_launchd_log
from k1link.web.compute_contour_network import _replace_environment_value
STARTUP = "com.nodedc.telemetry-startup.local"
@@ -194,6 +194,8 @@ def plan(stack: Path, ssh_alias: str, repository: Path, agents: Path):
StandardOutPath="/dev/null",
StandardErrorPath=str(launchd_log_path("telemetry-tunnel.log")),
)
startup = bounded_launchd_output(startup, repository)
tunnel = bounded_launchd_output(tunnel, repository)
core_path = agents / (CORE + ".plist")
core = plistlib.loads(private_file(core_path))
if core.get("Label") != CORE or core.get("WorkingDirectory") != str(repository):
+8 -2
View File
@@ -15,7 +15,12 @@ from pathlib import Path
from manage_mission_core_launch_agent import _write_atomic
from k1link.launchd_logs import launchd_log_path, prepare_launchd_log
from k1link.launchd_logs import (
bounded_launchd_output,
launchd_log_path,
prepare_launchd_log,
service_command,
)
LABELS = {
"observatory": "com.nodedc.observatory-worker-tunnel.local",
@@ -48,10 +53,11 @@ def main():
raise ValueError("LaunchAgent cannot be a symlink")
previous = agent.read_bytes()
desired = plistlib.loads(previous)
if desired["Label"] != label or desired["ProgramArguments"][0] != "/usr/bin/ssh":
if desired["Label"] != label or service_command(desired)[0] != "/usr/bin/ssh":
raise ValueError("Unexpected tunnel declaration")
log = launchd_log_path(a.tunnel + "-worker-tunnel.log")
desired.update(StandardOutPath=str(log), StandardErrorPath=str(log))
desired = bounded_launchd_output(desired, Path(__file__).resolve().parents[1])
payload = plistlib.dumps(desired, sort_keys=True)
plan = dict(
label=label,
+616
View File
@@ -0,0 +1,616 @@
"""Operator-side lifecycle for intermediate Linux inputs, never runtime/evidence GC.
Only four exact archive families in two build directories are eligible. Unknown
legacy files stay protected. Producers publish atomically with a persistent
active hold; completing a build explicitly releases that hold. No TTL can guess
that a remote build, disconnected transfer or qualification has finished.
"""
from __future__ import annotations
import argparse
import fcntl
import hashlib
import json
import os
import re
import shutil
import stat
import time
import uuid
import zipfile
from contextlib import contextmanager
from pathlib import Path
SCHEMA = "missioncore.build-retention/v1"
POLICY = "two-closed-inputs-per-line-v1"
KEEP = 2
MAX_ACTIVE_PER_FAMILY = 8
RESERVE = 2 * 1024**3
SOFT_BUDGET = 6 * 1024**3
ROOTS = {
"apps/node-agent/build": ("mission-core-node-linux-build-",),
"plugins/insta360-x4/build": (
"mission-core-x4-build-",
"mission-core-x4-package-build-",
"mission-core-x4-owner-build-",
),
}
PATTERN = re.compile(r"(.+)-([a-f0-9]{24})\.pyz\Z")
class RetentionError(RuntimeError):
pass
def _canonical(value):
return json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode()
def _stamp(s):
return [s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns, s.st_nlink]
def _plain(path, *, directory=False):
s = path.lstat()
if not (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode)):
raise RetentionError(f"Not a plain {'directory' if directory else 'file'}: {path}")
return s
def _atomic(path, value):
if path.exists() or path.is_symlink():
_plain(path)
temporary = path.with_name("." + path.name + "." + uuid.uuid4().hex + ".tmp")
try:
with temporary.open("xb") as stream:
os.chmod(temporary, 0o600)
stream.write(_canonical(value) + b"\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
fd = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
finally:
temporary.unlink(missing_ok=True)
class BuildRetention:
def __init__(self, root):
supplied = Path(root).absolute()
if supplied.is_symlink():
raise RetentionError("Repository root is a symlink")
self.root = supplied.resolve(strict=True)
self.control = self.root / ".runtime/build-retention"
self.state_path = self.control / "state.json"
def _directory(self, relative, *, create=False):
current = self.root
for part in Path(relative).parts:
if part in (".", "..", "/"):
raise RetentionError("Unsafe directory")
current /= part
if create and not current.exists() and not current.is_symlink():
current.mkdir(mode=0o700, exist_ok=True)
_plain(current, directory=True)
return current
def _path(self, relative):
p = Path(relative)
if p.is_absolute() or str(p.parent) not in ROOTS:
raise RetentionError("Path is outside managed build-input families")
match = PATTERN.fullmatch(p.name)
if not match or match[1] + "-" not in ROOTS[str(p.parent)]:
raise RetentionError("Only intermediate build inputs are managed")
return self._directory(p.parent) / p.name
@contextmanager
def _lock(self, *, write=False):
# A fresh read-only plan does not create even a lock or state directory.
if not self.control.exists() and not self.control.is_symlink() and not write:
yield
return
self._directory(".runtime/build-retention", create=write)
lock = self.control / "lock"
if not write and not lock.exists():
raise RetentionError("Incomplete retention control directory")
fd = os.open(
lock, (os.O_RDWR | os.O_CREAT if write else os.O_RDONLY) | os.O_NOFOLLOW, 0o600
)
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise RetentionError("Invalid retention lock")
fcntl.flock(fd, fcntl.LOCK_EX if write else fcntl.LOCK_SH)
yield
finally:
os.close(fd)
def _state(self):
if not self.state_path.exists() and not self.state_path.is_symlink():
return {"schema": SCHEMA, "revision": 0, "inputs": {}}
_plain(self.state_path)
state = json.loads(self.state_path.read_text())
if state.get("schema") != SCHEMA or not isinstance(state.get("inputs"), dict):
raise RetentionError("Unknown retention registry schema")
return state
def _save(self, state):
state["revision"] += 1
_atomic(self.state_path, state)
def _read(self, relative, *, physical=None):
path = physical or self._path(relative)
before = _plain(path)
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, "rb") as stream:
if _stamp(before) != _stamp(os.fstat(stream.fileno())):
raise RetentionError("Input changed while opening")
digest = hashlib.file_digest(stream, "sha256").hexdigest()
stream.seek(0)
with zipfile.ZipFile(stream) as archive:
name = (
"manifest.json"
if "/mission-core-x4-owner-build-" in relative
else "source.json"
)
if len([x for x in archive.namelist() if x == name]) != 1:
raise RetentionError("Missing or duplicate build manifest")
if archive.getinfo(name).file_size > 16 * 1024**2:
raise RetentionError("Build manifest is too large")
raw = archive.read(name)
manifest = json.loads(raw)
if _stamp(before) != _stamp(os.fstat(stream.fileno())):
raise RetentionError("Input changed while reading")
if _stamp(before) != _stamp(_plain(path)):
raise RetentionError("Input path changed while reading")
match = PATTERN.fullmatch(Path(relative).name)
if not match or hashlib.sha256(raw).hexdigest()[:24] != match[2]:
raise RetentionError("Build manifest identity differs from filename")
prefix = match[1]
schema = manifest.get("schema")
if (
prefix == "mission-core-node-linux-build"
and schema == "missioncore.node.linux-build-source/v1"
):
profile = manifest.get("profile")
if profile not in {"node-only", "node-core"}:
raise RetentionError("Unknown Node build profile")
line = "node/" + profile
elif (
prefix in {"mission-core-x4-build", "mission-core-x4-package-build"}
and schema == "missioncore.insta360.build-source/v1"
):
kind = manifest.get("kind", "native")
if kind != ("native" if prefix == "mission-core-x4-build" else "package"):
raise RetentionError("X4 kind differs from filename")
line = "x4/" + kind
elif (
prefix == "mission-core-x4-owner-build"
and schema == "missioncore.insta360.owner-wrapper-build/v1"
):
line = "x4/owner"
else:
raise RetentionError("Unknown build manifest schema/family")
base = manifest.get("base")
if base is not None:
if not isinstance(base, dict) or set(base) != {"name", "sha256"}:
raise RetentionError("Invalid base reference")
if Path(base["name"]).name != base["name"] or not re.fullmatch(
r"[a-f0-9]{64}", base["sha256"]
):
raise RetentionError("Unsafe base reference")
base = {"path": str(Path(relative).parent / base["name"]), "sha256": base["sha256"]}
self._path(base["path"])
return {
"path": relative,
"line": line,
"sha256": digest,
"bytes": before.st_size,
"stamp": _stamp(before),
"base": base,
}
def _inventory(self):
rows, errors = {}, []
for directory, prefixes in ROOTS.items():
if not (self.root / directory).exists() and not (self.root / directory).is_symlink():
continue
try:
root = self._directory(directory)
for p in sorted(root.iterdir()):
# Recognizable but malformed archives block deletion, rather than disappearing.
if p.suffix != ".pyz" or not p.name.startswith(prefixes):
continue
relative = str(p.relative_to(self.root))
try:
self._path(relative)
rows[relative] = self._read(relative)
except (
RetentionError,
OSError,
ValueError,
KeyError,
TypeError,
zipfile.BadZipFile,
) as exc:
errors.append(f"{relative}: {exc}")
except (RetentionError, OSError) as exc:
errors.append(f"{directory}: {exc}")
return rows, errors
def _plan(self):
state = self._state()
rows, errors = self._inventory()
reasons = {name: [] for name in rows}
eligible = {}
for name, record in state["inputs"].items():
if not record.get("deleted") and name not in rows:
errors.append(f"Registered input missing: {name}")
for name, row in rows.items():
record = state["inputs"].get(name)
if not record:
reasons[name].append("legacy-unreviewed")
else:
if record.get("deleted") or any(
record.get(k) != row[k] for k in ("sha256", "bytes", "line", "base")
):
errors.append(f"Registered identity changed: {name}")
if record["state"] == "active":
reasons[name].append("active-build:" + record["owner"])
elif record["state"] != "closed":
errors.append(f"Invalid lifecycle state: {name}")
for pin, reason in sorted(record["pins"].items()):
reasons[name].append(f"pin:{pin}:{reason}")
if record["state"] == "closed" and not record["pins"]:
eligible.setdefault(row["line"], []).append(name)
base = row["base"]
if base and (
base["path"] not in rows or rows[base["path"]]["sha256"] != base["sha256"]
):
errors.append(f"Missing or changed base: {name}")
for names in eligible.values():
names.sort(key=lambda n: (state["inputs"][n]["published_ns"], n), reverse=True)
for name in names[:KEEP]:
reasons[name].append("latest-two-completed-in-line")
# Protect the entire dependency closure, including legacy/active/pinned roots.
visiting, visited = set(), set()
def protect(name):
if name in visiting:
errors.append(f"Cyclic base graph: {name}")
return
if name in visited:
return
visiting.add(name)
base = rows[name]["base"]
if base and base["path"] in rows:
reasons[base["path"]].append("base-of:" + name)
protect(base["path"])
visiting.remove(name)
visited.add(name)
for name in sorted(rows):
if reasons[name]:
protect(name)
# Validate even candidate-only dependency components before any unlink.
def cycle(name, chain):
if name in chain:
errors.append(f"Cyclic base graph: {name}")
return
base = rows[name]["base"]
if base and base["path"] in rows:
cycle(base["path"], chain | {name})
for name in rows:
cycle(name, set())
decisions = [
dict(
row,
action="retain" if reasons[name] or errors else "delete",
reasons=sorted(set(reasons[name]))
or (["blocked-by-inventory-error"] if errors else ["superseded-completed-input"]),
)
for name, row in sorted(rows.items())
]
total = sum(x["bytes"] for x in decisions)
result = {
"schema": "missioncore.build-retention-plan/v1",
"policy": POLICY,
"root": str(self.root),
"registry_sha256": hashlib.sha256(_canonical(state)).hexdigest(),
"inputs": decisions,
"errors": sorted(set(errors)),
"total_logical_bytes": total,
"soft_budget_bytes": SOFT_BUDGET,
"over_soft_budget": total > SOFT_BUDGET,
"candidate_bytes_upper_bound": sum(
x["bytes"] for x in decisions if x["action"] == "delete"
),
}
result["plan_id"] = hashlib.sha256(_canonical(result)).hexdigest()
return result
def plan(self):
with self._lock():
return self._plan()
def _record(self, state, row, *, active, reason, pin=None):
name = row["path"]
previous = state["inputs"].get(name)
if previous and not previous.get("deleted"):
raise RetentionError("Input already registered; use finish/pin/unpin")
record = {k: row[k] for k in ("sha256", "bytes", "line", "base")}
record.update(
state="active" if active else "closed",
published_ns=time.time_ns() if active else row["stamp"][3],
owner=uuid.uuid4().hex,
reason=reason,
pins={pin: reason} if pin else {},
)
state["inputs"][name] = record
self._save(state)
return record["owner"]
def adopt(self, relative, *, pin, reason):
"""Legacy enrollment always pins; it never silently makes a file disposable."""
if not pin or not reason.strip():
raise RetentionError("A legacy hold and a reason are required")
with self._lock(write=True):
return self._record(
self._state(), self._read(relative), active=False, pin=pin, reason=reason
)
def pin(self, relative, *, pin, reason, remove=False):
if not pin or not reason.strip():
raise RetentionError("A pin identity and reason are required")
with self._lock(write=True):
state = self._state()
record = state["inputs"][relative]
row = self._read(relative)
if record.get("deleted") or row["sha256"] != record["sha256"]:
raise RetentionError("Registered input changed")
if remove:
if pin not in record["pins"]:
raise RetentionError("Unknown pin")
del record["pins"][pin]
else:
record["pins"][pin] = reason
record["reason"] = reason
self._save(state)
def finish(self, relative, *, owner, outcome, reason):
if (
outcome not in {"intermediate", "failed", "cancelled", "qualified", "rollback"}
or not reason.strip()
):
raise RetentionError("Explicit terminal outcome and reason required")
with self._lock(write=True):
state = self._state()
record = state["inputs"][relative]
row = self._read(relative)
if record.get("deleted") or record["sha256"] != row["sha256"]:
raise RetentionError("Registered input changed")
if record["state"] != "active" or record["owner"] != owner:
raise RetentionError("Build owner changed or build is already closed")
record.update(state="closed", outcome=outcome, reason=reason)
if outcome in {"qualified", "rollback"}:
record["pins"][outcome] = reason
self._save(state)
# A finish only releases a hold. Destructive work uses a reviewable plan.
return self.plan()
@contextmanager
def publish(self, output, *, required_bytes=0):
"""Atomic publication + persistent hold; failed staging removes only its own temp."""
output = Path(output).absolute()
relative = str(output.relative_to(self.root))
with self._lock(write=True):
path = self._path(relative)
if path.exists() or path.is_symlink():
raise FileExistsError(path)
state = self._state()
# Family prefix gives a conservative count before the archive exists.
prefix = PATTERN.fullmatch(path.name)[1]
active = sum(
1
for n, r in state["inputs"].items()
if not r.get("deleted")
and r["state"] == "active"
and Path(n).name.startswith(prefix + "-")
)
if active >= MAX_ACTIVE_PER_FAMILY:
raise RetentionError(
"Eight unfinished inputs in this family; finish or cancel their owners first"
)
if required_bytes < 0 or shutil.disk_usage(path.parent).free < RESERVE + required_bytes:
raise RetentionError("Insufficient build space; preserve 2 GiB after staging")
temporary = path.with_name(".retention-" + uuid.uuid4().hex + ".part")
try:
yield temporary
row = self._read(relative, physical=temporary)
seen, base = {relative}, row["base"]
while base:
if base["path"] in seen:
raise RetentionError("Cyclic publication base graph")
seen.add(base["path"])
dependency = self._read(base["path"])
if dependency["sha256"] != base["sha256"]:
raise RetentionError("Publication base changed")
base = dependency["base"]
os.chmod(temporary, 0o600)
with temporary.open("rb") as stream:
os.fsync(stream.fileno())
# No replace: a non-cooperating publisher must not lose its file.
os.link(temporary, path, follow_symlinks=False)
temporary.unlink()
# A crash before registry commit leaves an unknown, protected file.
self._record(state, row, active=True, reason="Awaiting explicit build outcome")
finally:
temporary.unlink(missing_ok=True)
def apply(self, expected):
with self._lock(write=True):
current = self._plan()
if expected != current:
raise RetentionError("Stale or edited plan; generate a fresh plan")
if current["errors"]:
raise RetentionError("Inventory errors block all deletions")
state = self._state()
candidates = [x for x in current["inputs"] if x["action"] == "delete"]
# Delete dependants before bases: interruption must leave a usable graph.
def depth(row):
count, base = 0, row["base"]
by_path = {x["path"]: x for x in current["inputs"]}
while base:
count += 1
base = by_path[base["path"]]["base"]
return count
candidates.sort(key=lambda row: (-depth(row), row["path"]))
receipt_dir = self._directory(".runtime/build-retention/receipts", create=True)
receipt_path = receipt_dir / (uuid.uuid4().hex + ".json")
receipt = {
"schema": "missioncore.build-retention-receipt/v1",
"plan_id": current["plan_id"],
"started_ns": time.time_ns(),
"status": "applying",
"plan": current,
"removed": [],
"free_before": shutil.disk_usage(self.root).free,
}
_atomic(receipt_path, receipt)
try:
# All bytes were verified by _plan under the shared publication lock.
# Metadata is checked again immediately before each unlink.
for row in candidates:
path = self._path(row["path"])
if _stamp(_plain(path)) != row["stamp"]:
raise RetentionError("Input changed before unlink")
receipt["next"] = row["path"]
_atomic(receipt_path, receipt)
path.unlink()
receipt["removed"].append(
{"path": row["path"], "sha256": row["sha256"], "bytes": row["bytes"]}
)
state["inputs"][row["path"]]["deleted"] = True
self._save(state)
_atomic(receipt_path, receipt)
receipt["status"] = "complete"
except BaseException as exc:
receipt.update(status="interrupted", error=str(exc))
raise
finally:
receipt.update(
finished_ns=time.time_ns(), free_after=shutil.disk_usage(self.root).free
)
_atomic(receipt_path, receipt)
return dict(receipt, receipt=str(receipt_path))
def recover(self, receipt_name):
"""Reconcile only journaled unlinks after a process/storage interruption."""
if not re.fullmatch(r"[a-f0-9]{32}\.json", receipt_name):
raise RetentionError("Invalid receipt name")
with self._lock(write=True):
path = self._directory(".runtime/build-retention/receipts") / receipt_name
_plain(path)
receipt = json.loads(path.read_text())
if receipt["schema"] != "missioncore.build-retention-receipt/v1" or receipt[
"status"
] not in {"applying", "interrupted"}:
raise RetentionError("Receipt does not need recovery")
state = self._state()
planned = {x["path"]: x for x in receipt["plan"]["inputs"] if x["action"] == "delete"}
journaled = {x["path"] for x in receipt["removed"]} | {receipt.get("next")}
recovered = []
for name in sorted(n for n in journaled if n is not None):
row = planned[name]
record = state["inputs"][name]
if (
record["sha256"] != row["sha256"]
or record["state"] != "closed"
or record["pins"]
):
raise RetentionError("Recovery input was changed or protected")
candidate = self._path(name)
if candidate.exists() or candidate.is_symlink():
if self._read(name)["sha256"] != row["sha256"]:
raise RetentionError("Recovery input identity changed")
elif not record.get("deleted"):
record["deleted"] = True
recovered.append(name)
self._save(state)
receipt.update(
status="reconciled", reconciled_ns=time.time_ns(), recovered_missing=recovered
)
_atomic(path, receipt)
return {"recovered_missing": recovered, "receipt": str(path), "deleted_now": 0}
def publish_input(output, *, required_bytes=0):
"""Producer hook; this module is operator tooling, not an onboard dependency."""
return BuildRetention(Path(__file__).resolve().parents[2]).publish(
output, required_bytes=required_bytes
)
def input_hold(output):
"""Small lifecycle handle included in the producer's existing JSON response."""
store = BuildRetention(Path(__file__).resolve().parents[2])
relative = str(Path(output).absolute().relative_to(store.root))
with store._lock():
record = store._state()["inputs"][relative]
return {"path": relative, "owner": record["owner"], "state": record["state"]}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[2])
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("plan")
apply = commands.add_parser("apply")
apply.add_argument("--plan", type=Path, required=True)
recover = commands.add_parser("recover")
recover.add_argument("receipt", help="Basename of an interrupted receipt")
for name in ("adopt", "pin", "unpin", "finish"):
child = commands.add_parser(name)
child.add_argument("path", help="Repository-relative intermediate input path")
child.add_argument("--reason", required=True)
if name == "finish":
child.add_argument(
"--owner", required=True, help="Owner from plan/registry active-build reason"
)
child.add_argument(
"--outcome",
choices=("intermediate", "failed", "cancelled", "qualified", "rollback"),
required=True,
)
else:
child.add_argument("--pin", required=True)
args = parser.parse_args()
store = BuildRetention(args.root)
if args.command == "plan":
result = store.plan()
elif args.command == "apply":
result = store.apply(json.loads(args.plan.read_text()))
elif args.command == "recover":
result = store.recover(args.receipt)
elif args.command == "adopt":
store.adopt(args.path, pin=args.pin, reason=args.reason)
result = store.plan()
elif args.command == "finish":
result = store.finish(args.path, owner=args.owner, outcome=args.outcome, reason=args.reason)
else:
store.pin(args.path, pin=args.pin, reason=args.reason, remove=args.command == "unpin")
result = store.plan()
print(json.dumps(result, indent=2, sort_keys=True))
if result.get("errors"):
raise SystemExit(2)
if __name__ == "__main__":
main()