STRA-8 add Linux changed-scope coverage gate
Linux / verify (pull_request) Failing after 1m15s
Linux / changed-scope-coverage (pull_request) Skipped
Linux / keyless-cuda (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-static-cli (pull_request) Skipped
Linux / linux-cli-container (pull_request) Skipped
Linux / release-cli (pull_request) Skipped
Linux / verify (pull_request) Failing after 1m15s
Linux / changed-scope-coverage (pull_request) Skipped
Linux / keyless-cuda (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-static-cli (pull_request) Skipped
Linux / linux-cli-container (pull_request) Skipped
Linux / release-cli (pull_request) Skipped
This commit is contained in:
@@ -0,0 +1,617 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the pinned Linux unit suite and enforce changed-production Rust coverage."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BASELINE = "d3e63a7"
|
||||
NIGHTLY = "nightly-2026-10-05"
|
||||
RUSTC_VERSION = "rustc 1.101.0-nightly (282215592 2026-10-04)"
|
||||
LLVM_VERSION = "LLVM version 23.1.3-rust-1.101.0-nightly"
|
||||
RUST_FILES = (
|
||||
"control-plane/src/kar_overlay.rs",
|
||||
"control-plane/src/kar_stream_encode.rs",
|
||||
"control-plane/src/kar_writer.rs",
|
||||
"control-plane/src/model_pipeline.rs",
|
||||
"control-plane/src/prepare_preview.rs",
|
||||
"control-plane/src/stream_parts.rs",
|
||||
)
|
||||
DOCUMENT_FILES = ("docs/build-validation.md", "docs/compressed-runtime.md")
|
||||
SCOPE_FILES = (*RUST_FILES, *DOCUMENT_FILES)
|
||||
SCOPE_DEFINITION = (
|
||||
"Full bodies of production functions with added lines or corresponding deleted baseline lines; "
|
||||
"cfg(test) item/block lines are excluded; generated production closures remain included."
|
||||
)
|
||||
|
||||
|
||||
def _blank(chars: list[str], start: int, end: int) -> None:
|
||||
for index in range(start, end):
|
||||
if chars[index] != "\n":
|
||||
chars[index] = " "
|
||||
|
||||
|
||||
def _block_end(source: str, start: int) -> int:
|
||||
depth, index = 1, start + 2
|
||||
while index < len(source) and depth:
|
||||
if source.startswith("/*", index):
|
||||
depth, index = depth + 1, index + 2
|
||||
elif source.startswith("*/", index):
|
||||
depth, index = depth - 1, index + 2
|
||||
else:
|
||||
index += 1
|
||||
if depth:
|
||||
raise ValueError(f"unclosed Rust block comment at byte {start}")
|
||||
return index
|
||||
|
||||
|
||||
def _raw_string_end(source: str, start: int) -> int | None:
|
||||
match = re.match(r"(?:br|r)(#{0,})\"", source[start:])
|
||||
if not match:
|
||||
return None
|
||||
marker = '"' + match.group(1)
|
||||
end = source.find(marker, start + match.end())
|
||||
return len(source) if end < 0 else end + len(marker)
|
||||
|
||||
|
||||
def _quoted_end(source: str, start: int) -> int:
|
||||
index = start + 1
|
||||
while index < len(source):
|
||||
if source[index] == "\\":
|
||||
index += 2
|
||||
elif source[index] == '"':
|
||||
return index + 1
|
||||
else:
|
||||
index += 1
|
||||
raise ValueError(f"unclosed Rust string at byte {start}")
|
||||
|
||||
|
||||
def _char_end(source: str, start: int) -> int | None:
|
||||
if start + 2 >= len(source):
|
||||
return None
|
||||
index = start + 1
|
||||
if source[index] == "\\":
|
||||
index += 2
|
||||
if source[start + 1 : start + 3] == "\\u":
|
||||
close = source.find("}", start + 3)
|
||||
if close < 0:
|
||||
return None
|
||||
index = close + 1
|
||||
else:
|
||||
index += 1
|
||||
return index + 1 if index < len(source) and source[index] == "'" else None
|
||||
|
||||
|
||||
def mask_rust(source: str) -> str:
|
||||
chars, index = list(source), 0
|
||||
while index < len(source):
|
||||
raw_end = _raw_string_end(source, index)
|
||||
if raw_end is not None:
|
||||
_blank(chars, index, raw_end)
|
||||
index = raw_end
|
||||
elif source.startswith("//", index):
|
||||
end = source.find("\n", index)
|
||||
end = len(source) if end < 0 else end
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
elif source.startswith("/*", index):
|
||||
end = _block_end(source, index)
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
elif source[index] == '"':
|
||||
end = _quoted_end(source, index)
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
elif source[index] == "'" and (end := _char_end(source, index)):
|
||||
_blank(chars, index, end)
|
||||
index = end
|
||||
else:
|
||||
index += 1
|
||||
return "".join(chars)
|
||||
|
||||
|
||||
def matching(mask: str, start: int, left: str, right: str) -> int:
|
||||
depth = 0
|
||||
for index in range(start, len(mask)):
|
||||
depth += mask[index] == left
|
||||
depth -= mask[index] == right
|
||||
if depth == 0:
|
||||
return index
|
||||
raise ValueError(f"unclosed Rust delimiter {left!r} at byte {start}")
|
||||
|
||||
|
||||
def _body_depths(depths: list[int], char: str, previous: str) -> None:
|
||||
if char == "(": depths[0] += 1
|
||||
elif char == ")": depths[0] -= 1
|
||||
elif char == "[": depths[1] += 1
|
||||
elif char == "]": depths[1] -= 1
|
||||
elif char == "<": depths[2] += 1
|
||||
elif char == ">" and previous != "-" and depths[2]: depths[2] -= 1
|
||||
|
||||
|
||||
def _body_open(mask: str, start: int) -> int:
|
||||
depths = [0, 0, 0]
|
||||
for index in range(start, len(mask)):
|
||||
char = mask[index]
|
||||
_body_depths(depths, char, mask[index - 1] if index else "")
|
||||
if char in "{;" and not any(depths):
|
||||
return index
|
||||
return len(mask)
|
||||
|
||||
|
||||
def _skip_space(mask: str, index: int) -> int:
|
||||
while index < len(mask) and mask[index].isspace():
|
||||
index += 1
|
||||
return index
|
||||
|
||||
|
||||
def _skip_attributes(mask: str, index: int) -> int:
|
||||
while True:
|
||||
index = _skip_space(mask, index)
|
||||
if not mask.startswith("#[", index):
|
||||
return index
|
||||
index = matching(mask, index + 1, "[", "]") + 1
|
||||
|
||||
|
||||
def _skip_visibility(mask: str, index: int) -> int:
|
||||
if not re.match(r"pub\b", mask[index:]):
|
||||
return index
|
||||
index = _skip_space(mask, index + 3)
|
||||
if index < len(mask) and mask[index] == "(":
|
||||
index = matching(mask, index, "(", ")") + 1
|
||||
return _skip_space(mask, index)
|
||||
|
||||
|
||||
def _statement_depths(depths: list[int], char: str) -> bool:
|
||||
if char == "(": depths[0] += 1
|
||||
elif char == ")": depths[0] -= 1
|
||||
elif char == "[": depths[1] += 1
|
||||
elif char == "]": depths[1] -= 1
|
||||
elif char == "{": depths[2] += 1
|
||||
elif char == "}": depths[2] -= 1
|
||||
return char == "}" and not any(depths)
|
||||
|
||||
|
||||
def _statement_end(mask: str, start: int) -> int:
|
||||
depths = [0, 0, 0]
|
||||
for index, char in enumerate(mask[start:], start):
|
||||
if _statement_depths(depths, char):
|
||||
return index + 1
|
||||
if char == ";" and not any(depths):
|
||||
return index + 1
|
||||
raise ValueError(f"cannot find end of Rust statement at byte {start}")
|
||||
|
||||
|
||||
def _item_end(mask: str, start: int) -> int:
|
||||
macro = re.match(r"(?:macro_rules!\s*[A-Za-z_][A-Za-z0-9_]*|[A-Za-z_:][A-Za-z0-9_:]*!)\s*", mask[start:])
|
||||
if macro:
|
||||
group = _skip_space(mask, start + macro.end())
|
||||
if group >= len(mask) or mask[group] not in "{([":
|
||||
raise ValueError(f"unsupported cfg(test) macro at byte {start}")
|
||||
close = {"{": "}", "(": ")", "[": "]"}[mask[group]]
|
||||
return matching(mask, group, mask[group], close) + 1
|
||||
item = re.match(r"(fn|mod|impl|struct|enum|trait|use|const|static|type|extern)\b", mask[start:])
|
||||
if not item:
|
||||
return _statement_end(mask, start)
|
||||
kind, cursor = item.group(1), start + item.end()
|
||||
if kind == "fn":
|
||||
paren = mask.find("(", cursor)
|
||||
close = matching(mask, paren, "(", ")")
|
||||
cursor = _body_open(mask, close + 1)
|
||||
if kind in {"use", "const", "static", "type"}:
|
||||
return _statement_end(mask, cursor)
|
||||
opening = _body_open(mask, cursor)
|
||||
if opening < len(mask) and mask[opening] == "{":
|
||||
return matching(mask, opening, "{", "}") + 1
|
||||
return _statement_end(mask, cursor)
|
||||
|
||||
|
||||
def cfg_test_spans(source: str, mask: str) -> list[tuple[int, int]]:
|
||||
spans = []
|
||||
pattern = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]")
|
||||
for attr in pattern.finditer(mask):
|
||||
if attr.start() and mask[attr.start() - 1] == "!":
|
||||
spans.append((0, len(source)))
|
||||
continue
|
||||
start = _skip_visibility(mask, _skip_attributes(mask, attr.end()))
|
||||
end = _item_end(mask, start)
|
||||
spans.append((attr.start(), end))
|
||||
return _merge_spans(spans)
|
||||
|
||||
|
||||
def _merge_spans(spans: list[tuple[int, int]]) -> list[tuple[int, int]]:
|
||||
merged = []
|
||||
for start, end in sorted(spans):
|
||||
if merged and start <= merged[-1][1]:
|
||||
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
|
||||
else:
|
||||
merged.append((start, end))
|
||||
return merged
|
||||
|
||||
|
||||
def _span_lines(source: str, spans: list[tuple[int, int]]) -> set[int]:
|
||||
lines = set()
|
||||
for start, end in spans:
|
||||
first = source.count("\n", 0, start) + 1
|
||||
last = source.count("\n", 0, end) + 1
|
||||
lines.update(range(first, last + 1))
|
||||
return lines
|
||||
|
||||
|
||||
def rust_functions(source: str) -> tuple[list[dict], set[int]]:
|
||||
mask, found = mask_rust(source), []
|
||||
test_spans = cfg_test_spans(source, mask)
|
||||
test_lines = _span_lines(source, test_spans)
|
||||
for match in re.finditer(r"\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\b", mask):
|
||||
if any(start <= match.start() < end for start, end in test_spans):
|
||||
continue
|
||||
paren = mask.find("(", match.end())
|
||||
close = matching(mask, paren, "(", ")")
|
||||
opening = _body_open(mask, close + 1)
|
||||
if opening >= len(mask) or mask[opening] != "{":
|
||||
continue
|
||||
end = matching(mask, opening, "{", "}") + 1
|
||||
found.append({"name": match.group(1), "start": source.count("\n", 0, match.start()) + 1,
|
||||
"end": source.count("\n", 0, end) + 1})
|
||||
return found, test_lines
|
||||
|
||||
|
||||
def parse_diff_hunks(diff: str) -> tuple[set[int], set[int]]:
|
||||
added, deleted, new_line, old_line = set(), set(), 0, 0
|
||||
for line in diff.splitlines():
|
||||
if line.startswith("@@"):
|
||||
match = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
|
||||
if not match:
|
||||
raise ValueError(f"invalid unified diff hunk: {line}")
|
||||
old_line, new_line = int(match.group(1)), int(match.group(2))
|
||||
elif line.startswith("+++") or line.startswith("---") or line.startswith("\\"):
|
||||
continue
|
||||
elif line.startswith("+"):
|
||||
added.add(new_line)
|
||||
new_line += 1
|
||||
elif line.startswith("-"):
|
||||
deleted.add(old_line)
|
||||
old_line += 1
|
||||
elif line.startswith(" "):
|
||||
old_line += 1
|
||||
new_line += 1
|
||||
return added, deleted
|
||||
|
||||
|
||||
def select_production_functions(source: str, baseline_source: str, diff: str) -> tuple[list[dict], set[int]]:
|
||||
additions, deletions = parse_diff_hunks(diff)
|
||||
current, test_lines = rust_functions(source)
|
||||
old, old_test_lines = rust_functions(baseline_source)
|
||||
additions.difference_update(test_lines)
|
||||
deletions.difference_update(old_test_lines)
|
||||
deleted_names = {item["name"] for item in old if any(item["start"] <= line <= item["end"] for line in deletions)}
|
||||
selected = [item for item in current if item["name"] in deleted_names or
|
||||
any(item["start"] <= line <= item["end"] for line in additions)]
|
||||
if not selected:
|
||||
raise ValueError("baseline diff selects no current production functions")
|
||||
return selected, test_lines
|
||||
|
||||
|
||||
def parse_lcov(text: str) -> list[dict]:
|
||||
records, record = [], None
|
||||
for line in text.splitlines():
|
||||
if line.startswith("SF:"):
|
||||
if record is not None:
|
||||
raise ValueError("LCOV source record lacks end_of_record")
|
||||
record = {"sf": line[3:], "da": [], "fn": [], "fnda": [], "brda": []}
|
||||
elif line == "end_of_record":
|
||||
if record is None:
|
||||
raise ValueError("LCOV end_of_record without SF")
|
||||
records.append(record)
|
||||
record = None
|
||||
elif record is not None:
|
||||
_parse_lcov_row(record, line)
|
||||
if record is not None:
|
||||
raise ValueError("LCOV source record lacks end_of_record")
|
||||
return records
|
||||
|
||||
|
||||
def _parse_lcov_row(record: dict, line: str) -> None:
|
||||
try:
|
||||
if line.startswith("DA:"):
|
||||
parts = line[3:].split(",")
|
||||
record["da"].append((int(parts[0]), int(parts[1])))
|
||||
elif line.startswith("FN:"):
|
||||
number, name = line[3:].split(",", 1)
|
||||
record["fn"].append((int(number), name))
|
||||
elif line.startswith("FNDA:"):
|
||||
count, name = line[5:].split(",", 1)
|
||||
record["fnda"].append((int(count), name))
|
||||
elif line.startswith("BRDA:"):
|
||||
number, block, branch, taken = line[5:].split(",", 3)
|
||||
record["brda"].append((int(number), block, branch, taken))
|
||||
except (IndexError, ValueError) as error:
|
||||
raise ValueError(f"invalid LCOV row: {line}") from error
|
||||
|
||||
|
||||
def _record_path(record: dict) -> str:
|
||||
path = record["sf"].replace("\\", "/")
|
||||
return next((name for name in RUST_FILES if path == name or path.endswith("/" + name)), "")
|
||||
|
||||
|
||||
def _inside(line: int, functions: list[dict], test_lines: set[int]) -> bool:
|
||||
return line not in test_lines and any(item["start"] <= line <= item["end"] for item in functions)
|
||||
|
||||
|
||||
def _merge_lcov(records: list[dict]) -> dict:
|
||||
by_path = {}
|
||||
for record in records:
|
||||
path = _record_path(record)
|
||||
if path:
|
||||
by_path.setdefault(path, []).append(record)
|
||||
return by_path
|
||||
|
||||
|
||||
def _file_metrics(records: list[dict], functions: list[dict], test_lines: set[int]) -> dict:
|
||||
da, fn, fnda, branch = _merge_record_metrics(records)
|
||||
lines = {line: count for line, count in da.items() if _inside(line, functions, test_lines)}
|
||||
funcs = {key: fnda.get(key[1], 0) for key in fn if _inside(key[0], functions, test_lines)}
|
||||
branches = {key: value for key, value in branch.items() if _inside(key[0], functions, test_lines)}
|
||||
return _metrics(lines, funcs, branches)
|
||||
|
||||
|
||||
def _merge_record_metrics(records: list[dict]) -> tuple[dict, dict, dict, dict]:
|
||||
da, fn, fnda, branch = {}, {}, {}, {}
|
||||
for record in records:
|
||||
_merge_record(record, da, fn, fnda, branch)
|
||||
return da, fn, fnda, branch
|
||||
|
||||
|
||||
def _merge_record(record: dict, da: dict, fn: dict, fnda: dict, branch: dict) -> None:
|
||||
for line, count in record["da"]:
|
||||
da[line] = da.get(line, 0) + count
|
||||
for line, name in record["fn"]:
|
||||
fn[(line, name)] = fn.get((line, name), 0)
|
||||
for count, name in record["fnda"]:
|
||||
fnda[name] = fnda.get(name, 0) + count
|
||||
for line, block, number, taken in record["brda"]:
|
||||
key = (line, block, number)
|
||||
branch[key] = _branch_total(branch.get(key), taken)
|
||||
|
||||
|
||||
def _branch_total(previous: str | None, taken: str) -> str:
|
||||
if previous is None or taken == "-" or previous == "-":
|
||||
return taken
|
||||
return str(int(previous) + int(taken))
|
||||
|
||||
|
||||
def _metrics(lines: dict, functions: dict, branches: dict) -> dict:
|
||||
line_misses = sorted(line for line, hits in lines.items() if hits == 0)
|
||||
fn_misses = [{"line": line, "name": name} for (line, name), hits in functions.items() if hits == 0]
|
||||
branch_misses = [{"line": line, "block": block, "branch": branch, "taken": taken}
|
||||
for (line, block, branch), taken in branches.items() if taken in {"0", "-"}]
|
||||
return {"lines": _metric(len(lines) - len(line_misses), len(lines), line_misses),
|
||||
"functions": _metric(len(functions) - len(fn_misses), len(functions), fn_misses),
|
||||
"branches": _metric(len(branches) - len(branch_misses), len(branches), branch_misses)}
|
||||
|
||||
|
||||
def _metric(hit: int, total: int, misses: list) -> dict:
|
||||
return {"hit": hit, "total": total, "percent": (100.0 * hit / total) if total else 0.0,
|
||||
"misses": misses}
|
||||
|
||||
|
||||
def coverage_report(records: list[dict], scopes: dict[str, tuple[list[dict], set[int]]]) -> dict:
|
||||
by_path, files = _merge_lcov(records), {}
|
||||
totals = {kind: {"hit": 0, "total": 0, "misses": []} for kind in ("lines", "functions", "branches")}
|
||||
for path in RUST_FILES:
|
||||
if path not in by_path:
|
||||
raise ValueError(f"LCOV is missing required Rust source record: {path}")
|
||||
functions, test_lines = scopes[path]
|
||||
metrics = _file_metrics(by_path[path], functions, test_lines)
|
||||
files[path] = {"functions": functions, "metrics": metrics}
|
||||
for kind, values in metrics.items():
|
||||
totals[kind]["hit"] += values["hit"]
|
||||
totals[kind]["total"] += values["total"]
|
||||
totals[kind]["misses"].extend({**miss, "file": path} if isinstance(miss, dict)
|
||||
else {"line": miss, "file": path} for miss in values["misses"])
|
||||
for kind, values in totals.items():
|
||||
values["percent"] = 100.0 * values["hit"] / values["total"] if values["total"] else 0.0
|
||||
return {"baseline": BASELINE, "files": files, "totals": totals}
|
||||
|
||||
|
||||
def _run(command: list[str], root: Path, env: dict | None = None) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(command, cwd=root, env=env, text=True, capture_output=True, check=False)
|
||||
|
||||
|
||||
def _rust_tools(root: Path) -> tuple[Path, Path, dict]:
|
||||
rustc = _run(["rustc", f"+{NIGHTLY}", "-vV"], root)
|
||||
if rustc.returncode:
|
||||
raise RuntimeError(f"pinned rustc is unavailable: {rustc.stderr.strip()}")
|
||||
versions = rustc.stdout.strip()
|
||||
if RUSTC_VERSION not in versions:
|
||||
raise RuntimeError(f"unexpected pinned rustc version: {versions.splitlines()[0]}")
|
||||
details = dict(line.split(": ", 1) for line in versions.splitlines() if ": " in line)
|
||||
sysroot = _run(["rustc", f"+{NIGHTLY}", "--print", "sysroot"], root)
|
||||
if sysroot.returncode or "host" not in details:
|
||||
raise RuntimeError("cannot resolve pinned LLVM tool directory")
|
||||
bindir = Path(sysroot.stdout.strip()) / "lib" / "rustlib" / details["host"] / "bin"
|
||||
tools = (bindir / "llvm-cov", bindir / "llvm-profdata")
|
||||
for tool in tools:
|
||||
version = _run([str(tool), "--version"], root)
|
||||
if version.returncode or LLVM_VERSION not in version.stdout:
|
||||
raise RuntimeError(f"unexpected {tool.name} version: {version.stdout.strip()}")
|
||||
return tools[0], tools[1], {"rustc": versions.splitlines()[0], "llvm": LLVM_VERSION, "host": details["host"]}
|
||||
|
||||
|
||||
def _package_id(root: Path) -> str:
|
||||
result = _run(["cargo", "metadata", "--manifest-path", "control-plane/Cargo.toml",
|
||||
"--locked", "--format-version=1", "--no-deps"], root)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"cargo metadata failed: {result.stderr.strip()}")
|
||||
packages = [item["id"] for item in json.loads(result.stdout)["packages"]
|
||||
if item["name"] == "strata-control"]
|
||||
if len(packages) != 1:
|
||||
raise RuntimeError(f"expected one strata-control package, found {len(packages)}")
|
||||
return packages[0]
|
||||
|
||||
|
||||
def _cargo_harness(json_path: Path, package_id: str) -> Path:
|
||||
found = []
|
||||
for line in json_path.read_text().splitlines():
|
||||
try: item = json.loads(line)
|
||||
except json.JSONDecodeError: continue
|
||||
if _is_test_lib_artifact(item, package_id):
|
||||
found.append(Path(item["executable"]))
|
||||
if len(found) != 1 or not found[0].is_file():
|
||||
raise RuntimeError(f"expected one built strata-control lib test binary, found {len(found)}")
|
||||
return found[0]
|
||||
|
||||
|
||||
def _is_test_lib_artifact(item: dict, package_id: str) -> bool:
|
||||
target = item.get("target", {})
|
||||
return (item.get("reason") == "compiler-artifact" and item.get("package_id") == package_id
|
||||
and target.get("name") == "strata_control" and target.get("kind") == ["lib"]
|
||||
and target.get("test") and item.get("executable"))
|
||||
|
||||
|
||||
def _changed_scopes(root: Path) -> tuple[dict, dict]:
|
||||
if _run(["git", "cat-file", "-e", f"{BASELINE}^{{commit}}"], root).returncode:
|
||||
raise RuntimeError(f"baseline commit {BASELINE} is unavailable")
|
||||
if _run(["git", "merge-base", "--is-ancestor", BASELINE, "HEAD"], root).returncode:
|
||||
raise RuntimeError(f"baseline {BASELINE} is not an ancestor of HEAD")
|
||||
scopes, functions_by_file = {}, {}
|
||||
for path in RUST_FILES:
|
||||
source = (root / path).read_text()
|
||||
old = _run(["git", "show", f"{BASELINE}:{path}"], root)
|
||||
diff = _run(["git", "diff", "--no-ext-diff", "--unified=0", BASELINE, "--", path], root)
|
||||
if old.returncode or diff.returncode:
|
||||
raise RuntimeError(f"cannot read baseline/diff for {path}")
|
||||
funcs, test_lines = select_production_functions(source, old.stdout, diff.stdout)
|
||||
scopes[path] = (funcs, test_lines)
|
||||
functions_by_file[path] = funcs
|
||||
return scopes, functions_by_file
|
||||
|
||||
|
||||
def _diff_hash(root: Path, paths: tuple[str, ...]) -> str:
|
||||
result = _run(["git", "diff", "--binary", BASELINE, "--", *paths], root)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"cannot hash changed paths: {', '.join(paths)}")
|
||||
return hashlib.sha256(result.stdout.encode()).hexdigest()
|
||||
|
||||
|
||||
def _commit(root: Path, revision: str) -> str:
|
||||
result = _run(["git", "rev-parse", revision], root)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"cannot resolve commit {revision}")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def _coverage_env(out: Path) -> dict:
|
||||
env = os.environ.copy()
|
||||
flags = "-C instrument-coverage -Zcoverage-options=branch --cfg=coverage "
|
||||
flags += "--cfg=coverage_nightly -C link-arg=-Wl,--no-keep-memory"
|
||||
env.update({"RUSTFLAGS": flags,
|
||||
"CARGO_BUILD_JOBS": "1", "CARGO_INCREMENTAL": "0", "RUST_TEST_THREADS": "1",
|
||||
"CARGO_PROFILE_DEV_DEBUG": "0", "CARGO_PROFILE_TEST_DEBUG": "0",
|
||||
"LLVM_PROFILE_FILE": str(out / "profraw" / "%m-%p.profraw")})
|
||||
(out / "profraw").mkdir(parents=True, exist_ok=True)
|
||||
return env
|
||||
|
||||
|
||||
def _write_summary(out: Path, report: dict) -> None:
|
||||
(out / "summary.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
|
||||
rows = [f"Changed-production coverage vs {report['baseline']}"]
|
||||
for kind, value in report.get("totals", {}).items():
|
||||
rows.append(f"{kind}: {value['hit']}/{value['total']} ({value.get('percent', 0.0):.2f}%)")
|
||||
rows.append(f"Gate: {'PASS' if report.get('passed') else 'FAIL'}")
|
||||
rows.append(f"Reason: {report.get('failure', 'all required gates passed')}")
|
||||
(out / "summary.txt").write_text("\n".join(rows) + "\n")
|
||||
|
||||
|
||||
def _run_instrumented_tests(root: Path, out: Path, env: dict) -> tuple[int, Path, int]:
|
||||
cargo_json, cargo_stderr = out / "cargo.jsonl", out / "cargo.stderr"
|
||||
command = ["cargo", f"+{NIGHTLY}", "test", "--manifest-path", "control-plane/Cargo.toml",
|
||||
"--locked", "-p", "strata-control", "--lib", "--message-format=json-render-diagnostics"]
|
||||
with cargo_json.open("w") as stdout, cargo_stderr.open("w") as stderr:
|
||||
test = subprocess.run(command, cwd=root, env=env, stdout=stdout, stderr=stderr, check=False)
|
||||
binary = _cargo_harness(cargo_json, _package_id(root))
|
||||
profiles = sorted((out / "profraw").glob("*.profraw"))
|
||||
if not profiles:
|
||||
raise RuntimeError("instrumented tests produced no profraw files")
|
||||
return test.returncode, binary, len(profiles)
|
||||
|
||||
|
||||
def _export_lcov(root: Path, out: Path, llvm_cov: Path, llvm_profdata: Path,
|
||||
binary: Path) -> str:
|
||||
profiles = sorted((out / "profraw").glob("*.profraw"))
|
||||
profile = out / "merged.profdata"
|
||||
merge = _run([str(llvm_profdata), "merge", "-sparse", "-o", str(profile), *map(str, profiles)], root)
|
||||
if merge.returncode:
|
||||
(out / "llvm-profdata.stderr").write_text(merge.stderr)
|
||||
raise RuntimeError("llvm-profdata merge failed")
|
||||
export = _run([str(llvm_cov), "export", "--format=lcov", f"--instr-profile={profile}", str(binary)], root)
|
||||
(out / "llvm-cov.stderr").write_text(export.stderr)
|
||||
if export.returncode:
|
||||
raise RuntimeError("llvm-cov export failed")
|
||||
(out / "coverage.raw.lcov").write_text(export.stdout)
|
||||
return export.stdout
|
||||
|
||||
|
||||
def _coverage_passed(state: dict, test_exit: int) -> bool:
|
||||
exact = all(values["total"] > 0 and values["hit"] == values["total"]
|
||||
for values in state["totals"].values())
|
||||
return test_exit == 0 and exact
|
||||
|
||||
|
||||
def _stable_diff(root: Path, state: dict) -> None:
|
||||
if state["rust_six_path_diff_sha256"] != _diff_hash(root, RUST_FILES):
|
||||
raise RuntimeError("Rust source diff changed during coverage collection")
|
||||
if state["full_eight_path_diff_sha256"] != _diff_hash(root, SCOPE_FILES):
|
||||
raise RuntimeError("eight-path source/docs diff changed during coverage collection")
|
||||
|
||||
|
||||
def _attach_scope_result(state: dict, test_exit: int) -> None:
|
||||
state["scope_files"] = list(RUST_FILES)
|
||||
state["scope_definition"] = SCOPE_DEFINITION
|
||||
state["measurement"] = "unit line/function/branch coverage; literal 100 percent required"
|
||||
state["source_diff_sha256"] = state["rust_six_path_diff_sha256"]
|
||||
state["passed"] = _coverage_passed(state, test_exit)
|
||||
state["failure"] = "" if state["passed"] else "unit tests failed or changed-scope coverage was not exactly 100%"
|
||||
|
||||
|
||||
def run_coverage(root: Path, out: Path) -> int:
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
state = {"baseline": BASELINE, "head": "unknown", "passed": False, "failure": "not started"}
|
||||
try:
|
||||
state["head"] = _commit(root, "HEAD")
|
||||
state["baseline_commit"] = _commit(root, BASELINE)
|
||||
scopes, _ = _changed_scopes(root)
|
||||
state["rust_six_path_diff_sha256"] = _diff_hash(root, RUST_FILES)
|
||||
state["full_eight_path_diff_sha256"] = _diff_hash(root, SCOPE_FILES)
|
||||
llvm_cov, llvm_profdata, versions = _rust_tools(root)
|
||||
state["toolchain"] = versions
|
||||
test_exit, binary, profile_count = _run_instrumented_tests(root, out, _coverage_env(out))
|
||||
state.update(cargo_exit_code=test_exit, selected_test_binary=str(binary), profraw_files=profile_count)
|
||||
raw = _export_lcov(root, out, llvm_cov, llvm_profdata, binary)
|
||||
report = coverage_report(parse_lcov(raw), scopes)
|
||||
state.update(report)
|
||||
_stable_diff(root, state)
|
||||
_attach_scope_result(state, test_exit)
|
||||
except Exception as error:
|
||||
state["failure"] = f"{type(error).__name__}: {error}"
|
||||
_write_summary(out, state)
|
||||
print((out / "summary.txt").read_text(), end="")
|
||||
return 0 if state["passed"] else 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path.cwd())
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
return run_coverage(args.root.resolve(), args.output_dir.resolve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/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_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.assertIn("if: always()", job)
|
||||
self.assertIn("actions/upload-artifact@v4.4.3", job)
|
||||
self.assertIn("coverage.raw.lcov", job)
|
||||
self.assertIn("summary.json", job)
|
||||
self.assertIn("summary.txt", 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)
|
||||
Reference in New Issue
Block a user