Add CMS deployment builders, policy sources and regression suite

This commit is contained in:
Codex
2026-11-04 21:51:05 +03:00
parent 28d8466ef9
commit aeaaae50c3
22 changed files with 2316 additions and 0 deletions
+178
View File
@@ -0,0 +1,178 @@
"""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/DC_CMS"
REPOSITORY_ID = 33
WORKFLOW = "ci.yml@refs/heads/master"
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") == "master"
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-dc-cms-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 snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]