Files
leleka/scripts/test-changed-scope-coverage.py
T
Pavlo Ratushnyi 4cb41467dd
Linux / verify (pull_request) Successful in 2m11s
Linux / changed-scope-coverage (pull_request) Skipped
Linux / keyless-cuda (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 16s
Linux / linux-static-cli (pull_request) Successful in 5m13s
Linux / release-cli (pull_request) Skipped
Add raw LCOV function diagnostics
2026-10-07 03:23:47 +02:00

183 lines
9.8 KiB
Python

#!/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]
EXISTING_JOBS_SHA256 = "26cf64e51e207b9f81cef306e4ec31f3ed817334699e0b0fe7c7a031cb848a25"
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
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.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 _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)