blob: 7164e1133c3f0d77c24cc0401c5babf73d3baa92 [file] [edit]
#!/usr/bin/env python3
# Copyright 2026 The Fuchsia Authors
#
# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
"""Cross-consumer conformance contract lockstep checker and fixture generator.
Validates every trusted contract policy under `ci/contracts/<name>.toml`:
1. Dispatches through an explicit fail-closed `CONTRACT_REGISTRY`, requires
every registered contract to have a policy under `ci/contracts/` (within
the Pass-2 Human review surface), and requires `contract.name == <stem>`.
2. Mirrors production `check_assumed_stubs_envelope`,
`parse_assumed_stubs_list`, and `parse_census` in
`trusted/cargo-anneal/src/core/inspect/schema.rs` (omitted-when-empty
sorted/deduped non-blank stub lists, `scope <= cfg`, `cfg == sorted
census stubs`, no selected stub, exact `<PREFIX> (<cfg joined ', '>) are `
disclosure when `cfg` non-empty and forbidden when `cfg` empty, strict
JSON types on every census and selected entry). All 4 valid and 12
invalid receipt vectors execute directly against `cargo-anneal inspect`
(`tests/cargo-anneal/tests/inspect/assume_stub_contract.rs`); in
`anneal-obligations` (`tools/anneal-spec/obligations/tests/
assume_stub_contract.rs`, via byte-for-byte lockstep `vector_mirrors`),
all 4 valid vectors pass, 6 obligations-enforced invalid vectors are
rejected, and the 6 `scope`/`assumptions` vectors are asserted accepted
because `cargo-anneal inspect` owns those checks.
3. Generates a pure `Init.*`-only Lean 4 module strictly outside Pass-1
`trusted/` and `theory/` (pre-resolve `lstat` symlink and traversal
checks) containing raw JSON vector data and an independent Lean evaluator
so Lean kernel reduction checks every vector without reusing Python
booleans.
4. Scans production trees (`trusted/`, `theory/`, `correspondence/`,
`tools/`, `crates/`, `ci/`) across snake_case, kebab-case, and camelCase
to reject unregistered consumers; non-consuming incidental references must
be declared under `[[exemptions]]` with an explicit reason.
"""
from __future__ import annotations
import argparse
import ast
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import sys
import tokenize
import tomllib
from typing import Any, Callable
REPO_ROOT = Path(__file__).resolve().parent.parent
SCAN_ROOTS = ("trusted", "theory", "correspondence", "tools", "crates", "ci")
SCAN_SKIP_DIRS = frozenset({"target", ".lake", ".anneal", ".git", "__pycache__", ".build"})
SCAN_EXTS = (".rs", ".lean", ".py", ".cc", ".cpp", ".c", ".h", ".hpp", ".toml", ".sh")
ASSUMED_STUB_DISCLOSURE_PREFIX = (
"items stubbed via --assume-stub or #[anneal::assume_stub]"
)
# Exact Unicode `White_Space` codepoints matching Rust `char::is_whitespace` /
# `str::trim` (explicitly excluding ASCII control chars U+001C..U+001F that
# Python `str.strip()` treats as whitespace).
RUST_WHITESPACE_CHARS = (
"\t\n\x0b\x0c\r \x85\xa0\u1680"
"\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
"\u2028\u2029\u202f\u205f\u3000"
)
def _rust_trim(s: str) -> str:
return s.strip(RUST_WHITESPACE_CHARS)
def _read_regular_bytes(path: Path) -> bytes:
if path.is_symlink() or not path.is_file():
raise ValueError(f"expected regular file, got {path}")
return path.read_bytes()
def _read_regular_utf8(path: Path) -> str:
return _read_regular_bytes(path).decode("utf-8")
def _build_ident_regex(identifiers: list[str]) -> re.Pattern[str]:
"""Match snake_case, kebab-case, and camelCase variants."""
alts: list[str] = []
for raw in identifiers:
parts = [p for p in re.split(r"[^A-Za-z0-9]+", raw.strip()) if p]
if parts:
alts.append("[_-]?".join(re.escape(p) for p in parts))
return re.compile(r"(?i)(?:" + "|".join(alts) + r")")
def _append_unique(reasons: list[str], code: str) -> None:
if code not in reasons:
reasons.append(code)
def _is_nonneg_int(val: Any) -> bool:
return isinstance(val, int) and not isinstance(val, bool) and val >= 0
def _parse_assumed_stubs_list(
container: Any,
reasons: list[str],
) -> list[str]:
"""Port of `parse_assumed_stubs_list` from `inspect/schema.rs`."""
if not isinstance(container, dict):
_append_unique(reasons, "malformed_envelope_object")
return []
arr = container.get("assumed_stubs")
# Match `strict_json::ObjectCursor::opt_array` (JSON null is absent).
if arr is None:
return []
if not isinstance(arr, list) or not all(isinstance(x, str) for x in arr):
_append_unique(reasons, "invalid_assumed_stubs_type")
return []
if not arr:
_append_unique(reasons, "empty_assumed_stubs_array")
return []
if any(not _rust_trim(x) for x in arr):
_append_unique(reasons, "blank_assumed_stub_entry")
if not all(arr[i] < arr[i + 1] for i in range(len(arr) - 1)):
_append_unique(reasons, "unsorted_or_duplicate_assumed_stubs")
return list(arr)
def evaluate_assume_stub_vector(vec: dict[str, Any]) -> tuple[bool, list[str]]:
"""Strict 1:1 port of production `inspect/schema.rs` receipt invariants."""
reasons: list[str] = []
kind = vec.get("kind")
if kind == "receipt":
schema_ver = vec.get("schema_version")
if not _is_nonneg_int(schema_ver) or schema_ver != 3:
_append_unique(reasons, "invalid_receipt_schema_version")
scope_stubs = _parse_assumed_stubs_list(vec.get("scope"), reasons)
cfg_stubs = _parse_assumed_stubs_list(vec.get("configuration"), reasons)
selected = vec.get("selected")
census = vec.get("census")
assumptions = vec.get("assumptions")
if not isinstance(selected, list) or not isinstance(census, list) or not isinstance(assumptions, list):
_append_unique(reasons, "malformed_receipt_arrays")
return False, reasons
if not all(isinstance(a, str) for a in assumptions):
_append_unique(reasons, "invalid_assumptions_type")
return False, reasons
stub_def_ids: set[int] = set()
census_stub_paths: set[str] = set()
for item in census:
if not isinstance(item, dict):
_append_unique(reasons, "malformed_census_item")
continue
def_id = item.get("def_id")
path_s = item.get("path")
kind_s = item.get("kind")
has_body = item.get("has_body")
sel_flag = item.get("selected")
req_flag = item.get("required")
if (
not _is_nonneg_int(def_id)
or not isinstance(path_s, str)
or not isinstance(kind_s, str)
or not isinstance(has_body, bool)
or not isinstance(sel_flag, bool)
or not isinstance(req_flag, bool)
):
_append_unique(reasons, "malformed_census_item")
continue
if "assumed_stub_reason" in item and item["assumed_stub_reason"] is not None:
reason_val = item["assumed_stub_reason"]
if not isinstance(reason_val, str) or not _rust_trim(reason_val):
_append_unique(reasons, "missing_nonempty_stub_reason")
stub_def_ids.add(def_id)
census_stub_paths.add(path_s)
if sel_flag:
_append_unique(reasons, "stub_cannot_be_selected")
for sel in selected:
if (
not isinstance(sel, dict)
or not _is_nonneg_int(sel.get("def_id"))
or not isinstance(sel.get("path"), str)
or not _is_nonneg_int(sel.get("body_index"))
):
_append_unique(reasons, "malformed_selected_item")
continue
if sel["def_id"] in stub_def_ids:
_append_unique(reasons, "stub_cannot_be_selected")
census_stubs_sorted = sorted(census_stub_paths)
if cfg_stubs != census_stubs_sorted:
_append_unique(reasons, "cfg_disagrees_with_census_stubs")
if any(req_stub not in cfg_stubs for req_stub in scope_stubs):
_append_unique(reasons, "scope_not_subset_of_cfg")
if cfg_stubs:
expected_prefix = (
f"{ASSUMED_STUB_DISCLOSURE_PREFIX} ({', '.join(cfg_stubs)}) are "
)
if not any(a.startswith(expected_prefix) for a in assumptions):
_append_unique(reasons, "missing_assumptions_disclosure")
elif any(a.startswith(ASSUMED_STUB_DISCLOSURE_PREFIX) for a in assumptions):
_append_unique(reasons, "unexpected_stub_disclosure")
else:
reasons.append(f"unknown_vector_kind:{kind!r}")
return (len(reasons) == 0), reasons
def _lean_cps(s: str) -> str:
"""Encode a Python string as a Lean `List Nat` of Unicode scalar values."""
if not s:
return "[]"
return "[" + ", ".join(str(ord(ch)) for ch in s) + "]"
def _lean_cps_list(xs: list[str]) -> str:
if not xs:
return "[]"
return "[" + ", ".join(_lean_cps(x) for x in xs) + "]"
def _lean_nat_list(xs: list[int]) -> str:
if not xs:
return "[]"
return "[" + ", ".join(str(x) for x in xs) + "]"
def _lean_bool(v: bool) -> str:
return "true" if v else "false"
def _lean_name_str(s: str) -> str:
esc = s.replace("\\", "\\\\").replace('"', '\\"')
return f'"{esc}"'
def _render_raw_lean_vector(name: str, expected_valid: bool, vec: dict[str, Any]) -> str:
"""Serialize raw JSON receipt vector fields into Lean without verdicts."""
if not isinstance(vec, dict):
raise ValueError(f"{name}: vector root must be a JSON object")
kind = vec.get("kind")
if kind != "receipt":
raise ValueError(f"unsupported vector kind in {name}: {kind!r}")
schema_ver = vec.get("schema_version")
if not _is_nonneg_int(schema_ver):
raise ValueError(f"{name}: schema_version must be a non-negative int, got {schema_ver!r}")
scope_obj = vec.get("scope")
cfg_obj = vec.get("configuration")
if not isinstance(scope_obj, dict) or not isinstance(cfg_obj, dict):
raise ValueError(f"{name}: scope and configuration must be JSON objects")
raw_scope_stubs = scope_obj.get("assumed_stubs")
raw_cfg_stubs = cfg_obj.get("assumed_stubs")
scope_has = raw_scope_stubs is not None
cfg_has = raw_cfg_stubs is not None
if scope_has and (
not isinstance(raw_scope_stubs, list) or not all(isinstance(x, str) for x in raw_scope_stubs)
):
raise ValueError(f"{name}: scope.assumed_stubs must be list[str] or null")
if cfg_has and (
not isinstance(raw_cfg_stubs, list) or not all(isinstance(x, str) for x in raw_cfg_stubs)
):
raise ValueError(f"{name}: configuration.assumed_stubs must be list[str] or null")
scope_stubs = list(raw_scope_stubs) if scope_has else []
cfg_stubs = list(raw_cfg_stubs) if cfg_has else []
raw_census = vec.get("census")
raw_selected = vec.get("selected")
raw_assumptions = vec.get("assumptions")
if (
not isinstance(raw_census, list)
or not isinstance(raw_selected, list)
or not isinstance(raw_assumptions, list)
or not all(isinstance(a, str) for a in raw_assumptions)
):
raise ValueError(f"{name}: census, selected, and assumptions must be typed arrays")
census_terms: list[str] = []
for c in raw_census:
if not isinstance(c, dict):
raise ValueError(f"{name}: census item must be an object")
def_id = c.get("def_id")
path_s = c.get("path")
sel_b = c.get("selected")
if not _is_nonneg_int(def_id) or not isinstance(path_s, str) or not isinstance(sel_b, bool):
raise ValueError(f"{name}: malformed census item types")
raw_r = c.get("assumed_stub_reason")
has_r = raw_r is not None
if has_r and not isinstance(raw_r, str):
raise ValueError(f"{name}: assumed_stub_reason must be str or null, got {raw_r!r}")
r_str = raw_r if has_r else ""
census_terms.append(
f"{{ defId := {def_id}, path := {_lean_cps(path_s)}, "
f"selected := {_lean_bool(sel_b)}, "
f"hasStubReason := {_lean_bool(has_r)}, stubReason := {_lean_cps(r_str)} }}"
)
sel_ids: list[int] = []
for s in raw_selected:
if not isinstance(s, dict) or not _is_nonneg_int(s.get("def_id")):
raise ValueError(f"{name}: selected item def_id must be a non-negative int")
sel_ids.append(s["def_id"])
return (
f" {{ name := {_lean_name_str(name)}, expectedValid := {_lean_bool(expected_valid)}, "
f"schemaVersion := {schema_ver}, "
f"scopeHasField := {_lean_bool(scope_has)}, scopeStubs := {_lean_cps_list(scope_stubs)}, "
f"cfgHasField := {_lean_bool(cfg_has)}, cfgStubs := {_lean_cps_list(cfg_stubs)}, "
f"census := [{', '.join(census_terms)}], selectedDefIds := {_lean_nat_list(sel_ids)}, "
f"assumptions := {_lean_cps_list(raw_assumptions)} }}"
)
def render_assume_stub_lean_fixture(vectors_dir: Path) -> str:
"""Generate a pure `Init.*`-only Lean 4 module evaluating raw JSON vectors."""
entries: list[str] = []
for bucket, expected_valid in (("valid", True), ("invalid", False)):
vdir = vectors_dir / bucket
for jf in sorted(vdir.glob("*.json")):
vec = json.loads(_read_regular_utf8(jf))
entries.append(_render_raw_lean_vector(jf.stem, expected_valid, vec))
lines = [
"-- Copyright 2026 The Fuchsia Authors",
"--",
"-- Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0",
"-- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT",
"-- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.",
"-- This file may not be copied, modified, or distributed except according to",
"-- those terms.",
"",
"-- AUTO-GENERATED by `python3 ci/check_contract_lockstep.py --write-lean`.",
"-- Pure `Init.*`-only independent Lean evaluator over raw JSON vector data",
"-- (Unicode scalar value lists for kernel-reducible `rfl` checking),",
"-- strictly outside Pass-1 `trusted/` and `theory/`.",
"",
"import Init.Prelude",
"import Init.Data.List.Basic",
"",
"namespace ContractsTest.AssumeStub",
"",
"abbrev Text := List Nat",
"",
"structure CensusItem where",
" defId : Nat",
" path : Text",
" selected : Bool",
" hasStubReason : Bool",
" stubReason : Text",
" deriving Repr, DecidableEq",
"",
"structure Vector where",
" name : String",
" expectedValid : Bool",
" schemaVersion : Nat",
" scopeHasField : Bool",
" scopeStubs : List Text",
" cfgHasField : Bool",
" cfgStubs : List Text",
" census : List CensusItem",
" selectedDefIds : List Nat",
" assumptions : List Text",
" deriving Repr, DecidableEq",
"",
"def isRustWhitespace (n : Nat) : Bool :=",
" (n >= 0x09 && n <= 0x0D) || n == 0x20 || n == 0x85 || n == 0xA0 ||",
" n == 0x1680 || (n >= 0x2000 && n <= 0x200A) || n == 0x2028 ||",
" n == 0x2029 || n == 0x202F || n == 0x205F || n == 0x3000",
"",
"def isBlank (s : Text) : Bool :=",
" s.all isRustWhitespace",
"",
"def textLt : Text → Text → Bool",
" | [], [] => false",
" | [], _ :: _ => true",
" | _ :: _, [] => false",
" | x :: xs, y :: ys => if x == y then textLt xs ys else x < y",
"",
"def textStartsWith : Text → Text → Bool",
" | _, [] => true",
" | [], _ :: _ => false",
" | x :: xs, y :: ys => x == y && textStartsWith xs ys",
"",
"def isStrictlySorted : List Text → Bool",
" | [] => true",
" | [_] => true",
" | a :: b :: rest => textLt a b && isStrictlySorted (b :: rest)",
"",
"def insertUniqueSorted (x : Text) : List Text → List Text",
" | [] => [x]",
" | y :: ys =>",
" if x == y then y :: ys",
" else if textLt x y then x :: y :: ys",
" else y :: insertUniqueSorted x ys",
"",
"def sortUnique (xs : List Text) : List Text :=",
" xs.foldl (fun acc x => insertUniqueSorted x acc) []",
"",
"def joinComma : List Text → Text",
" | [] => []",
" | [x] => x",
" | x :: xs => x ++ [44, 32] ++ joinComma xs",
"",
"def disclosurePrefix : Text :=",
f" {_lean_cps(ASSUMED_STUB_DISCLOSURE_PREFIX)}",
"",
"def validStubList (present : Bool) (xs : List Text) : Bool :=",
" if !present then true",
" else !xs.isEmpty && xs.all (fun s => !isBlank s) && isStrictlySorted xs",
"",
"def validReceipt (v : Vector) : Bool :=",
" let listsOk := validStubList v.scopeHasField v.scopeStubs &&",
" validStubList v.cfgHasField v.cfgStubs",
" let stubItems := v.census.filter (fun c => c.hasStubReason)",
" let reasonsOk := stubItems.all (fun c => !isBlank c.stubReason)",
" let stubDefIds := stubItems.map (fun c => c.defId)",
" let notSelectedOk := stubItems.all (fun c => !c.selected) &&",
" v.selectedDefIds.all (fun id => !stubDefIds.contains id)",
" let censusStubPaths := sortUnique (stubItems.map (fun c => c.path))",
" let cfgSyncOk := v.cfgStubs == censusStubPaths",
" let scopeSubsetOk := v.scopeStubs.all (fun s => v.cfgStubs.contains s)",
" let disclosureOk :=",
" if v.cfgStubs.isEmpty then",
" v.assumptions.all (fun a => !textStartsWith a disclosurePrefix)",
" else",
f" let expected := disclosurePrefix ++ {_lean_cps(' (')} ++ joinComma v.cfgStubs ++ {_lean_cps(') are ')}",
" v.assumptions.any (fun a => textStartsWith a expected)",
" v.schemaVersion == 3 && listsOk && reasonsOk && notSelectedOk &&",
" cfgSyncOk && scopeSubsetOk && disclosureOk",
"",
"def vectors : List Vector := [",
",\n".join(entries),
"]",
"",
"def allMatch : Bool :=",
" vectors.all (fun v => validReceipt v == v.expectedValid)",
"",
"theorem assume_stub_vectors_conform : allMatch = true := rfl",
"",
"end ContractsTest.AssumeStub",
"",
]
return "\n".join(lines)
CONTRACT_REGISTRY: dict[
str,
tuple[
Callable[[dict[str, Any]], tuple[bool, list[str]]],
Callable[[Path], str],
],
] = {
"assume_stub": (evaluate_assume_stub_vector, render_assume_stub_lean_fixture),
}
def _resolve_safe_repo_path(
repo_root: Path,
rel_str: str,
*,
label: str = "path",
forbid_pass1: bool = False,
) -> tuple[Path | None, str | None]:
"""Validate `rel_str` is a non-symlink normalized repo-relative path."""
raw = rel_str.strip()
if not raw:
return None, f"{label} must be a normalized repo-relative path: `{rel_str}`"
p = PurePosixPath(raw)
if (
p.is_absolute()
or not p.parts
or ".." in p.parts
or "." in p.parts
or "\\" in raw
or raw.startswith("./")
or "/./" in raw
or raw.endswith("/.")
):
return None, f"{label} must be a normalized repo-relative path: `{rel_str}`"
repo_abs = repo_root.resolve()
# lstat-check every unresolved path component BEFORE resolve() so symlinks
# pointing elsewhere in-repo are rejected fail-closed.
cur = repo_abs
for part in p.parts:
cur = cur / part
if os.path.lexists(cur) and cur.is_symlink():
return None, f"{label} traverses a symlink: `{cur.relative_to(repo_abs).as_posix()}`"
cand = cur.resolve()
try:
rel_norm = cand.relative_to(repo_abs).as_posix()
except ValueError:
return None, f"{label} escapes repo root: `{rel_str}`"
if forbid_pass1 and (
rel_norm.startswith(("trusted/", "theory/", "correspondence/", "ci/", ".github/"))
or rel_norm in ("trusted", "theory", "correspondence", "ci", ".github")
):
return (
None,
f"{label} must live outside trusted/theory/correspondence/ci/.github/: `{rel_norm}`",
)
return cand, None
def _resolve_safe_lean_fixture_path(repo_root: Path, lean_rel: str) -> tuple[Path | None, str | None]:
"""Validate `lean_rel` is a non-symlink repo-relative path outside trusted trees."""
return _resolve_safe_repo_path(
repo_root,
lean_rel,
label="generated_lean_fixture",
forbid_pass1=True,
)
def _strip_rust_comments_and_strings(src: str, *, strip_strings: bool = True) -> str:
"""Strip Rust comments and optionally replace string/char literals with spaces."""
out: list[str] = []
i = 0
n = len(src)
while i < n:
ch = src[i]
# Line comment.
if ch == "/" and i + 1 < n and src[i + 1] == "/":
i += 2
out.append(" ")
while i < n and src[i] != "\n":
out.append(" ")
i += 1
continue
# Nested block comment.
if ch == "/" and i + 1 < n and src[i + 1] == "*":
depth = 1
i += 2
out.append(" ")
while i < n and depth > 0:
if src[i] == "/" and i + 1 < n and src[i + 1] == "*":
depth += 1
out.append(" ")
i += 2
elif src[i] == "*" and i + 1 < n and src[i + 1] == "/":
depth -= 1
out.append(" ")
i += 2
else:
out.append("\n" if src[i] == "\n" else " ")
i += 1
continue
# Raw string literal: r#"..."#, br#"..."#, cr#"..."#.
prev_ident = i > 0 and (src[i - 1].isalnum() or src[i - 1] == "_")
if not prev_ident:
j = i
if src[j] in ("b", "c") and j + 1 < n and src[j + 1] == "r":
j += 1
if j < n and src[j] == "r":
k = j + 1
while k < n and src[k] == "#":
k += 1
if k < n and src[k] == '"':
hashes = k - (j + 1)
close = '"' + ("#" * hashes)
end = src.find(close, k + 1)
stop = (end + len(close)) if end != -1 else n
if strip_strings:
for c in src[i:stop]:
out.append("\n" if c == "\n" else " ")
else:
out.append(src[i:stop])
i = stop
continue
# Regular string / byte string / c-string literal.
if ch == '"' or (
not prev_ident and ch in ("b", "c") and i + 1 < n and src[i + 1] == '"'
):
start = i
if ch != '"':
i += 1
i += 1
while i < n:
if src[i] == "\\" and i + 1 < n:
i += 2
elif src[i] == '"':
i += 1
break
else:
i += 1
if strip_strings:
for c in src[start:i]:
out.append("\n" if c == "\n" else " ")
else:
out.append(src[start:i])
continue
# Char / byte literal (avoid consuming Rust lifetimes like `'a`).
if ch == "'" or (
not prev_ident and ch == "b" and i + 1 < n and src[i + 1] == "'"
):
start = i
q = i + 1 if ch == "b" else i
if q + 3 < n and src[q + 1] == "\\" and src[q + 2] != "\n":
end_q = q + 3
while end_q < n and src[end_q] not in ("'", "\n"):
end_q += 1
if end_q < n and src[end_q] == "'":
out.append(" " * (end_q + 1 - start) if strip_strings else src[start : end_q + 1])
i = end_q + 1
continue
elif q + 2 < n and src[q + 1] not in ("'", "\n") and src[q + 2] == "'":
out.append(" " * (q + 3 - start) if strip_strings else src[start : q + 3])
i = q + 3
continue
out.append(ch)
i += 1
return "".join(out)
def _strip_comments_preserve_strings(src: str, suffix: str) -> str:
"""Strip comments while preserving executable code and string literals."""
if suffix == ".rs":
return _strip_rust_comments_and_strings(src, strip_strings=False)
if suffix == ".py":
lines = src.splitlines(keepends=True)
try:
for tok in tokenize.generate_tokens(io.StringIO(src).readline):
if tok.type == tokenize.COMMENT:
sl, sc = tok.start
el, ec = tok.end
if sl == el and 1 <= sl <= len(lines):
line = lines[sl - 1]
nl = "\r\n" if line.endswith("\r\n") else ("\n" if line.endswith("\n") else "")
core = line[: len(line) - len(nl)] if nl else line
lines[sl - 1] = core[:sc] + (" " * (ec - sc)) + core[ec:] + nl
return "".join(lines)
except tokenize.TokenError:
return re.sub(r"#[^\n]*", "", src)
return src
ALLOWED_ACTIVE_TEST_CFGS: frozenset[str] = frozenset(
{
"cfg(test)",
'cfg(all(target_os="linux",target_arch="x86_64"))',
'cfg(all(target_arch="x86_64",target_os="linux"))',
}
)
def _extract_preceding_attrs(
clean_src: str, fn_start: int, code_src: str | None = None
) -> list[str]:
"""Return outer `#[...]` attribute bodies directly preceding `fn_start`."""
text_src = code_src if code_src is not None else clean_src
attrs: list[str] = []
pos = fn_start
while pos > 0:
while pos > 0 and clean_src[pos - 1].isspace():
pos -= 1
if pos == 0 or clean_src[pos - 1] != "]":
break
depth = 0
j = pos - 1
while j >= 0:
if clean_src[j] == "]":
depth += 1
elif clean_src[j] == "[":
depth -= 1
if depth == 0:
break
j -= 1
if depth != 0 or j == 0 or clean_src[j - 1] != "#":
break
attrs.append(text_src[j + 1 : pos - 1].strip())
pos = j - 1
attrs.reverse()
return attrs
def _enclosing_open_delims(clean_src: str, target_pos: int) -> list[tuple[int, str]]:
"""Return `(offset, delim)` for unmatched `{`/`(`/ `[` enclosing `target_pos`."""
closers = {"}": "{", ")": "(", "]": "["}
stack: list[tuple[int, str]] = []
for idx in range(target_pos):
ch = clean_src[idx]
if ch in ("{", "(", "["):
stack.append((idx, ch))
elif ch in closers and stack and stack[-1][1] == closers[ch]:
stack.pop()
return stack
def _enclosing_open_braces(clean_src: str, target_pos: int) -> list[int]:
"""Return positions of unmatched `{` characters enclosing `target_pos`."""
return [pos for pos, ch in _enclosing_open_delims(clean_src, target_pos) if ch == "{"]
def _extract_leading_outer_attrs(
clean_src: str, code_src: str, seg_start: int, limit: int
) -> list[str]:
"""Return outer `#[...]` attrs at the head of `[seg_start, limit)`."""
attrs: list[str] = []
p = seg_start
while p < limit:
while p < limit and clean_src[p].isspace():
p += 1
if p >= limit:
break
if clean_src.startswith("#![", p):
depth = 0
j = p + 2
while j < limit:
if clean_src[j] == "[":
depth += 1
elif clean_src[j] == "]":
depth -= 1
if depth == 0:
p = j + 1
break
j += 1
else:
break
continue
if clean_src.startswith("#[", p):
depth = 0
j = p + 1
while j < limit:
if clean_src[j] == "[":
depth += 1
elif clean_src[j] == "]":
depth -= 1
if depth == 0:
attrs.append(code_src[p + 2 : j].strip())
p = j + 1
break
j += 1
else:
break
continue
break
return attrs
def _extract_enclosing_item_attrs(
clean_src: str, code_src: str, brace_pos: int
) -> list[str]:
"""Return outer `#[...]` attributes gating the item/block opening at `brace_pos`."""
paren = 0
bracket = 0
j = brace_pos - 1
while j >= 0:
ch = clean_src[j]
if ch == ")":
paren += 1
elif ch == "(" and paren > 0:
paren -= 1
elif ch == "]":
bracket += 1
elif ch == "[" and bracket > 0:
bracket -= 1
elif paren == 0 and bracket == 0 and ch in (";", "{", "}"):
break
j -= 1
seg_start = j + 1
attrs = _extract_leading_outer_attrs(clean_src, code_src, seg_start, brace_pos)
attrs.extend(_extract_preceding_attrs(clean_src, brace_pos, code_src))
return attrs
def _iter_inner_attrs(clean_src: str, code_src: str) -> list[tuple[int, str]]:
"""Return `(offset, body)` for every `#![...]` inner attribute."""
out: list[tuple[int, str]] = []
idx = 0
n = len(clean_src)
while idx < n:
pos = clean_src.find("#![", idx)
if pos == -1:
break
depth = 0
j = pos + 2
while j < n:
if clean_src[j] == "[":
depth += 1
elif clean_src[j] == "]":
depth -= 1
if depth == 0:
out.append((pos, code_src[pos + 3 : j].strip()))
idx = j + 1
break
j += 1
else:
break
return out
def _is_disallowed_cfg_attr(attr_body: str) -> bool:
compact = re.sub(r"\s+", "", attr_body)
if not (compact.startswith("cfg(") or compact.startswith("cfg_attr(")):
return False
return compact not in ALLOWED_ACTIVE_TEST_CFGS
def _is_in_gated_or_macro_scope(
clean_src: str, code_src: str, fn_start: int
) -> bool:
"""Return True if `fn_start` is gated by `#![cfg]`, `#[cfg]` scope, or `macro_rules!`."""
fn_delims = _enclosing_open_delims(clean_src, fn_start)
fn_braces = [pos for pos, ch in fn_delims if ch == "{"]
for attr_pos, attr_body in _iter_inner_attrs(clean_src, code_src):
if not _is_disallowed_cfg_attr(attr_body):
continue
attr_braces = _enclosing_open_braces(clean_src, attr_pos)
if fn_braces[: len(attr_braces)] == attr_braces:
return True
for delim_pos, delim_ch in fn_delims:
prefix = clean_src[:delim_pos].rstrip()
if re.search(r"\bmacro_rules!\s+[A-Za-z_][A-Za-z0-9_]*$", prefix):
return True
if delim_ch == "{":
for attr in _extract_enclosing_item_attrs(clean_src, code_src, delim_pos):
if _is_disallowed_cfg_attr(attr):
return True
return False
def _has_active_rust_test(raw_src: str, sym: str | None = None) -> bool:
"""Return True iff `raw_src` defines an active unignored, ungated `#[test] fn`."""
code_src = _strip_rust_comments_and_strings(raw_src, strip_strings=False)
clean = _strip_rust_comments_and_strings(raw_src, strip_strings=True)
name_pat = re.escape(sym) if sym is not None else r"[A-Za-z_][A-Za-z0-9_]*"
fn_re = re.compile(
rf"(?:^|[\s;}}])(?:pub(?:\s*\([^)]*\))?\s+)?(?:async\s+)?fn\s+{name_pat}\s*\("
)
for m in fn_re.finditer(clean):
fn_start = m.start()
if clean[fn_start] in (";", "}") or clean[fn_start].isspace():
fn_start += 1
attrs = _extract_preceding_attrs(clean, fn_start, code_src)
has_test = False
disabled = False
for attr in attrs:
compact = re.sub(r"\s+", "", attr)
if compact == "test" or compact.endswith("::test"):
has_test = True
if (
compact == "ignore"
or compact.startswith("ignore=")
or compact.startswith("cfg(")
or compact.startswith("cfg_attr(")
or compact == "should_panic"
or compact.startswith("should_panic(")
or compact.startswith("should_panic=")
):
disabled = True
if has_test and not disabled and not _is_in_gated_or_macro_scope(clean, code_src, fn_start):
return True
return False
def _is_cargo_test_root(rel_posix: str) -> bool:
"""Return True iff `rel_posix` is a Cargo auto-discovered integration test root."""
parts = Path(rel_posix).parts
if len(parts) >= 2 and parts[-2] == "tests" and parts[-1].endswith(".rs"):
return True
if len(parts) >= 3 and parts[-3] == "tests" and parts[-1] == "main.rs":
return True
return False
def _rust_test_root_compiles_submodule(
root_path: Path, root_src: str, target_path: Path
) -> bool:
"""Return True iff `root_path` actively declares an ungated `mod` compiling `target_path`."""
code_src = _strip_rust_comments_and_strings(root_src, strip_strings=False)
clean = _strip_rust_comments_and_strings(root_src, strip_strings=True)
target_abs = target_path.resolve()
mod_re = re.compile(
r"(?:^|[\s;\}])(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;"
)
for m in mod_re.finditer(clean):
mod_start = m.start()
if clean[mod_start] in (";", "}") or clean[mod_start].isspace():
mod_start += 1
if _is_in_gated_or_macro_scope(clean, code_src, mod_start):
continue
attrs = _extract_preceding_attrs(clean, mod_start, code_src)
if any(_is_disallowed_cfg_attr(attr) for attr in attrs):
continue
explicit_path: str | None = None
for attr in attrs:
pm = re.match(r'^path\s*=\s*(?:r(#*)"([^"]+)"\1|"([^"]+)")$', attr)
if pm:
explicit_path = pm.group(2) if pm.group(2) is not None else pm.group(3)
mod_name = m.group(1)
candidates: list[Path] = []
if explicit_path is not None:
candidates.append((root_path.parent / explicit_path).resolve())
elif root_path.name in ("lib.rs", "main.rs", "mod.rs"):
candidates.append((root_path.parent / f"{mod_name}.rs").resolve())
candidates.append((root_path.parent / mod_name / "mod.rs").resolve())
else:
candidates.append((root_path.parent / root_path.stem / f"{mod_name}.rs").resolve())
candidates.append((root_path.parent / root_path.stem / mod_name / "mod.rs").resolve())
if target_abs in candidates:
return True
return False
def _is_python_skip_decorator(dec: ast.expr) -> bool:
target = dec.func if isinstance(dec, ast.Call) else dec
if isinstance(target, ast.Name):
leaf = target.id
elif isinstance(target, ast.Attribute):
leaf = target.attr
else:
return False
return leaf in {"skip", "skipIf", "skipUnless", "expectedFailure", "skipif"}
def _python_exec_code_and_active_test(src: str) -> tuple[str | None, bool, str | None]:
"""Parse Python source via `ast`, strip docstrings/comments, and check active `def test_*`."""
try:
tree = ast.parse(src)
except SyntaxError as exc:
return None, False, f"invalid Python syntax: {exc}"
docstring_spans: list[tuple[int, int, int, int]] = []
has_active_test = False
def _visit_body(body: list[ast.stmt], skipped_scope: bool) -> None:
nonlocal has_active_test
if (
body
and isinstance(body[0], ast.Expr)
and isinstance(body[0].value, ast.Constant)
and isinstance(body[0].value.value, str)
and body[0].end_lineno is not None
and body[0].end_col_offset is not None
):
docstring_spans.append(
(body[0].lineno, body[0].col_offset, body[0].end_lineno, body[0].end_col_offset)
)
for stmt in body:
if isinstance(stmt, ast.ClassDef):
cls_skipped = skipped_scope or any(
_is_python_skip_decorator(d) for d in stmt.decorator_list
)
_visit_body(stmt.body, cls_skipped)
elif isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
fn_skipped = skipped_scope or any(
_is_python_skip_decorator(d) for d in stmt.decorator_list
)
if stmt.name.startswith("test_") and not fn_skipped:
has_active_test = True
_visit_body(stmt.body, fn_skipped)
_visit_body(tree.body, False)
code_txt = _strip_comments_preserve_strings(src, ".py")
if docstring_spans:
lines = code_txt.splitlines(keepends=True)
for sl, sc, el, ec in docstring_spans:
for ln_no in range(sl, el + 1):
idx = ln_no - 1
if idx < 0 or idx >= len(lines):
continue
line = lines[idx]
has_nl = line.endswith("\n")
core_b = (line[:-1] if has_nl else line).encode("utf-8")
start_c = sc if ln_no == sl else 0
end_c = ec if ln_no == el else len(core_b)
start_c = max(0, min(start_c, len(core_b)))
end_c = max(start_c, min(end_c, len(core_b)))
masked = core_b[:start_c] + (b" " * (end_c - start_c)) + core_b[end_c:]
lines[idx] = masked.decode("utf-8", errors="ignore") + ("\n" if has_nl else "")
code_txt = "".join(lines)
return code_txt, has_active_test, None
def _is_registered_path(rel_posix: str, prefixes: list[str]) -> bool:
for pref in prefixes:
if pref.endswith("/"):
if rel_posix.startswith(pref):
return True
else:
if rel_posix == pref or rel_posix.startswith(pref + "/"):
return True
return False
def check_contract(repo_root: Path, policy_toml: Path, *, write_lean: bool = False) -> list[str]:
errors: list[str] = []
repo_abs = repo_root.resolve()
trusted_contracts_dir = (repo_abs / "ci" / "contracts").resolve()
if policy_toml.is_symlink() or not policy_toml.is_file():
return [f"missing or symlinked contract policy: {policy_toml}"]
try:
policy_toml.resolve().relative_to(trusted_contracts_dir)
except ValueError:
return [f"contract policy must live under ci/contracts/: {policy_toml}"]
try:
cfg = tomllib.loads(_read_regular_utf8(policy_toml))
except (ValueError, OSError, tomllib.TOMLDecodeError) as exc:
return [f"failed to load contract policy {policy_toml}: {exc}"]
meta = cfg.get("contract") or {}
name = str(meta.get("name") or "").strip()
if name != policy_toml.stem:
return [f"contract.name `{name}` does not match policy filename `{policy_toml.name}`"]
if name not in CONTRACT_REGISTRY:
return [f"[{name}] unregistered contract name (must register evaluator in CONTRACT_REGISTRY)"]
evaluator, lean_renderer = CONTRACT_REGISTRY[name]
identifiers = [str(x) for x in (meta.get("identifiers") or []) if str(x)]
if not identifiers:
return [f"[{name}] policy must declare non-empty identifiers"]
ident_re = _build_ident_regex(identifiers)
consumers = cfg.get("consumers") or []
exemptions = cfg.get("exemptions") or []
schema_cfg = cfg.get("schema") or {}
vectors_rel = str(meta.get("vectors_dir") or "").strip()
src_vectors_dir, vec_dir_err = _resolve_safe_repo_path(
repo_root, vectors_rel, label="vectors_dir", forbid_pass1=True
)
if vec_dir_err or src_vectors_dir is None:
return [f"[{name}] invalid vectors_dir: {vec_dir_err}"]
# 1. Validate valid and invalid vectors, exact expected_failure, and fields
# FIRST so malformed JSON or schema violations produce structured errors
# before Lean rendering runs.
valid_dir = src_vectors_dir / "valid"
invalid_dir = src_vectors_dir / "invalid"
valid_files = sorted(valid_dir.glob("*.json")) if valid_dir.is_dir() else []
invalid_files = sorted(invalid_dir.glob("*.json")) if invalid_dir.is_dir() else []
vector_errs_before = len(errors)
if not valid_files:
errors.append(f"[{name}] no valid vectors in {valid_dir}")
if not invalid_files:
errors.append(f"[{name}] no invalid vectors in {invalid_dir}")
rec_fields = list(schema_cfg.get("receipt_fields") or [])
def _check_per_vector_fields(vf: Path, vec: dict[str, Any]) -> None:
if vec.get("kind") == "receipt":
for fld in rec_fields:
if fld not in vec:
errors.append(f"[{name}] {vf.name}: receipt missing schema field `{fld}`")
for vf in valid_files:
try:
vec = json.loads(_read_regular_utf8(vf))
except (ValueError, OSError, json.JSONDecodeError) as exc:
errors.append(f"[{name}] failed to read valid vector {vf.name}: {exc}")
continue
if not isinstance(vec, dict):
errors.append(f"[{name}] valid vector {vf.name} root must be a JSON object")
continue
_check_per_vector_fields(vf, vec)
ok, reasons = evaluator(vec)
if not ok:
errors.append(f"[{name}] valid vector {vf.name} failed invariants: {reasons}")
for ivf in invalid_files:
try:
vec = json.loads(_read_regular_utf8(ivf))
except (ValueError, OSError, json.JSONDecodeError) as exc:
errors.append(f"[{name}] failed to read invalid vector {ivf.name}: {exc}")
continue
if not isinstance(vec, dict):
errors.append(f"[{name}] invalid vector {ivf.name} root must be a JSON object")
continue
_check_per_vector_fields(ivf, vec)
has_single = "expected_failure" in vec
has_multi = "expected_failures" in vec
if has_single and has_multi:
errors.append(
f"[{name}] invalid vector {ivf.name} must set only one of `expected_failure` or `expected_failures`"
)
continue
if has_multi:
raw_fails = vec.get("expected_failures")
if (
not isinstance(raw_fails, list)
or not raw_fails
or not all(isinstance(x, str) and x.strip() for x in raw_fails)
):
errors.append(
f"[{name}] invalid vector {ivf.name} `expected_failures` must be a non-empty list of non-blank strings"
)
continue
exp_fails = [x.strip() for x in raw_fails]
else:
raw_fail = vec.get("expected_failure")
if not isinstance(raw_fail, str) or not raw_fail.strip():
errors.append(
f"[{name}] invalid vector {ivf.name} missing required `expected_failure` or `expected_failures`"
)
continue
exp_fails = [raw_fail.strip()]
ok, reasons = evaluator(vec)
if ok:
errors.append(f"[{name}] invalid vector {ivf.name} unexpectedly passed invariants")
elif reasons != exp_fails:
errors.append(
f"[{name}] invalid vector {ivf.name} failed with {reasons}, expected {exp_fails!r}"
)
# 2. Generate or validate Lean fixture safely outside trusted/ and theory/.
lean_rel = str(meta.get("generated_lean_fixture") or "").strip()
if lean_rel and len(errors) == vector_errs_before:
lean_path, path_err = _resolve_safe_lean_fixture_path(repo_root, lean_rel)
if path_err:
errors.append(f"[{name}] {path_err}")
elif lean_path is not None:
try:
expected_lean = lean_renderer(src_vectors_dir)
except (ValueError, OSError, json.JSONDecodeError) as exc:
errors.append(f"[{name}] failed to render Lean fixture: {exc}")
expected_lean = None
if expected_lean is not None:
if write_lean:
lean_path.parent.mkdir(parents=True, exist_ok=True)
lean_path.write_text(expected_lean, encoding="utf-8")
elif not lean_path.is_file():
errors.append(f"[{name}] generated Lean fixture missing: {lean_rel}")
else:
try:
actual_lean = _read_regular_utf8(lean_path)
except (ValueError, OSError) as exc:
errors.append(f"[{name}] generated Lean fixture invalid: {exc}")
else:
if actual_lean != expected_lean:
errors.append(
f"[{name}] generated Lean fixture `{lean_rel}` drifted from JSON vectors "
"(run `python3 ci/check_contract_lockstep.py --write-lean`)"
)
# 2b. Verify any declared vector_mirrors match `vectors/{valid,invalid}`
# byte-for-byte (for isolated CI workspaces that do not mount `tests/`).
for mirror_rel in meta.get("vector_mirrors") or []:
m_path, m_err = _resolve_safe_repo_path(
repo_root, str(mirror_rel), label="vector_mirror", forbid_pass1=True
)
if m_err or m_path is None:
errors.append(f"[{name}] invalid vector_mirror `{mirror_rel}`: {m_err}")
continue
if not m_path.is_dir():
errors.append(f"[{name}] vector_mirror directory missing: `{mirror_rel}`")
continue
try:
expected_map = {
p.relative_to(src_vectors_dir).as_posix(): _read_regular_bytes(p)
for p in sorted(src_vectors_dir.rglob("*.json"))
}
actual_map = {
p.relative_to(m_path).as_posix(): _read_regular_bytes(p)
for p in sorted(m_path.rglob("*.json"))
}
except (ValueError, OSError) as exc:
errors.append(f"[{name}] vector_mirror `{mirror_rel}` read error: {exc}")
continue
if expected_map != actual_map:
missing = sorted(set(expected_map) - set(actual_map))
extra = sorted(set(actual_map) - set(expected_map))
changed = sorted(
k for k in (set(expected_map) & set(actual_map))
if expected_map[k] != actual_map[k]
)
errors.append(
f"[{name}] vector_mirror `{mirror_rel}` drifted from `{src_vectors_dir.relative_to(repo_abs).as_posix()}` "
f"(missing={missing}, extra={extra}, changed={changed})"
)
# 3. Verify consumer test entries exist (confined inside repo, non-symlink)
# and reference the contract.
registered_prefixes: list[str] = []
for c in consumers:
pref = str(c.get("path_prefix") or "").strip()
t_entry = str(c.get("test_entry") or "").strip()
if not pref:
errors.append(f"[{name}] consumer entry missing path_prefix")
continue
registered_prefixes.append(pref)
t_path, t_err = _resolve_safe_repo_path(
repo_root, t_entry, label=f"consumer `{pref}` test_entry"
)
if t_err or t_path is None:
errors.append(f"[{name}] {t_err}")
continue
if not t_path.is_file():
errors.append(f"[{name}] consumer `{pref}` test_entry does not exist: `{t_entry}`")
else:
try:
txt = _read_regular_utf8(t_path)
except (ValueError, OSError) as exc:
errors.append(f"[{name}] consumer `{pref}` test_entry read error: {exc}")
continue
if t_path.suffix == ".py":
py_code, has_py_test, py_err = _python_exec_code_and_active_test(txt)
if py_err is not None or py_code is None:
errors.append(f"[{name}] consumer `{pref}` test_entry `{t_entry}` {py_err}")
continue
code_txt = py_code
if not has_py_test:
errors.append(
f"[{name}] consumer `{pref}` test_entry `{t_entry}` lacks an active `def test_*`"
)
else:
code_txt = _strip_comments_preserve_strings(txt, t_path.suffix)
if t_path.suffix == ".rs":
if not _has_active_rust_test(txt):
errors.append(
f"[{name}] consumer `{pref}` test_entry `{t_entry}` lacks an active `#[test]`"
)
t_rel = t_path.relative_to(repo_abs).as_posix()
test_root_rel = str(c.get("test_root") or "").strip()
if not _is_cargo_test_root(t_rel) and not test_root_rel:
errors.append(
f"[{name}] consumer `{pref}` non-root Rust test_entry `{t_entry}` "
"must declare `test_root`"
)
elif test_root_rel:
r_path, r_err = _resolve_safe_repo_path(
repo_root, test_root_rel, label=f"consumer `{pref}` test_root"
)
if r_err or r_path is None:
errors.append(f"[{name}] {r_err}")
elif not r_path.is_file():
errors.append(
f"[{name}] consumer `{pref}` test_root does not exist: `{test_root_rel}`"
)
elif not _is_cargo_test_root(r_path.relative_to(repo_abs).as_posix()):
errors.append(
f"[{name}] consumer `{pref}` test_root `{test_root_rel}` "
"is not a Cargo integration test root"
)
else:
try:
root_txt = _read_regular_utf8(r_path)
except (ValueError, OSError) as exc:
errors.append(
f"[{name}] consumer `{pref}` test_root read error: {exc}"
)
else:
if not _rust_test_root_compiles_submodule(r_path, root_txt, t_path):
errors.append(
f"[{name}] consumer `{pref}` test_root `{test_root_rel}` "
f"does not actively compile `{t_entry}`"
)
if not ident_re.search(code_txt):
errors.append(
f"[{name}] consumer `{pref}` test_entry `{t_entry}` does not reference "
"any contract identifier in executable code"
)
req_vec_ref = str(c.get("required_vector_ref") or "").strip()
if req_vec_ref and req_vec_ref not in code_txt:
errors.append(
f"[{name}] consumer `{pref}` test_entry `{t_entry}` must load `{req_vec_ref}`"
)
if c.get("require_all_vector_stems"):
for vf in list(valid_files) + list(invalid_files):
if vf.name not in code_txt:
errors.append(
f"[{name}] consumer `{pref}` test_entry `{t_entry}` missing "
f"static embed for vector `{vf.name}`"
)
for idx, ex in enumerate(exemptions):
if not isinstance(ex, dict):
errors.append(f"[{name}] exemptions[{idx}] must be a table")
continue
pref = str(ex.get("path_prefix") or "").strip()
reason = str(ex.get("reason") or "").strip()
if not pref:
errors.append(f"[{name}] exemptions[{idx}] missing path_prefix")
continue
if not reason:
errors.append(f"[{name}] exemption `{pref}` missing non-empty reason")
continue
registered_prefixes.append(pref)
# 4. Verify capture property test file and required #[test] functions exist.
cap_props = cfg.get("capture_property_positions") or {}
prop_test = str(cap_props.get("test_entry") or "").strip()
req_syms = [str(s) for s in (cap_props.get("required_test_symbols") or []) if str(s).strip()]
if req_syms and not prop_test:
errors.append(
f"[{name}] capture_property_positions sets required_test_symbols without test_entry"
)
elif prop_test:
prop_path, prop_err = _resolve_safe_repo_path(
repo_root, prop_test, label="capture_property_positions.test_entry"
)
if prop_err or prop_path is None:
errors.append(f"[{name}] {prop_err}")
elif not prop_path.is_file():
errors.append(f"[{name}] capture_property_positions.test_entry missing: `{prop_test}`")
else:
prop_txt: str | None = None
try:
prop_txt = _read_regular_utf8(prop_path)
except (ValueError, OSError) as exc:
errors.append(f"[{name}] capture_property_positions.test_entry read error: {exc}")
if prop_txt is not None:
for sym in req_syms:
if not _has_active_rust_test(prop_txt, sym):
errors.append(
f"[{name}] active capture property test `#[test] fn {sym}` "
f"missing or disabled in `{prop_test}`"
)
# 5. Unregistered consumer scan across production code directories,
# pruning build-output trees (target/, .lake/, .anneal/, etc.).
for root_name in SCAN_ROOTS:
root_dir = repo_abs / root_name
if not root_dir.is_dir():
continue
for dirpath, dirnames, filenames in os.walk(root_dir, followlinks=False):
dirnames[:] = sorted(d for d in dirnames if d not in SCAN_SKIP_DIRS)
dpath = Path(dirpath)
for fname in sorted(filenames):
fpath = dpath / fname
if fpath.is_symlink() or not fpath.is_file():
continue
if fpath.suffix not in SCAN_EXTS:
continue
rel = fpath.relative_to(repo_abs).as_posix()
if (
"/tests/" in f"/{rel}"
or "_tests/" in rel
or rel.endswith("_test.py")
or rel.startswith("ci/test_")
):
continue
if _is_registered_path(rel, registered_prefixes):
continue
try:
txt = fpath.read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
if ident_re.search(txt):
errors.append(
f"[{name}] unregistered consumer `{rel}` references contract identifier "
f"(register it in ci/contracts/{name}.toml with a test_entry)"
)
return errors
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description="Check cross-consumer conformance contracts in lockstep")
ap.add_argument("--repo-root", default=str(REPO_ROOT))
ap.add_argument("--write-lean", action="store_true", help="Regenerate Lean data fixtures from JSON vectors")
args = ap.parse_args(argv)
repo_root = Path(args.repo_root).resolve()
cdir = repo_root / "ci" / "contracts"
if not cdir.is_dir():
print(f"ERROR: contracts policy directory not found: {cdir}", file=sys.stderr)
return 1
all_errors: list[str] = []
seen_names: set[str] = set()
checked = 0
for policy_toml in sorted(cdir.glob("*.toml")):
checked += 1
seen_names.add(policy_toml.stem)
all_errors.extend(check_contract(repo_root, policy_toml, write_lean=args.write_lean))
for reg_name in sorted(CONTRACT_REGISTRY):
if reg_name not in seen_names:
all_errors.append(
f"[{reg_name}] registered contract policy missing: ci/contracts/{reg_name}.toml"
)
if checked == 0:
print("ERROR: no contract policies found under ci/contracts/", file=sys.stderr)
return 1
if all_errors:
for e in all_errors:
print(f"ERROR: {e}", file=sys.stderr)
return 1
print(f"check_contract_lockstep: OK ({checked} contract(s) verified)")
return 0
if __name__ == "__main__":
raise SystemExit(main())