"""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()