From b8285ee6b09f5ef5e457d2f66aae6f1d45466f74 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:15 +0200 Subject: [PATCH 01/16] R06: allowlist updater execution and post-restart health commands --- .../scripture_archive_platform/transport/contracts.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py index 95fdbc006..ae7d9a423 100644 --- a/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py +++ b/lanes/dev1/repair_overlay/scripture_archive_platform/transport/contracts.py @@ -22,7 +22,7 @@ "authoring.undo","authoring.redo","authoring.publish_version","authoring.list_versions","authoring.rollback_version", "keymap.list","keymap.rebind","keymap.clear","keymap.reset_context","keymap.reset_all", "keymap.export","keymap.import","settings.get","settings.set", - "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.cancel_pending","dossier.get","diagnostics.get_report" + "speech.status","speech.synthesize_prompt","application_update.select_verify","application_update.select_verify_stage","application_update.pending_status","application_update.prepare_apply","application_update.apply_and_restart","application_update.cancel_pending","application_update.commit_post_restart_health","dossier.get","diagnostics.get_report" }) _PLAYER_TRUTH_OWNERS = frozenset({"D5/runtime", "REFERENCE_TEST_ONLY"}) @@ -102,7 +102,7 @@ def validate_request_shape(request:Any)->tuple[str,str,dict[str,Any]]: raise ValueError('authoring.pack_compatibility accepts an empty payload') if cmd=='speech.status' and payload: raise ValueError('speech.status accepts an empty payload') - if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.cancel_pending'} and payload: + if cmd in {'application_update.pending_status','application_update.prepare_apply','application_update.apply_and_restart','application_update.cancel_pending','application_update.commit_post_restart_health'} and payload: raise ValueError(f'{cmd} accepts an empty payload') if cmd=='speech.synthesize_prompt': allowed={'provider_id','voice_id','speed','allow_network'} From ae21639dd6d44730008faef60fdbdb464ce366ae Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:18 +0200 Subject: [PATCH 02/16] R06: isolate staged candidate in publisher rejection regression --- runtime_engine/tests/test_application_update_updater.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 738340656..79d16c131 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -148,11 +148,10 @@ def test_consume_handoff_fails_closed_when_publisher_check_rejects(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) target = root / "ScriptureArchive.exe" - staged = root / "ScriptureArchive.new.exe" target.write_bytes(old) - staged.write_bytes(new) pending = self._pending(new) - staged_named = root / pending.artifact_name + staged_named = root / "staged" / pending.artifact_name + staged_named.parent.mkdir() staged_named.write_bytes(new) with patch( From b25ce1852c219bb66c47142ab38b7596553dd6f6 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:23 +0200 Subject: [PATCH 03/16] R06: provision pytest for runtime integration suite --- .github/workflows/r06-dev10-integration.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/r06-dev10-integration.yml b/.github/workflows/r06-dev10-integration.yml index eb32befdc..ec10d8675 100644 --- a/.github/workflows/r06-dev10-integration.yml +++ b/.github/workflows/r06-dev10-integration.yml @@ -31,6 +31,8 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.13' + - name: Install runtime test dependency + run: python -m pip install --disable-pip-version-check pytest - name: Compile runtime, tests and integration tools working-directory: runtime_engine run: python -m compileall -q scripture_archive_runtime tests tools From a617ea13d08192e49f4aaca28f1caccc8d4e52cb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:26 +0200 Subject: [PATCH 04/16] R06: align packaging fail-closed assertions with dual artifacts --- .../tests/test_packaged_diagnostics.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py index 38488669a..9287fc175 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -166,22 +166,32 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "pip upgrade"', 'Assert-NativeSuccess "build dependency install"', 'Assert-NativeSuccess "Windows release diagnostics"', - 'Assert-NativeSuccess "PyInstaller build"', + 'Assert-NativeSuccess "PyInstaller application build"', + 'Assert-NativeSuccess "PyInstaller updater build"', 'Assert-NativeSuccess "Python version query"', - 'Assert-NativeSuccess "artifact verification"', + 'Assert-NativeSuccess "application artifact verification"', + 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) stale_cleanup = "Remove-Item -LiteralPath $Out -Force" self.assertIn(stale_cleanup, build) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( - build.index('Assert-NativeSuccess "PyInstaller build"'), + build.index('Assert-NativeSuccess "PyInstaller application build"'), build.index('if (-not (Test-Path -LiteralPath $Out -PathType Leaf))'), ) self.assertLess( - build.index('Assert-NativeSuccess "artifact verification"'), + build.index('Assert-NativeSuccess "PyInstaller updater build"'), + build.index('if (-not (Test-Path -LiteralPath $UpdaterOut -PathType Leaf))'), + ) + self.assertLess( + build.index('Assert-NativeSuccess "application artifact verification"'), build.index('Write-Output "Built $Out'), ) + self.assertLess( + build.index('Assert-NativeSuccess "updater artifact verification"'), + build.index('Write-Output "Built $UpdaterOut'), + ) def test_desktop_host_wraps_update_layer_with_read_only_diagnostics(self): platform = Path(__file__).resolve().parents[1] From 798010afccfc7d70e6e5e1f108b487d7983304ed Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:16:29 +0200 Subject: [PATCH 05/16] R06: assert semantic initial install-button disable state --- .../repair_overlay/tests/test_packaged_updater_host_launch.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py index 5098cedad..5c7f5c36a 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_updater_host_launch.py @@ -250,7 +250,8 @@ def test_frontend_exposes_accessible_two_step_install_without_html_injection(sel self.assertIn("application_update.apply_and_restart", script) self.assertIn("pending-update-apply-restart", script) self.assertIn("Встановити й перезапустити", script) - self.assertIn("button.disabled=true", script) + self.assertIn("apply.disabled=true", script) + self.assertIn("button.disabled=busy", script) self.assertIn("aria-live", script) self.assertIn("textContent", script) self.assertNotIn("innerHTML", script) From 70cf1175bb20854a86c1be37c2316a894c18b72a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:18:47 +0200 Subject: [PATCH 06/16] R06: assert stale cleanup covers both packaged artifacts --- lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py index 9287fc175..ab9b50e49 100644 --- a/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py +++ b/lanes/dev1/repair_overlay/tests/test_packaged_diagnostics.py @@ -173,7 +173,8 @@ def test_builder_fails_closed_on_native_failure_and_stale_artifact(self): 'Assert-NativeSuccess "updater artifact verification"', ): self.assertIn(step, build) - stale_cleanup = "Remove-Item -LiteralPath $Out -Force" + stale_cleanup = "Remove-Item -LiteralPath $artifact -Force" + self.assertIn("foreach ($artifact in @($Out, $UpdaterOut))", build) self.assertIn(stale_cleanup, build) self.assertLess(build.index(stale_cleanup), build.index("pyinstaller.exe")) self.assertLess( From 6658c41a13aca369b12e5b39f5b1dd0ec95d38cd Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:22:20 +0200 Subject: [PATCH 07/16] R06: make health regressions discoverable by unittest --- .../tests/test_application_update_health.py | 239 +++++++++--------- 1 file changed, 124 insertions(+), 115 deletions(-) diff --git a/runtime_engine/tests/test_application_update_health.py b/runtime_engine/tests/test_application_update_health.py index e5fa9db77..3c459511f 100644 --- a/runtime_engine/tests/test_application_update_health.py +++ b/runtime_engine/tests/test_application_update_health.py @@ -3,8 +3,8 @@ import hashlib import json from pathlib import Path - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_health import ( @@ -50,123 +50,132 @@ def _publish(tmp_path: Path): return root, target, rollback, previous, installed, receipt -def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - - assert receipt.previous_version == PREVIOUS_VERSION - assert receipt.target_version == TARGET_VERSION - assert receipt.installed_executable_name == target.name - assert receipt.previous_sha256 == _sha(previous) - assert receipt.installed_sha256 == _sha(installed) - assert inspect_update_health_receipt( - root, - current_version=TARGET_VERSION, - install_target=target, - ) == receipt - - payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) - assert payload["schema"] == HEALTH_RECEIPT_SCHEMA - assert payload["status"] == "awaiting_health_commit" - serialized = json.dumps(payload) - assert str(tmp_path) not in serialized - assert "install_target" not in payload - assert "rollback_path" not in payload - - -def test_publish_is_idempotent_only_for_same_exact_identity(tmp_path: Path) -> None: - root, target, rollback, previous, installed, first = _publish(tmp_path) - before = (root / "update-health.json").read_bytes() - second = publish_update_health_receipt( - root, - previous_version=PREVIOUS_VERSION, - target_version=TARGET_VERSION, - install_target=target, - previous_sha256=_sha(previous), - installed_sha256=_sha(installed), - ) - assert second == first - assert (root / "update-health.json").read_bytes() == before +class ApplicationUpdateHealthTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def test_publish_and_inspect_bind_version_name_and_exact_installed_rollback_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + + self.assertEqual(receipt.previous_version, PREVIOUS_VERSION) + self.assertEqual(receipt.target_version, TARGET_VERSION) + self.assertEqual(receipt.installed_executable_name, target.name) + self.assertEqual(receipt.previous_sha256, _sha(previous)) + self.assertEqual(receipt.installed_sha256, _sha(installed)) + self.assertEqual( + inspect_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ), + receipt, + ) - with pytest.raises(ApplicationUpdateError, match="different identity"): - publish_update_health_receipt( + payload = json.loads((root / "update-health.json").read_text(encoding="utf-8")) + self.assertEqual(payload["schema"], HEALTH_RECEIPT_SCHEMA) + self.assertEqual(payload["status"], "awaiting_health_commit") + serialized = json.dumps(payload) + self.assertNotIn(str(self.tmp_path), serialized) + self.assertNotIn("install_target", payload) + self.assertNotIn("rollback_path", payload) + + def test_publish_is_idempotent_only_for_same_exact_identity(self) -> None: + root, target, rollback, previous, installed, first = _publish(self.tmp_path) + before = (root / "update-health.json").read_bytes() + second = publish_update_health_receipt( root, previous_version=PREVIOUS_VERSION, - target_version="1.2.0", + target_version=TARGET_VERSION, install_target=target, previous_sha256=_sha(previous), installed_sha256=_sha(installed), ) - - -def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - - with pytest.raises(ApplicationUpdateError, match="target version is not current"): - inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) - - target.write_bytes(b"x" * len(installed)) - with pytest.raises(ApplicationUpdateError, match="installed application bytes changed"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - target.write_bytes(installed) - - rollback.write_bytes(b"y" * len(previous)) - with pytest.raises(ApplicationUpdateError, match="rollback bytes changed"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - -def test_receipt_shape_extra_field_and_symlink_fail_closed(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - path = root / "update-health.json" - payload = json.loads(path.read_text(encoding="utf-8")) - payload["unexpected"] = True - path.write_text(json.dumps(payload), encoding="utf-8") - with pytest.raises(ApplicationUpdateError, match="shape is invalid"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - path.unlink() - real = root / "real-health.json" - real.write_text("{}", encoding="utf-8") - try: - path.symlink_to(real) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): - inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - - -def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - pending = root / "pending-update.json" - pending.write_text("old-version journal need not be parsed", encoding="utf-8") - - committed = commit_update_health_receipt( - root, - current_version=TARGET_VERSION, - install_target=target, - ) - assert committed == receipt - assert not pending.exists() - assert not (root / "update-health.json").exists() - assert not rollback.exists() - assert target.read_bytes() == installed - - -def test_failed_health_proof_preserves_receipt_pending_and_rollback(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - pending = root / "pending-update.json" - pending.write_text("old-version journal", encoding="utf-8") - target.write_bytes(b"tampered") - - with pytest.raises(ApplicationUpdateError): - commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) - assert pending.exists() - assert (root / "update-health.json").exists() - assert rollback.exists() - - -def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(tmp_path: Path) -> None: - root, target, rollback, previous, installed, receipt = _publish(tmp_path) - assert discard_update_health_receipt(root) is True - assert discard_update_health_receipt(root) is False - assert rollback.read_bytes() == previous - assert target.read_bytes() == installed + self.assertEqual(second, first) + self.assertEqual((root / "update-health.json").read_bytes(), before) + + with self.assertRaisesRegex(ApplicationUpdateError, "different identity"): + publish_update_health_receipt( + root, + previous_version=PREVIOUS_VERSION, + target_version="1.2.0", + install_target=target, + previous_sha256=_sha(previous), + installed_sha256=_sha(installed), + ) + + def test_inspect_fails_closed_on_version_installed_or_rollback_tamper(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + + with self.assertRaisesRegex(ApplicationUpdateError, "target version is not current"): + inspect_update_health_receipt(root, current_version="1.2.0", install_target=target) + + target.write_bytes(b"x" * len(installed)) + with self.assertRaisesRegex(ApplicationUpdateError, "installed application bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + target.write_bytes(installed) + + rollback.write_bytes(b"y" * len(previous)) + with self.assertRaisesRegex(ApplicationUpdateError, "rollback bytes changed"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_receipt_shape_extra_field_and_symlink_fail_closed(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + path = root / "update-health.json" + payload = json.loads(path.read_text(encoding="utf-8")) + payload["unexpected"] = True + path.write_text(json.dumps(payload), encoding="utf-8") + with self.assertRaisesRegex(ApplicationUpdateError, "shape is invalid"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + path.unlink() + real = root / "real-health.json" + real.write_text("{}", encoding="utf-8") + try: + path.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + inspect_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + + def test_commit_disarms_old_pending_then_receipt_and_rollback_after_exact_proof(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + pending = root / "pending-update.json" + pending.write_text("old-version journal need not be parsed", encoding="utf-8") + + committed = commit_update_health_receipt( + root, + current_version=TARGET_VERSION, + install_target=target, + ) + self.assertEqual(committed, receipt) + self.assertFalse(pending.exists()) + self.assertFalse((root / "update-health.json").exists()) + self.assertFalse(rollback.exists()) + self.assertEqual(target.read_bytes(), installed) + + def test_failed_health_proof_preserves_receipt_pending_and_rollback(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + pending = root / "pending-update.json" + pending.write_text("old-version journal", encoding="utf-8") + target.write_bytes(b"tampered") + + with self.assertRaises(ApplicationUpdateError): + commit_update_health_receipt(root, current_version=TARGET_VERSION, install_target=target) + self.assertTrue(pending.exists()) + self.assertTrue((root / "update-health.json").exists()) + self.assertTrue(rollback.exists()) + + def test_discard_only_disarms_receipt_and_preserves_recovery_bytes(self) -> None: + root, target, rollback, previous, installed, receipt = _publish(self.tmp_path) + self.assertIs(discard_update_health_receipt(root), True) + self.assertIs(discard_update_health_receipt(root), False) + self.assertEqual(rollback.read_bytes(), previous) + self.assertEqual(target.read_bytes(), installed) + + +if __name__ == "__main__": + unittest.main() From 620b45915b2543eea7f8a34c9d9f2a04c7b8c0d2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:22:37 +0200 Subject: [PATCH 08/16] R06: make parent-wait regressions discoverable by unittest --- .../test_application_update_parent_wait.py | 86 ++++++++++--------- 1 file changed, 45 insertions(+), 41 deletions(-) diff --git a/runtime_engine/tests/test_application_update_parent_wait.py b/runtime_engine/tests/test_application_update_parent_wait.py index 41e41fbc8..aafb2497e 100644 --- a/runtime_engine/tests/test_application_update_parent_wait.py +++ b/runtime_engine/tests/test_application_update_parent_wait.py @@ -1,8 +1,7 @@ from __future__ import annotations import os - -import pytest +import unittest from scripture_archive_runtime.application_update_parent_wait import ( ParentProcessWaitError, @@ -10,56 +9,61 @@ ) -def test_wait_uses_exact_pid_and_bounded_timeout() -> None: - seen: list[tuple[int, int]] = [] - - def backend(pid: int, timeout_ms: int) -> None: - seen.append((pid, timeout_ms)) - - wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) - assert seen == [(4242, 30_000)] - - -def test_wait_rejects_own_pid_before_backend() -> None: - called = False +class ParentProcessWaitTests(unittest.TestCase): + def test_wait_uses_exact_pid_and_bounded_timeout(self) -> None: + seen: list[tuple[int, int]] = [] - def backend(pid: int, timeout_ms: int) -> None: - nonlocal called - called = True + def backend(pid: int, timeout_ms: int) -> None: + seen.append((pid, timeout_ms)) - with pytest.raises(ParentProcessWaitError, match="own process"): - wait_for_parent_exit(os.getpid(), wait_backend=backend) - assert called is False + wait_for_parent_exit(4242, timeout_ms=30_000, wait_backend=backend) + self.assertEqual(seen, [(4242, 30_000)]) + def test_wait_rejects_own_pid_before_backend(self) -> None: + called = False -@pytest.mark.parametrize("pid", [0, -1, True, 1.5, "1"]) -def test_wait_rejects_invalid_pid(pid) -> None: - with pytest.raises(ParentProcessWaitError): - wait_for_parent_exit(pid, wait_backend=lambda *_: None) + def backend(pid: int, timeout_ms: int) -> None: + nonlocal called + called = True + with self.assertRaisesRegex(ParentProcessWaitError, "own process"): + wait_for_parent_exit(os.getpid(), wait_backend=backend) + self.assertFalse(called) -@pytest.mark.parametrize("timeout_ms", [0, -1, 120_001, True, 1.5]) -def test_wait_rejects_invalid_or_unbounded_timeout(timeout_ms) -> None: - with pytest.raises(ParentProcessWaitError): - wait_for_parent_exit(4242, timeout_ms=timeout_ms, wait_backend=lambda *_: None) + def test_wait_rejects_invalid_pid(self) -> None: + for pid in [0, -1, True, 1.5, "1"]: + with self.subTest(pid=pid): + with self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit(pid, wait_backend=lambda *_: None) # type: ignore[arg-type] + def test_wait_rejects_invalid_or_unbounded_timeout(self) -> None: + for timeout_ms in [0, -1, 120_001, True, 1.5]: + with self.subTest(timeout_ms=timeout_ms): + with self.assertRaises(ParentProcessWaitError): + wait_for_parent_exit( # type: ignore[arg-type] + 4242, + timeout_ms=timeout_ms, + wait_backend=lambda *_: None, + ) -def test_wait_is_windows_only_without_injected_backend() -> None: - with pytest.raises(ParentProcessWaitError, match="Windows-only"): - wait_for_parent_exit(4242, os_name="posix") + def test_wait_is_windows_only_without_injected_backend(self) -> None: + with self.assertRaisesRegex(ParentProcessWaitError, "Windows-only"): + wait_for_parent_exit(4242, os_name="posix") + def test_wait_wraps_backend_failure(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise OSError("boom") -def test_wait_wraps_backend_failure() -> None: - def backend(pid: int, timeout_ms: int) -> None: - raise OSError("boom") + with self.assertRaisesRegex(ParentProcessWaitError, "wait failed"): + wait_for_parent_exit(4242, wait_backend=backend) - with pytest.raises(ParentProcessWaitError, match="wait failed"): - wait_for_parent_exit(4242, wait_backend=backend) + def test_wait_preserves_fail_closed_backend_verdict(self) -> None: + def backend(pid: int, timeout_ms: int) -> None: + raise ParentProcessWaitError("parent process did not exit before timeout") + with self.assertRaisesRegex(ParentProcessWaitError, "did not exit"): + wait_for_parent_exit(4242, wait_backend=backend) -def test_wait_preserves_fail_closed_backend_verdict() -> None: - def backend(pid: int, timeout_ms: int) -> None: - raise ParentProcessWaitError("parent process did not exit before timeout") - with pytest.raises(ParentProcessWaitError, match="did not exit"): - wait_for_parent_exit(4242, wait_backend=backend) +if __name__ == "__main__": + unittest.main() From 09e2b92bac9f6490cda6a69638f676bdc3be02de Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:23:07 +0200 Subject: [PATCH 09/16] R06: make process regressions discoverable by unittest --- .../tests/test_application_update_process.py | 275 +++++++++--------- 1 file changed, 145 insertions(+), 130 deletions(-) diff --git a/runtime_engine/tests/test_application_update_process.py b/runtime_engine/tests/test_application_update_process.py index 55390bc03..ddb75ba75 100644 --- a/runtime_engine/tests/test_application_update_process.py +++ b/runtime_engine/tests/test_application_update_process.py @@ -2,8 +2,8 @@ from pathlib import Path import os - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update_process import ( UpdateProcessError, @@ -25,149 +25,164 @@ def _files(tmp_path: Path) -> tuple[Path, Path, Path]: return updater, app, staging -def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - assert plan.parent_pid == os.getpid() - assert plan.updater_executable == updater.resolve() - assert plan.installed_executable == app.resolve() - assert plan.staging_root == staging.resolve() - assert plan.argv() == ( - str(updater.resolve()), - "--scripture-archive-apply", - "--wait-pid", - str(os.getpid()), - "--installed-executable", - str(app.resolve()), - "--staging-root", - str(staging.resolve()), - ) - - -def test_build_plan_rejects_external_updater(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - external = tmp_path / "outside-updater.exe" - external.write_bytes(updater.read_bytes()) - with pytest.raises(UpdateProcessError, match="packaged beside"): - build_updater_process_plan( - updater_executable=external, - installed_executable=app, - staging_root=staging, - ) +class ApplicationUpdateProcessTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) + def tearDown(self) -> None: + self.temp.cleanup() -def test_build_plan_rejects_current_app_as_updater(tmp_path: Path) -> None: - _, app, staging = _files(tmp_path) - with pytest.raises(UpdateProcessError, match="distinct"): - build_updater_process_plan( - updater_executable=app, + def test_build_plan_binds_sibling_packaged_updater_current_pid_and_fixed_argv(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, installed_executable=app, staging_root=staging, ) + self.assertEqual(plan.parent_pid, os.getpid()) + self.assertEqual(plan.updater_executable, updater.resolve()) + self.assertEqual(plan.installed_executable, app.resolve()) + self.assertEqual(plan.staging_root, staging.resolve()) + self.assertEqual( + plan.argv(), + ( + str(updater.resolve()), + "--scripture-archive-apply", + "--wait-pid", + str(os.getpid()), + "--installed-executable", + str(app.resolve()), + "--staging-root", + str(staging.resolve()), + ), + ) - -def test_build_plan_rejects_symlinked_updater_target_and_staging(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - updater_link = updater.parent / "link-updater.exe" - staging_link = tmp_path / "state-link" - try: - updater_link.symlink_to(updater) - staging_link.symlink_to(staging, target_is_directory=True) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - with pytest.raises(UpdateProcessError, match="non-symlink"): - build_updater_process_plan( - updater_executable=updater_link, + def test_build_plan_rejects_external_updater(self) -> None: + updater, app, staging = _files(self.tmp_path) + external = self.tmp_path / "outside-updater.exe" + external.write_bytes(updater.read_bytes()) + with self.assertRaisesRegex(UpdateProcessError, "packaged beside"): + build_updater_process_plan( + updater_executable=external, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_current_app_as_updater(self) -> None: + _, app, staging = _files(self.tmp_path) + with self.assertRaisesRegex(UpdateProcessError, "distinct"): + build_updater_process_plan( + updater_executable=app, + installed_executable=app, + staging_root=staging, + ) + + def test_build_plan_rejects_symlinked_updater_target_and_staging(self) -> None: + updater, app, staging = _files(self.tmp_path) + updater_link = updater.parent / "link-updater.exe" + staging_link = self.tmp_path / "state-link" + try: + updater_link.symlink_to(updater) + staging_link.symlink_to(staging, target_is_directory=True) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + with self.assertRaisesRegex(UpdateProcessError, "non-symlink"): + build_updater_process_plan( + updater_executable=updater_link, + installed_executable=app, + staging_root=staging, + ) + with self.assertRaisesRegex(UpdateProcessError, "real directory"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging_link, + ) + + def test_build_plan_rejects_foreign_parent_pid(self) -> None: + updater, app, staging = _files(self.tmp_path) + with self.assertRaisesRegex(UpdateProcessError, "current host process"): + build_updater_process_plan( + updater_executable=updater, + installed_executable=app, + staging_root=staging, + parent_pid=os.getpid() + 1, + ) + + def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( + updater_executable=updater, installed_executable=app, staging_root=staging, ) - with pytest.raises(UpdateProcessError, match="real directory"): - build_updater_process_plan( + seen: dict[str, object] = {} + + class Child: + pid = 43210 + + def fake_popen(argv, **kwargs): + seen["argv"] = argv + seen.update(kwargs) + return Child() + + pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") + self.assertEqual(pid, 43210) + self.assertEqual(seen["argv"], list(plan.argv())) + self.assertEqual(seen["cwd"], str(app.resolve().parent)) + self.assertIs(seen["shell"], False) + self.assertIs(seen["close_fds"], True) + self.assertEqual(seen["creationflags"], 0) + + def test_launch_wraps_process_failure(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, - staging_root=staging_link, + staging_root=staging, ) + def broken_popen(*args, **kwargs): + raise OSError("boom") + + with self.assertRaisesRegex(UpdateProcessError, "failed to launch"): + launch_updater_process(plan, popen=broken_popen) -def test_build_plan_rejects_foreign_parent_pid(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - with pytest.raises(UpdateProcessError, match="current host process"): - build_updater_process_plan( + def test_parser_accepts_only_fixed_host_contract(self) -> None: + updater, app, staging = _files(self.tmp_path) + plan = build_updater_process_plan( updater_executable=updater, installed_executable=app, staging_root=staging, - parent_pid=os.getpid() + 1, ) - - -def test_launch_is_shell_free_fixed_cwd_and_returns_child_pid(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - seen: dict[str, object] = {} - - class Child: - pid = 43210 - - def fake_popen(argv, **kwargs): - seen["argv"] = argv - seen.update(kwargs) - return Child() - - pid = launch_updater_process(plan, popen=fake_popen, os_name="posix") - assert pid == 43210 - assert seen["argv"] == list(plan.argv()) - assert seen["cwd"] == str(app.resolve().parent) - assert seen["shell"] is False - assert seen["close_fds"] is True - assert seen["creationflags"] == 0 - - -def test_launch_wraps_process_failure(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - - def broken_popen(*args, **kwargs): - raise OSError("boom") - - with pytest.raises(UpdateProcessError, match="failed to launch"): - launch_updater_process(plan, popen=broken_popen) - - -def test_parser_accepts_only_fixed_host_contract(tmp_path: Path) -> None: - updater, app, staging = _files(tmp_path) - plan = build_updater_process_plan( - updater_executable=updater, - installed_executable=app, - staging_root=staging, - ) - pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) - assert pid == os.getpid() - assert parsed_app == app.resolve() - assert parsed_staging == staging.resolve() - - -@pytest.mark.parametrize( - "argv", - [ - (), - ("--scripture-archive-apply",), - ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), - ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), - ("--scripture-archive-apply", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b", "--extra"), - ], -) -def test_parser_rejects_noncanonical_or_extended_commands(argv: tuple[str, ...]) -> None: - with pytest.raises(UpdateProcessError): - parse_trusted_updater_argv(argv) + pid, parsed_app, parsed_staging = parse_trusted_updater_argv(plan.argv()[1:]) + self.assertEqual(pid, os.getpid()) + self.assertEqual(parsed_app, app.resolve()) + self.assertEqual(parsed_staging, staging.resolve()) + + def test_parser_rejects_noncanonical_or_extended_commands(self) -> None: + invalid_commands = [ + (), + ("--scripture-archive-apply",), + ("--wrong", "--wait-pid", "1", "--installed-executable", "a", "--staging-root", "b"), + ("--scripture-archive-apply", "--wait-pid", "01", "--installed-executable", "a", "--staging-root", "b"), + ( + "--scripture-archive-apply", + "--wait-pid", + "1", + "--installed-executable", + "a", + "--staging-root", + "b", + "--extra", + ), + ] + for argv in invalid_commands: + with self.subTest(argv=argv): + with self.assertRaises(UpdateProcessError): + parse_trusted_updater_argv(argv) + + +if __name__ == "__main__": + unittest.main() From 2c89169f1085f6c9263d0b9eadd015073c9fe4f6 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:23:21 +0200 Subject: [PATCH 10/16] R06: make relaunch regressions discoverable by unittest --- .../tests/test_application_update_relaunch.py | 96 +++++++++++-------- 1 file changed, 54 insertions(+), 42 deletions(-) diff --git a/runtime_engine/tests/test_application_update_relaunch.py b/runtime_engine/tests/test_application_update_relaunch.py index 0f631ea48..6c05123d0 100644 --- a/runtime_engine/tests/test_application_update_relaunch.py +++ b/runtime_engine/tests/test_application_update_relaunch.py @@ -1,64 +1,76 @@ from __future__ import annotations from pathlib import Path - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_relaunch import launch_installed_application -def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(tmp_path: Path) -> None: - install = tmp_path / "Program Files" / "Архів Писання" - install.mkdir(parents=True) - target = install / "Scripture Archive.exe" - target.write_bytes(b"updated") - calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] +class ApplicationUpdateRelaunchTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) - def spawn(argv, **kwargs): - calls.append((tuple(argv), dict(kwargs))) - return object() + def tearDown(self) -> None: + self.temp.cleanup() - launch_installed_application(target, spawn=spawn) + def test_relaunch_uses_exact_target_without_shell_and_fixed_working_directory(self) -> None: + install = self.tmp_path / "Program Files" / "Архів Писання" + install.mkdir(parents=True) + target = install / "Scripture Archive.exe" + target.write_bytes(b"updated") + calls: list[tuple[tuple[str, ...], dict[str, object]]] = [] - assert calls == [ - ((str(target),), {"cwd": str(install), "close_fds": True}), - ] + def spawn(argv, **kwargs): + calls.append((tuple(argv), dict(kwargs))) + return object() + launch_installed_application(target, spawn=spawn) -def test_relaunch_rejects_symlink_target_before_spawn(tmp_path: Path) -> None: - real = tmp_path / "real.exe" - real.write_bytes(b"updated") - target = tmp_path / "Scripture Archive.exe" - try: - target.symlink_to(real) - except (OSError, NotImplementedError): - pytest.skip("symlinks unavailable") - spawned = False + self.assertEqual( + calls, + [ + ((str(target),), {"cwd": str(install), "close_fds": True}), + ], + ) - def spawn(*args, **kwargs): - nonlocal spawned - spawned = True + def test_relaunch_rejects_symlink_target_before_spawn(self) -> None: + real = self.tmp_path / "real.exe" + real.write_bytes(b"updated") + target = self.tmp_path / "Scripture Archive.exe" + try: + target.symlink_to(real) + except (OSError, NotImplementedError): + self.skipTest("symlinks unavailable") + spawned = False - with pytest.raises(ApplicationUpdateError, match="regular non-symlink"): - launch_installed_application(target, spawn=spawn) - assert spawned is False + def spawn(*args, **kwargs): + nonlocal spawned + spawned = True + with self.assertRaisesRegex(ApplicationUpdateError, "regular non-symlink"): + launch_installed_application(target, spawn=spawn) + self.assertFalse(spawned) -def test_relaunch_translates_process_creation_failure(tmp_path: Path) -> None: - target = tmp_path / "Scripture Archive.exe" - target.write_bytes(b"updated") + def test_relaunch_translates_process_creation_failure(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") - def spawn(*args, **kwargs): - raise OSError("cannot execute") + def spawn(*args, **kwargs): + raise OSError("cannot execute") - with pytest.raises(ApplicationUpdateError, match="could not be started"): - launch_installed_application(target, spawn=spawn) + with self.assertRaisesRegex(ApplicationUpdateError, "could not be started"): + launch_installed_application(target, spawn=spawn) + + def test_relaunch_requires_callable_spawner(self) -> None: + target = self.tmp_path / "Scripture Archive.exe" + target.write_bytes(b"updated") + with self.assertRaisesRegex(ApplicationUpdateError, "process spawner"): + launch_installed_application(target, spawn=None) # type: ignore[arg-type] -def test_relaunch_requires_callable_spawner(tmp_path: Path) -> None: - target = tmp_path / "Scripture Archive.exe" - target.write_bytes(b"updated") - with pytest.raises(ApplicationUpdateError, match="process spawner"): - launch_installed_application(target, spawn=None) # type: ignore[arg-type] +if __name__ == "__main__": + unittest.main() From 37eba77e187bf96a4460902b368d333eaed7fe1f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:24:07 +0200 Subject: [PATCH 11/16] R06: make updater runner regressions discoverable by unittest --- .../tests/test_application_update_runner.py | 551 +++++++++--------- 1 file changed, 291 insertions(+), 260 deletions(-) diff --git a/runtime_engine/tests/test_application_update_runner.py b/runtime_engine/tests/test_application_update_runner.py index e2599005e..87a7551eb 100644 --- a/runtime_engine/tests/test_application_update_runner.py +++ b/runtime_engine/tests/test_application_update_runner.py @@ -2,8 +2,8 @@ from pathlib import Path import os - -import pytest +import tempfile +import unittest from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_parent_wait import ParentProcessWaitError @@ -35,7 +35,9 @@ def _result(plan) -> UpdateApplyResult: return UpdateApplyResult( previous_sha256="1" * 64, installed_sha256="2" * 64, - rollback_path=plan.installed_executable.with_name(plan.installed_executable.name + ".scripture-archive.rollback"), + rollback_path=plan.installed_executable.with_name( + plan.installed_executable.name + ".scripture-archive.rollback" + ), target_path=plan.installed_executable, target_version="1.1.0", ) @@ -49,279 +51,308 @@ def _discard_noop(*args, **kwargs): return False -def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(tmp_path: Path) -> None: - plan = _plan(tmp_path) - events: list[object] = [] - sentinel = _result(plan) - - def wait_for_exit(parent_pid: int) -> None: - events.append(("wait", parent_pid)) +class ApplicationUpdateRunnerTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.tmp_path = Path(self.temp.name) - def consume(staging_root, **kwargs): - events.append(("consume", Path(staging_root), kwargs)) - return sentinel + def tearDown(self) -> None: + self.temp.cleanup() - def publish_health(staging_root, **kwargs): - events.append(("health", Path(staging_root), kwargs)) - return object() + def test_runner_waits_applies_publishes_health_then_relaunches_exact_target(self) -> None: + plan = _plan(self.tmp_path) + events: list[object] = [] + sentinel = _result(plan) - def launch(target: Path) -> None: - events.append(("launch", target)) - - verifier = lambda installed, staged: True - result = execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=verifier, - wait_for_exit=wait_for_exit, - consume=consume, - publish_health=publish_health, - discard_health=_discard_noop, - launch=launch, - ) + def wait_for_exit(parent_pid: int) -> None: + events.append(("wait", parent_pid)) - assert result is sentinel - assert events[0] == ("wait", os.getpid()) - kind, staging, kwargs = events[1] - assert kind == "consume" - assert staging == plan.staging_root - assert kwargs == { - "current_version": "1.0.0", - "install_target": plan.installed_executable, - "verify_same_publisher": verifier, - } - kind, staging, kwargs = events[2] - assert kind == "health" - assert staging == plan.staging_root - assert kwargs == { - "previous_version": "1.0.0", - "target_version": "1.1.0", - "install_target": plan.installed_executable, - "previous_sha256": sentinel.previous_sha256, - "installed_sha256": sentinel.installed_sha256, - } - assert events[3] == ("launch", plan.installed_executable) - - -def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - events: list[object] = [] - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - def discard(staging_root: Path) -> bool: - events.append(("discard", Path(staging_root))) - return True - - def launch(target: Path) -> None: - events.append(("launch", target)) - - with pytest.raises(ApplicationUpdateError, match="health receipt publication failed; rollback restored"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("receipt failed")), - discard_health=discard, - rollback=rollback, - launch=launch, - ) - assert events == [ - ("rollback", plan.installed_executable, sentinel.previous_sha256), - ("discard", plan.staging_root), - ] + def consume(staging_root, **kwargs): + events.append(("consume", Path(staging_root), kwargs)) + return sentinel + def publish_health(staging_root, **kwargs): + events.append(("health", Path(staging_root), kwargs)) + return object() -def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - events: list[object] = [] + def launch(target: Path) -> None: + events.append(("launch", target)) - def publish(staging_root, **kwargs): - events.append(("publish", Path(staging_root))) - return object() - - def launch(target: Path) -> None: - events.append(("launch", target)) - raise ApplicationUpdateError("spawn failed") - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - def discard(staging_root: Path) -> bool: - events.append(("discard", Path(staging_root))) - return True - - with pytest.raises(ApplicationUpdateError, match="rollback restored prior bytes"): - execute_trusted_updater( + verifier = lambda installed, staged: True + result = execute_trusted_updater( plan.argv()[1:], current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=publish, - discard_health=discard, + verify_same_publisher=verifier, + wait_for_exit=wait_for_exit, + consume=consume, + publish_health=publish_health, + discard_health=_discard_noop, launch=launch, - rollback=rollback, ) - assert events == [ - ("publish", plan.staging_root), - ("launch", plan.installed_executable), - ("rollback", plan.installed_executable, sentinel.previous_sha256), - ("discard", plan.staging_root), - ] - - -def test_runner_surfaces_combined_relaunch_and_rollback_failure(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = _result(plan) - - with pytest.raises(ApplicationUpdateError, match="relaunch failed and rollback also failed"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=_publish_noop, - discard_health=_discard_noop, - launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), - rollback=lambda *args, **kwargs: (_ for _ in ()).throw(OSError("rollback failed")), + self.assertIs(result, sentinel) + self.assertEqual(events[0], ("wait", os.getpid())) + kind, staging, kwargs = events[1] + self.assertEqual(kind, "consume") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "current_version": "1.0.0", + "install_target": plan.installed_executable, + "verify_same_publisher": verifier, + }, ) - - -def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(tmp_path: Path) -> None: - plan = _plan(tmp_path) - sentinel = UpdateApplyResult( - previous_sha256="1" * 64, - installed_sha256="2" * 64, - rollback_path=plan.installed_executable.with_suffix(".rollback"), - target_path=tmp_path / "other.exe", - target_version="1.1.0", - ) - events: list[object] = [] - - def publish(*args, **kwargs): - events.append(("health",)) - - def launch(target: Path) -> None: - events.append(("launch", target)) - - def rollback(target: Path, *, expected_previous_sha256: str) -> str: - events.append(("rollback", target, expected_previous_sha256)) - return expected_previous_sha256 - - with pytest.raises(ApplicationUpdateError, match="unexpected install target; rollback restored"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=lambda parent_pid: None, - consume=lambda *args, **kwargs: sentinel, - publish_health=publish, - discard_health=_discard_noop, - launch=launch, - rollback=rollback, + kind, staging, kwargs = events[2] + self.assertEqual(kind, "health") + self.assertEqual(staging, plan.staging_root) + self.assertEqual( + kwargs, + { + "previous_version": "1.0.0", + "target_version": "1.1.0", + "install_target": plan.installed_executable, + "previous_sha256": sentinel.previous_sha256, + "installed_sha256": sentinel.installed_sha256, + }, ) - assert events == [("rollback", plan.installed_executable, sentinel.previous_sha256)] - - -def test_runner_never_consumes_when_parent_exit_cannot_be_proven(tmp_path: Path) -> None: - plan = _plan(tmp_path) - consumed = False - - def blocked_wait(parent_pid: int) -> None: - raise ParentProcessWaitError("parent still alive") - - def consume(*args, **kwargs): - nonlocal consumed - consumed = True - raise AssertionError("must not consume") - - with pytest.raises(ParentProcessWaitError, match="parent still alive"): - execute_trusted_updater( - plan.argv()[1:], - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=blocked_wait, - consume=consume, + self.assertEqual(events[3], ("launch", plan.installed_executable)) + + def test_runner_health_publish_failure_rolls_back_and_disarms_before_no_launch(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + def launch(target: Path) -> None: + events.append(("launch", target)) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "health receipt publication failed; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("receipt failed") + ), + discard_health=discard, + rollback=rollback, + launch=launch, + ) + self.assertEqual( + events, + [ + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], ) - assert consumed is False - -def test_runner_rejects_malformed_command_before_wait_or_consume() -> None: - waited = False - consumed = False - - def wait_for_exit(parent_pid: int) -> None: - nonlocal waited - waited = True - - def consume(*args, **kwargs): - nonlocal consumed - consumed = True - raise AssertionError("must not consume") - - with pytest.raises(UpdateProcessError, match="invalid updater command shape"): - execute_trusted_updater( - ("--scripture-archive-apply", "--wait-pid", "1"), - current_version="1.0.0", - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=wait_for_exit, - consume=consume, + def test_runner_rolls_back_and_disarms_health_when_updated_process_cannot_start(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + events: list[object] = [] + + def publish(staging_root, **kwargs): + events.append(("publish", Path(staging_root))) + return object() + + def launch(target: Path) -> None: + events.append(("launch", target)) + raise ApplicationUpdateError("spawn failed") + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + def discard(staging_root: Path) -> bool: + events.append(("discard", Path(staging_root))) + return True + + with self.assertRaisesRegex(ApplicationUpdateError, "rollback restored prior bytes"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=discard, + launch=launch, + rollback=rollback, + ) + + self.assertEqual( + events, + [ + ("publish", plan.staging_root), + ("launch", plan.installed_executable), + ("rollback", plan.installed_executable, sentinel.previous_sha256), + ("discard", plan.staging_root), + ], ) - assert waited is False - assert consumed is False - -@pytest.mark.parametrize("current_version", ["", "1", "01.0.0", "1.0", "1.0.0 "]) -def test_runner_rejects_invalid_trusted_current_version_before_wait( - tmp_path: Path, current_version: str -) -> None: - plan = _plan(tmp_path) - waited = False - - def wait_for_exit(parent_pid: int) -> None: - nonlocal waited - waited = True - - with pytest.raises(ApplicationUpdateError): - execute_trusted_updater( - plan.argv()[1:], - current_version=current_version, - verify_same_publisher=lambda installed, staged: True, - wait_for_exit=wait_for_exit, + def test_runner_surfaces_combined_relaunch_and_rollback_failure(self) -> None: + plan = _plan(self.tmp_path) + sentinel = _result(plan) + + with self.assertRaisesRegex( + ApplicationUpdateError, + "relaunch failed and rollback also failed", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=_publish_noop, + discard_health=_discard_noop, + launch=lambda target: (_ for _ in ()).throw(OSError("spawn failed")), + rollback=lambda *args, **kwargs: (_ for _ in ()).throw( + OSError("rollback failed") + ), + ) + + def test_runner_rolls_back_consumer_target_substitution_before_health_or_launch(self) -> None: + plan = _plan(self.tmp_path) + sentinel = UpdateApplyResult( + previous_sha256="1" * 64, + installed_sha256="2" * 64, + rollback_path=plan.installed_executable.with_suffix(".rollback"), + target_path=self.tmp_path / "other.exe", + target_version="1.1.0", ) - assert waited is False - - -@pytest.mark.parametrize( - ("override", "message"), - [ - ({"verify_same_publisher": None}, "same-publisher verifier"), - ({"wait_for_exit": None}, "parent-exit waiter"), - ({"consume": None}, "apply consumer"), - ({"launch": None}, "application launcher"), - ({"rollback": None}, "rollback consumer"), - ({"publish_health": None}, "health receipt publisher"), - ({"discard_health": None}, "health receipt discarder"), - ], -) -def test_runner_requires_callable_security_dependencies_before_wait( - tmp_path: Path, override: dict[str, object], message: str -) -> None: - plan = _plan(tmp_path) - kwargs = { - "current_version": "1.0.0", - "verify_same_publisher": lambda installed, staged: True, - } - kwargs.update(override) - with pytest.raises(ApplicationUpdateError, match=message): - execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] + events: list[object] = [] + + def publish(*args, **kwargs): + events.append(("health",)) + + def launch(target: Path) -> None: + events.append(("launch", target)) + + def rollback(target: Path, *, expected_previous_sha256: str) -> str: + events.append(("rollback", target, expected_previous_sha256)) + return expected_previous_sha256 + + with self.assertRaisesRegex( + ApplicationUpdateError, + "unexpected install target; rollback restored", + ): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=lambda parent_pid: None, + consume=lambda *args, **kwargs: sentinel, + publish_health=publish, + discard_health=_discard_noop, + launch=launch, + rollback=rollback, + ) + self.assertEqual( + events, + [("rollback", plan.installed_executable, sentinel.previous_sha256)], + ) + + def test_runner_never_consumes_when_parent_exit_cannot_be_proven(self) -> None: + plan = _plan(self.tmp_path) + consumed = False + + def blocked_wait(parent_pid: int) -> None: + raise ParentProcessWaitError("parent still alive") + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(ParentProcessWaitError, "parent still alive"): + execute_trusted_updater( + plan.argv()[1:], + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=blocked_wait, + consume=consume, + ) + self.assertFalse(consumed) + + def test_runner_rejects_malformed_command_before_wait_or_consume(self) -> None: + waited = False + consumed = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + def consume(*args, **kwargs): + nonlocal consumed + consumed = True + raise AssertionError("must not consume") + + with self.assertRaisesRegex(UpdateProcessError, "invalid updater command shape"): + execute_trusted_updater( + ("--scripture-archive-apply", "--wait-pid", "1"), + current_version="1.0.0", + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + consume=consume, + ) + self.assertFalse(waited) + self.assertFalse(consumed) + + def test_runner_rejects_invalid_trusted_current_version_before_wait(self) -> None: + invalid_versions = ["", "1", "01.0.0", "1.0", "1.0.0 "] + for current_version in invalid_versions: + with self.subTest(current_version=current_version): + plan = _plan(self.tmp_path / current_version.replace(".", "_").replace(" ", "_")) + waited = False + + def wait_for_exit(parent_pid: int) -> None: + nonlocal waited + waited = True + + with self.assertRaises(ApplicationUpdateError): + execute_trusted_updater( + plan.argv()[1:], + current_version=current_version, + verify_same_publisher=lambda installed, staged: True, + wait_for_exit=wait_for_exit, + ) + self.assertFalse(waited) + + def test_runner_requires_callable_security_dependencies_before_wait(self) -> None: + overrides = [ + ({"verify_same_publisher": None}, "same-publisher verifier"), + ({"wait_for_exit": None}, "parent-exit waiter"), + ({"consume": None}, "apply consumer"), + ({"launch": None}, "application launcher"), + ({"rollback": None}, "rollback consumer"), + ({"publish_health": None}, "health receipt publisher"), + ({"discard_health": None}, "health receipt discarder"), + ] + for index, (override, message) in enumerate(overrides): + with self.subTest(message=message): + plan = _plan(self.tmp_path / f"dependency-{index}") + kwargs = { + "current_version": "1.0.0", + "verify_same_publisher": lambda installed, staged: True, + } + kwargs.update(override) + with self.assertRaisesRegex(ApplicationUpdateError, message): + execute_trusted_updater(plan.argv()[1:], **kwargs) # type: ignore[arg-type] + + +if __name__ == "__main__": + unittest.main() From afbd2276852a893b4aae9aeeed2c5fd48f3d6dcb Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:24:22 +0200 Subject: [PATCH 12/16] R06: keep runtime regression gates dependency-free --- .github/workflows/r06-dev10-integration.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/r06-dev10-integration.yml b/.github/workflows/r06-dev10-integration.yml index ec10d8675..eb32befdc 100644 --- a/.github/workflows/r06-dev10-integration.yml +++ b/.github/workflows/r06-dev10-integration.yml @@ -31,8 +31,6 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.13' - - name: Install runtime test dependency - run: python -m pip install --disable-pip-version-check pytest - name: Compile runtime, tests and integration tools working-directory: runtime_engine run: python -m compileall -q scripture_archive_runtime tests tools From 0ac5ba484d386be0b066938929584d1fda19990f Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 14:27:11 +0200 Subject: [PATCH 13/16] R06: lock update transport commands to empty payload --- ..._application_update_transport_contracts.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py diff --git a/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py b/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py new file mode 100644 index 000000000..8e1b1a07f --- /dev/null +++ b/lanes/dev1/repair_overlay/tests/test_application_update_transport_contracts.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import unittest + +from scripture_archive_platform.transport.contracts import validate_request_shape + + +API_VERSION = "scripture.transport.v1" +UPDATE_COMMANDS = ( + "application_update.apply_and_restart", + "application_update.commit_post_restart_health", +) + + +def request(command: str, payload=None, *, request_id: str = "update-contract-rid"): + return { + "api_version": API_VERSION, + "request_id": request_id, + "command": command, + "payload": {} if payload is None else payload, + } + + +class ApplicationUpdateTransportContractTests(unittest.TestCase): + def test_host_owned_update_commands_are_allowlisted_with_empty_payload(self) -> None: + for command in UPDATE_COMMANDS: + with self.subTest(command=command): + rid, parsed_command, payload = validate_request_shape(request(command)) + self.assertEqual(rid, "update-contract-rid") + self.assertEqual(parsed_command, command) + self.assertEqual(payload, {}) + + def test_browser_cannot_supply_update_process_path_or_identity_authority(self) -> None: + injected_payloads = ( + {"pid": 1}, + {"path": r"C:\attacker.exe"}, + {"version": "9.9.9"}, + {"sha256": "0" * 64}, + ) + for command in UPDATE_COMMANDS: + for payload in injected_payloads: + with self.subTest(command=command, payload=payload): + with self.assertRaisesRegex(ValueError, "empty payload"): + validate_request_shape(request(command, payload)) + + +if __name__ == "__main__": + unittest.main() From b448b40de9f7cbcedc29aba96989ca5678003090 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 20:36:20 +0200 Subject: [PATCH 14/16] R06 updater: carry atomic authority/resource repair into convergence --- .../application_update_updater.py | 48 ++++++++++++++----- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/runtime_engine/scripture_archive_runtime/application_update_updater.py b/runtime_engine/scripture_archive_runtime/application_update_updater.py index 49cffdfa2..249a479b1 100644 --- a/runtime_engine/scripture_archive_runtime/application_update_updater.py +++ b/runtime_engine/scripture_archive_runtime/application_update_updater.py @@ -119,7 +119,11 @@ def _consume_apply_handoff_locked( installed_sha = _sha256_file(target) if installed_sha != pending.artifact_sha256: raise ApplicationUpdateError("installed artifact failed exact-byte verification") - discard_apply_handoff(root) + post_publish_handoff = inspect_apply_handoff(root, current_version=current_version) + if post_publish_handoff != pending: + raise ApplicationUpdateError("apply handoff changed after atomic publication") + if discard_apply_handoff(root) is not True: + raise ApplicationUpdateError("apply handoff disappeared during disarm") except Exception as apply_error: try: candidate.unlink() @@ -297,20 +301,38 @@ def _discard_file(path: Path) -> None: def _copy_exact(source: Path, destination: Path) -> None: try: - descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) + source_handle = source.open("rb") except OSError as exc: - raise ApplicationUpdateError("could not create update copy safely") from exc - try: - with source.open("rb") as src, os.fdopen(descriptor, "wb", closefd=True) as dst: - shutil.copyfileobj(src, dst, length=_COPY_CHUNK) - dst.flush() - os.fsync(dst.fileno()) - except Exception: + raise ApplicationUpdateError("update source could not be opened") from exc + + with source_handle as src: try: - destination.unlink() - except OSError: - pass - raise + descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o700) + except OSError as exc: + raise ApplicationUpdateError("could not create update copy safely") from exc + try: + destination_handle = os.fdopen(descriptor, "wb", closefd=True) + except Exception: + try: + os.close(descriptor) + finally: + try: + destination.unlink() + except OSError: + pass + raise + + try: + with destination_handle as dst: + shutil.copyfileobj(src, dst, length=_COPY_CHUNK) + dst.flush() + os.fsync(dst.fileno()) + except Exception: + try: + destination.unlink() + except OSError: + pass + raise def _sha256_file(path: Path) -> str: From 0446825c6bfff2d33cf7e7c8b2895f06c516856a Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 20:36:49 +0200 Subject: [PATCH 15/16] R06 updater: carry authority/resource regressions into convergence --- .../tests/test_application_update_updater.py | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 79d16c131..7b5a18a47 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -1,6 +1,7 @@ from __future__ import annotations import hashlib +import os from pathlib import Path import tempfile import unittest @@ -9,6 +10,7 @@ from scripture_archive_runtime.application_update import ApplicationUpdateError from scripture_archive_runtime.application_update_pending import PendingApplicationUpdate from scripture_archive_runtime.application_update_updater import ( + _copy_exact, consume_apply_handoff, rollback_installed_update, ) @@ -332,6 +334,126 @@ def fail_post_publish_hash(path: Path) -> str: old, ) + def test_consume_handoff_rolls_back_when_authority_changes_after_publication(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + inspections = [pending, pending, pending, None] + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + side_effect=inspections, + ) as inspect, patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, + ) as discard: + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(inspect.call_count, 4) + discard.assert_not_called() + self.assertEqual(target.read_bytes(), old) + self.assertEqual( + (root / "ScriptureArchive.exe.scripture-archive.rollback").read_bytes(), + old, + ) + + def test_consume_handoff_rolls_back_if_disarm_reports_missing_authority(self): + old = b"old executable bytes" + new = b"new signed executable bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "ScriptureArchive.exe" + staged = root / "staged" / "ScriptureArchive.exe" + staged.parent.mkdir() + target.write_bytes(old) + staged.write_bytes(new) + pending = self._pending(new) + + with patch( + "scripture_archive_runtime.application_update_updater.inspect_apply_handoff", + return_value=pending, + ), patch( + "scripture_archive_runtime.application_update_updater.staged_artifact_path", + return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=False, + ): + with self.assertRaisesRegex( + ApplicationUpdateError, + "failed after publication; rollback restored", + ): + consume_apply_handoff( + root, + current_version="1.0.0", + install_target=target, + verify_same_publisher=lambda _current, _candidate: True, + ) + + self.assertEqual(target.read_bytes(), old) + + def test_copy_exact_source_open_failure_never_creates_destination(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + destination = root / "destination.exe" + + with patch.object( + Path, + "open", + side_effect=OSError("forced source-open failure"), + ), patch( + "scripture_archive_runtime.application_update_updater.os.open", + ) as destination_open: + with self.assertRaisesRegex( + ApplicationUpdateError, + "update source could not be opened", + ): + _copy_exact(source, destination) + + destination_open.assert_not_called() + self.assertFalse(destination.exists()) + + def test_copy_exact_fdopen_failure_closes_descriptor_and_removes_destination(self): + source_bytes = b"source bytes" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source.exe" + destination = root / "destination.exe" + source.write_bytes(source_bytes) + + with patch( + "scripture_archive_runtime.application_update_updater.os.fdopen", + side_effect=OSError("forced fdopen failure"), + ), patch( + "scripture_archive_runtime.application_update_updater.os.close", + wraps=os.close, + ) as close_descriptor: + with self.assertRaisesRegex(OSError, "forced fdopen failure"): + _copy_exact(source, destination) + + close_descriptor.assert_called_once() + self.assertFalse(destination.exists()) + def test_consume_handoff_disarms_apply_authority_after_success(self): old = b"old executable bytes" new = b"new signed executable bytes" From c55bb2731ba4415372134a75103fd5b2147748b2 Mon Sep 17 00:00:00 2001 From: Oleksii-debug Date: Tue, 29 Sep 2026 20:39:19 +0200 Subject: [PATCH 16/16] R06 updater: align convergence success fixture with disarm contract --- runtime_engine/tests/test_application_update_updater.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/runtime_engine/tests/test_application_update_updater.py b/runtime_engine/tests/test_application_update_updater.py index 7b5a18a47..cdf97e150 100644 --- a/runtime_engine/tests/test_application_update_updater.py +++ b/runtime_engine/tests/test_application_update_updater.py @@ -51,6 +51,9 @@ def test_consume_handoff_replaces_exact_bytes_and_keeps_verified_rollback(self): ), patch( "scripture_archive_runtime.application_update_updater.staged_artifact_path", return_value=staged, + ), patch( + "scripture_archive_runtime.application_update_updater.discard_apply_handoff", + return_value=True, ): result = consume_apply_handoff( root,