#!/usr/bin/env python3 """Deterministic parser and workflow-contract tests for the manual coverage gate.""" from __future__ import annotations import importlib.util import json import subprocess import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[1] # Reviewed snapshots from frozen infrastructure commit ac070fe2fa8bf0db9aa4f5fe627736c465e6e3e1. EXISTING_JOBS_SHA256 = "4072554cb17e5afc49aba44a1ecbb5b71fa2d0bbf417512a432e3d519f16496b" COVERAGE_JOB_SHA256 = "131cd1dc20e77f509137bf5db596466405899d6ed06c702869c46d72b79f38ea" PUSH_PULL_SHA256 = "cefb2858cd9b21076e171fa764dbf2df1472b911cc0743caa6fac7d09a216c89" SPEC = importlib.util.spec_from_file_location("changed_scope", ROOT / "scripts/check-changed-scope-coverage.py") COVERAGE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(COVERAGE) def _job_block(text: str, name: str) -> str: lines = text.splitlines(keepends=True) start = next(index for index, line in enumerate(lines) if line == f" {name}:\n") end = next((index for index in range(start + 1, len(lines)) if lines[index].startswith(" ") and not lines[index].startswith(" ") and lines[index].strip().endswith(":")), len(lines)) return "".join(lines[start:end]) def _lcov(path: str, branch: str = "1") -> str: return (f"SF:{path}\nFN:1,live\nFNDA:1,live\nDA:1,1\nDA:2,1\n" f"BRDA:2,0,0,{branch}\nend_of_record\n") class ChangedScopeCoverageTests(unittest.TestCase): def test_rust_mask_and_cfg_test_exclusion(self) -> None: source = ''' // fn comment() {} const TEXT: &str = r###"fn raw_fake() {}"###; pub fn live(value: u8) -> u8 { if value > 0 { value } else { 0 } } #[cfg(test)] mod tests { #[test] fn hidden() {} } pub fn with_test_only_block() { #[cfg(test)] if true { unreachable!(); } } ''' functions, test_lines = COVERAGE.rust_functions(source) self.assertEqual([item["name"] for item in functions], ["live", "with_test_only_block"]) self.assertTrue(test_lines) self.assertNotIn("fn raw_fake", COVERAGE.mask_rust(source)) def test_diff_hunks_select_only_added_and_deleted_new_lines(self) -> None: diff = "--- a/x\n+++ b/x\n@@ -2,2 +2,2 @@\n old\n+added\n-gone\n" self.assertEqual(COVERAGE.parse_diff_hunks(diff), ({3}, {3})) def test_changed_scope_selects_body_but_excludes_test_additions(self) -> None: old = "fn stable() { 1 }\nfn live() { 2 }\n#[cfg(test)]\nmod tests { fn sample() {} }\n" new = "fn stable() { 1 }\nfn live() { 3 }\n#[cfg(test)]\nmod tests { fn sample() { 4 } }\n" diff = ("@@ -2 +2 @@\n-fn live() { 2 }\n+fn live() { 3 }\n" "@@ -4 +4 @@\n-mod tests { fn sample() {} }\n+mod tests { fn sample() { 4 } }\n") selected, _ = COVERAGE.select_production_functions(new, old, diff) self.assertEqual([item["name"] for item in selected], ["live"]) def test_lcov_zero_and_unknown_branches_fail_closed(self) -> None: record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "-"))[0] metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set()) self.assertEqual(metrics["branches"]["hit"], 0) self.assertEqual(metrics["branches"]["misses"][0]["taken"], "-") record = COVERAGE.parse_lcov(_lcov("control-plane/src/kar_writer.rs", "0"))[0] metrics = COVERAGE._file_metrics([record], [{"name": "live", "start": 1, "end": 3}], set()) self.assertEqual(metrics["branches"]["hit"], 0) def test_coverage_requires_every_production_file_and_exact_hits(self) -> None: scopes = {path: ([{"name": "live", "start": 1, "end": 3}], set()) for path in COVERAGE.RUST_FILES} records = [COVERAGE.parse_lcov(_lcov(path))[0] for path in COVERAGE.RUST_FILES] report = COVERAGE.coverage_report(records, scopes) self.assertTrue(all(item["hit"] == item["total"] for item in report["totals"].values())) with self.assertRaisesRegex(ValueError, "missing required Rust source"): COVERAGE.coverage_report(records[:-1], scopes) records[0]["brda"][0] = (2, "0", "0", "0") report = COVERAGE.coverage_report(records, scopes) self.assertNotEqual(report["totals"]["branches"]["hit"], report["totals"]["branches"]["total"]) def test_failure_summary_prints_deterministic_complete_miss_inventory(self) -> None: report = {"baseline": "d3e63a7", "passed": False, "failure": "coverage below 100%", "totals": {"lines": {"hit": 0, "total": 1, "misses": [{"file": "b.rs", "line": 9}, {"file": "a.rs", "line": 4}]}, "functions": {"hit": 0, "total": 1, "misses": [{"file": "a.rs", "line": 7, "name": "f"}]}, "branches": {"hit": 0, "total": 1, "misses": [{"file": "b.rs", "line": 9, "block": "1", "branch": "0", "taken": "-"}]}}} lines = COVERAGE.summary_lines(report) self.assertEqual(lines[6:9], ["Miss inventory (file:line; deterministic order):", "lines misses: 2", " a.rs:4"]) self.assertIn(" a.rs:7 f", lines) self.assertIn(" b.rs:9 block=1 branch=0 taken=-", lines) self.assertEqual(lines, COVERAGE.summary_lines(report)) self.assertFalse(any("a.rs:4" in line for line in COVERAGE.summary_lines( {**report, "passed": True}))) def test_raw_function_diagnostics_show_fn_and_exact_fnda_without_changing_metrics(self) -> None: path = "control-plane/src/kar_writer.rs" lcov = (f"SF:{path}\nFN:10,crate::write_section\nFNDA:1,crate::write_section\n" "FN:12,crate::write_section::{closure#0}\n" "FNDA:0,crate::write_section::{closure#0}\nDA:10,1\nDA:12,0\n" "BRDA:12,0,0,0\nend_of_record\n") records = [COVERAGE.parse_lcov(lcov)[0]] records.extend(COVERAGE.parse_lcov(_lcov(other))[0] for other in COVERAGE.RUST_FILES if other != path) scopes = {name: ([], set()) for name in COVERAGE.RUST_FILES} scopes[path] = ([{"name": "write_section", "start": 10, "end": 14}], set()) before = COVERAGE.coverage_report(records, scopes) diagnostics = COVERAGE.raw_function_diagnostics(records, scopes) after = COVERAGE.coverage_report(records, scopes) self.assertEqual(before, after) self.assertIn("zero-hit FN:12,crate::write_section::{closure#0}", diagnostics) self.assertIn("raw FN:12,crate::write_section::{closure#0}", diagnostics) self.assertIn("exact raw FNDA:0,crate::write_section::{closure#0}", diagnostics) self.assertNotIn("zero-hit FN:10,crate::write_section", diagnostics) def test_raw_function_diagnostics_are_empty_when_all_selected_functions_hit(self) -> None: path = "control-plane/src/kar_writer.rs" records = COVERAGE.parse_lcov(_lcov(path))[0:] scopes = {name: ([], set()) for name in COVERAGE.RUST_FILES} scopes[path] = ([{"name": "live", "start": 1, "end": 3}], set()) self.assertEqual(COVERAGE.raw_function_diagnostics(records, scopes), "") def test_cargo_json_selects_only_the_package_lib_test_executable(self) -> None: with tempfile.TemporaryDirectory() as directory: binary = Path(directory) / "strata_control-test" binary.touch() rows = [{"reason": "compiler-artifact", "package_id": "other 1.0.0", "target": {"name": "strata_control", "kind": ["lib"], "test": True}, "executable": str(binary)}, {"reason": "compiler-artifact", "package_id": "strata-control 1.0.0", "target": {"name": "strata_control", "kind": ["lib"], "test": True}, "executable": str(binary)}] log = Path(directory) / "cargo.jsonl" log.write_text("\n".join(json.dumps(row) for row in rows)) self.assertEqual(COVERAGE._cargo_harness(log, "strata-control 1.0.0"), binary) def test_workflow_adds_opt_in_cpu_job_without_changing_existing_jobs(self) -> None: current = (ROOT / ".github/workflows/linux.yml").read_text() original = subprocess.run(["git", "show", "HEAD:.github/workflows/linux.yml"], cwd=ROOT, capture_output=True, text=True, check=True).stdout self._assert_workflow_contract(current, original) def _assert_workflow_contract(self, current: str, original: str) -> None: job_names = ("verify", "keyless-cuda", "hosted-cuda-package", "linux-static-cli", "linux-cli-container", "release-cli") self.assertEqual(_digest("".join(_job_block(current, name) for name in job_names)), EXISTING_JOBS_SHA256) self.assertEqual(_digest(_push_pull_block(current)), PUSH_PULL_SHA256) for name in job_names: self.assertEqual(_job_block(current, name), _job_block(original, name), name) self.assertIn("pull_request:\n workflow_dispatch:", current) self.assertIn("changed_scope_coverage:\n description:", current) self.assertIn("type: boolean\n default: false", current) job = _job_block(current, "changed-scope-coverage") self.assertEqual(_digest(job), COVERAGE_JOB_SHA256) self.assertIn("needs: verify", job) self.assertIn("runs-on: ubuntu-latest", job) self.assertNotIn("self-hosted", job) self.assertNotIn("strata-gpu", job) self.assertIn("inputs.changed_scope_coverage", job) self.assertIn("nightly-2026-10-05", job) self.assertIn("scripts/check-changed-scope-coverage.py", job) self.assertNotIn("actions/upload-artifact", job) self.assertNotIn("download-artifact", job) def test_workflow_rejects_restored_unchecked_installer_in_every_bootstrap_job(self) -> None: current = (ROOT / ".github/workflows/linux.yml").read_text() self._assert_workflow_contract(current, current) unchecked_bootstrap = ( " curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs " "| sh -s -- -y --profile minimal --default-toolchain none\n" ' echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"\n' ' export PATH="$HOME/.cargo/bin:$PATH"\n' " " ) for name in ("verify", "changed-scope-coverage", "hosted-cuda-package", "linux-static-cli", "release-cli"): with self.subTest(job=name): block = _job_block(current, name) self.assertEqual(block.count(" scripts/install-pinned-rustup.sh "), 1) restored = block.replace(" scripts/install-pinned-rustup.sh ", unchecked_bootstrap, 1) mutated = current.replace(block, restored, 1) # Matching HEAD cannot rescue a committed insecure bootstrap: the fixed # reviewed snapshots must refuse it independently of that comparison. with self.assertRaises(AssertionError): self._assert_workflow_contract(mutated, mutated) def _digest(value: str) -> str: import hashlib return hashlib.sha256(value.encode()).hexdigest() def _push_pull_block(text: str) -> str: start = text.index("on:\n") + len("on:\n") end = text.index(" workflow_dispatch:", start) return text[start:end] if __name__ == "__main__": unittest.main(verbosity=2)