from pathlib import Path import copy import tempfile import unittest from unittest.mock import Mock, patch from common import atomic_json, read_json from sequence_matrix import PROFILE_FLAGS, compare_profile_contracts, payload_counts, require_ready, require_t2_fallback_bindings, require_transport, rp_command, run_pilot, systemd_measure class SequenceMatrixTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.root = Path(self.tmp.name) def test_commands_preserve_protocol_state_and_use_full_scope(self): private = self.root / "object" manifest = {"tls": {"ca": "/fixture/ca.pem"}} command1 = rp_command(Path("/fixture/rpki"), private, private / "step_0000", manifest, 1794218084957, "object", ["--tal-path", "/fixture/a.tal", "--ta-path", "/fixture/a.cer"]) command2 = rp_command(Path("/fixture/rpki"), private, private / "step_0001", manifest, 1794218384957, "object", ["--tal-path", "/fixture/a.tal", "--ta-path", "/fixture/a.cer"]) self.assertEqual(command1[command1.index("--db") + 1], command2[command2.index("--db") + 1]) self.assertNotIn("--max-instances", command1) self.assertNotIn("--disable-rrdp", command1) self.assertNotIn("--enable-crypto-signature-cache", command1) self.assertEqual(command2[command2.index("--validation-time") + 1], "2026-11-09T09:59:44Z") self.assertEqual(set(PROFILE_FLAGS), {"baseline", "signature", "object", "pp", "hybrid"}) self.assertEqual(PROFILE_FLAGS["baseline"], []) self.assertEqual(set(PROFILE_FLAGS["hybrid"]), set(PROFILE_FLAGS["object"] + PROFILE_FLAGS["pp"])) def test_native_route_and_scope_must_match_actual_outcomes(self): scope = {"included_repositories": ["good", "fallback"], "excluded_repositories": ["gap"], "routes": {"epoch_0012.json": {"fallback": {"rsync_uri": "rsync://native/repo/"}}}} table = {"rrdp": {"good": "Success", "fallback": {"Failure": "recorded"}, "gap": {"Failure": "excluded"}}, "rsync": {"rsync://native/repo/": "Success"}} require_transport(table, scope, "epoch_0012.json") for key, value in (("fallback", "Success"), ("good", {"Failure": "new failure"}), ("gap", "Success")): changed = {"rrdp": {**table["rrdp"], key: value}, "rsync": table["rsync"]} with self.subTest(key=key), self.assertRaises(ValueError): require_transport(changed, scope, "epoch_0012.json") with self.assertRaises(ValueError): require_transport({**table, "rsync": {}}, scope, "epoch_0012.json") with self.assertRaises(ValueError): require_transport({**table, "rrdp": {**table["rrdp"], "unbound": "Success"}}, scope, "epoch_0012.json") def test_full_payload_counts_do_not_require_loading_the_report(self): stdout = self.root / "stdout.log" stdout.write_text("vrps=1046609\naspas=4046\naudit_publication_points=56142\n") self.assertEqual(payload_counts(self.root), {"vrps": 1046609, "aspas": 4046, "publication_points": 56142}) for body in ("vrps=0\naspas=1\naudit_publication_points=1\n", "vrps=1\n", "vrps=1\nvrps=2\naspas=1\naudit_publication_points=1\n"): stdout.write_text(body) with self.assertRaises(ValueError): payload_counts(self.root) def test_readiness_rejects_wrong_scope_or_dead_server(self): ready = self.root / "ready.json" atomic_json(ready, {"epoch": "epoch", "scope": "scope"}) server = Mock() server.poll.return_value = None self.assertEqual(require_ready(ready, server, "epoch", "scope")["epoch"], "epoch") with self.assertRaisesRegex(ValueError, "different"): require_ready(ready, server, "epoch", "another-scope") server.poll.return_value = 1 with self.assertRaisesRegex(RuntimeError, "exited"): require_ready(ready, server, "epoch", "scope") def test_cgroup_measurement_retains_accounting_then_stops_only_own_unit(self): properties = "\n".join(["ActiveState=active", "SubState=exited", "Result=success", "ExecMainCode=1", "ExecMainStatus=0", "CPUUsageNSec=1000000000", "MemoryPeak=2000000"]) with patch("sequence_matrix.call", side_effect=[Mock(), Mock(stdout=properties)]) as call_mock, \ patch("sequence_matrix.subprocess.run") as stop_mock: result = systemd_measure(["/fixture/rpki", "--db", "/fixture/state/db"], self.root, {"TMPDIR": "/fixture/tmp"}, 5) self.assertEqual(result["cpu_ns"], 1000000000) self.assertEqual(result["memory_peak_bytes"], 2000000) launcher = call_mock.call_args_list[0].args[0] self.assertIn("RemainAfterExit=yes", launcher) self.assertIn("AllowedCPUs=1-3", launcher) self.assertIn("MemoryMax=5G", launcher) self.assertIn("rp187rp", launcher) self.assertEqual(stop_mock.call_args.args[0], ["systemctl", "stop", result["unit"]]) self.assertEqual(read_json(self.root / "process-resource.json")["cpu_ns"], 1000000000) def test_failed_cgroup_sample_does_not_publish_valid_metrics_and_is_stopped(self): props = "ActiveState=failed\nSubState=failed\nResult=oom-kill\nExecMainStatus=9\n" with patch("sequence_matrix.call", side_effect=[Mock(), Mock(stdout=props)]), \ patch("sequence_matrix.subprocess.run") as stop_mock: with self.assertRaisesRegex(RuntimeError, "failed"): systemd_measure(["/fixture/rpki"], self.root, {"TMPDIR": "/fixture/tmp"}, 5) self.assertFalse((self.root / "process-resource.json").exists()) self.assertTrue((self.root / "systemd-final.json").exists()) self.assertEqual(stop_mock.call_args.args[0][:2], ["systemctl", "stop"]) def test_pilot_never_executes_on_an_unassigned_machine(self): with patch("sequence_matrix.socket.gethostname", return_value="unassigned"), \ patch("sequence_matrix.call") as call_mock: with self.assertRaisesRegex(ValueError, "designated 186"): run_pilot({}) call_mock.assert_not_called() def test_cross_profile_contract_allows_different_cache_histories_only(self): baseline = {"cache": {"publicationPoint": False}, "validationTime": "2026-11-09T10:49:44Z", "binarySha256": "33" * 32, "policy": {"strict": True}, "fallbackReplaySelections": [{"manifestRsyncUri": "rsync://example/repo/a.mft", "vcirSha256": "11" * 32, "reuseIdentitySha256": "22" * 32}]} actual = copy.deepcopy(baseline) actual["cache"]["publicationPoint"] = True actual["fallbackReplaySelections"][0].update(vcirSha256="44" * 32, reuseIdentitySha256="55" * 32) proof = compare_profile_contracts(actual, baseline) self.assertTrue(proof["pass"]) self.assertEqual(proof["baseline_fallback"], baseline["fallbackReplaySelections"]) self.assertEqual(proof["actual_fallback"], actual["fallbackReplaySelections"]) for field, value in [("validationTime", "2026-11-09T10:44:44Z"), ("binarySha256", "66" * 32), ("policy", {"strict": False}), ("unexpectedPolicyField", True)]: bad = copy.deepcopy(actual) bad[field] = value with self.subTest(field=field), self.assertRaisesRegex(ValueError, "configuration"): compare_profile_contracts(bad, baseline) for mutation in [lambda rows: rows.clear(), lambda rows: rows.append(copy.deepcopy(rows[0])), lambda rows: rows[0].update(manifestRsyncUri="rsync://example/repo/b.mft"), lambda rows: rows[0].update(vcirSha256="bad"), lambda rows: rows[0].update(reuseIdentitySha256=""), lambda rows: rows[0].update(extra=True)]: bad = copy.deepcopy(actual) mutation(bad["fallbackReplaySelections"]) with self.assertRaises(ValueError): compare_profile_contracts(bad, baseline) self.assertEqual(actual["fallbackReplaySelections"][0]["vcirSha256"], "44" * 32) def test_cross_profile_contract_checks_no_fallback_and_ordering(self): self.assertTrue(compare_profile_contracts({"cache": {}}, {"cache": {}})["pass"]) a = {"manifestRsyncUri": "rsync://example/a.mft", "vcirSha256": "11" * 32, "reuseIdentitySha256": "22" * 32} b = {**a, "manifestRsyncUri": "rsync://example/b.mft"} for rows in [[b, a], [a, a], None, {}, "bad"]: with self.subTest(rows=rows), self.assertRaises(ValueError): compare_profile_contracts({"fallbackReplaySelections": rows}, {}) def test_t2_must_use_its_own_exact_cache_binding(self): selected = [{"manifestRsyncUri": "rsync://example/a.mft", "vcirSha256": "11" * 32, "reuseIdentitySha256": "22" * 32}] contract = {"fallbackReplaySelections": selected} equivalence = {"fallback": {"matches": True, "expected": copy.deepcopy(selected), "actual": copy.deepcopy(selected), "missing": [], "unexpected": []}} require_t2_fallback_bindings(contract, equivalence) for part in ("expected", "actual"): for field in ("manifestRsyncUri", "vcirSha256", "reuseIdentitySha256"): bad = copy.deepcopy(equivalence) bad["fallback"][part][0][field] = "different" with self.subTest(part=part, field=field), self.assertRaises(ValueError): require_t2_fallback_bindings(contract, bad) for field, value in [("matches", False), ("missing", selected), ("unexpected", selected)]: bad = copy.deepcopy(equivalence) bad["fallback"][field] = value with self.subTest(field=field), self.assertRaises(ValueError): require_t2_fallback_bindings(contract, bad) with self.assertRaises(ValueError): require_t2_fallback_bindings(contract, {}) if __name__ == "__main__": unittest.main()