"""Durable release ordering. Pure state policy; no network or runtime authority. The canonical installer remains the only production executor. A controller may reserve a verified artifact here, then must reconcile its canonical receipt after any crash before admitting another deployment. """ import re import sqlite3 REPOSITORY = "SILVER/NODEDC_DEVICE_CORE" REPOSITORY_ID = 38 WORKFLOW = "ci.yml@refs/heads/main" TERMINAL = {"deployed", "failed", "superseded", "blocked"} SHA = re.compile(r"[0-9a-f]{40}") DIGEST = re.compile(r"[0-9a-f]{64}") class QueueError(ValueError): pass def positive(value): return type(value) is int and 0 < value < 2**53 def normalize_run(run): if not isinstance(run, dict): raise QueueError("invalid_run") if not all(positive(run.get(key)) for key in ("id", "run_number", "run_attempt")): raise QueueError("invalid_run_identity") if not isinstance(run.get("head_sha"), str) or not SHA.fullmatch(run["head_sha"]): raise QueueError("invalid_source_sha") status = run.get("status") if status not in ("queued", "waiting", "in_progress", "completed"): raise QueueError("unknown_run_status") conclusion = run.get("conclusion") if status == "completed" and conclusion not in ( "success", "failure", "cancelled", "skipped", "timed_out", "action_required", "neutral", "stale", ): raise QueueError("unknown_run_conclusion") relevant = (run.get("event") == "push" and run.get("head_branch") == "main" and run.get("path") == WORKFLOW) phase = "pending" if status != "completed" else "ready" if conclusion == "success" else "unqualified" if not relevant: phase = "ignored" return (run["id"], run["run_number"], run["head_sha"], str(run.get("event", "")), str(run.get("head_branch", "")), str(run.get("path", "")), run["run_attempt"], phase) class DeploymentQueue: def __init__(self, path, *, first_run_number): if not positive(first_run_number): raise QueueError("invalid_activation_floor") self.db = sqlite3.connect(str(path), timeout=10, isolation_level=None) self.db.row_factory = sqlite3.Row self.db.execute("PRAGMA journal_mode=WAL") self.db.execute("PRAGMA synchronous=FULL") self.db.executescript(""" CREATE TABLE IF NOT EXISTS policy ( id INTEGER PRIMARY KEY CHECK(id=1), repository TEXT NOT NULL, repository_id INTEGER NOT NULL, first_run INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS runs ( id INTEGER PRIMARY KEY, number INTEGER NOT NULL UNIQUE, sha TEXT NOT NULL, event TEXT NOT NULL, branch TEXT NOT NULL, workflow TEXT NOT NULL, attempt INTEGER NOT NULL, phase TEXT NOT NULL, artifact TEXT, digest TEXT, receipt TEXT ); CREATE INDEX IF NOT EXISTS runs_phase_number ON runs(phase,number); CREATE INDEX IF NOT EXISTS runs_sha_phase ON runs(sha,phase); """) self.db.execute("INSERT OR IGNORE INTO policy VALUES(1,?,?,?)", (REPOSITORY, REPOSITORY_ID, first_run_number)) policy = self.db.execute("SELECT * FROM policy WHERE id=1").fetchone() if (policy["repository"], policy["repository_id"], policy["first_run"]) != (REPOSITORY, REPOSITORY_ID, first_run_number): self.db.close() raise QueueError("queue_policy_changed") self.first_run = first_run_number def close(self): self.db.close() def transaction(self, operation): self.db.execute("BEGIN IMMEDIATE") try: value = operation() self.db.execute("COMMIT") return value except BaseException: self.db.execute("ROLLBACK") raise def observe(self, runs, *, repository, repository_id): if repository != REPOSITORY or type(repository_id) is not int or repository_id != REPOSITORY_ID: raise QueueError("repository_identity_mismatch") values = [normalize_run(run) for run in runs] def apply(): for value in values: identity, number, sha, event, branch, workflow, attempt, phase = value if number < self.first_run: continue existing = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone() if existing is None: self.db.execute("INSERT INTO runs(id,number,sha,event,branch,workflow,attempt,phase) VALUES(?,?,?,?,?,?,?,?)", value) continue if tuple(existing[k] for k in ("number", "sha", "event", "branch", "workflow")) != (number, sha, event, branch, workflow): raise QueueError("run_identity_changed") if attempt < existing["attempt"]: continue # A stale API page cannot rewind a rerun. if existing["phase"] in TERMINAL or existing["phase"] == "deploying": continue if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase == "pending": continue if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase != existing["phase"]: raise QueueError("terminal_run_outcome_changed") self.db.execute("UPDATE runs SET phase=?,attempt=? WHERE id=?", (phase, attempt, identity)) self.transaction(apply) def _next(self): blocked = self.db.execute("SELECT id,phase FROM runs WHERE phase IN ('deploying','blocked') ORDER BY number LIMIT 1").fetchone() if blocked: raise QueueError("canonical_reconciliation_required:" + str(blocked["id"])) while True: row = self.db.execute("SELECT * FROM runs WHERE phase IN ('pending','ready') ORDER BY number LIMIT 1").fetchone() if row is None or row["phase"] != "ready": return None newer = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND number>=? LIMIT 1", (row["number"],)).fetchone() duplicate = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND sha=? LIMIT 1", (row["sha"],)).fetchone() if newer or duplicate: self.db.execute("UPDATE runs SET phase='superseded' WHERE id=?", (row["id"],)) continue return dict(row) def next_ready(self): return self.transaction(self._next) def reserve(self, identity, *, digest, artifact): if not isinstance(digest, str) or not DIGEST.fullmatch(digest): raise QueueError("invalid_artifact_digest") def apply(): row = self._next() if row is None or row["id"] != identity: raise QueueError("deployment_order_mismatch") expected = "nodedc-device-core-release-v1-r" + str(identity) + "-" + row["sha"] + ".tgz" if artifact != expected: raise QueueError("artifact_identity_mismatch") self.db.execute("UPDATE runs SET phase='deploying',digest=?,artifact=? WHERE id=?", (digest, artifact, identity)) return {**row, "phase": "deploying", "digest": digest, "artifact": artifact} return self.transaction(apply) def reconcile(self, identity, *, digest, artifact, outcome, receipt): """Caller must prove the canonical applied/failed journal and archive. No receipt or uncertain/failed rollback => blocked, never automatic retry. A clean rollback may be followed by a new release, never this artifact. """ if outcome not in ("deployed", "rolled-back", "ambiguous"): raise QueueError("invalid_canonical_outcome") if not isinstance(receipt, str) or not receipt or len(receipt) > 240: raise QueueError("canonical_receipt_required") phase = {"deployed": "deployed", "rolled-back": "failed", "ambiguous": "blocked"}[outcome] def apply(): row = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone() if row is None or (row["digest"], row["artifact"]) != (digest, artifact): raise QueueError("canonical_artifact_mismatch") if row["phase"] == phase and row["receipt"] == receipt: return if row["phase"] != "deploying": raise QueueError("canonical_outcome_conflict") self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity)) self.transaction(apply) def reconcile_r46(self, identity, *, digest, artifact, receipt): """Exact terminal blocked -> failed recovery after canonical proof. This never makes the failed artifact ready again. The caller verifies the immutable failed evidence and the separate successful recovery. """ sha = 'e30a6dd2a1eae306d811977188f5d118aefed4ab' expected_receipt = 'canonical-reconciled:device-core-release-r46-reconciliation-v1-20261105-001' if (type(identity) is not int or identity != 46 or digest != 'b985f67bf160014a7e81679e072fc164d69e9ea21feb8165af0163fbed10adba' or artifact != 'nodedc-device-core-release-v1-r46-'+sha+'.tgz' or receipt != expected_receipt): raise QueueError('r46_reconciliation_identity_mismatch') def apply(): row = self.db.execute('SELECT * FROM runs WHERE id=?', (identity,)).fetchone() if row is None or tuple(row[k] for k in ('number','sha','event','branch','workflow','digest','artifact')) != (39,sha,'push','main',WORKFLOW,digest,artifact): raise QueueError('r46_reconciliation_row_mismatch') if row['phase'] == 'failed' and row['receipt'] == receipt: return if row['phase'] != 'blocked' or row['receipt'] != 'canonical-rollback-unconfirmed': raise QueueError('r46_reconciliation_predecessor_mismatch') self.db.execute("UPDATE runs SET phase='failed',receipt=? WHERE id=?", (receipt,identity)) self.transaction(apply) def snapshot(self): return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]