"""Catch publication injection, secret writes, routing and redeploy mistakes. The daemon's E2E path never builds the perf site; these run in the perf gate. Route tests run routes.js under node, the code the site itself runs. """ import contextlib import io import json from pathlib import Path import shutil import subprocess import tempfile import tomllib import unittest from unittest import mock import ci import isolation import publish from records import baseline, run_url from render import build_site, page, write_file from compare import accept_line, compare # render put perf on the path ROUTES = Path(__file__).with_name("routes.js") A, B = "a" * 40, "ab" + "c" * 38 def record(rkey, event="push", ref="refs/heads/main", committed="", created=""): return { "rkey": rkey, "commit": rkey[:40], "event": event, "ref": ref, "committedAt": committed or "2026-11-01T10:00:00Z", "createdAt": created or "2026-11-01T10:00:00Z", } def routes(script): """Run `script` with PerfRoutes in scope and return what it prints as JSON.""" node = shutil.which("node") if node is None: raise unittest.SkipTest("node is not on PATH (nix develop provides it)") program = f"const PerfRoutes = require({json.dumps(str(ROUTES))}).PerfRoutes;\n" output = subprocess.check_output([node, "-e", program + script], text=True) return json.loads(output) def run_record( commit: str, *, prior: float | None = None, **gated: tuple[float, str] ) -> dict[str, str]: """A main record whose summary gates `name=(value, verdict)`.""" metrics = { name: {"value": value, "noise": 0, "verdict": verdict, "baseline": prior} for name, (value, verdict) in gated.items() } return {"commit": commit, "summary": json.dumps({"gated": metrics})} class PublicationIsolationTest(unittest.TestCase): def test_failed_process_observation_prevents_cleanup_success(self): sandbox = isolation.Sandbox(Path("/tmp/fixture-perf-agent")) with mock.patch.object( isolation, "sudo", side_effect=[ subprocess.CompletedProcess([], 0), subprocess.CompletedProcess([], 2), ], ): with self.assertRaises(isolation.IsolationError): sandbox.close() self.assertFalse(sandbox.closed) def test_publication_follows_verified_cleanup_and_preserves_failures(self): for failed, measurement, verdict, publication in ( (False, 0, "pass", 0), (True, 0, "pass", 0), (False, 1, "pass", 0), (False, 0, "fail", 0), (False, 0, "pass", 1), ): with self.subTest( cleanup_failed=failed, measurement=measurement, verdict=verdict, publication=publication, ): events = [] sandbox = mock.Mock() def close(): events.append("cleanup") if failed: raise isolation.IsolationError("fixture cleanup failure") sandbox.close.side_effect = close @contextlib.contextmanager def measuring(): yield Path("/tmp/fixture-report"), None, sandbox, {} def run(argv, **kwargs): if argv[0] == "nix": self.assertEqual(events, ["cleanup"]) events.append("publish") return subprocess.CompletedProcess( argv, publication if argv[0] == "nix" else 0 ) with ( mock.patch.object(ci, "measuring", measuring), mock.patch.object(ci, "replay", return_value=measurement), mock.patch.object( ci, "read_result", return_value={ "gated": { "boot": {"value": 1, "budget": 2, "verdict": "pass"} }, "verdict": verdict, }, ), mock.patch.object(ci, "build_site"), mock.patch.object(ci.subprocess, "run", side_effect=run), mock.patch.dict(ci.os.environ, {"WISP_APP_PASSWORD": "fixture"}), contextlib.redirect_stdout(io.StringIO()) as output, ): if failed: with self.assertRaises(isolation.IsolationError): ci.main() else: with self.assertRaises(SystemExit) as stopped: ci.main() self.assertEqual( bool(stopped.exception.code), bool(measurement or verdict != "pass" or publication), ) log = output.getvalue() self.assertLess( log.index(f"performance verdict: {verdict}"), log.index('"gated"'), ) status = ( "performance report failed: fixture cleanup failure" if failed else f"publication process exit: {publication}" ) self.assertLess(log.index(status), log.index('"gated"')) self.assertEqual( events, ["cleanup"] if failed else ["cleanup", "publish"] ) class BaselineTest(unittest.TestCase): def test_a_regressed_metric_is_not_the_next_baseline(self): records = [ run_record(B, boot=(200, "regressed"), turn=(5, "pass")), run_record(A, boot=(100, "pass"), turn=(4, "pass")), ] chosen = baseline(records, {})["gated"] self.assertEqual((chosen["boot"]["value"], chosen["boot"]["commit"]), (100, A)) self.assertEqual((chosen["turn"]["value"], chosen["turn"]["commit"]), (5, B)) def test_an_accepted_metric_is_the_baseline_for_that_metric_only(self): records = [ run_record(B, boot=(200, "regressed"), turn=(9, "regressed")), run_record(A, boot=(100, "pass"), turn=(4, "pass")), ] accepted = {"boot": {B: {"value": 200, "reason": "measured honestly"}}} chosen = baseline(records, accepted) self.assertEqual(chosen["gated"]["boot"]["value"], 200) self.assertEqual(chosen["gated"]["turn"]["value"], 4) self.assertEqual(chosen["commit"], B) def test_an_acceptance_names_the_value_it_accepted(self): records = [ run_record(B, boot=(201, "regressed")), run_record(A, boot=(100, "pass")), ] accepted = {"boot": {B: {"value": 200, "reason": "a rerun measured 201"}}} self.assertEqual(baseline(records, accepted)["gated"]["boot"]["value"], 100) def test_an_improvement_only_one_run_measured_is_not_the_next_baseline(self): # 3f97c9e9 measured kernel_cell_slope at -259 KB per cell, against 5.6 KB # on every run before and after it, and failed the next push. records = [ run_record(B, turn=(5705, "regressed")), run_record(A, turn=(-259189, "improved")), run_record("d" * 40, turn=(5647, "pass")), ] chosen = baseline(records, {})["gated"]["turn"] self.assertEqual((chosen["value"], chosen["commit"]), (5647, "d" * 40)) self.assertIsNone(baseline(records[1:2], {})) def test_an_improvement_the_next_run_repeats_is_the_baseline(self): records = [ run_record(B, turn=(3010, "improved")), run_record(A, turn=(3000, "improved")), run_record("d" * 40, turn=(5647, "pass")), ] self.assertEqual(baseline(records, {})["gated"]["turn"]["value"], 3000) def test_a_low_pass_cannot_make_normal_variation_regress(self) -> None: # b708ac11's low reading was inside the noise floor, so it said pass. # Adopting it immediately made unchanged code on 5c7a8a26 fail. records = [ run_record("c" * 40, turn_peak_beam_blocks=(5995912, "regressed")), run_record(B, prior=5663864, turn_peak_beam_blocks=(5253096, "pass")), run_record(A, turn_peak_beam_blocks=(5663864, "pass")), ] chosen = baseline(records, {}) self.assertEqual(chosen["gated"]["turn_peak_beam_blocks"]["commit"], A) result = { "commit": "c" * 40, "gated": {"turn_peak_beam_blocks": {"value": 5995912, "noise": 215456}}, } # Keep the comparison rules that exposed the bug independent of later # recalibration of the real metric's noise floor. budgets = { "metrics": { "turn_peak_beam_blocks": { "kind": "memory", "ceiling": 6500000, "floor": 600000, } } } self.assertEqual(compare(result, chosen, budgets)["verdict"], "pass") def test_repeated_lower_passes_can_lower_the_baseline(self) -> None: records = [ run_record(B, prior=5663864, turn=(5300000, "pass")), run_record(A, prior=5663864, turn=(5253096, "pass")), run_record("d" * 40, turn=(5663864, "pass")), ] self.assertEqual(baseline(records, {})["gated"]["turn"]["commit"], A) def test_the_printed_accept_line_accepts_that_measurement(self): result = { "commit": B, "mode": "replay", "gated": {"request_bytes_per_turn": {"value": 49956.1, "noise": 0}}, } old = baseline([run_record(A, request_bytes_per_turn=(48704.1, "pass"))], {}) compare(result, old) metric = result["gated"]["request_bytes_per_turn"] self.assertEqual((metric["verdict"], metric["base_commit"]), ("regressed", A)) line = accept_line("request_bytes_per_turn", B, 49956.1) self.assertEqual(metric["accept"], line) accepted = tomllib.loads(line) record = run_record(B, request_bytes_per_turn=(49956.1, "regressed")) chosen = baseline([record], accepted)["gated"]["request_bytes_per_turn"] self.assertEqual(chosen["commit"], B) def test_the_committed_acceptances_parse(self): for metric, entries in tomllib.loads( (Path(__file__).parents[1] / "accepted.toml").read_text() ).items(): for commit, entry in entries.items(): self.assertRegex(commit, "^[0-9a-f]{40}$") self.assertTrue(entry["reason"], metric) self.assertIn("value", entry) class ReportTest(unittest.TestCase): def test_config_json_cannot_close_its_script_element(self): attack = "" output = page({"did": attack}, "v") self.assertNotIn(attack, output) payload = output.split('id="config">', 1)[1].split("", 1)[0] self.assertEqual(json.loads(payload), {"did": attack}) def test_secret_shaped_content_is_rejected_before_file_creation(self): with tempfile.TemporaryDirectory() as temporary: path = Path(temporary) / "index.html" with self.assertRaisesRegex(ValueError, "secret scan rejected"): write_file(path, "sk-proj-" + "x" * 30) self.assertFalse(path.exists()) def test_rejected_write_leaves_existing_page_unchanged(self): with tempfile.TemporaryDirectory() as temporary: path = Path(temporary) / "index.html" write_file(path, "existing page") with self.assertRaisesRegex(ValueError, "secret scan rejected"): write_file(path, b"sk-or-v1-" + b"x" * 30) self.assertEqual(path.read_text(), "existing page") def test_paths_name_pages(self): parsed = routes( "console.log(JSON.stringify(['', '/', 'main/', 'abc1234/', " "'abc1234-2', '" + A + "/', 'ABC1234/', 'abc12/', 'x/y/'].map(PerfRoutes.parse)))" ) self.assertEqual( [p["page"] for p in parsed], [ "index", "index", "main", "run", "run", "run", "missing", "missing", "missing", ], ) self.assertEqual((parsed[4]["prefix"], parsed[4]["suffix"]), ("abc1234", "-2")) def test_run_paths_resolve_to_one_record(self): runs = [ record(A), record(A + "-2", event="manual", ref="local"), record(B), record("ab" + "d" * 38), ] found = routes( f"const runs = {json.dumps(runs)};\n" "const key = (path) => {\n" " const r = PerfRoutes.resolve(PerfRoutes.parse(path), runs);\n" " return r.run ? r.run.rkey : r.ambiguous ? r.ambiguous.map((x) => x.rkey) : null;\n" "};\n" "console.log(JSON.stringify([key('aaaaaaa/'), key('aaaaaaa-2/'), " "key('aaaaaaa-3/'), key('abccccc/'), key('ab' + 'c'.repeat(38) + '/'), " "key('0000000/'), key('abc1234/')]))" ) self.assertEqual(found[:2], [A, A + "-2"]) self.assertIsNone(found[2]) self.assertEqual(found[3:5], [B, B]) self.assertEqual(found[5:], [None, None]) # Two commits sharing their first seven characters are ambiguous. both = routes( f"const runs = {json.dumps([record(B), record('abccccc' + 'd' * 33)])};\n" "console.log(JSON.stringify(PerfRoutes.resolve(PerfRoutes.parse('abccccc'), runs)" ".ambiguous.length))" ) self.assertEqual(both, 2) def test_run_url_matches_the_page_path(self): keys = routes( "console.log(JSON.stringify([PerfRoutes.pathKey('" + A + "'), PerfRoutes.pathKey('" + A + "-2')]))" ) self.assertEqual( [run_url(A), run_url(A + "-2")], [publish.SITE_URL + key + "/" for key in keys], ) def test_main_is_the_latest_main_push_by_commit_instant(self): runs = [ # 06:00-05:00 is 11:00Z, later than 08:30+03:00 (05:30Z). record(A, committed="2026-11-02T06:00:35-05:00"), record(B, committed="2026-11-02T08:30:16+03:00"), record("e" * 40, event="pull_request", committed="2026-11-03T00:00:00Z"), ] latest = routes( f"const runs = {json.dumps(runs)};\n" "console.log(JSON.stringify(PerfRoutes.resolve({ page: 'main' }, runs).run.rkey))" ) self.assertEqual(latest, A) def test_site_deploys_only_a_changed_app_from_trusted_events(self): deploy = publish.should_deploy self.assertTrue(deploy("push", "refs/heads/main", "old", "new")) self.assertTrue(deploy("push", "main", None, "new")) self.assertTrue(deploy("manual", "refs/heads/main", "old", "new")) self.assertFalse(deploy("manual", "refs/heads/perf-one-site", "old", "new")) self.assertFalse(deploy("manual", "local", "old", "new")) self.assertFalse(deploy("push", "refs/heads/main", "new", "new")) self.assertFalse(deploy("pull_request", "refs/heads/main", "old", "new")) self.assertFalse(deploy("push", "refs/heads/feature", "old", "new")) def test_site_version_changes_with_its_files_only(self): with tempfile.TemporaryDirectory() as one, tempfile.TemporaryDirectory() as two: first, again = build_site(one), build_site(two) self.assertEqual(first, again) served = json.loads((Path(one) / "version.json").read_text()) self.assertEqual(served, {"version": first}) self.assertNotEqual(build_site(one, pds="https://pds.invalid"), first) def test_update_site_skips_an_unchanged_site(self): with tempfile.TemporaryDirectory() as temporary: built = build_site(temporary) with ( mock.patch.object(publish, "served_version", return_value=built), mock.patch.object(publish, "deploy") as deploy, ): publish.update_site("push", "refs/heads/main", "password") deploy.assert_not_called() with ( mock.patch.object(publish, "served_version", side_effect=["old", built]), mock.patch.object(publish, "deploy") as deploy, ): publish.update_site("push", "refs/heads/main", "password") deploy.assert_called_once() if __name__ == "__main__": unittest.main()