diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index c3fa7a5..334f7bd 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -32870,6 +32870,66 @@ def device_release_runtime_snapshot_v2(): return result +def device_release_field_digests(fields): + """Diagnostic hashes only. Never retain environment/inspect values here.""" + result = {} + for section in ("HostConfig", "Config"): + values = fields.get(section) + if not isinstance(values, dict) or len(values) > 256: + die("Device Core runtime diagnostic section is invalid") + for key, value in values.items(): + if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,100}", key): + die("Device Core runtime diagnostic field name is invalid") + result[section + "." + key] = device_release_drift_digest(value) + for key in ("Mounts", "networks"): + result[key] = device_release_drift_digest(fields.get(key)) + return result + + +def device_release_capture_field_digests(expected_runtime): + """Bind diagnostics to the already checked container generation and digest.""" + observations = device_release_drift_sample() + if set(observations) != set(expected_runtime): + die("Device Core runtime diagnostic inventory changed") + result = {} + for service, sample in observations.items(): + expected = expected_runtime[service] + fields = device_release_mounts_v2(sample["fields"]) + if (sample["runtime"]["containerId"] != expected["containerId"] + or sample["runtime"]["imageId"] != expected["imageId"] + or device_release_drift_digest(fields) != expected["runtimeConfigSha256"]): + die("Device Core runtime changed while capturing diagnostic evidence: " + service) + result[service] = device_release_field_digests(fields) + return result + + +def device_release_runtime_drift_message(before, current, service): + message = "Device Core release runtime configuration drift: " + service + expected = before.get("runtimeFieldDigests", {}).get(service) + if expected is None: + return message # Legacy snapshots retain their exact acceptance semantics. + report = {"schema": "nodedc.device-core.runtime-drift-fields.v1", + "service": service, + "expectedSha256": before["runtime"][service]["runtimeConfigSha256"], + "actualSha256": current[service]["runtimeConfigSha256"]} + try: + if not isinstance(expected, dict) or any( + not isinstance(key, str) or not re.fullmatch(r"(?:HostConfig|Config)\.[A-Za-z][A-Za-z0-9_]{0,100}|Mounts|networks", key) + or not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value) + for key, value in expected.items()): + die("Device Core saved runtime field digests are invalid") + actual = device_release_capture_field_digests(current)[service] + changed = sorted(key for key in set(expected) | set(actual) if expected.get(key) != actual.get(key)) + report["changedFields"] = [{"path": key, "expectedSha256": expected.get(key), + "actualSha256": actual.get(key)} for key in changed[:64]] + report["truncated"] = len(changed) > 64 + report["evidence"] = "captured" if changed else "inconsistent" + except Exception: + # Do not copy raw external exception text into a public failed receipt. + report["evidence"] = "unavailable" + return message + "; field_evidence=" + json.dumps(report, sort_keys=True, separators=(",", ":")) + + def device_release_mount_order_proof(fields, expected): # Unlike the diagnostic probe, this CANNOT change Binds or NetworkMode. # The legacy backup contains only a digest, so prove an exact old preimage. @@ -32931,9 +32991,11 @@ def preflight_device_release(payload, entries, patch_id): validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True) run_healthchecks("device-core-release", entries, DEVICE_RELEASE_SERVICES) before = device_release_runtime_snapshot_v2() + field_digests = device_release_capture_field_digests(before) compose = {str(p): sha256_file(p) for p in component_compose_files("device-plane")} return {"runtimeFingerprintVersion": 2, "descriptor": d, "predecessor": predecessor["releaseId"] if predecessor else "manager-v13/core-v4/edge-v4", - "runtime": before, "compose": compose, "otherComposeServices": device_release_other_compose_services(), + "runtime": before, "runtimeFieldDigests": field_digests, + "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")} @@ -32949,7 +33011,7 @@ def accept_device_release(before, *, rollback=False): die("Device Core release changed a preserved service: " + service) continue if new["runtimeConfigSha256"] != old["runtimeConfigSha256"]: - die("Device Core release runtime configuration drift: " + service) + die(device_release_runtime_drift_message(before, current, service)) if rollback: expected_image = old["imageId"] else: diff --git a/infra/deploy-runner/test_device_core_mount_order.py b/infra/deploy-runner/test_device_core_mount_order.py index 0677988..e3c062e 100644 --- a/infra/deploy-runner/test_device_core_mount_order.py +++ b/infra/deploy-runner/test_device_core_mount_order.py @@ -162,8 +162,11 @@ class MountOrderTests(unittest.TestCase): for name in ['validate_device_manager_control_plane_runtime','run_healthchecks']: stack.enter_context(mock.patch.object(R,name)) legacy = stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot')) + detail = stack.enter_context(mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':{'Config.Env':'a'*64}})) before = R.preflight_device_release(self.root,R.DEVICE_RELEASE_ENTRIES,'id') self.assertEqual(before['runtimeFingerprintVersion'],2);legacy.assert_not_called() + self.assertEqual(before['runtimeFieldDigests'],{'device-manager':{'Config.Env':'a'*64}}) + detail.assert_called_once_with(before['runtime']) def test_preflight_and_post_health_dispatch_v2_only_with_exact_identity(self): old = samples_fixture();before = evidence_fixture(old);current = reorder(old) diff --git a/infra/deploy-runner/test_device_core_release.py b/infra/deploy-runner/test_device_core_release.py index 104830f..d21bc76 100644 --- a/infra/deploy-runner/test_device_core_release.py +++ b/infra/deploy-runner/test_device_core_release.py @@ -178,7 +178,7 @@ class ReleaseTests(unittest.TestCase): 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): + def execute_apply(self, *, fail_at=None, failure_message=None): live=self.root/'live';live.mkdir() old=fixture(live,number=11,sha='b'*40) before={'runtime':runtime(),'compose':{},'descriptor':self.d,'otherComposeServices':{}, @@ -190,7 +190,7 @@ class ReleaseTests(unittest.TestCase): def operation(name): def call(*args,**kwargs): events.append(name) - if name==fail_at:raise R.DeployError('injected '+name) + if name==fail_at:raise R.DeployError(failure_message or 'injected '+name) return call with ExitStack() as stack: for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'), @@ -237,6 +237,22 @@ class ReleaseTests(unittest.TestCase): 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_drift_details_survive_rollback_in_the_canonical_failed_receipt(self): + fields={'HostConfig':{'NetworkMode':'private'},'Config':{'Env':['TOKEN=private-value']},'Mounts':[],'networks':['private','edge']} + previous=R.device_release_field_digests(fields) + fields['HostConfig']['NetworkMode']='edge' + current=R.device_release_field_digests(fields) + before={'runtime':runtime(),'runtimeFieldDigests':{'device-manager':previous}} + with mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':current}): + message=R.device_release_runtime_drift_message(before,runtime(),'device-manager') + events,applied,failed=self.execute_apply(fail_at='accept',failure_message=message) + self.assertFalse(applied) + self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release') + self.assertEqual(failed[0]['message'],message) + self.assertIn('HostConfig.NetworkMode',message) + self.assertNotIn('private-value',json.dumps(failed)) + self.assertEqual(events[-1],'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') diff --git a/infra/deploy-runner/test_device_core_runtime_evidence.py b/infra/deploy-runner/test_device_core_runtime_evidence.py new file mode 100644 index 0000000..77ac2c1 --- /dev/null +++ b/infra/deploy-runner/test_device_core_runtime_evidence.py @@ -0,0 +1,110 @@ +"""Retain the failing configuration difference without weakening its gate.""" +import copy +import json +import unittest +from unittest import mock + +from test_device_core_release import R, runtime + + +def fields(): + return {"HostConfig": {"NetworkMode": "private", "ReadonlyRootfs": True, + "Mounts": [{"Type": "bind", "Source": "/secret-a", "Target": "/a", "ReadOnly": True}, + {"Type": "bind", "Source": "/data-b", "Target": "/b", "ReadOnly": False}]}, + "Config": {"Env": ["SECRET=synthetic-value-never-log"], "User": "1000", + "Cmd": ["node", "app.mjs"], "Entrypoint": None, + "WorkingDir": "/app", "ExposedPorts": {"18122/tcp": {}}}, + "Mounts": [], "networks": ["private", "edge"]} + + +class RuntimeEvidenceTests(unittest.TestCase): + def observations(self, value=None): + value = value or fields() + rows = runtime() + samples = {} + for service, row in rows.items(): + row["runtimeConfigSha256"] = R.device_release_drift_digest(R.device_release_mounts_v2(value)) + samples[service] = {"runtime": copy.deepcopy(row), "fields": copy.deepcopy(value)} + return rows, samples + + def test_capture_is_hash_only_and_does_not_change_normalized_fingerprint(self): + rows, samples = self.observations() + original = copy.deepcopy(samples) + with mock.patch.object(R, "device_release_drift_sample", return_value=samples): + result = R.device_release_capture_field_digests(rows) + self.assertEqual(samples, original) + encoded = json.dumps(result) + for private in ("synthetic-value-never-log", "/secret-a", "/data-b", "18122/tcp"): + self.assertNotIn(private, encoded) + self.assertIn("Config.Env", result["device-manager"]) + self.assertEqual(result["device-manager"]["Config.Env"], R.device_release_drift_digest(fields()["Config"]["Env"])) + + def test_unstable_generation_image_and_fields_are_rejected(self): + for kind in ("containerId", "imageId", "configuration"): + rows, samples = self.observations() + if kind == "configuration": + samples["device-manager"]["fields"]["HostConfig"]["ReadonlyRootfs"] = False + else: + samples["device-manager"]["runtime"][kind] = "changed" + with self.subTest(kind=kind), mock.patch.object(R, "device_release_drift_sample", return_value=samples): + with self.assertRaisesRegex(R.DeployError, "changed while capturing"): + R.device_release_capture_field_digests(rows) + + def test_unknown_inventory_is_rejected(self): + rows, samples = self.observations() + samples.pop("device-manager") + with mock.patch.object(R, "device_release_drift_sample", return_value=samples): + with self.assertRaisesRegex(R.DeployError, "inventory changed"): + R.device_release_capture_field_digests(rows) + + def test_mount_order_has_same_evidence_but_mount_options_do_not(self): + a = fields(); b = copy.deepcopy(a); b["HostConfig"]["Mounts"].reverse() + digest = lambda f: R.device_release_field_digests(R.device_release_mounts_v2(f)) + self.assertEqual(digest(a), digest(b)) + b["HostConfig"]["Mounts"][0]["ReadOnly"] = True + self.assertNotEqual(digest(a), digest(b)) + + def test_mismatch_remains_rejected_and_reports_only_changed_field_hashes(self): + old, _ = self.observations() + value = fields(); value["HostConfig"]["NetworkMode"] = "edge" + current, samples = self.observations(value) + before = {"runtimeFingerprintVersion": 2, "runtime": old, + "runtimeFieldDigests": {s: R.device_release_field_digests(R.device_release_mounts_v2(fields())) for s in old}} + # Only the recreated Manager differs; preserved services remain exact. + current = copy.deepcopy(old); current["device-manager"] = samples["device-manager"]["runtime"] + samples = {s: {"runtime": current[s], "fields": value if s == "device-manager" else fields()} for s in current} + with mock.patch.object(R, "device_release_runtime_snapshot_v2", return_value=current), \ + mock.patch.object(R, "device_release_drift_sample", return_value=samples): + with self.assertRaises(R.DeployError) as caught: + R.accept_device_release(before, rollback=True) + message = str(caught.exception) + report = json.loads(message.split("; field_evidence=", 1)[1]) + self.assertEqual(report["evidence"], "captured") + self.assertEqual([x["path"] for x in report["changedFields"]], ["HostConfig.NetworkMode"]) + self.assertNotEqual(report["expectedSha256"], report["actualSha256"]) + self.assertNotIn("synthetic-value-never-log", message) + self.assertNotIn('"edge"', message) + + def test_failed_observation_does_not_mask_rejection_or_leak_error(self): + rows, _ = self.observations() + before = {"runtime": rows, "runtimeFieldDigests": {"device-manager": R.device_release_field_digests(fields())}} + with mock.patch.object(R, "device_release_drift_sample", side_effect=OSError("SECRET=cannot-print")): + text = R.device_release_runtime_drift_message(before, rows, "device-manager") + self.assertIn('"evidence":"unavailable"', text) + self.assertNotIn("cannot-print", text) + + def test_legacy_snapshot_keeps_exact_failure_and_requires_no_extra_inspect(self): + rows, _ = self.observations() + with mock.patch.object(R, "device_release_drift_sample") as probe: + text = R.device_release_runtime_drift_message({"runtime": rows}, rows, "device-manager") + self.assertEqual(text, "Device Core release runtime configuration drift: device-manager") + probe.assert_not_called() + + def test_untrusted_field_name_is_never_emitted(self): + value = fields(); value["HostConfig"]["SECRET=value"] = "sensitive" + with self.assertRaisesRegex(R.DeployError, "field name is invalid"): + R.device_release_field_digests(value) + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/device-core-deploy/ACCEPTANCE_20260929.md b/infra/device-core-deploy/ACCEPTANCE_20260929.md new file mode 100644 index 0000000..5fdfafb --- /dev/null +++ b/infra/device-core-deploy/ACCEPTANCE_20260929.md @@ -0,0 +1,105 @@ +# Device Core automatic deployment acceptance + +Date: 2026-09-29. First automatic release accepted; the second was rejected by runtime +acceptance and successfully rolled back. Ordered-release acceptance remains open. This report concerns Device Core only. B2 multi-client contours are +a separate implementation in `NODEDC_MISSION_CORE_ARNAVI-VPS`. + +## Installed authority + +Platform source: `f7416bc59a19a9ac53c4f4591eaf50a7f4a41641`. +Root runner SHA-256: +`c1301d1072f3d5d39ba422a09847a05a5aad8a753c816d7fb6916d1f1cadd9c6`. +The operator's promotion returned `verify-install-ok`, Python3.8.15. + +Controller artifact: +`nodedc-device-core-autodeploy-v1-20260929-001.tgz`, SHA-256 +`fe9298baa5f41a35c2705ee9946b730ff2de7d5b5c9b2b8eb1b4cca0bc8ed12b`. +Canonical ledger386 records success at18:35:52Z, with backup +`device-core-autodeploy-device-core-autodeploy-v1-20260929-001-20260929-213533`. +Native timer, private token import, no published ports and preservation of +existing applications were checked by canonical apply. + +The temporary Mac token file and NAS enrollment staging were removed after +private import. The NAS retains its root-private working credential and queue. +The observer on the Mac only reads Gitea/SMB and verifies hashes; it has no +stage, plan or apply role in these automatic releases. + +## Two consecutive main pushes + +Both commits were pushed before the first release completed, without a manual +NAS plan/apply. Build runner1 has capacity1. The controller orders releases by +their durable run identity and invokes the canonical installer itself. + +| Run | Device Core source | Artifact SHA-256 | Canonical result | +| --- | --- | --- | --- | +| 8 | `154f243cfde4c9407a28c4d0cb63d29b4cea7c4c` | `2d830958572509df220125a90251d1106abee50e5d891852140e83496ba325f6` | ledger387, success18:56:55Z | +| 9 | `e912e6ffaf7e142afa02254c6c48ac645eb2db63` | `5e678e69b316ceb547112c45ac51cc2294b2f301f2bdc380bcf4347e504739fb` | failed ledger79, clean rollback19:04:04Z | + +Each artifact basename is +`nodedc-device-core-release-v1-r-.tgz`. +Run8 backup: +`device-core-release-device-core-release-v1-r8-154f243cfde4c9407a28c4d0cb63d29b4cea7c4c-20260929-215159`. +Its archive digest matches the independently retrieved Gitea receipt; the inbox +entry is absent, there is exactly one applied receipt and no failed receipt. +The lifecycle inspector classifies it as `terminal_success`; never replay it. + +## Actual interruption and product checks + +After staging run8, a subsequent Gitea request failed with `api_unavailable` +at18:51:05Z. The controller retained the candidate and automatically resumed; +its backup was created at18:51:59Z, followed by successful application at18:56:55Z. +No operator command, new commit, timeout expiry or re-enrollment was required. +This verifies one observed network-interruption recovery, not every outage case. + +Only Core and Manager are rebuilt/recreated by the normal release domain. +Canonical acceptance checks selected generations/images, exact source and +runtime configuration, health, database/Gateway/backhaul preservation and other +Compose services. A green CI run alone is never treated as deployment. + +After run8, the public Manager `/healthz` returned200 with `ok`, `authRequired` +and `deviceCoreConfigured` true. The authenticated browser rendered Device Core +as DC SUDO, opened Devices and retained DCTOUCH and +Robot2B — Moscow Trike Delivery in the owner/project selectors. + +## Reproducible normal use and limits + +Push to Device Core `main` from any computer. Read qualification in Gitea Actions; +read installation from the canonical applied journal and its archive/backup. +The controller's sanitized `runtime-status.json` is the last completed cycle; +it can still show that cycle while a new build/apply runs. `waiting` after a +release does not mean the installed release disappeared. + +Main application updates need no SMB copy, SSH session or per-commit sudo. +Root-runner changes, schema/build foundation migrations, topology changes and +onboarding another repository remain separately registered infrastructure work. +The ordinary release domain intentionally cannot introduce those transitions. + +Source tests cover failed/pending CI, duplicate/overlapping runs, changed +pagination, mismatched identities, crash reservation reconciliation and clean or +uncertain rollback. Run9 encountered a real Manager configuration mismatch and passed automatic +rollback. Production was not deliberately crashed for this acceptance. Fleet capacity, B2 auth and contour isolation +are not established by these deployment checks. + +## Run9 incident + +The canonical failure is `Device Core release runtime configuration drift: +device-manager`, failed ledger79, rollback `ok:device-core-release` at19:04:04Z. +The failed archive is the run9 basename with suffix `.20260929-215803`. +Its digest and backup are verified; it must never be replayed. Run8 remains the +accepted source. The old before snapshot retains only an aggregate configuration +hash, so the exact differing field was not retained before rollback removed the +failed container. Two-network NetworkMode selection is a hypothesis, not a +proven cause. Add per-field hash evidence without changing acceptance semantics +before attempting a forward fix. + +The prepared instrumentation keeps fingerprint v2 unchanged and records only +per-field hashes plus the names of changed fields in the canonical failure +receipt. Eight focused evidence cases cover redaction, stable container identity, +mount-order equivalence versus option changes, network mismatch rejection and +legacy snapshots. An additional real apply/rollback dispatcher test confirms +that the diagnostic survives rollback in the failed journal. +Validation:75 Device Core release/bootstrap/recovery tests;75 registry tests +(1 historical skip);170 Device Core artifact tests (17 historical skips); +Python3.8 syntax and diff checks. Runner candidate SHA-256: +`3eefc75591bb08339d79c6a484912d7d6a8881fe8729e966b6f0bf32da21da80`. +It is prepared, not installed. No new release has been submitted after run9. diff --git a/infra/device-core-deploy/README.md b/infra/device-core-deploy/README.md index f7b7aeb..828e0c0 100644 --- a/infra/device-core-deploy/README.md +++ b/infra/device-core-deploy/README.md @@ -2,8 +2,11 @@ Status: 2026-09-29. The build runner is installed and push-to-main qualification works. Release r7 (`edf69068ec64e3d105d5324d39b8eaeface21215`) is accepted -in canonical ledger 385. Production polling is **not activated**. DCPLATFORM-21 owns the deployment -contract; DCPLATFORM-37 tracks activation. +in canonical ledger 385. The outbound production controller was activated by +`device-core-autodeploy-v1-20260929-001` in ledger 386 at18:35:52Z on2026-09-29. +Run8 deployed automatically; run9 failed Manager runtime configuration acceptance +and rolled back successfully. Full ordered-release acceptance remains open. +DCPLATFORM-21 owns the deployment contract; DCPLATFORM-37 tracks acceptance. ## Release domain @@ -102,22 +105,46 @@ The frozen generic `run_compose` function is byte-identical to the previous Engi canon. Device Core uses its own exact Core+Manager Compose entry with unchanged `--pull never --no-build --no-deps`, including rollback. -## Remaining activation work +## Activation and acceptance -- Promote the reviewed root runner through the separate SHA-pinned admin gate. -- Build/stage the bootstrap via `build_autodeploy.py`, then fresh plan and apply. -- Accept a new main commit through CI → automatic canonical deployment, including - ordered commits, failed checks and recovery. Source tests are not NAS acceptance. -- Remove the temporary Mac token copy after private NAS import is verified. +- Runner012 was promoted and verified as + `c1301d1072f3d5d39ba422a09847a05a5aad8a753c816d7fb6916d1f1cadd9c6`. +- The data-only bootstrap built by `build_autodeploy.py` passed fresh plan/apply; + artifact SHA is `fe9298baa5f41a35c2705ee9946b730ff2de7d5b5c9b2b8eb1b4cca0bc8ed12b`. +- NAS imported its root-private credential and removed enrollment staging. The + temporary Mac credential was removed after acceptance. Neither a Mac nor SMB + needs to remain connected for recurring delivery. +- Ordered automatic releases are being verified against their CI receipts, + archive digests, unique canonical journal rows and backups. Failed-check and + crash/reconciliation tests are source qualification, not a claim that the NAS + was deliberately crashed during production acceptance. No helper from this directory is executed on NAS or installed by an application release. User-facing NAS deployment commands remain canonical plan/apply. ## Validation +Run9 was rejected for a Manager runtime configuration difference and rolled back +successfully to run8. Its failed archive must not be replayed. The initial +snapshots retained only an aggregate configuration hash, so the specific field +was not available after rollback removed the failed container. + +The next runner candidate adds diagnostic field hashes to new before snapshots. +It binds each observation to the checked container/image/configuration identity. +On a mismatch, the canonical failed receipt retains changed field names and +their hashes before the failed generation is removed. Raw environment values, +inspect payloads and external exception text are not included. The v2 comparison, +network/mount semantics, selected services and rollback checks are unchanged. +Old snapshots still use their original aggregate hash. This instrumentation is +not a fix for an as-yet-unidentified configuration difference and is not installed +until the separate root promotion succeeds. + +See [live acceptance and the run9 incident](ACCEPTANCE_20260929.md). + ```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/deploy-runner -p test_device_core_runtime_evidence.py python3 -m unittest discover -s infra/gitea-ci -p 'test_*.py' ```