Item 3: failed checks keep their evidence lines (verify, gate, unit record). done 3 / next 4 (dead code and seams)

This commit is contained in:
swaits committed 2026-11-23 12:22:51 -07:00
1 parent 23a7cc7aec
commit ed018a364c
8 files changed
+154 -24

No files matched your search

+11 -3
View File
@@ -165,16 +165,24 @@ def fit(lines, limit=MAX_LINES):
% (len(flat) - limit + 1)])
def shown_lines(r, evidence_lines, tail_lines):
"""The lines to show for one result: the evidence that identifies the failure first, then the last
lines of its output that the evidence did not already include."""
ev = [ln for ln in str(r.get("evidence") or "").splitlines() if ln.strip()][:evidence_lines]
tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip() and ln not in ev][-tail_lines:]
return ev + tail
def failure_lines(results, per_check=4, checks=4):
"""A short report of the blocking results: id, status, and the last lines of what they printed."""
"""A short report of the blocking results: id, status, the lines that identify each failure, then
the last lines of what it printed."""
from . import verify as V
out = []
bad = V.blocking(results)
for r in bad[:checks]:
head = "- %s [%s%s]" % (r["id"], r["status"], (": " + r["reason"]) if r.get("reason") else "")
out.append(head)
tail = [ln for ln in str(r.get("tail") or "").splitlines() if ln.strip()][-per_check:]
out += [" " + ln[:200] for ln in tail]
out += [" " + ln[:200] for ln in shown_lines(r, per_check, 1)]
if len(bad) > checks:
out.append("- and %d more failing" % (len(bad) - checks))
return out
+2 -2
View File
@@ -183,8 +183,8 @@ def enforced_results(c, project, deadline=None, default_timeout=60):
to = float(e.get("timeout_s") or default_timeout)
if deadline is not None:
to = min(to, deadline - time.time())
st, dur, tail = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0})
out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail,
st, dur, tail, ev = V.run_cmd(e["cmd"], project, to, e.get("expect") or {"exit": 0})
out.append(dict(base, status=st, duration_s=round(dur, 3), tail=tail, evidence=ev,
claim="enforced learning %s: %s" % (lid, e["cmd"])))
return out
+2 -1
View File
@@ -90,7 +90,8 @@ def release(project):
def save_state(project, contract_id, fp, results, deep_ids):
items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]}
items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:],
"evidence": r.get("evidence") or ""}
for r in results if r.get("tier") == "deep"]
st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids),
"ok": all(i["status"] in ("passed", "skipped", "not-applicable") for i in items), "items": items}
+2 -1
View File
@@ -374,7 +374,8 @@ def _decide(payload):
store.log_error("gate-deep", e)
failing = V.blocking(results)
if ds and ds["state"] == "failed" and ds["fresh"]:
failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"]} for i in ds["failed"]]
failing = failing + [{"id": i["id"], "status": "failed", "reason": "deep", "tail": i["tail"],
"evidence": i.get("evidence") or ""} for i in ds["failed"]]
miss = assure.missing(profile, c, project, results, errs, ds["state"] if ds else None)
if miss or failing:
+1 -1
View File
@@ -412,7 +412,7 @@ def latest_results(c, rows):
ever_failed.add(cid)
latest[cid] = {"item": r["item"], "id": cid, "status": st, "reason": r.get("reason"),
"duration_s": r.get("duration_s", 0.0), "mandatory": r.get("mandatory", True),
"tier": r.get("tier", "fast"), "ts": r.get("ts")}
"tier": r.get("tier", "fast"), "ts": r.get("ts"), "evidence": r.get("evidence") or ""}
for x in (c.get("checks") or []) + (c.get("invariants") or []):
if isinstance(x, dict) and x.get("id") and x["id"] not in latest:
latest[x["id"]] = {"item": "check", "id": x["id"], "status": "not-run",
+68 -16
View File
@@ -6,7 +6,7 @@ change selection is skipped (not affected by this change), or not-applicable whe
file it watches exists; an identical-inputs pass is skipped (reused: passed at <time>).
Nothing that did not run is ever reported as passed, on any path.
"""
import hashlib, json, os, signal, subprocess, time
import hashlib, json, os, re, signal, subprocess, time
from fnmatch import fnmatch
from pathlib import PurePosixPath
@@ -21,16 +21,65 @@ def _tail(s):
return s[-TAIL:] if len(s) > TAIL else s
EVIDENCE_LINES = 60 # at most this many lines of evidence per failed check
EVIDENCE_CHARS = 3000
EVIDENCE_LINE = 300 # and each line is cut here
EDGE = 30 # unknown output: this many lines from the start and from the end
# What names a failure in each known runner's output. A line that matches is kept, with the few lines
# after it that carry the assertion or the panic message.
_RUNNERS = (
("unittest", re.compile(r"^(FAIL|ERROR): \S+ \(.+\)"), re.compile(r"^\s*(\w+\.)*\w*(Error|Exception|Failure)\b.*|^\s+self\.assert\w+\(.*")),
("pytest", re.compile(r"^(FAILED|ERROR) \S+|^_{3,} .+ _{3,}$"), re.compile(r"^E\s+.*|^\S+:\d+: \w+")),
("cargo test", re.compile(r"^test \S+ \.\.\. FAILED$|^---- \S+ stdout ----$"), re.compile(r"^thread '.*' panicked at.*|^\s+(left|right):.*|^assertion .*")),
("go test", re.compile(r"^\s*--- FAIL: \S+"), re.compile(r"^\s+\S+\.go:\d+:.*|^\s+(expected|actual|got|want).*|^panic: .*")),
("jest", re.compile(r"^\s*● .+ › .+|^FAIL \S+"), re.compile(r"^\s*(expect\(|Expected|Received).*|^\s*(\w*Error):? .*")),
)
def _clip(lines):
out, chars = [], 0
for ln in lines:
ln = ln.rstrip()[:EVIDENCE_LINE]
chars += len(ln) + 1
if len(out) >= EVIDENCE_LINES or chars > EVIDENCE_CHARS:
break
out.append(ln)
return out
def evidence(text):
"""The lines that identify a failure, scrubbed of secrets and bounded in size. For output of a known
test runner (unittest, pytest, cargo test, go test, jest): each failing test's name line and the
assertion lines after it. Otherwise the first and the last 30 lines. A runner prints its summary last,
so the tail alone loses the failing test; these lines are what the agent needs first."""
lines = [ln for ln in str(text or "").splitlines() if ln.strip()]
picked = []
for _name, head, detail in _RUNNERS:
if not any(head.match(ln) for ln in lines):
continue
for i, ln in enumerate(lines):
if head.match(ln):
picked.append(ln)
picked += [d for d in lines[i + 1:i + 40] if detail.match(d) and not head.match(d)][:3]
break
if not picked:
picked = lines if len(lines) <= 2 * EDGE else lines[:EDGE] + ["... (%d lines not shown)" % (len(lines) - 2 * EDGE)] + lines[-EDGE:]
from . import learning
return "\n".join(learning.scrub_secrets(ln) for ln in _clip(dict.fromkeys(picked)))
def run_cmd(cmd, cwd, timeout, expect):
"""Return (status, duration, tail). status: passed/failed/not-run (a timeout never ran to a verdict)."""
"""Return (status, duration, tail, evidence). status: passed/failed/not-run (a timeout never ran to a
verdict). `evidence` is empty unless the check failed or timed out."""
t0 = time.time()
if timeout <= 0:
return "not-run", 0.0, "not run: time budget exhausted"
return "not-run", 0.0, "not run: time budget exhausted", ""
try:
p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL, start_new_session=True)
except OSError as e:
return "failed", 0.0, "could not start: %s" % e
return "failed", 0.0, "could not start: %s" % e, "could not start: %s" % e
try:
out, err = p.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
@@ -39,20 +88,21 @@ def run_cmd(cmd, cwd, timeout, expect):
except OSError:
pass
try:
p.communicate(timeout=5)
out, err = p.communicate(timeout=5)
except Exception:
pass
return "not-run", time.time() - t0, "timed out after %gs" % timeout
out = err = b""
seen = (out or b"").decode("utf-8", "replace") + "\n" + (err or b"").decode("utf-8", "replace")
return "not-run", time.time() - t0, "timed out after %gs" % timeout, evidence(seen)
dur = time.time() - t0
o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace")
tail = _tail(o + ("\n" if o and e else "") + e)
want = expect.get("exit", 0)
if p.returncode != want:
return "failed", dur, "exit %d, expected %d\n%s" % (p.returncode, want, tail)
return "failed", dur, "exit %d, expected %d\n%s" % (p.returncode, want, tail), evidence(o + "\n" + e)
sc = expect.get("stdout_contains")
if sc is not None and sc not in o:
return "failed", dur, "stdout does not contain %r\n%s" % (sc, tail)
return "passed", dur, tail
return "failed", dur, "stdout does not contain %r\n%s" % (sc, tail), evidence(o + "\n" + e)
return "passed", dur, tail, ""
def tree_fp(project, contract_path):
@@ -200,16 +250,16 @@ def _run_item(item, x, tier, project, deadline, default_timeout):
"tier": tier, "mandatory": x.get("mandatory", True), "independent": bool(x.get("independent", False)),
"covers": x.get("covers"), "reason": None, "saved_s": 0.0}
if x.get("rung") in (5, 6):
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="")
r.update(status="not-run", reason="needs human", duration_s=0.0, tail="", evidence="")
else:
to = float(x.get("timeout_s", default_timeout))
if deadline is not None:
to = min(to, deadline - time.time())
st, dur, tail = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
st, dur, tail, ev = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0}))
reason = None
if st == "not-run":
reason = "timed out" if tail.startswith("timed out") else tail.removeprefix("not run: ")
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail)
r.update(status=st, reason=reason, duration_s=round(dur, 3), tail=tail, evidence=ev)
return r
@@ -217,7 +267,7 @@ def _not_run_result(base_item, x, tier, status, reason, saved=0.0):
return {"item": base_item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"),
"claim": x.get("claim"), "tier": tier, "mandatory": x.get("mandatory", True),
"independent": bool(x.get("independent", False)), "covers": x.get("covers"),
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "saved_s": round(saved, 3)}
"status": status, "reason": reason, "duration_s": 0.0, "tail": "", "evidence": "", "saved_s": round(saved, 3)}
def run(c, project, deadline=None, default_timeout=60, tiers=("fast",), changed=None, reuse=True,
@@ -326,7 +376,7 @@ def record(c, project, results, fp=None):
"seen_failing": bool(r.get("seen_failing")), "mandatory": r.get("mandatory", True),
"independent": bool(r.get("independent", False)), "covers": r.get("covers"),
"tool": store.tool(), "session": store.session_id(), "run": run_id,
"tier": r.get("tier", "fast"), "fp": fp})
"tier": r.get("tier", "fast"), "fp": fp, "evidence": r.get("evidence") or ""})
return run_id
@@ -340,13 +390,15 @@ def format_table(results):
def failure_report(results, limit=4000):
"""What failed and why: the lines that identify each failure first, then the last lines of the output."""
from . import assure
parts = []
bad = {id(r) for r in blocking(results)} | {id(r) for r in results if r["status"] == "failed"}
for r in results:
if id(r) in bad:
label = r["status"] + ((": " + r["reason"]) if r.get("reason") else "")
parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], label, r.get("claim") or "",
"\n".join(" " + l for l in (r["tail"] or "").splitlines()[-15:])))
"\n".join(" " + l for l in assure.shown_lines(r, 20, 5))))
s = "\n".join(parts)
return s if len(s) <= limit else s[:limit] + "\n... (truncated)"
+10
View File
@@ -528,6 +528,16 @@ class FlowTests(GateBase):
self.assertEqual(a, "block")
self.assertIn("bad", msg)
def test_the_send_back_shows_the_failing_test_not_only_the_end_of_the_output(self):
"""R-5.6-1, R-5.6-4: the failure printed 300 lines above the end of the output is in the gate's message."""
cmd = ("echo 'FAIL: test_needle (mod.T.test_needle)'; echo 'AssertionError: needle missing'; "
"for i in $(seq 1 300); do echo \"summary $i\"; done; exit 1")
self.write_contract(contract([check("t", cmd)]) | {"risk": {"profile": "isolated"}})
a, msg = self.call()
self.assertEqual(a, "block")
self.assertIn("FAIL: test_needle (mod.T.test_needle)", msg)
self.assertIn("AssertionError: needle missing", msg)
def test_a_check_over_the_budget_is_reported_not_passed(self):
"""R-15-5: a check that cannot finish in time is not-run, never passed."""
with open(os.path.join(self.tmp, "cfg"), "w"):
+58
View File
@@ -2,6 +2,64 @@ import json, unittest
from support import *
class EvidenceTests(SisiCase):
"""R-5.6-1, R-5.6-4: a failed check keeps the lines that identify the failure, not only the tail of its output."""
NOISE = "for i in $(seq 1 300); do echo \"summary noise $i\"; done"
def test_a_failure_300_lines_above_the_end_is_in_the_stored_result_and_the_report(self):
cmd = "echo 'FAIL: test_alpha (mod.T.test_alpha)'; echo 'AssertionError: 1 != 2'; %s; exit 1" % self.NOISE
r = self.sisi("verify") if self.write_contract(contract([check("t", cmd)])) is None else None
self.assertEqual(r.returncode, 1)
row = [x for x in self.results() if x["check"] == "t"][0]
self.assertEqual(row["status"], "failed")
self.assertIn("FAIL: test_alpha (mod.T.test_alpha)", row["evidence"])
self.assertIn("AssertionError: 1 != 2", row["evidence"])
self.assertLess(len(row["evidence"]), 3100)
shown = r.stdout[r.stdout.index("FAILED:"):]
self.assertIn("test_alpha", shown)
self.assertLess(shown.index("test_alpha"), shown.index("summary noise 300"))
def test_each_known_runner_keeps_its_failing_test_names(self):
from sisi import verify as V
outputs = {
"unittest": ("FAIL: test_a (m.T.test_a)\n----\nTraceback\nAssertionError: x\n" + "ok\n" * 200 + "FAILED (failures=1)", "test_a (m.T.test_a)"),
"pytest": ("_____ test_b _____\nE assert 1 == 2\n" + "x\n" * 200 + "FAILED tests/t.py::test_b - assert 1 == 2", "tests/t.py::test_b"),
"cargo": ("test tests::c ... FAILED\n---- tests::c stdout ----\nthread 'tests::c' panicked at src/l.rs:1:1:\n" + "x\n" * 200 + "test result: FAILED", "tests::c"),
"go": ("--- FAIL: TestD (0.00s)\n d_test.go:9: want 1 got 2\n" + "x\n" * 200 + "FAIL\tpkg", "TestD"),
"jest": (" ● suite › case e\n Expected: 1\n Received: 2\n" + "x\n" * 200 + "Tests: 1 failed", "case e"),
}
for name, (text, want) in outputs.items():
with self.subTest(name):
ev = V.evidence(text)
self.assertIn(want, ev)
self.assertNotIn("\nx\nx\nx", ev)
def test_unknown_output_keeps_the_first_and_last_30_lines_bounded_and_scrubbed(self):
from sisi import verify as V
text = "\n".join(["line %d" % i for i in range(1, 401)] + ["password=hunter2hunter2"])
ev = V.evidence(text)
self.assertIn("line 1\n", ev + "\n")
self.assertIn("line 30\n", ev + "\n")
self.assertNotIn("line 31\n", ev + "\n")
self.assertIn("line 400", ev)
self.assertNotIn("hunter2", ev)
self.assertLessEqual(len(V.evidence("y" * 100000)), V.EVIDENCE_CHARS)
def test_a_timeout_keeps_what_it_had_printed(self):
c = contract([check("slow", "echo 'FAIL: test_slow (m.T.test_slow)'; sleep 5", timeout_s=0.5)])
self.write_contract(c)
self.sisi("verify")
row = [x for x in self.results() if x["check"] == "slow"][0]
self.assertEqual(row["status"], "not-run")
self.assertIn("test_slow", row["evidence"])
def test_a_passing_check_stores_no_evidence(self):
self.write_contract(contract([check("ok", "echo fine; test -d .")]))
self.sisi("verify")
self.assertEqual([x["evidence"] for x in self.results() if x["check"] == "ok"], [""])
class VerifyTests(SisiCase):
def run_verify(self, c, *extra):
self.write_contract(c)