feat(deploy): add the recurring Device Core release domain and durable queue policy

This commit is contained in:
Codex
2026-09-29 18:41:21 +03:00
parent d87a0c48b4
commit d161d7fb91
5 changed files with 941 additions and 1 deletions
+307 -1
View File
@@ -2960,6 +2960,13 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
)
COMPONENTS = {
"device-core-release": {
"payload_root": DEVICE_PLANE_ROOT,
"compose_root": DEVICE_PLANE_ROOT,
"compose_project": "nodedc-device-plane",
"compose_no_deps": True,
"services": ("device-control-core", "device-manager"),
},
"mission-core-map-access": {
"payload_root": Path("/volume1/docker/nodedc-platform/mission-core-map-access"),
"bootstrap_root": True,
@@ -4956,6 +4963,8 @@ def denied_payload_path(component, rel):
def allowed_payload_path(component, rel):
validate_posix_path(rel)
if component == "device-core-release":
return device_release_payload_path(rel)
reason = denied_payload_path(component, rel)
if reason:
die(f"path rejected: {rel}: {reason}")
@@ -11570,6 +11579,8 @@ def load_artifact(artifact, work_dir):
die(f"files.txt entry missing in payload: {rel}")
validate_payload_tree(manifest["component"], payload_dir, entries)
if manifest["component"] == "device-core-release":
validate_device_release_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "gitea-actions-config":
validate_gitea_actions_payload(payload_dir, entries, manifest["id"])
if manifest["component"] == "gitea-ci":
@@ -22414,6 +22425,10 @@ def is_platform_provider_catalog_only(entries):
def component_services(component, entries=None):
if component == "device-core-release":
if tuple(entries or ()) != DEVICE_RELEASE_ENTRIES:
die("Device Core release service selection requires exact entries")
return DEVICE_RELEASE_SERVICES
if is_device_plane_control_core_release_slice(component, entries):
return ("device-control-core",)
@@ -22738,6 +22753,8 @@ def component_compose_files(
allow_prepared_engine_backend=False,
expected_node_intelligence_gateway_sha256=None,
):
if component == "device-core-release":
return component_compose_files("device-plane")
if component == "engine":
root = component_root(component)
files = [root / "docker-compose.yml"]
@@ -23017,6 +23034,12 @@ def component_build_args(component, entries=None):
def component_builds(component, entries=None):
if component == "device-core-release":
component_services(component, entries)
return (
(DEVICE_PLANE_ROOT, ("build", "--no-cache", "--network=host", "-f", "services/device-control-core/Dockerfile", "-t", "nodedc/device-control-core:local", ".")),
(DEVICE_PLANE_ROOT / "services/device-manager", ("build", "--no-cache", "-t", "nodedc/device-manager:local", ".")),
)
if is_platform_device_core_hub_trust_slice(component, entries):
return ()
@@ -32257,6 +32280,255 @@ def rollback_gitea_ci(root, backup_dir, entries, current_stamp, runtime_started)
# and are never archived in the data-only source partition.
# Recurring application releases: a separate domain from immutable historical
# Device Plane transitions. No Compose, database, secret or controller payload.
DEVICE_RELEASE_ENTRY = "deployment/device-core-release-v1.json"
DEVICE_RELEASE_ENTRIES = (
".dockerignore", "package.json", "package-lock.json",
"packages/device-protocol-contract", "packages/device-edge-channel-contract",
"packages/infrastructure-telemetry-contract", "services/device-control-core",
"services/device-manager", DEVICE_RELEASE_ENTRY,
)
DEVICE_RELEASE_SERVICES = ("device-control-core", "device-manager")
DEVICE_RELEASE_INVENTORY = (*DEVICE_PLANE_RUNTIME_SERVICES, "device-manager", "device-backhaul-target")
DEVICE_RELEASE_BASELINES = (
("device-edge-core-channel-upgrade-v4-20260812-023", "c10d5b6b7d55ab239f85b6c8130e34ce9f84985e3b46e6e5534733156c7982fc"),
("device-control-core-release-v4-20260823-047", "4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c"),
("device-manager-release-v13-20260823-051", "3d4b5c01330a73ae9ba82475d0029a5bb54763261ff105e8d04626e597fdf84c"),
)
DEVICE_RELEASE_STEPS = ["design-install", "design-core", "design-react", "device-install",
"unit-tests", "ci-contract", "build", "artifact-contracts"]
def device_release_payload_path(rel):
# Reuse the established deny rules, then narrow them to the two app trees.
reason = denied_payload_path("device-plane", rel)
if any(part.lower() in {"runtime", "runtime-data", "secrets", "credentials", "uploads", "logs", "data", "node_modules", ".git", "__pycache__"} for part in PurePosixPath(rel).parts):
reason = "runtime or secret subtree"
if reason:
die("Device Core release rejected path: " + rel + ": " + reason)
parents = {str(p) for entry in DEVICE_RELEASE_ENTRIES for p in PurePosixPath(entry).parents if str(p) != "."}
if rel in parents or rel in DEVICE_RELEASE_ENTRIES or any(
rel.startswith(entry + "/") for entry in DEVICE_RELEASE_ENTRIES[3:8]
):
return True
die("Device Core release path is outside the application scope: " + rel)
def validate_device_release_payload(payload, entries, patch_id):
if tuple(entries) != DEVICE_RELEASE_ENTRIES:
die("Device Core release requires the exact application entry set")
d = read_strict_json(payload / DEVICE_RELEASE_ENTRY, "Device Core release", max_bytes=256 * 1024)
if (set(d) != {"schemaVersion", "releaseId", "repository", "repositoryId", "branch",
"sourceCommit", "runId", "runNumber", "qualification", "filesSha256", "packagedManagerDistSha256"}
or d.get("schemaVersion") != "nodedc.device-core.release.v1"
or d.get("repository") != "SILVER/NODEDC_DEVICE_CORE" or type(d.get("repositoryId")) is not int
or d["repositoryId"] != 38 or d.get("branch") != "main"
or not isinstance(d.get("sourceCommit"), str) or not re.fullmatch(r"[a-f0-9]{40}", d["sourceCommit"])
or any(type(d.get(k)) is not int or not 0 < d[k] < 2**53 for k in ("runId", "runNumber"))
or d.get("releaseId") != patch_id
or patch_id != "device-core-release-v1-r" + str(d["runId"]) + "-" + d["sourceCommit"]):
die("Device Core release identity mismatch")
actual = collect_exact_files(payload, DEVICE_RELEASE_ENTRIES[:-1], "Device Core release")
if not actual or d.get("filesSha256") != actual:
die("Device Core release file manifest mismatch")
q = d.get("qualification")
if (not isinstance(q, dict) or q.get("schema") != "nodedc.device-core.qualification.v1"
or q.get("status") != "qualified" or q.get("deployed") is not False
or q.get("sourceCommit") != d["sourceCommit"] or q.get("steps") != DEVICE_RELEASE_STEPS
or q.get("packageLockSha256") != actual["package-lock.json"]
or not isinstance(q.get("sources"), dict)):
die("Device Core release qualification mismatch")
# Dist is produced by CI; an incomplete or substituted UI must fail here.
dist = payload / "services/device-manager/dist"
digest = hashlib.sha256()
count = 0
for path in sorted(dist.rglob("*"), key=lambda p: p.relative_to(dist).as_posix()):
if path.is_file():
name = path.relative_to(dist).as_posix().encode()
data = path.read_bytes()
digest.update(len(name).to_bytes(8, "big") + name)
digest.update(len(data).to_bytes(8, "big") + data)
count += 1
if not count or d.get("packagedManagerDistSha256") != digest.hexdigest():
die("Device Core qualified UI digest mismatch")
return d
def device_release_applied_archive(row):
name = row.get("artifact")
if (not isinstance(name, str) or Path(name).name != name or not name.endswith(".tgz")
or row.get("status") != "ok" or not re.fullmatch(r"[a-f0-9]{64}", str(row.get("sha256")))):
die("Device Core predecessor receipt is malformed")
archive = APPLIED_DIR / name
if archive.is_symlink() or not archive.is_file() or sha256_file(archive) != row["sha256"]:
die("Device Core predecessor archive mismatch")
return archive
def device_release_predecessor(candidate):
applied = load_state(STATE_FILE)
for row in load_state(FAILED_STATE_FILE):
if row.get("component") == "device-core-release" and row.get("started_apply") and not str(row.get("rollback_status", "")).startswith("ok:"):
die("Device Core release requires reconciliation of a failed rollback")
normal = [row for row in applied if row.get("component") == "device-core-release"]
installed = DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY
expected = {}
predecessor = None
if normal:
row = normal[-1]
with tempfile.TemporaryDirectory(prefix="device-release-baseline-", dir=TMP_DIR) as tmp:
manifest, entries, payload = load_artifact(device_release_applied_archive(row), Path(tmp))
if manifest["component"] != "device-core-release" or manifest["id"] != row["id"]:
die("Device Core predecessor identity mismatch")
predecessor = validate_device_release_payload(payload, entries, row["id"])
expected = collect_exact_files(payload, entries, "Device Core predecessor")
if candidate["runNumber"] <= predecessor["runNumber"] or candidate["sourceCommit"] == predecessor["sourceCommit"]:
die("Device Core release is stale or already deployed")
else:
if installed.exists() or installed.is_symlink():
die("Device Core release descriptor has no canonical applied receipt")
# The first normal release is anchored in the three exact live releases,
# independently of the report or file hashes supplied by CI.
for identity, digest in DEVICE_RELEASE_BASELINES:
rows = [r for r in applied if r.get("id") == identity and r.get("sha256") == digest and r.get("component") == "device-plane"]
if len(rows) != 1:
die("Device Core initial predecessor journal mismatch: " + identity)
with tempfile.TemporaryDirectory(prefix="device-release-initial-", dir=TMP_DIR) as tmp:
safe_extract(device_release_applied_archive(rows[0]), Path(tmp))
payload = Path(tmp) / "payload"
# Historical descriptors/Compose stay outside the write set.
selected = parse_files_list(Path(tmp) / "files.txt")
files = collect_exact_files(payload, selected, "Device Core initial predecessor")
# Reconstruct the exact published sequence. A directory entry
# replaces that whole subtree, including files removed later.
expected = {rel: value for rel, value in expected.items() if not any(
rel == entry or rel.startswith(entry + "/") for entry in selected
)}
expected.update(files)
for rel, digest in expected.items():
path = DEVICE_PLANE_ROOT / rel
if path.is_symlink() or not path.is_file() or sha256_file(path) != digest:
die("Device Core initial predecessor source drift: " + rel)
expected = {rel: value for rel, value in expected.items() if any(
rel == entry or rel.startswith(entry + "/") for entry in DEVICE_RELEASE_ENTRIES[:-1]
)}
compare_entries = DEVICE_RELEASE_ENTRIES if normal else DEVICE_RELEASE_ENTRIES[:-1]
if collect_exact_files(DEVICE_PLANE_ROOT, compare_entries, "Device Core installed source") != expected:
die("Device Core installed application tree differs from its canonical predecessor")
return predecessor
def device_release_runtime_snapshot():
inventory = device_plane_runtime_inventory(DEVICE_RELEASE_INVENTORY)
if set(device_plane_inventory_service_names(inventory)) != set(DEVICE_RELEASE_INVENTORY):
die("Device Core release requires all existing services")
result = {}
for row in inventory["services"]:
if not row["running"] or row["health"] not in (None, "healthy"):
die("Device Core predecessor service is not healthy: " + row["service"])
info = inspect_device_plane_container(row["containerId"])
host = json.loads(json.dumps(info.get("HostConfig") or {}))
if isinstance(host.get("Ulimits"), list):
host["Ulimits"].sort(key=lambda x: json.dumps(x, sort_keys=True))
config = info.get("Config") or {}
fields = {"HostConfig": host,
"Config": {k: config.get(k) for k in ("Env", "User", "Cmd", "Entrypoint", "WorkingDir", "ExposedPorts")},
"Mounts": sorted(info.get("Mounts") or [], key=lambda x: json.dumps(x, sort_keys=True)),
"networks": sorted((info.get("NetworkSettings") or {}).get("Networks") or {})}
if isinstance(fields["Config"]["Env"], list):
fields["Config"]["Env"].sort()
row["runtimeConfigSha256"] = hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest()
result[row["service"]] = row
return result
def device_release_other_compose_services():
# Compose services have a persistent owner. Ephemeral Actions job containers
# have no Compose project and can legitimately finish during deployment.
proc = subprocess.run([str(DOCKER), "ps", "-aq", "--no-trunc", "--filter", "label=com.docker.compose.project"], capture_output=True, text=True, check=True)
result = {}
for identity in proc.stdout.split():
if not re.fullmatch(r"[a-f0-9]{64}", identity):
die("Device Core preserved container identity mismatch")
info = inspect_container(identity)
labels = (info.get("Config") or {}).get("Labels") or {}
if labels.get("com.docker.compose.project") == "nodedc-device-plane":
continue
if str(labels.get("com.docker.compose.oneoff", "False")).lower() == "true":
continue
result[identity] = {"fingerprint": gitea_actions_fingerprint_v2(info),
"running": (info.get("State") or {}).get("Running"),
"startedAt": (info.get("State") or {}).get("StartedAt")}
return result
def preflight_device_release(payload, entries, patch_id):
d = validate_device_release_payload(payload, entries, patch_id)
predecessor = device_release_predecessor(d)
# Normal app releases cannot introduce schema or Docker recipe transitions.
# Those use separately reviewed migration/topology domains.
immutable = (".dockerignore", "services/device-control-core/Dockerfile", "services/device-manager/Dockerfile", "services/device-control-core/migrations")
if collect_exact_files(payload, immutable, "Device Core candidate foundation") != collect_exact_files(DEVICE_PLANE_ROOT, immutable, "Device Core installed foundation"):
die("Device Core release changes the immutable database/build foundation")
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True)
before = device_release_runtime_snapshot()
compose = {str(p): sha256_file(p) for p in component_compose_files("device-plane")}
return {"descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4",
"runtime": before, "compose": compose, "otherComposeServices": device_release_other_compose_services(),
"installedFiles": collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES if predecessor else DEVICE_RELEASE_ENTRIES[:-1], "Device Core rollback baseline")}
def accept_device_release(before, *, rollback=False):
current = device_release_runtime_snapshot()
for service, old in before["runtime"].items():
new = current[service]
if service not in DEVICE_RELEASE_SERVICES:
if new != old:
die("Device Core release changed a preserved service: " + service)
continue
if new["runtimeConfigSha256"] != old["runtimeConfigSha256"]:
die("Device Core release runtime configuration drift: " + service)
if rollback:
expected_image = old["imageId"]
else:
image = docker_json(["image", "inspect", "nodedc/" + service + ":local"], "Device Core release image")
if not isinstance(image, list) or len(image) != 1:
die("Device Core release image inspection mismatch")
expected_image = image[0].get("Id")
if new["containerId"] == old["containerId"]:
die("Device Core release did not recreate the selected service: " + service)
if new["imageId"] != expected_image:
die("Device Core release selected image mismatch: " + service)
if device_release_other_compose_services() != before["otherComposeServices"]:
die("Device Core release changed an unrelated Compose service")
if {str(p): sha256_file(p) for p in component_compose_files("device-plane")} != before["compose"]:
die("Device Core release changed Compose topology")
validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True)
if rollback:
entries = DEVICE_RELEASE_ENTRIES if DEVICE_RELEASE_ENTRY in before["installedFiles"] else DEVICE_RELEASE_ENTRIES[:-1]
if collect_exact_files(DEVICE_PLANE_ROOT, entries, "Device Core rollback source") != before["installedFiles"]:
die("Device Core rollback source mismatch")
if DEVICE_RELEASE_ENTRY not in before["installedFiles"] and (DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY).exists():
die("Device Core rollback left an orphan release descriptor")
else:
d = before["descriptor"]
validate_device_release_payload(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, d["releaseId"])
print("device_release_accept=" + ("rollback" if rollback else before["descriptor"]["sourceCommit"]) + ";database-volumes-and-topology=preserved")
def rollback_device_release(root, backup_dir, entries, current_stamp, before, runtime_started):
restore_platform_overlay(root, backup_dir, entries, current_stamp)
# Builds may have replaced a tag even if Compose never started. Restore both
# exact old image IDs; rollback never depends on a registry or a new build.
for service in DEVICE_RELEASE_SERVICES:
subprocess.run([str(DOCKER), "image", "tag", before["runtime"][service]["imageId"], "nodedc/" + service + ":local"], check=True)
if runtime_started:
run_compose("device-core-release", DEVICE_RELEASE_SERVICES, entries)
run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES)
accept_device_release(before, rollback=True)
def plan_artifact(artifact):
validate_artifact_location(artifact)
ensure_layout()
@@ -32309,6 +32581,11 @@ def plan_artifact(artifact):
gitea_salvage_preflight = None
with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp:
manifest, entries, payload_dir = load_artifact(artifact, Path(tmp))
if manifest["component"] == "device-core-release":
release_before = preflight_device_release(payload_dir, entries, manifest["id"])
print("device_release_source=" + release_before["descriptor"]["sourceCommit"])
print("device_release_predecessor=" + release_before["predecessor"])
print("device_release_scope=core,manager;database-volumes-topology-secrets=preserved;rollback=exact-image-ids")
if is_gitea_fresh_install_slice(manifest["component"], entries):
validate_gitea_compose_schema(payload_dir / GITEA_COMPOSE_REL)
if is_gitea_incident_salvage_slice(manifest["component"], entries):
@@ -36488,6 +36765,8 @@ def run_compose(component, services, entries=None):
or touches_engine_credential_provisioner(component, entries)
or (component == "engine" and ENGINE_CREDENTIAL_BACKEND_ACTIVATION_FILE.exists())):
cmd.extend(["--pull", "never"])
if component == "device-core-release":
cmd.extend(["--pull", "never", "--no-build"])
if COMPONENTS[component].get("compose_build"):
cmd.append("--build")
if component_compose_no_deps(component, entries):
@@ -38464,6 +38743,14 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan
def run_healthchecks(component, entries=None, services=None):
if component == "device-core-release":
if tuple(services or ()) != DEVICE_RELEASE_SERVICES or tuple(entries or ()) != DEVICE_RELEASE_ENTRIES:
die("Device Core release health scope mismatch")
for service in DEVICE_RELEASE_INVENTORY:
healthcheck_compose_service_with_grace("device-plane", service)
for check in component_healthchecks("device-plane", entries, services):
healthcheck_url(check)
return
if component == "gitea-actions-config":
if tuple(services or ()) != ("gitea",) or tuple(entries or ()) not in ((GITEA_ACTIONS_ENTRY,), (GITEA_ACTIONS_V2_ENTRY,)):
die("Gitea Actions service/entry set mismatch")
@@ -39576,6 +39863,7 @@ def apply_artifact(artifact):
engine_backend_initial_mode = None
runtime_started = False
gitea_ci_before = None
device_release_before = None
gitea_actions_before = None
current_stamp = stamp()
@@ -39625,6 +39913,8 @@ def apply_artifact(artifact):
gitea_ci_before = preflight_gitea_ci(entries)
if component == "gitea-actions-config":
gitea_actions_before = preflight_gitea_actions(entries)
if component == "device-core-release":
device_release_before = preflight_device_release(payload_dir, entries, patch_id)
artifact_only = component_artifact_only(component)
defer_bootstrap_root = is_gitea_bootstrap_slice(
component,
@@ -40150,6 +40440,10 @@ def apply_artifact(artifact):
include_nginx_html = component == "engine" and component_publish_dist(component, entries)
create_backup(root, backup_dir, entries, include_nginx_html)
if component == "device-core-release":
proof = backup_dir / "device-release-before.json"
proof.write_text(json.dumps(device_release_before, sort_keys=True) + "\n", encoding="utf-8")
proof.chmod(0o600)
if component == "gitea-ci":
(backup_dir / "ci-runtime-before.json").write_text(
json.dumps(gitea_ci_before, sort_keys=True) + "\n",
@@ -40237,6 +40531,10 @@ def apply_artifact(artifact):
# can be safely reconciled by recreating on that runtime.
engine_backend_recreated = True
run_compose(component, services, entries)
elif component == "device-core-release":
run_build(component, entries)
runtime_started = True
run_compose(component, services, entries)
elif component == "gitea-actions-config":
runtime_started = True
apply_gitea_actions(gitea_actions_before, backup_dir)
@@ -40276,6 +40574,8 @@ def apply_artifact(artifact):
):
die("Engine L2 closed-loop app generation was not recreated")
run_healthchecks(component, entries, services)
if component == "device-core-release":
accept_device_release(device_release_before)
if component == "gitea-ci":
if gitea_ci_inventory() != gitea_ci_before:
die("Gitea CI altered the preserved container inventory")
@@ -40350,7 +40650,13 @@ def apply_artifact(artifact):
and backup_dir is not None
and root is not None
):
if component == "gitea-actions-config":
if component == "device-core-release":
try:
rollback_device_release(root, backup_dir, entries, current_stamp, device_release_before, runtime_started)
rollback_status = "ok:device-core-release"
except Exception as rollback_exc:
rollback_status = "failed:" + type(rollback_exc).__name__
elif component == "gitea-actions-config":
try:
rollback_gitea_actions(root, backup_dir, entries, current_stamp,
gitea_actions_before, runtime_started)
@@ -0,0 +1,251 @@
"""Recurring release boundary, source provenance and exact rollback tests."""
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import hashlib
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import shutil
import tarfile
import tempfile
import unittest
from unittest import mock
loader = importlib.machinery.SourceFileLoader('device_release_runner', str(Path(__file__).with_name('nodedc-deploy')))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec)
loader.exec_module(R)
def put(root, rel, data):
target = root / rel
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
def fixture(root, number=12, sha='a'*40):
files = {'.dockerignore': b'.env\nsecrets\n', 'package.json': b'{}', 'package-lock.json': b'{}',
'services/device-control-core/Dockerfile': b'FROM node:22-alpine\n',
'services/device-manager/Dockerfile': b'FROM node:22-alpine\n',
'services/device-control-core/src/server.mjs': b'fixture',
'services/device-control-core/migrations/001.sql': b'-- fixture',
'services/device-manager/server/app.mjs': b'fixture',
'services/device-manager/dist/index.html': b'<div>fixture</div>'}
for entry in R.DEVICE_RELEASE_ENTRIES[3:6]: files[entry+'/src/index.mjs'] = b'fixture'
digest = hashlib.sha256()
name = b'index.html'; data = files['services/device-manager/dist/index.html']
digest.update(len(name).to_bytes(8,'big')+name+len(data).to_bytes(8,'big')+data)
identity = 'device-core-release-v1-r'+str(number)+'-'+sha
d = {'schemaVersion':'nodedc.device-core.release.v1','repository':'SILVER/NODEDC_DEVICE_CORE',
'repositoryId':38,'branch':'main','sourceCommit':sha,'runId':number,'runNumber':number,
'releaseId':identity,'filesSha256':{k:hashlib.sha256(v).hexdigest() for k,v in files.items()},
'packagedManagerDistSha256':digest.hexdigest(),
'qualification':{'schema':'nodedc.device-core.qualification.v1','status':'qualified','deployed':False,
'sourceCommit':sha,'steps':R.DEVICE_RELEASE_STEPS,'packageLockSha256':hashlib.sha256(b'{}').hexdigest(),
'sources':{}}}
files[R.DEVICE_RELEASE_ENTRY] = json.dumps(d).encode()
for path, value in files.items(): put(root, path, value)
return d
def archive(root, destination, d):
with tarfile.open(destination,'w:gz') as a:
for name, data in [('manifest.env', ('id='+d['releaseId']+'\ncomponent=device-core-release\ntype=app-overlay\n').encode()),
('files.txt', ('\n'.join(R.DEVICE_RELEASE_ENTRIES)+'\n').encode())]:
info=tarfile.TarInfo(name);info.size=len(data);a.addfile(info,io.BytesIO(data))
a.add(root,arcname='payload')
def runtime():
return {s:{'service':s,'containerId':str(i)*64,'imageId':'sha256:'+str(i)*64,
'status':'running','running':True,'health':'healthy','restartCount':0,'runtimeConfigSha256':'f'*64}
for i,s in enumerate(R.DEVICE_RELEASE_INVENTORY,1)}
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.root=Path(self.tmp.name);self.payload=self.root/'payload';self.payload.mkdir()
self.d=fixture(self.payload);self.a=self.root/'release.tgz';archive(self.payload,self.a,self.d)
def test_real_archive_exact_scope_and_builds(self):
work=self.root/'work';work.mkdir()
manifest, entries, _=R.load_artifact(self.a,work)
self.assertEqual(manifest['id'],self.d['releaseId'])
self.assertEqual(R.component_services('device-core-release',entries),R.DEVICE_RELEASE_SERVICES)
self.assertEqual(len(R.component_builds('device-core-release',entries)),2)
self.assertTrue(R.component_compose_no_deps('device-core-release',entries))
with mock.patch.object(R,'component_compose_files', wraps=R.component_compose_files) as f, mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root):
# New component delegates effective Compose to its existing owner.
R.component_compose_files('device-core-release')
self.assertIn(mock.call('device-plane'),f.call_args_list)
def test_no_partial_or_broad_service_selection(self):
for entries in [None,[],R.DEVICE_RELEASE_ENTRIES[:-1],list(R.DEVICE_RELEASE_ENTRIES)+['services/device-gateway']]:
with self.subTest(entries=entries),self.assertRaises(R.DeployError):R.component_services('device-core-release',entries)
def test_path_boundary_rejects_infrastructure_and_secrets(self):
for rel in ['docker-compose.device-plane.yml','services/device-gateway/src/app.mjs',
'services/device-manager/.env','services/device-manager/secrets/key',
'services/device-control-core/test/a.mjs','../escape','data/db','infra/watch.py',
'services/device-control-core/runtime/cache','services/device-manager/dist/a.pem']:
with self.subTest(rel=rel),self.assertRaises(R.DeployError):R.allowed_payload_path('device-core-release',rel)
def test_identity_and_qualification_cannot_select_another_target(self):
for key,value in [('repository','SILVER/other'),('repositoryId',True),('branch','develop'),
('runId',True),('runNumber',0),('sourceCommit','main'),('services',['device-postgres']),
('packagedManagerDistSha256','f'*64),('qualification',{})]:
d=copy.deepcopy(self.d);d[key]=value;put(self.payload,R.DEVICE_RELEASE_ENTRY,json.dumps(d).encode())
with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_payload_tampering_missing_files_and_extra_files(self):
path=self.payload/'services/device-manager/dist/index.html'
old=path.read_bytes();path.write_bytes(old+b'changed')
with self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
path.write_bytes(old);put(self.payload,'services/device-manager/server/extra.mjs',b'new')
with self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_packaged_digest_uses_lexical_paths_including_file_directory_prefixes(self):
files={'favicon.ico':b'icon','favicon/icon.png':b'image','index.html':b'<div>fixture</div>'}
digest=hashlib.sha256()
for name,value in sorted(files.items()):
put(self.payload,'services/device-manager/dist/'+name,value)
self.d['filesSha256']['services/device-manager/dist/'+name]=hashlib.sha256(value).hexdigest()
encoded=name.encode();digest.update(len(encoded).to_bytes(8,'big')+encoded+len(value).to_bytes(8,'big')+value)
self.d['packagedManagerDistSha256']=digest.hexdigest()
put(self.payload,R.DEVICE_RELEASE_ENTRY,json.dumps(self.d).encode())
R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_new_schema_or_build_recipe_requires_a_separate_domain(self):
live=self.root/'live';shutil.copytree(self.payload,live)
for rel in ['services/device-control-core/migrations/001.sql','services/device-manager/Dockerfile']:
previous=(live/rel).read_bytes();(live/rel).write_bytes(b'drift')
with mock.patch.object(R,'DEVICE_PLANE_ROOT',live),mock.patch.object(R,'device_release_predecessor',return_value=None),mock.patch.object(R,'validate_device_manager_control_plane_runtime') as runtime_check,self.assertRaisesRegex(R.DeployError,'immutable database/build foundation'):
R.preflight_device_release(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
runtime_check.assert_not_called();(live/rel).write_bytes(previous)
def test_predecessor_from_canonical_archive_rejects_stale_or_source_drift(self):
live=self.root/'live';shutil.copytree(self.payload,live)
row={'id':self.d['releaseId'],'artifact':self.a.name,'status':'ok','component':'device-core-release','sha256':R.sha256_file(self.a)}
with mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.STATE_FILE else []),mock.patch.object(R,'APPLIED_DIR',self.root),mock.patch.object(R,'DEVICE_PLANE_ROOT',live),mock.patch.object(R,'TMP_DIR',self.root):
newer={'runNumber':13,'sourceCommit':'b'*40}
self.assertEqual(R.device_release_predecessor(newer)['releaseId'],self.d['releaseId'])
for value in [{'runNumber':12,'sourceCommit':'b'*40},{'runNumber':13,'sourceCommit':'a'*40}]:
with self.assertRaises(R.DeployError):R.device_release_predecessor(value)
put(live,'services/device-manager/server/drift.mjs',b'changed')
with self.assertRaisesRegex(R.DeployError,'differs'):R.device_release_predecessor(newer)
def test_failed_rollback_blocks_later_release(self):
row={'component':'device-core-release','started_apply':True,'rollback_status':'failed:RuntimeError'}
with mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.FAILED_STATE_FILE else []),self.assertRaisesRegex(R.DeployError,'reconciliation'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_orphan_descriptor_never_becomes_accepted_predecessor(self):
with mock.patch.object(R,'load_state',return_value=[]),mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload),self.assertRaisesRegex(R.DeployError,'no canonical'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_initial_predecessor_is_required(self):
with mock.patch.object(R,'load_state',return_value=[]),mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root/'missing'),self.assertRaisesRegex(R.DeployError,'journal mismatch'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_rollback_uses_previous_images_without_build_or_registry(self):
before={'runtime':runtime()}; calls=[]
with mock.patch.object(R,'restore_platform_overlay',side_effect=lambda *a:calls.append('source')),mock.patch.object(R.subprocess,'run',side_effect=lambda *a,**k:calls.append(a[0])),mock.patch.object(R,'run_compose',side_effect=lambda *a:calls.append('compose')),mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')),mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('accept')),mock.patch.object(R,'run_build') as build:
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',before,True)
self.assertEqual(calls[0],'source');self.assertEqual(calls[-3:],['compose','health','accept']);build.assert_not_called()
self.assertEqual([x[1:3] for x in calls if isinstance(x,list)],[['image','tag'],['image','tag']])
self.assertEqual(calls[1][-2],before['runtime']['device-control-core']['imageId'])
def test_build_failure_restores_tags_but_does_not_restart_services(self):
with mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R.subprocess,'run') as command,mock.patch.object(R,'run_compose') as compose,mock.patch.object(R,'run_healthchecks') as health,mock.patch.object(R,'accept_device_release'):
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',{'runtime':runtime()},False)
self.assertEqual(command.call_count,2);compose.assert_not_called();health.assert_not_called()
def test_acceptance_rejects_preserved_service_recreation_or_new_config(self):
old=runtime();before={'runtime':old,'compose':{},'descriptor':self.d}
for service,key,value in [('device-postgres','containerId','z'*64),('device-manager','runtimeConfigSha256','e'*64),('device-control-core','containerId',old['device-control-core']['containerId'])]:
new=copy.deepcopy(old)
for selected in R.DEVICE_RELEASE_SERVICES:new[selected]['containerId']='c'*64
new[service][key]=value
with self.subTest(service=service,key=key),mock.patch.object(R,'device_release_runtime_snapshot',return_value=new),mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':old[args[-1].split('/')[1].split(':')[0]]['imageId']}]),self.assertRaises(R.DeployError):R.accept_device_release(before)
def test_compose_never_rebuilds_pulls_or_starts_dependencies(self):
with mock.patch.object(R,'compose_base_cmd',return_value=['docker','compose']),mock.patch.object(R,'component_compose_root',return_value=self.root),mock.patch.object(R.subprocess,'run') as command:
R.run_compose('device-core-release',R.DEVICE_RELEASE_SERVICES,R.DEVICE_RELEASE_ENTRIES)
cmd=command.call_args_list[0].args[0]
for arg in ['--no-deps','--no-build','--force-recreate']:self.assertIn(arg,cmd)
self.assertEqual(cmd[cmd.index('--pull')+1],'never');self.assertEqual(cmd[-2:],list(R.DEVICE_RELEASE_SERVICES))
def execute_apply(self, *, fail_at=None):
live=self.root/'live';live.mkdir()
old=fixture(live,number=11,sha='b'*40)
before={'runtime':runtime(),'compose':{},'descriptor':self.d,'otherComposeServices':{},
'installedFiles':R.collect_exact_files(live,R.DEVICE_RELEASE_ENTRIES,'test')}
events=[]
config={**R.COMPONENTS['device-core-release'],'payload_root':live,'compose_root':live}
for directory in ['inbox','applied','failed','backups','state','tmp']:(self.root/directory).mkdir()
compose=live/'compose.yml';compose.write_text('fixture')
def operation(name):
def call(*args,**kwargs):
events.append(name)
if name==fail_at:raise R.DeployError('injected '+name)
return call
with ExitStack() as stack:
for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),
('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),
('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),
('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),
('LOCK_DIR',self.root/'lock'),('DOCKER',Path('/usr/bin/true'))]:
stack.enter_context(mock.patch.object(R,name,value))
stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-release':config}))
for name in ['require_root','ensure_layout','validate_artifact_location']:
stack.enter_context(mock.patch.object(R,name))
stack.enter_context(mock.patch.object(R,'component_compose_files',return_value=(compose,)))
stack.enter_context(mock.patch.object(R,'preflight_device_release',return_value=before))
for name,label in [('run_build','build'),('run_compose','compose'),('run_healthchecks','health')]:
stack.enter_context(mock.patch.object(R,name,side_effect=operation(label)))
def acceptance(*args,**kwargs):
if kwargs.get('rollback'):
events.append('rollback-accept')
self.assertEqual(R.collect_exact_files(live,R.DEVICE_RELEASE_ENTRIES,'restored'),before['installedFiles'])
else:operation('accept')()
stack.enter_context(mock.patch.object(R,'accept_device_release',side_effect=acceptance))
stack.enter_context(mock.patch.object(R.subprocess,'run',side_effect=operation('tag')))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail_at:
with self.assertRaises(R.DeployError):R.apply_artifact(self.a)
else:R.apply_artifact(self.a)
applied=R.load_state(R.STATE_FILE);failed=R.load_state(R.FAILED_STATE_FILE)
return events,applied,failed
def test_apply_journals_success_only_after_acceptance(self):
events,applied,failed=self.execute_apply()
self.assertEqual(events,['build','compose','health','accept'])
self.assertEqual(len(applied),1);self.assertFalse(failed)
self.assertEqual(applied[0]['sha256'],R.sha256_file(self.root/'applied/release.tgz'))
self.assertFalse(self.a.exists())
def test_failed_build_preserves_runtime_and_restores_source_and_tags(self):
events,applied,failed=self.execute_apply(fail_at='build')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release')
self.assertEqual(events,['build','tag','tag','rollback-accept'])
def test_failed_acceptance_rolls_back_before_failure_journal(self):
events,applied,failed=self.execute_apply(fail_at='accept')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release')
self.assertEqual(events,['build','compose','health','accept','tag','tag','compose','health','rollback-accept'])
def test_persistent_health_failure_is_reconciliation_required(self):
events,applied,failed=self.execute_apply(fail_at='health')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'failed:DeployError')
self.assertNotIn('rollback-accept',events)
def test_health_checks_selected_and_preserved_services(self):
with mock.patch.object(R,'healthcheck_compose_service_with_grace') as check,mock.patch.object(R,'healthcheck_url'),mock.patch.object(R,'component_healthchecks',return_value=[]):
R.run_healthchecks('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
self.assertEqual([x.args[1] for x in check.call_args_list],list(R.DEVICE_RELEASE_INVENTORY))
if __name__=='__main__':unittest.main()
+67
View File
@@ -0,0 +1,67 @@
# Device Core recurring deployment
Status: 2026-09-29. The build runner is installed and push-to-main qualification
works. Production polling is **not activated**. DCPLATFORM-21 owns the deployment
contract; DCPLATFORM-37 tracks activation.
## Release domain
The root-owned `infra/deploy-runner/nodedc-deploy` adds `device-core-release`.
Device Core's `infra/ci/package_release.py` creates the only accepted nine-entry,
data-only package. It binds repository 38, main, full source commit, CI run ID and
number, completed qualification, every source file, and the served UI digest.
The served digest uses lexically sorted relative POSIX paths, with 8-byte big-endian
path/data lengths; it excludes source maps independently of the full build digest.
The first deployment proves the exact applied sequence: Edge channel v4 (023),
Control Core v4 (047), Manager v13 (051). Later deployments prove the most recent
normal-release archive, journal and complete installed file map. Stale runs,
repeated source commits, source drift and unresolved rollback failures fail closed.
Historical transition rules are unchanged.
Only `device-control-core` and `device-manager` are built and recreated, using the
existing effective Compose project/files and `--no-deps --no-build --pull never`.
The database, Gateway, backhaul, volumes, existing ports, mounts, identities and
all other persistent Compose services remain unchanged. Migration files and build
recipes must match the installed foundation; changes need a separately reviewed
migration/topology transition. Build jobs never receive installation credentials.
Apply backs up the exact replaced source and old image IDs before writing. Failed
builds restore source and tags without restarting services. Failed activation
restores both old images without rebuilding, recreates only the selected services,
then verifies health, source, configuration and preservation before recording a
successful rollback. A failed rollback blocks further releases for reconciliation.
Successful apply requires new selected container generations, correct images,
healthy dependencies, unchanged topology and source hashes before `deploy-ok`.
## Durable queue foundation
`deployment_queue.py` supplies transactional SQLite ordering and restart recovery.
It has no network or runtime authority. It rejects mismatched run identity, waits
for earlier pending runs, records artifact reservation before installation, skips
duplicate/already superseded sources, and requires a canonical journal/archive
receipt after a crash. It does not discover API pages or prove Git ancestry.
## Remaining activation work
- Implement outbound authenticated Gitea polling with complete pagination and
refresh of pending runs; verify repository, run, jobs, artifact and Git ancestry.
- Import a narrowly scoped read token into root-private controller runtime.
- Add and test the canonical controller bootstrap domain and fixed service unit.
- Install via the root runner, then accept push → qualified artifact → canonical
plan/apply, serial commits, failed tests, rollback and restart recovery on NAS.
No helper from this directory is installed by an application release. Do not run
helper code from SMB or use Docker as a deployment shortcut.
## Validation
```sh
python3 -m unittest discover -s infra/device-core-deploy -p 'test_*.py'
python3 -m unittest discover -s infra/deploy-runner -p test_device_core_release.py
python3 -m unittest discover -s infra/gitea-ci -p 'test_*.py'
```
The Device Core repository's full `infra/deploy-runner` suite must also pass against
the changed canonical runner. Its historical skipped tests remain reported as
skipped, not as live acceptance.
@@ -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/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 snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]
@@ -0,0 +1,138 @@
import tempfile
from pathlib import Path
import unittest
from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID
def run(number, *, status="completed", conclusion="success", **updates):
return {"id": number + 100, "run_number": number, "run_attempt": 1,
"head_sha": format(number, "040x"), "event": "push", "head_branch": "main",
"path": "ci.yml@refs/heads/main", "status": status, "conclusion": conclusion, **updates}
class QueueTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / "queue.db"
self.q = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(lambda: self.q.close())
def observe(self, *values):
self.q.observe(list(values), repository=REPOSITORY, repository_id=REPOSITORY_ID)
def reserve(self, number):
r = self.q.next_ready()
self.assertEqual(r["number"], number)
return self.q.reserve(r["id"], digest="a"*64,
artifact="nodedc-device-core-release-v1-r"+str(r["id"])+"-"+r["sha"]+".tgz")
def finish(self, row, outcome="deployed"):
self.q.reconcile(row["id"], digest=row["digest"], artifact=row["artifact"],
outcome=outcome, receipt="canonical-test-receipt-"+str(row["id"]))
def test_overlapping_pushes_wait_for_older_qualification(self):
self.observe(run(2), run(1, status="in_progress", conclusion=None))
self.assertIsNone(self.q.next_ready())
self.observe(run(1))
self.finish(self.reserve(1))
self.finish(self.reserve(2))
self.assertIsNone(self.q.next_ready())
def test_failed_tests_do_not_deploy_and_next_push_can_proceed(self):
self.observe(run(2), run(1, conclusion="failure"))
self.finish(self.reserve(2))
self.assertEqual(self.q.snapshot()[0]["phase"], "unqualified")
def test_duplicate_observations_and_receipts_are_idempotent(self):
self.observe(run(1), run(1))
row = self.reserve(1)
self.finish(row)
self.finish(row)
self.observe(run(1))
self.assertEqual(len(self.q.snapshot()), 1)
self.assertIsNone(self.q.next_ready())
def test_wrong_branch_event_and_workflow_never_deploy(self):
self.observe(run(1, head_branch="feature"), run(2, event="workflow_dispatch"), run(3, path="other.yml@refs/heads/main"))
self.assertIsNone(self.q.next_ready())
self.assertEqual({r["phase"] for r in self.q.snapshot()}, {"ignored"})
def test_wrong_repository_and_malformed_sha_rejected(self):
for repo, identity in [("other/Device", 38), (REPOSITORY, 39), (REPOSITORY, 38.0)]:
with self.assertRaises(QueueError): self.q.observe([run(1)], repository=repo, repository_id=identity)
with self.assertRaises(QueueError): self.observe(run(1, head_sha="main; execute"))
self.assertEqual(self.q.snapshot(), [])
def test_identity_conflict_rolls_back_entire_observation(self):
self.observe(run(1))
with self.assertRaises(QueueError): self.observe(run(2), run(1, head_sha="b"*40))
self.assertEqual(len(self.q.snapshot()), 1)
def test_restart_preserves_pending_and_requires_reconciliation_for_reserved(self):
self.observe(run(1), run(2))
row = self.reserve(1)
self.q.close()
self.q = DeploymentQueue(self.path, first_run_number=1)
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
self.finish(row)
self.assertEqual(self.q.next_ready()["number"], 2)
def test_ambiguous_or_failed_rollback_halts_following_deploys(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "ambiguous")
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
def test_clean_rollback_never_retries_same_artifact_but_allows_forward_fix(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "rolled-back")
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 2)
def test_late_old_run_and_same_source_cannot_downgrade_installed_revision(self):
self.observe(run(5))
self.finish(self.reserve(5))
self.observe(run(4), run(6, head_sha=run(5)["head_sha"]))
self.assertIsNone(self.q.next_ready())
self.assertEqual([r["phase"] for r in self.q.snapshot()], ["superseded", "deployed", "superseded"])
def test_second_controller_cannot_reserve_another_deploy(self):
self.observe(run(1), run(2))
second = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(second.close)
self.reserve(1)
with self.assertRaises(QueueError): second.next_ready()
def test_wrong_receipt_cannot_close_crashed_deployment(self):
self.observe(run(1))
row = self.reserve(1)
with self.assertRaisesRegex(QueueError, "artifact_mismatch"):
self.q.reconcile(row["id"], digest="b"*64, artifact=row["artifact"], outcome="deployed", receipt="wrong")
with self.assertRaises(QueueError): self.q.next_ready()
def test_activation_floor_is_persistent_and_old_history_is_not_deployed(self):
self.q.close()
self.path = Path(self.temp.name) / "second.db"
self.q = DeploymentQueue(self.path, first_run_number=3)
self.observe(run(1), run(2), run(3))
self.assertEqual(self.q.next_ready()["number"], 3)
with self.assertRaisesRegex(QueueError, "policy_changed"):
DeploymentQueue(self.path, first_run_number=1)
def test_terminal_api_outcome_cannot_change_without_a_new_attempt(self):
self.observe(run(1, conclusion="failure"))
with self.assertRaisesRegex(QueueError, "outcome_changed"): self.observe(run(1))
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 1)
def test_large_backlog_of_duplicate_sources_is_iterative(self):
self.observe(run(1))
self.finish(self.reserve(1))
self.observe(*(run(n, head_sha=run(1)["head_sha"]) for n in range(2, 1200)))
self.assertIsNone(self.q.next_ready())
self.assertEqual(len(self.q.snapshot()), 1199)
if __name__ == "__main__":
unittest.main()