dp-zp-agent/test/rule_trace/run.py
2026-11-24 18:34:42 +01:00

235 lines
13 KiB
Python

"""Run a test set through the API and record, per question, the rules, the answer path and where it failed.
.venv/bin/python test/rule_trace/run.py --cases SET.json --out RESULTS.jsonl [--hours 4.25] [--resume]
[--only-failed OLD.jsonl] [--base http://localhost:8000]
[--filter REGEX] [--limit N]
Questions run one after another (nothing else may use the API meanwhile). Each row holds the static tags
(static_tags.py), the answer, the route of the backend (tools/answers/route_trace.py, read from
data/logs/answer_timings.jsonl), the checks and the failure point. The run stops after --hours and
continues with --resume. At the end (also after the time limit) a summary is printed and written next to
the results: RESULTS.summary.md (tables: report.py) and RESULTS.summary.json (counts).
--filter keeps the cases whose id, category, template or origin matches; --limit runs the first N.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
for path in (str(ROOT), str(Path(__file__).resolve().parent)):
if path not in sys.path:
sys.path.insert(0, path)
from scoring import check, failure_point, last_branch # noqa: E402
from static_tags import tags # noqa: E402
TIMINGS = ROOT / "data" / "logs" / "answer_timings.jsonl"
MORE = "Chceš vidieť ďalšie?"
def _env(name: str) -> str:
from tools.evaluation.gold_set import _env as env
return env(name)
def ask(base: str, question: str, engine: str, token: str | None) -> dict:
body = {"query": question, "engine": engine, **({"context_token": token} if token else {})}
request = urllib.request.Request(base.rstrip("/") + "/answer", data=json.dumps(body, ensure_ascii=False).encode(),
headers={"Content-Type": "application/json", "X-API-Key": _env("SEARCH_API_KEY")})
with urllib.request.urlopen(request, timeout=300) as response:
return json.load(response)
def trace_of(question: str, offset: int) -> dict:
"""The timing record of this question: the last line written after `offset` with its hash."""
digest = hashlib.sha256(question.strip().encode()).hexdigest()[:12]
try:
with TIMINGS.open("rb") as handle:
handle.seek(offset)
lines = handle.read().decode("utf-8", "ignore").splitlines()
except OSError:
return {}
for line in reversed(lines):
try:
row = json.loads(line)
except ValueError:
continue
if row.get("q") == digest:
return row
return {}
def diagnostics(result: dict) -> dict:
"""What the API itself says about the answer, compact: the name resolution, the evidence it stands on,
coverage and truncation, the options it offered and the data version (never the context token)."""
names = result.get("name_resolution") or {}
context = result.get("conversation_context") or {}
evidence = result.get("evidence") or []
return {
"accepted": result.get("accepted_for_delivery"), "complete": result.get("complete"),
"truncated": result.get("truncated"), "truncation_reasons": result.get("truncation_reasons") or [],
"names": {"status": names.get("status"), "reason": names.get("reason"), "resolved_query": names.get("resolved_query"),
"matches": [{k: m.get(k) for k in ("input", "name", "method")} for m in names.get("matches") or []]},
"coverage": result.get("answer_coverage"), "presentation_notes": result.get("presentation_notes") or [],
"claims": len(result.get("claims") or []), "evidence_count": len(evidence),
"evidence": [{k: e.get(k) for k in ("person", "source_path", "line", "kind", "work_label", "date")} for e in evidence[:8]],
"options": {k: [o.get("label") or o.get("name") or str(o)[:80] if isinstance(o, dict) else str(o)[:80] for o in v][:8]
for k, v in context.items() if k != "token" and isinstance(v, list)},
"data_version": {"index": (result.get("index_version") or {}).get("version"),
"knowledge": result.get("knowledge_version")},
"source_count": len(result.get("source_urls") or []),
}
def run_case(case: dict, base: str) -> dict:
token, result, steps = None, {}, []
started = time.time()
for question in [s.strip() for s in case["question"].split(" => ") if s.strip()]:
offset = TIMINGS.stat().st_size if TIMINGS.exists() else 0
t = time.time()
try:
result = ask(base, question, case["engine"], token)
except Exception as error: # a failed request is a failed case, never skipped
result = {"status": "request_error", "reason": repr(error)[:200], "answer": ""}
trace = trace_of(question, offset)
token = (result.get("conversation_context") or {}).get("token") or token
steps.append({"question": question, "status": result.get("status"), "reason": result.get("reason"),
"delivery": {k: (result.get("delivery_check") or {}).get(k) for k in ("layer", "code")},
"seconds": round(time.time() - t, 1), "route": trace.get("route") or [],
"notes": trace.get("notes") or {}, "parts": trace.get("steps") or {},
"model_calls": trace.get("model_calls"), "answer": (result.get("answer") or "")[:600],
**diagnostics(result)})
if result.get("status") == "request_error":
break
# A list shown in pages is read to its end with "áno", as a user would (and as the gold set does): its names
# on later pages are part of the answer.
pages = 1
while MORE in (result.get("answer") or "") and token and pages < 20 and result.get("status") != "request_error":
try:
more = ask(base, "áno", case["engine"], token)
except Exception:
break
token = (more.get("conversation_context") or {}).get("token") # no new token: the list has no further page
result = {**result, "answer": (result.get("answer") or "").replace(MORE, "") + "\n\n" + (more.get("answer") or ""),
"source_urls": list(dict.fromkeys([*(result.get("source_urls") or []), *(more.get("source_urls") or [])]))}
pages += 1
return {"result": result, "steps": steps, "seconds": round(time.time() - started, 1), "pages": pages}
def main(argv=None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--cases", required=True)
parser.add_argument("--out", required=True)
parser.add_argument("--base", default="http://localhost:8000")
parser.add_argument("--hours", type=float, default=4.25)
parser.add_argument("--resume", action="store_true")
parser.add_argument("--only-failed", help="results of an earlier run: ask again only its failed cases")
parser.add_argument("--filter", help="regex on id, category, template or origin")
parser.add_argument("--limit", type=int, help="only the first N cases (after the filter)")
args = parser.parse_args(argv)
cases = json.loads(Path(args.cases).read_text(encoding="utf-8"))["cases"]
if args.filter:
import re
pattern = re.compile(args.filter)
cases = [c for c in cases if any(pattern.search(str(c.get(k) or "")) for k in ("id", "category", "template", "origin"))]
if args.only_failed:
failed = {json.loads(l)["id"] for l in Path(args.only_failed).read_text(encoding="utf-8").splitlines()
if l.strip() and not json.loads(l)["pass"]}
cases = [c for c in cases if c["id"] in failed]
out = Path(args.out)
done = set()
if args.resume and out.exists():
# a question whose request failed (the API was down) is asked again
done = {r["id"] for r in map(json.loads, filter(str.strip, out.read_text(encoding="utf-8").splitlines()))
if r.get("status") != "request_error"}
deadline = time.time() + args.hours * 3600
todo = [c for c in cases if c["id"] not in done]
if args.limit:
todo = todo[:args.limit]
print(f"{len(todo)} otázok, limit {args.hours} h, výsledky: {out}", flush=True)
began, passed, broken = time.time(), 0, 0
with out.open("a" if args.resume else "w", encoding="utf-8") as handle:
for n, case in enumerate(todo, 1):
if time.time() > deadline:
print("Časový limit: zvyšok pokračuje s --resume.", flush=True)
break
static = tags(case["question"])
ran = run_case(case, args.base)
last = ran["steps"][-1] if ran["steps"] else {}
trace = {"route": last.get("route"), "notes": last.get("notes")}
checks = check(case, ran["result"])
point = failure_point(case, ran["result"], checks, trace)
row = {"id": case["id"], "engine": case["engine"], "category": case.get("category"),
"difficulty": case.get("difficulty"), "template": case.get("template"), "origin": case.get("origin"),
"question": case["question"], "pass": point is None, "failure_point": point,
"failed_checks": [k for k, v in checks.items() if not v], "branch": last_branch(last.get("route") or []),
"static": static, "seconds": ran["seconds"], "status": ran["result"].get("status"),
"reason": ran["result"].get("reason"),
"delivery": {k: (ran["result"].get("delivery_check") or {}).get(k) for k in ("layer", "code")},
"negative": bool(case.get("negative")), "compound": bool(case.get("compound")),
"expect": case.get("expect"), "answer": (ran["result"].get("answer") or "")[:2500],
"source_urls": (ran["result"].get("source_urls") or [])[:12], "pages": ran.get("pages", 1),
"steps": ran["steps"]}
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
handle.flush()
passed += row["pass"]
broken = broken + 1 if row["status"] == "request_error" else 0
if broken >= 5:
print("API neodpovedá (5 chýb spojenia za sebou): beh zastavený, po oprave pokračuj s --resume.", flush=True)
break
left = (time.time() - began) / n * (len(todo) - n) / 3600
print(f"{n:04d}/{len(todo)} {case['id']:<10} {case['engine']:<8} {'PASS' if row['pass'] else 'FAIL'} "
f"{ran['seconds']:>6}s spolu {passed}/{n} zostáva ~{left:.1f} h {(point or '')[:60]}", flush=True)
summarize(out)
return 0
def summarize(out: Path) -> None:
"""The pass rate and the tables of all rows written so far (also of earlier --resume runs)."""
from collections import Counter
from report import report
latest = {} # the last row of each question (a repeated request_error is replaced by its new answer)
for line in out.read_text(encoding="utf-8").splitlines():
if line.strip():
row = json.loads(line)
latest[row["id"]] = row
rows = list(latest.values())
if not rows:
return
ok = sum(r["pass"] for r in rows)
def rate(group):
return f"{sum(r['pass'] for r in group)}/{len(group)} ({100 * sum(r['pass'] for r in group) / max(1, len(group)):.0f} %)"
lines = ["", "=" * 72, f"VÝSLEDOK: prešlo {ok}, zlyhalo {len(rows) - ok}, spolu {len(rows)} "
f"({100 * ok / len(rows):.1f} %)", "=" * 72]
for title, key in (("nástroj", lambda r: r["engine"]), ("typ otázky", lambda r: "záporná" if r.get("negative")
else "zložená" if r.get("compound") else "kladná"), ("obťažnosť", lambda r: r.get("difficulty") or "-"),
("pôvod", lambda r: r.get("origin") or "-")):
groups: dict = {}
for r in rows:
groups.setdefault(key(r), []).append(r)
lines.append(f"{title:<12} " + " | ".join(f"{k}: {rate(v)}" for k, v in sorted(groups.items())))
places = Counter((r.get("failure_point") or "?").split(":")[0] for r in rows if not r["pass"])
statuses = Counter(f"{r.get('status')}/{r.get('reason') or (r.get('delivery') or {}).get('code') or '-'}"
for r in rows if not r["pass"])
lines += ["", "Kde zlyhalo (najčastejšie):"] + [f" {n:>5} {k}" for k, n in places.most_common(12)]
lines += ["", "Stav / dôvod zlyhaných:"] + [f" {n:>5} {k}" for k, n in statuses.most_common(10)]
lines += ["", f"Podrobné tabuľky: {out.with_suffix('.summary.md')}", f"Všetky záznamy: {out}"]
print("\n".join(lines), flush=True)
out.with_suffix(".summary.md").write_text(report(rows), encoding="utf-8")
out.with_suffix(".summary.json").write_text(json.dumps({
"cases": len(rows), "passed": ok, "failed": len(rows) - ok, "pass_rate": round(ok / len(rows), 4),
"failure_places": dict(places.most_common()), "failed_statuses": dict(statuses.most_common()),
"by_engine": {e: {"cases": len(g), "passed": sum(r["pass"] for r in g)} for e in {r["engine"] for r in rows}
for g in [[r for r in rows if r["engine"] == e]]}}, ensure_ascii=False, indent=1), encoding="utf-8")
if __name__ == "__main__":
raise SystemExit(main())