Skip to content
Merged
1,687 changes: 1,608 additions & 79 deletions src/inferrsi/harness/evaluator/_act_base/l0_gatekeeper.py

Large diffs are not rendered by default.

27 changes: 23 additions & 4 deletions src/inferrsi/harness/evaluator/_act_base/l0_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import os
import re
import subprocess
from bisect import bisect_right
from dataclasses import dataclass
from pathlib import Path

Expand Down Expand Up @@ -51,15 +52,33 @@ def changes_between(repo: Path, base: str, candidate: str) -> list[Change]:
HUNK = re.compile(rb"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)


def changed_lines(repo: Path, old_oid: str, new_oid: str) -> tuple[set[int], set[int]]:
@dataclass(frozen=True)
class LineChanges:
old: set[int]
new: set[int]
offsets: list[tuple[int, int]]

def prior_line(self, line: int) -> int | None:
if line in self.new:
return None
end = bisect_right(self.offsets, line, key=lambda row: row[0])
return line + self.offsets[end - 1][1]


def changed_lines(repo: Path, old_oid: str, new_oid: str) -> LineChanges:
old, new = set(), set()
offsets = [(1, 0)]
if old_oid != new_oid:
patch = git(repo, "diff", "--text", "--unified=0", "--inter-hunk-context=0",
"--no-color", "--no-ext-diff", "--no-textconv", old_oid, new_oid, "--")
for left, nleft, right, nright in HUNK.findall(patch):
old.update(range(int(left), int(left) + int(nleft or 1)))
new.update(range(int(right), int(right) + int(nright or 1)))
return old, new
left, nleft, right, nright = int(left), int(nleft or 1), int(right), int(nright or 1)
old.update(range(left, left + nleft))
new.update(range(right, right + nright))
# Git anchors empty ranges at the preceding line, including line zero.
old_end, new_end = left + max(1, nleft), right + max(1, nright)
offsets.append((new_end, old_end - new_end))
return LineChanges(old, new, offsets)


def blobs(repo: Path, object_ids):
Expand Down
11 changes: 11 additions & 0 deletions src/inferrsi/harness/evaluator/_act_base/l0_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,7 @@ def visit(node, prefix):
SUBMIT = re.compile(r"\b(?:(?:cuda|cu|hip|aclrt)\w*Async|(?:cuda|cu|hip|aclrt)LaunchKernel\w*|(?:cuda|cu|hip)GraphLaunch|aclmdlExecuteAsync|aclnn(?!\w*GetWorkspaceSize\b)\w+|nccl(?:All\w+|Reduce\w*|Broadcast|Send|Recv)|Hccl(?:All\w+|Reduce\w*|Broadcast|Send|Recv))\s*\(|<<<")
SET_STREAM = re.compile(r"\b(?:setCurrent(?:CUDA|NPU|HIP)Stream|cublasSetStream(?:_v2)?)\s*\(")
CREATE_STREAM = re.compile(r"\b(?:(?:cuda|cu|hip)StreamCreate\w*|aclrtCreateStream\w*)\s*\(")
CALLER_STREAM_PARAM = re.compile(r"\b(?:cudaStream_t|CUstream|hipStream_t|aclrtStream)\s+(?:const\s+)?(\w+)\b")
RESOURCE = re.compile(r"\b(?:get(?:NPU)?StreamFromPool|getCurrent(?:CUDA|NPU|HIP)Stream)\s*\(")
CONTROL_CPP = re.compile(r"\b(if(?:\s+constexpr)?|else|for|while|switch|catch|try|do)\b\s*")
CURRENT_CPP = re.compile(r"(?:\w+::)*getCurrent(?:CUDA|NPU|HIP)Stream\s*\(\s*\)")
Expand Down Expand Up @@ -542,6 +543,14 @@ def stream_ref(expr, pos):
flow.regions.append(Region(side, work[0][0], work[-1][1],
line_at(begin + 1 + guard.start()), deadline,
path=conditional(guard.start()), device=device))
header_text = clean[header_start:begin]
caller_stream_params = set(CALLER_STREAM_PARAM.findall(header_text))
single_caller_stream = (
next(iter(caller_stream_params))
if (len(caller_stream_params) == 1 and not guards and not current
and not flow.lifecycle and not SET_STREAM.search(body) and not RESOURCE.search(body))
else None
)
for submit in SUBMIT.finditer(body):
if submit.group() == "<<<":
args, _ = _arguments(body, submit.end(), ">>>")
Expand All @@ -556,6 +565,8 @@ def stream_ref(expr, pos):
device = ("npu" if api.startswith(("acl", "Hccl")) else "hip"
if api.startswith("hip") else "cuda")
side = stream_ref(side, submit.start())
if single_caller_stream and side == single_caller_stream:
continue
if not re.fullmatch(r"[a-zA-Z_]\w*(?:(?:\.|->)\w+)*", side):
continue
if not any(a < submit.start() < b and stream == side for a, b, stream in guarded):
Expand Down
2 changes: 2 additions & 0 deletions src/inferrsi/harness/evaluator/_l1_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ def _map_warn_rule_to_probe(rule_id: str) -> str | None:
return "graph_and_trace_attribution"
if rule_id in {"AUXILIARY_BENCHMARK_MODIFIED", "BUILD_TEST_SOURCE"}:
return "scope_attribution"
# Numeric reference checks do not establish sampling or exception fallback behavior.
# These, request contracts, and metric timing remain unmapped until matching probes exist.
return None


Expand Down
6 changes: 4 additions & 2 deletions src/inferrsi/harness/evaluator/_static_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@
REPORT_STATUSES = {"waiting", "rejected", "warning", "clear", "no_change"} | REFUSALS
_FAMILIES = {
"comparison": {"PY_MONKEY_PATCH_TIMING", "AUXILIARY_BENCHMARK_DEPENDENCY",
"AUXILIARY_BENCHMARK_MODIFIED", "BUILD_TEST_SOURCE"},
"precision": {"VALIDATION_REMOVED", "PY_NUMERIC_MODE", "BUILD_NUMERIC_FLAGS"},
"AUXILIARY_BENCHMARK_MODIFIED", "BUILD_TEST_SOURCE",
"PY_CONTRACT_MUTATION", "PY_METRICS_TIMING_TAMPER"},
"precision": {"VALIDATION_REMOVED", "PY_NUMERIC_MODE", "BUILD_NUMERIC_FLAGS",
"PY_SAMPLING_CONTRACT", "PY_SILENT_EXCEPT_FALLBACK"},
"scope": {"FORBIDDEN_PATH_MODIFIED", "OUT_OF_SCOPE_MODIFICATION"},
"syntax": {"SYNTAX_ERROR"},
"runtime": {"PY_FORBIDDEN_DYNAMIC", "PY_RUNTIME_CODE"},
Expand Down
49 changes: 44 additions & 5 deletions tests/apps/test_managed_pre_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ def tracked_downstream(root, pending, deadline):

# 1) A+B candidate with L0 BLOCK -> immediate FAIL, 0 L1 calls, 0 downstream calls, 1 round.
(repo / "kernels/reduce.cu").write_text(
"__global__ void k(int seq_len) { if (seq_len == 463) {} }\n", encoding="utf-8"
"__global__ void k(int seq_len) { if (seq_len == 463) { return; } }\n", encoding="utf-8"
)
(repo / "models/layer.py").write_text("def forward(x):\n return x + 1\n", encoding="utf-8")
assert main([
Expand All @@ -347,14 +347,32 @@ def tracked_downstream(root, pending, deadline):
assert r1["latest_observation"]["assessment"]["verdict"] == "FAIL"
assert not l1_calls and not downstream_calls
att1 = sess / r1["latest_observation"]["path"]
rep1 = json.loads((att1 / "pre_check_report.json").read_bytes())
report_path = att1 / "pre_check_report.json"
report_bytes = report_path.read_bytes()
rep1 = json.loads(report_bytes)
assert set(rep1) == {"candidate_pre_check", "verdict", "feedback"}
assert rep1["candidate_pre_check"] == "l1" and rep1["verdict"] == "FAIL"
assert not (att1 / "static-check.json").exists()
assert not list(att1.glob("static-report-*.json"))
# Recover must still leave L1/downstream calls at zero.
assert main(["session", "recover", "--session", str(sess)]) == 0
attempt_id = r1["latest_observation"]["attempt_id"]
audit = _static_round.read_private_audit(sess, attempt_id)
l0_receipt = json.loads(_static_round.private_l0_handoff_path(sess, attempt_id).read_bytes())
assert audit["handoff"] == l0_receipt["handoff"]
assert audit["basis"] == "l0_reject" and audit["device_executed"] is False
assert "probe_receipt" not in audit
assert ("CPP_SHAPE_MAGIC_BRANCH", "BLOCK") in {
(finding["rule_id"], finding["severity"]) for finding in audit["handoff"]["findings"]
}

# Recover from retained evidence without rescanning or dispatching.
report_path.unlink()
with monkeypatch.context() as hook:
hook.setattr(
_static_round, "scan_handoff", lambda *a, **kw: pytest.fail("Must not rerun L0")
)
assert main(["session", "recover", "--session", str(sess)]) == 0
capsys.readouterr()
assert report_path.read_bytes() == report_bytes
assert not l1_calls and not downstream_calls

# 2) Python syntax error at L0 -> exact diagnostic in pre_check_report.json, 0 L1 calls.
Expand Down Expand Up @@ -658,7 +676,14 @@ def test_l1_probe_timeout_missing_assets_cleanup_and_recovery_service_and_ordina
root = campaign["root"]
repo = campaign["repo"]
(repo / "models/layer.py").write_text(
"CONFIG = {'version': 'r3-missing-assets', 'a': 80, 'b': 80, 'quality': 1}\n",
"CONFIG = {'version': 'r3-missing-assets', 'a': 80, 'b': 80, 'quality': 1}\n"
"def general(x):\n return (x * 2, None)\n"
"def fast(x):\n return (x + x, None)\n"
"def forward(x, num_tokens):\n"
" output = general(x)\n"
" if num_tokens in {16, 64}:\n"
" return fast(x)[0]\n"
" return output[0]\n",
encoding="utf-8",
)
r1 = call(campaign, "round", "--candidate", repo, "--hypothesis", "R3 missing assets")
Expand All @@ -670,6 +695,20 @@ def test_l1_probe_timeout_missing_assets_cleanup_and_recovery_service_and_ordina
assert row1["assessment"]["verdict"] == "PASS"
rep1_path = root / row1["path"] / "pre_check_report.json"
rep1_bytes = rep1_path.read_bytes()
attempt_id = row1["attempt_id"]
audit = _static_round.read_private_audit(root, attempt_id)
l0_receipt = json.loads(_static_round.private_l0_handoff_path(root, attempt_id).read_bytes())
assert audit["handoff"] == l0_receipt["handoff"]
assert ("PY_SHAPE_MAGIC_SET", "WARN") in {
(finding["rule_id"], finding["severity"]) for finding in audit["handoff"]["findings"]
}
assert audit["l1_plan"]["required_probes"] == ["L1_B", "shape_domain_sweep"]
probe_receipt = audit["probe_receipt"]
assert probe_receipt == json.loads((rep1_path.parent / _l1_worker.FINISHED).read_bytes())
assert probe_receipt["attempt_id"] == l0_receipt["attempt_id"] == attempt_id
assert probe_receipt["snapshot_id"] == l0_receipt["snapshot_id"]
assert probe_receipt["evidence"]["status"] == "missing_assets"
assert probe_receipt["evidence"]["device_executed"] is False

# Public summary.json, observation.json, and exported Dashboard HTML must not leak private data.
summary_raw = (root / "summary.json").read_text(encoding="utf-8")
Expand Down
Loading
Loading