From 27c155276a703dd4fd39385011fc5e3f86afcae4 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 1 Oct 2026 14:38:35 +0300 Subject: [PATCH] Register lossless Device B2 shared contour schema transition --- .../device-b2-shared-contours-v1.json | 13 ++ .../device-b2-shared-contours-v1.rollback.sql | 20 ++ .../device-b2-shared-contours-v1.sql | 32 +++ infra/deploy-runner/nodedc-deploy | 206 +++++++++++++++++- .../test_device_b2_shared_contours.py | 186 ++++++++++++++++ 5 files changed, 453 insertions(+), 4 deletions(-) create mode 100644 infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.json create mode 100644 infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.rollback.sql create mode 100644 infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.sql create mode 100644 infra/deploy-runner/test_device_b2_shared_contours.py diff --git a/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.json b/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.json new file mode 100644 index 0000000..62d289a --- /dev/null +++ b/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.json @@ -0,0 +1,13 @@ +{ + "schemaVersion": "nodedc.device-b2-shared-contours.v1", + "releaseId": "device-b2-shared-contours-v1-20261001-001", + "baselineReleaseId": "device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718", + "baselineSha256": "fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe", + "files": { + "deployment/device-b2-shared-contours-v1.sql": "caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a", + "deployment/device-b2-shared-contours-v1.rollback.sql": "f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f" + }, + "transition": "one-contour-many-projects", + "services": [], + "rollback": "refuse-multiple-projects;preserve-all-rows" +} diff --git a/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.rollback.sql b/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.rollback.sql new file mode 100644 index 0000000..9d834d3 --- /dev/null +++ b/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.rollback.sql @@ -0,0 +1,20 @@ +begin; +set local lock_timeout = '5s'; +set local statement_timeout = '30s'; +lock table device_b2_contour_links in access exclusive mode; +do $$ +begin + if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-shared-contours/v1' + or (select pg_get_constraintdef(oid) from pg_constraint + where conrelid='device_b2_contour_links'::regclass and contype='p') + is distinct from 'PRIMARY KEY (source_id, contour_id, project_id)' then + raise exception 'device_b2_shared_contours_rollback_predecessor_mismatch'; + end if; + if exists(select 1 from device_b2_contour_links group by source_id,contour_id having count(*)>1) then + raise exception 'device_b2_shared_contours_rollback_would_lose_links'; + end if; +end $$; +alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey; +alter table device_b2_contour_links add primary key (source_id, contour_id); +comment on table device_b2_contour_links is 'nodedc.device-b2-foundation/v1'; +commit; diff --git a/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.sql b/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.sql new file mode 100644 index 0000000..f2a9a95 --- /dev/null +++ b/infra/deploy-runner/fixtures/device-b2-shared-contours/deployment/device-b2-shared-contours-v1.sql @@ -0,0 +1,32 @@ +begin; +set local lock_timeout = '5s'; +set local statement_timeout = '30s'; + +-- Separate, versioned foundation transition. Never run from application startup. +-- Preserve every assignment; only the identity of an assignment becomes a triple. +lock table device_b2_contour_links in access exclusive mode; +create temporary table device_b2_links_before on commit drop as + select * from device_b2_contour_links; +do $$ +begin + if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-foundation/v1' + or (select pg_get_constraintdef(oid) from pg_constraint + where conrelid='device_b2_contour_links'::regclass and contype='p') + is distinct from 'PRIMARY KEY (source_id, contour_id)' then + raise exception 'device_b2_shared_contours_predecessor_mismatch'; + end if; +end $$; +alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey; +alter table device_b2_contour_links add primary key (source_id, contour_id, project_id); +comment on table device_b2_contour_links is 'nodedc.device-b2-shared-contours/v1'; +do $$ +begin + if exists( + (select * from device_b2_links_before except all select * from device_b2_contour_links) + union all + (select * from device_b2_contour_links except all select * from device_b2_links_before) + ) then + raise exception 'device_b2_shared_contours_row_preservation_failed'; + end if; +end $$; +commit; diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 1106108..c0bb214 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -2962,6 +2962,9 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple( ) COMPONENTS = { + "device-b2-shared-contours": { + "payload_root": DEVICE_PLANE_ROOT, "artifact_only": True, "services": (), + }, "device-b2-foundation-reconciliation": { "payload_root": DEVICE_PLANE_ROOT, "artifact_only": True, "services": (), }, @@ -4991,6 +4994,10 @@ def denied_payload_path(component, rel): def allowed_payload_path(component, rel): validate_posix_path(rel) + if component == "device-b2-shared-contours": + if rel in ("deployment", *DEVICE_B2_SHARED_ENTRIES): + return True + die("Device B2 shared contours accepts only its three fixed files") if component == "device-b2-foundation-reconciliation": if rel in ("deployment", DEVICE_B2_RECON_ENTRY): return True @@ -11631,6 +11638,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-b2-shared-contours": + validate_device_b2_shared_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-b2-foundation-reconciliation": validate_device_b2_reconciliation_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-b2-foundation": @@ -22493,6 +22502,10 @@ def is_platform_provider_catalog_only(entries): def component_services(component, entries=None): + if component == "device-b2-shared-contours": + if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES: + die("Device B2 shared contours requires all three exact entries") + return () if component == "device-b2-foundation-reconciliation": if tuple(entries or ()) != (DEVICE_B2_RECON_ENTRY,): die("Device B2 reconciliation requires the exact descriptor entry") @@ -33334,6 +33347,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-b2-shared-contours": + preflight_device_b2_shared(payload_dir, entries, manifest["id"]) + print("device_b2_shared_scope=one-table-primary-key;services=none;build=none;ports=preserved") + print("device_b2_shared_preserved=all-links,applications,keys,volumes,containers,compose") + print("device_b2_shared_backup=private-table-dump;rollback=lossless-schema-only;multi-links-refused") if manifest["component"] == "device-b2-foundation-reconciliation": preflight_device_b2_reconciliation(payload_dir, entries, manifest["id"]) if manifest["component"] == "device-b2-foundation": @@ -39532,6 +39550,10 @@ 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-b2-shared-contours": + if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES or tuple(services or ()) != (): + die("Device B2 shared contours health scope mismatch") + return # Exact schema/runtime/product checks run in accept_device_b2_shared. if component == "device-b2-foundation-reconciliation": if tuple(services or ()) != (): die("Device B2 reconciliation cannot select services") @@ -40676,6 +40698,7 @@ def apply_artifact(artifact): device_autodeploy_before = None device_priority_before = None device_b2_before = None + device_b2_shared_before = None current_stamp = stamp() with DeployLock(): @@ -40720,6 +40743,8 @@ def apply_artifact(artifact): compose_root = component_compose_root(component) bootstrap_root = bool(COMPONENTS[component].get("bootstrap_root")) services = component_services(component, entries) + if component == "device-b2-shared-contours": + device_b2_shared_before = preflight_device_b2_shared(payload_dir, entries, patch_id) if component == "device-b2-foundation-reconciliation": preflight_device_b2_reconciliation(payload_dir, entries, patch_id) if component == "device-b2-foundation": @@ -41263,6 +41288,8 @@ 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-b2-shared-contours": + backup_device_b2_shared(backup_dir, device_b2_shared_before) if component == "device-b2-foundation": proof = backup_dir / "device-b2-before.json" proof.write_text(json.dumps(device_b2_before, sort_keys=True) + "\n") @@ -41373,6 +41400,8 @@ def apply_artifact(artifact): elif component == "device-core-autodeploy": runtime_started = True apply_device_autodeploy(device_autodeploy_before) + elif component == "device-b2-shared-contours": + device_b2_database((DEVICE_PLANE_ROOT / DEVICE_B2_SHARED_SQL).read_text()) elif component == "device-b2-foundation": def mark_device_b2_runtime_started(): nonlocal runtime_started @@ -41420,6 +41449,8 @@ def apply_artifact(artifact): ): die("Engine L2 closed-loop app generation was not recreated") run_healthchecks(component, entries, services) + if component == "device-b2-shared-contours": + accept_device_b2_shared(device_b2_shared_before, backup_dir) if component == "device-b2-foundation": accept_device_b2(device_b2_before, backup_dir) if component == "device-core-network-priority": @@ -41502,7 +41533,13 @@ def apply_artifact(artifact): and backup_dir is not None and root is not None ): - if component == "device-b2-foundation": + if component == "device-b2-shared-contours": + try: + rollback_device_b2_shared(root, backup_dir, entries, current_stamp, device_b2_shared_before) + rollback_status = "ok:device-b2-shared-contours" + except Exception as rollback_exc: + rollback_status = "failed:" + type(rollback_exc).__name__ + elif component == "device-b2-foundation": try: rollback_device_b2(root, backup_dir, entries, current_stamp, device_b2_before, runtime_started) rollback_status = "ok:device-b2-foundation" @@ -42884,6 +42921,7 @@ def device_b2_failed_barrier(): def device_b2_compose_files(files): + device_b2_shared_failed_barrier() # A failed foundation rollback blocks ordinary releases too, even when the # old source files were already restored and no overlay remains. device_b2_failed_barrier() @@ -42931,8 +42969,8 @@ def device_b2_schema(): ) x;""")) -def validate_device_b2_schema(schema): - if schema != DEVICE_B2_EXPECTED_SCHEMA: +def validate_device_b2_schema(schema, *, expected=None): + if schema != (DEVICE_B2_EXPECTED_SCHEMA if expected is None else expected): die('Device B2 foundation exact schema fields/constraints mismatch') return device_release_drift_digest(schema) @@ -43081,7 +43119,8 @@ def validate_installed_device_b2(): if not device_b2_compose_files(()): return device_b2_private_directory() - validate_device_b2_schema(device_b2_schema()) + expected = device_b2_shared_schema() if device_b2_shared_receipt() else DEVICE_B2_EXPECTED_SCHEMA + validate_device_b2_schema(device_b2_schema(), expected=expected) device_b2_strip_runtime(device_release_drift_sample()['device-control-core']['fields']) @@ -43140,6 +43179,165 @@ def rollback_device_b2(root, backup_dir, entries, stamp, before, runtime_started accept_device_b2(before,backup_dir,rollback=True) +# Additive schema transition. SQL is fixed by reviewed hashes, never commands +# selected by a manifest. All data and running service generations are preserved. +DEVICE_B2_SHARED_ID = 'device-b2-shared-contours-v1-20261001-001' +DEVICE_B2_SHARED_DESCRIPTOR = 'deployment/device-b2-shared-contours-v1.json' +DEVICE_B2_SHARED_SQL = 'deployment/device-b2-shared-contours-v1.sql' +DEVICE_B2_SHARED_REVERSE = 'deployment/device-b2-shared-contours-v1.rollback.sql' +DEVICE_B2_SHARED_ENTRIES = (DEVICE_B2_SHARED_DESCRIPTOR, DEVICE_B2_SHARED_SQL, DEVICE_B2_SHARED_REVERSE) +DEVICE_B2_SHARED_HASHES = { + DEVICE_B2_SHARED_SQL: 'caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a', + DEVICE_B2_SHARED_REVERSE: 'f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f', +} +DEVICE_B2_SHARED_BASELINE = 'device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718' +DEVICE_B2_SHARED_BASELINE_SHA = 'fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe' + + +def device_b2_shared_descriptor(): + return {'schemaVersion': 'nodedc.device-b2-shared-contours.v1', 'releaseId': DEVICE_B2_SHARED_ID, + 'baselineReleaseId': DEVICE_B2_SHARED_BASELINE, 'baselineSha256': DEVICE_B2_SHARED_BASELINE_SHA, + 'files': DEVICE_B2_SHARED_HASHES, 'transition': 'one-contour-many-projects', + 'services': [], 'rollback': 'refuse-multiple-projects;preserve-all-rows'} + + +def validate_device_b2_shared_payload(root, entries, identity): + if tuple(entries or ()) != DEVICE_B2_SHARED_ENTRIES or identity != DEVICE_B2_SHARED_ID: + die('Device B2 shared contours exact identity/entries mismatch') + for rel in DEVICE_B2_SHARED_ENTRIES: + path = root / rel + if path.is_symlink() or not path.is_file(): + die('Device B2 shared contours missing/unsafe payload') + if read_strict_json(root / DEVICE_B2_SHARED_DESCRIPTOR, 'Device B2 shared contours') != device_b2_shared_descriptor(): + die('Device B2 shared contours descriptor mismatch') + if any(sha256_file(root / rel) != digest for rel, digest in DEVICE_B2_SHARED_HASHES.items()): + die('Device B2 shared contours SQL digest mismatch') + + +def device_b2_shared_schema(): + result = json.loads(json.dumps(DEVICE_B2_EXPECTED_SCHEMA)) + links = result[0] + assert links['name'] == 'device_b2_contour_links' + links['marker'] = 'nodedc.device-b2-shared-contours/v1' + links['definitions'] = [ + 'PRIMARY KEY (source_id, contour_id, project_id)' if v == 'PRIMARY KEY (source_id, contour_id)' else v + for v in links['definitions']] + return result + + +def device_b2_shared_failed_barrier(): + if any(r.get('component') == 'device-b2-shared-contours' and r.get('started_apply') + and r.get('rollback_status') != 'ok:device-b2-shared-contours' for r in load_state(FAILED_STATE_FILE)): + die('Device B2 shared contours requires failed-state reconciliation') + + +def device_b2_shared_receipt(): + device_b2_shared_failed_barrier() + present = [(DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() + for p in DEVICE_B2_SHARED_ENTRIES] + rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-b2-shared-contours'] + if not any(present) and not rows: + return False + if not all(present) or len(rows) != 1 or rows[0].get('id') != DEVICE_B2_SHARED_ID or rows[0].get('status') != 'ok': + die('Device B2 shared contours has no unique complete applied receipt') + validate_device_b2_shared_payload(DEVICE_PLANE_ROOT, DEVICE_B2_SHARED_ENTRIES, DEVICE_B2_SHARED_ID) + with tempfile.TemporaryDirectory(prefix='device-b2-shared-receipt-', dir=TMP_DIR) as tmp: + manifest, entries, payload = load_artifact(device_release_applied_archive(rows[0]), Path(tmp)) + if manifest['component'] != 'device-b2-shared-contours': + die('Device B2 shared contours archive owner mismatch') + validate_device_b2_shared_payload(payload, entries, manifest['id']) + return True + + +def preflight_device_b2_shared(payload, entries, identity): + validate_device_b2_shared_payload(payload, entries, identity) + device_b2_shared_failed_barrier() + if any((DEVICE_PLANE_ROOT / p).exists() or (DEVICE_PLANE_ROOT / p).is_symlink() for p in entries): + die('Device B2 shared contours is initial-only') + if any(r.get('component') == 'device-b2-shared-contours' for r in load_state(STATE_FILE)): + die('Device B2 shared contours already has an applied receipt') + rows = [r for r in load_state(STATE_FILE) if r.get('component') == 'device-core-release'] + if not rows or rows[-1].get('id') != DEVICE_B2_SHARED_BASELINE or rows[-1].get('sha256') != DEVICE_B2_SHARED_BASELINE_SHA: + die('Device B2 shared contours requires exact accepted r37 baseline') + with tempfile.TemporaryDirectory(prefix='device-b2-shared-baseline-', dir=TMP_DIR) as tmp: + manifest, release_entries, source = load_artifact(device_release_applied_archive(rows[-1]), Path(tmp)) + if manifest['component'] != 'device-core-release' or tuple(release_entries) != DEVICE_RELEASE_ENTRIES: + die('Device B2 shared contours baseline owner/entries mismatch') + expected = collect_exact_files(source, release_entries, 'Device B2 shared contours baseline') + if collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, 'Device B2 shared contours installed source') != expected: + die('Device B2 shared contours installed source drift') + validate_installed_device_b2() + if not device_b2_compose_files(()): + die('Device B2 shared contours requires accepted B2 foundation') + validate_device_b2_schema(device_b2_schema()) + run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES) + return {'runtime': device_release_runtime_snapshot_v2(), + 'otherComposeServices': device_release_other_compose_services(), 'installedFiles': expected, + 'compose': {str(p): sha256_file(p) for p in component_compose_files('device-core-release')}} + + +def backup_device_b2_shared(backup_dir, before): + proof = backup_dir / 'device-b2-shared-before.json' + with proof.open('x') as output: + os.fchmod(output.fileno(), 0o600) + output.write(json.dumps(before, sort_keys=True) + '\n') + output.flush(); os.fsync(output.fileno()) + ids = device_plane_service_container_ids('device-postgres') + if len(ids) != 1: + die('Device B2 shared contours requires the existing PostgreSQL container') + path = backup_dir / 'device-b2-contour-links.dump' + with path.open('xb') as output: + os.fchmod(output.fileno(), 0o600) + result = subprocess.run([str(DOCKER), 'exec', ids[0], 'pg_dump', '-U', 'device_plane', '-d', 'device_plane', + '-Fc', '--strict-names', '-t', 'public.device_b2_contour_links'], + stdout=output, stderr=subprocess.PIPE, timeout=45, check=False) + output.flush(); os.fsync(output.fileno()) + with path.open('rb') as saved: + signature = saved.read(5) + if result.returncode or result.stderr or signature != b'PGDMP': + die('Device B2 shared contours private table backup failed') + digest = backup_dir / 'device-b2-contour-links.dump.sha256' + with digest.open('x') as output: + os.fchmod(output.fileno(), 0o600) + output.write(sha256_file(path) + '\n') + output.flush(); os.fsync(output.fileno()) + + +def accept_device_b2_shared(before, backup_dir, rollback=False): + dump = backup_dir / 'device-b2-contour-links.dump' + if dump.is_symlink() or not dump.is_file() or stat.S_IMODE(dump.stat().st_mode) != 0o600: + die('Device B2 shared contours backup is missing or unsafe') + if sha256_file(dump) != (backup_dir / 'device-b2-contour-links.dump.sha256').read_text().strip(): + die('Device B2 shared contours backup changed') + if not rollback: + validate_device_b2_shared_payload(DEVICE_PLANE_ROOT, DEVICE_B2_SHARED_ENTRIES, DEVICE_B2_SHARED_ID) + expected = DEVICE_B2_EXPECTED_SCHEMA if rollback else device_b2_shared_schema() + validate_device_b2_schema(device_b2_schema(), expected=expected) + device_b2_private_directory() + run_healthchecks('device-core-release', DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES) + if device_release_runtime_snapshot_v2() != before['runtime']: + die('Device B2 shared contours changed a preserved service generation/runtime') + if device_release_other_compose_services() != before['otherComposeServices']: + die('Device B2 shared contours changed unrelated services') + if any(sha256_file(Path(p)) != digest for p, digest in before['compose'].items()): + die('Device B2 shared contours changed existing Compose files') + if collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES, 'Device B2 shared contours source') != before['installedFiles']: + die('Device B2 shared contours changed application source') + print('device_b2_shared_accept=' + ('rollback' if rollback else 'shared-projects') + + ';rows=preserved;runtime=unchanged;backup=verified') + + +def rollback_device_b2_shared(root, backup_dir, entries, stamp, before): + schema = device_b2_schema() + if schema == device_b2_shared_schema(): + validate_device_b2_shared_payload(root, entries, DEVICE_B2_SHARED_ID) + device_b2_database((root / DEVICE_B2_SHARED_REVERSE).read_text()) + elif schema != DEVICE_B2_EXPECTED_SCHEMA: + die('Device B2 shared contours rollback retains unexpected schema for reconciliation') + restore_platform_overlay(root, backup_dir, entries, stamp) + accept_device_b2_shared(before, backup_dir, rollback=True) + + DEVICE_B2_RECON_ID = 'device-b2-foundation-reconciliation-v1-20260930-001' DEVICE_B2_RECON_ENTRY = 'deployment/device-b2-foundation-reconciliation-v1.json' DEVICE_B2_002_ID = 'device-b2-foundation-v1-20260930-002' diff --git a/infra/deploy-runner/test_device_b2_shared_contours.py b/infra/deploy-runner/test_device_b2_shared_contours.py new file mode 100644 index 0000000..5041870 --- /dev/null +++ b/infra/deploy-runner/test_device_b2_shared_contours.py @@ -0,0 +1,186 @@ +"""Exact schema transition, receipt boundary and data-preserving rollback.""" +import copy +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('shared_runner_test', 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) +FIXTURE = Path(__file__).with_name('fixtures')/'device-b2-shared-contours' + + +def archive(path, extra=None): + files = {'manifest.env': f'id={R.DEVICE_B2_SHARED_ID}\ncomponent=device-b2-shared-contours\ntype=app-overlay\n'.encode(), + 'files.txt': ('\n'.join(R.DEVICE_B2_SHARED_ENTRIES)+'\n').encode(), + **{'payload/'+p: (FIXTURE/p).read_bytes() for p in R.DEVICE_B2_SHARED_ENTRIES}} + files.update(extra or {}) + with tarfile.open(path, 'w:gz') as target: + for name, data in files.items(): + entry=tarfile.TarInfo(name); entry.size=len(data); entry.mode=0o644 + target.addfile(entry, io.BytesIO(data)) + + +class SharedContours(unittest.TestCase): + def test_exact_archive_load_and_empty_runtime_scope(self): + with tempfile.TemporaryDirectory() as tmp: + path=Path(tmp)/'a.tgz'; archive(path) + _, entries, payload=R.load_artifact(path, Path(tmp)/'unpack') + R.validate_device_b2_shared_payload(payload, entries, R.DEVICE_B2_SHARED_ID) + self.assertEqual(R.component_services('device-b2-shared-contours', entries), ()) + self.assertEqual(R.component_builds('device-b2-shared-contours', entries), ()) + self.assertTrue(R.component_artifact_only('device-b2-shared-contours')) + self.assertEqual(R.component_root('device-b2-shared-contours'), R.DEVICE_PLANE_ROOT) + + def test_extra_sql_env_hook_runtime_or_traversal_rejected(self): + for name in ('.env', 'hooks.sh', 'deployment/other.sql', 'secrets/admin.json', '../escape', + 'services/device-control-core/src/server.mjs', 'runtime/db.dump'): + with self.subTest(name=name), self.assertRaises(R.DeployError): + R.allowed_payload_path('device-b2-shared-contours', name) + for entries in ((), R.DEVICE_B2_SHARED_ENTRIES[:-1], tuple(reversed(R.DEVICE_B2_SHARED_ENTRIES))): + with self.assertRaises(R.DeployError): R.component_services('device-b2-shared-contours', entries) + + def test_modified_sql_descriptor_and_identity_rejected(self): + for rel in R.DEVICE_B2_SHARED_ENTRIES: + with self.subTest(rel=rel), tempfile.TemporaryDirectory() as tmp: + root=Path(tmp); shutil.copytree(FIXTURE, root, dirs_exist_ok=True) + path=root/rel + if rel == R.DEVICE_B2_SHARED_DESCRIPTOR: + v=json.loads(path.read_text()); v['services']=['device-postgres']; path.write_text(json.dumps(v)) + else: path.write_text('drop table device_b2_hosts;') + with self.assertRaises(R.DeployError): + R.validate_device_b2_shared_payload(root, R.DEVICE_B2_SHARED_ENTRIES, R.DEVICE_B2_SHARED_ID) + with self.assertRaises(R.DeployError): + R.validate_device_b2_shared_payload(FIXTURE, R.DEVICE_B2_SHARED_ENTRIES, 'unreviewed') + + def test_forward_schema_is_exact_and_old_contract_is_unchanged(self): + old=copy.deepcopy(R.DEVICE_B2_EXPECTED_SCHEMA); new=R.device_b2_shared_schema() + R.validate_device_b2_schema(old) + with self.assertRaises(R.DeployError): R.validate_device_b2_schema(new) + R.validate_device_b2_schema(new, expected=R.device_b2_shared_schema()) + self.assertEqual(R.DEVICE_B2_EXPECTED_SCHEMA, old) + self.assertEqual(old[1:], new[1:]) + for key in ('constraints', 'fields', 'validated', 'columns'): + self.assertEqual(old[0][key], new[0][key]) + for mutation in ('missing-fk', 'wrong-marker', 'extra-field', 'wrong-pk'): + value=copy.deepcopy(new) + if mutation=='missing-fk': value[0]['definitions'].pop(1) + if mutation=='wrong-marker': value[0]['marker']='other' + if mutation=='extra-field': value[0]['fields'].append(['unsafe','text',False]) + if mutation=='wrong-pk': value[0]['definitions'][-1]='PRIMARY KEY (contour_id)' + with self.subTest(mutation=mutation), self.assertRaises(R.DeployError): + R.validate_device_b2_schema(value, expected=new) + + def test_failed_mutation_blocks_normal_compose_even_without_overlay(self): + row={'component':'device-b2-shared-contours','started_apply':True,'rollback_status':'failed:DeployError'} + with mock.patch.object(R, 'load_state', return_value=[row]), self.assertRaises(R.DeployError): + R.device_b2_compose_files(()) + for r in ({**row,'started_apply':False}, {**row,'rollback_status':'ok:device-b2-shared-contours'}): + with mock.patch.object(R,'load_state',return_value=[r]): R.device_b2_shared_failed_barrier() + + def test_receipt_requires_all_files_unique_success_and_verified_archive(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp)/'live'; root.mkdir() + with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'TMP_DIR',Path(tmp)), \ + mock.patch.object(R,'load_state',return_value=[]): + self.assertFalse(R.device_b2_shared_receipt()) + shutil.copytree(FIXTURE,root,dirs_exist_ok=True) + with self.assertRaises(R.DeployError): R.device_b2_shared_receipt() + row={'component':'device-b2-shared-contours','id':R.DEVICE_B2_SHARED_ID,'status':'ok'} + good=Path(tmp)/'good.tgz'; archive(good) + state=lambda path: [row] if path==R.STATE_FILE else [] + with mock.patch.object(R,'load_state',side_effect=state), \ + mock.patch.object(R,'device_release_applied_archive',return_value=good) as checked: + self.assertTrue(R.device_b2_shared_receipt()); checked.assert_called_once_with(row) + for rows in ([row,row],[{**row,'id':'other'}],[{**row,'status':'failed'}]): + with mock.patch.object(R,'load_state',side_effect=lambda p:rows if p==R.STATE_FILE else []), self.assertRaises(R.DeployError): + R.device_b2_shared_receipt() + with mock.patch.object(R,'load_state',side_effect=state), \ + mock.patch.object(R,'device_release_applied_archive',side_effect=R.DeployError('archive mismatch')), \ + self.assertRaises(R.DeployError): R.device_b2_shared_receipt() + + def test_preflight_rejects_wrong_live_release_before_database_mutation(self): + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \ + mock.patch.object(R,'load_state',return_value=[]), mock.patch.object(R,'device_b2_database') as db: + with self.assertRaisesRegex(R.DeployError,'r37'): + R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID) + db.assert_not_called() + + def test_preflight_rejects_missing_foundation_and_wrong_source(self): + row={'component':'device-core-release','id':R.DEVICE_B2_SHARED_BASELINE,'sha256':R.DEVICE_B2_SHARED_BASELINE_SHA} + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \ + mock.patch.object(R,'TMP_DIR',Path(tmp)), \ + mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.STATE_FILE else []), \ + mock.patch.object(R,'device_release_applied_archive',return_value=Path(tmp)/'release.tgz'), \ + mock.patch.object(R,'load_artifact',return_value=({'component':'device-core-release'}, R.DEVICE_RELEASE_ENTRIES,Path(tmp))), \ + mock.patch.object(R,'collect_exact_files',side_effect=[{'a':'one'},{'a':'two'}]), \ + self.assertRaisesRegex(R.DeployError,'source drift'): + R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID) + + def test_rollback_never_restores_old_data_over_new_links(self): + with mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \ + mock.patch.object(R,'device_b2_database',side_effect=R.DeployError('would_lose_links')) as db, \ + mock.patch.object(R,'restore_platform_overlay') as restore, \ + mock.patch.object(R,'accept_device_b2_shared') as accept: + with self.assertRaisesRegex(R.DeployError,'would_lose_links'): + R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{}) + self.assertIn('rollback_would_lose_links',db.call_args.args[0]) + restore.assert_not_called(); accept.assert_not_called() + + def test_rollback_after_failed_transaction_restores_only_new_files(self): + with mock.patch.object(R,'device_b2_schema',return_value=R.DEVICE_B2_EXPECTED_SCHEMA), \ + mock.patch.object(R,'device_b2_database') as db, \ + mock.patch.object(R,'restore_platform_overlay') as restore, \ + mock.patch.object(R,'accept_device_b2_shared') as accept: + R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{}) + db.assert_not_called(); restore.assert_called_once(); accept.assert_called_once_with({},Path('/unused'),rollback=True) + + def test_unknown_schema_retained_without_destructive_attempt(self): + with mock.patch.object(R,'device_b2_schema',return_value=[]), mock.patch.object(R,'device_b2_database') as db, \ + mock.patch.object(R,'restore_platform_overlay') as restore, self.assertRaises(R.DeployError): + R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{}) + db.assert_not_called(); restore.assert_not_called() + + def test_private_table_backup_fixed_scope_and_failure_precedes_sql(self): + def dump(argv, **kwargs): + self.assertEqual(argv[-3:], ['--strict-names', '-t', 'public.device_b2_contour_links']) + kwargs['stdout'].write(b'PGDMP-synthetic-fixture') + return mock.Mock(returncode=0, stderr=b'') + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \ + mock.patch.object(R.subprocess,'run',side_effect=dump), mock.patch.object(R,'device_b2_database') as sql: + root=Path(tmp) + R.backup_device_b2_shared(root,{'runtime':{}}) + self.assertEqual((root/'device-b2-contour-links.dump').stat().st_mode & 0o777,0o600) + self.assertEqual((root/'device-b2-contour-links.dump.sha256').read_text().strip(),R.sha256_file(root/'device-b2-contour-links.dump')) + sql.assert_not_called() + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \ + mock.patch.object(R.subprocess,'run',return_value=mock.Mock(returncode=1,stderr=b'failed')), self.assertRaises(R.DeployError): + R.backup_device_b2_shared(Path(tmp),{}) + + def test_acceptance_checks_schema_backup_and_preserved_runtime_before_success(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp); shutil.copytree(FIXTURE,root,dirs_exist_ok=True) + dump=root/'device-b2-contour-links.dump'; dump.write_bytes(b'PGDMP-fixture'); dump.chmod(0o600) + (root/'device-b2-contour-links.dump.sha256').write_text(R.sha256_file(dump)+'\n') + before={'runtime':{'postgres':'same','core':'same'},'otherComposeServices':{},'compose':{},'installedFiles':{}} + with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \ + mock.patch.object(R,'device_b2_private_directory'), mock.patch.object(R,'run_healthchecks') as health, \ + mock.patch.object(R,'device_release_runtime_snapshot_v2',return_value=before['runtime']) as runtime, \ + mock.patch.object(R,'device_release_other_compose_services',return_value={}), \ + mock.patch.object(R,'collect_exact_files',return_value={}): + R.accept_device_b2_shared(before,root) + health.assert_called_once_with('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES) + runtime.return_value={'postgres':'recreated','core':'same'} + with self.assertRaisesRegex(R.DeployError,'preserved service'): R.accept_device_b2_shared(before,root) + runtime.return_value=before['runtime']; dump.write_bytes(b'changed') + with self.assertRaisesRegex(R.DeployError,'backup changed'): R.accept_device_b2_shared(before,root) + + +if __name__ == '__main__': unittest.main()