#!/usr/bin/env python3 """Quality-gate step of the evidence tooling (STRA-252, S0.4). Offline, stdlib only, Python >= 3.9. Wraps scripts/quality/*, changes none. CLI v1 (fixed by the leaf): quality_step.py --baseline --candidate --record [--tolerance --basis ] [--lossy] exit 0 identical, or within a tolerance that carries its basis exit 1 differs (also: the session output fails the tool-call-integrity check); the record is NOT labelled non-lossy exit 2 a tolerance given without --basis, or any usage / input error (nothing is written) The result is written into the `quality` block of the S0.1 record (schema.json, validated by validate.py): {verdict, tolerance, basis, baseline, tool_call_integrity, experimental (only with --lossy, then true)} verdict is one of: identical | within recorded tolerance | differs. If --record does not exist, a fragment {"quality": {...}} is created. This step is called AFTER a FASTER verdict of a 30-pair series (round 5, BA D10), never inside a screening stage. Non-lossy check (the logs are port smoke logs, docs/quality-gate.md). Each kind of evidence that BOTH logs carry is compared: q_pair scripts/quality/q_pair.py LOG_A LOG_B by subprocess (needs forced rows): exit 0 = every common forced row bit-identical. r_chunk the `PREFILL-R first=F rows=N fnv1a64=H` lines (LELEKA_TRACE_PREFILL_R, executor_original_prompt.rs): the (first, rows, hash) sequence per `REPLAY-ARM start label=` arm (one sequence when the log has none) must be equal. greedy_ids the `DBG corpus N output ... : ids` lines (same parser as q_pair, q_lib.parse_port_log): the ids per (request, pass). At least one kind must be present in both logs, else exit 2. All present kinds equal -> identical. Tolerance x (needs --basis): the only measured quantity is q_pair's d_top1 over the differing rows. Verdict `within recorded tolerance` needs q_pair present, 0 argmax flips and max d_top1 <= x. An r_chunk difference alone is then accepted (a chunk-size change alters the rounding order, docs/prefill-throughput.md; its effect is what d_top1 measures); a greedy-id difference never is (the output changed). Hashes and ids have no measure, so without q_pair a difference is `differs` whatever x is. --lossy: the candidate log is the replay log of scripts/quality/q_tail_gate.py (arms = passes; --ref N is the reference pass, default 0), CAPTURE_DIR is --capture-dir (default: /capture), --control LOG2 is its run-to-run control. The gate runs by subprocess; its verdict, rule and figures go into tolerance / basis; the baseline log is recorded as identity only. The record is marked `experimental: true`. --tolerance is refused with --lossy (the gate's rule is fixed in q_tail_gate.py). Tool-call integrity (every block carries it): --candidate-session FILE (and optionally --baseline-session FILE) is the session output, either Responses-style JSON (output[] items: function_call with `arguments` that parse to an object, message content text) or plain text. Every Qwen `..` block must be well formed; with a baseline session the sequence of calls must equal the baseline's. Without a candidate session the result is verdict NOT_CHECKED (never PASS). A FAIL turns the verdict into `differs`. """ import argparse import hashlib import json import math import os import re import subprocess import sys HERE = os.path.dirname(os.path.abspath(__file__)) QUALITY_DIR = os.path.abspath(os.path.join(HERE, "..", "..", "quality")) V_IDENTICAL = "identical" V_WITHIN = "within recorded tolerance" V_DIFFERS = "differs" TEXT_LIMIT = 1800 class InputError(Exception): """A usage or input problem: exit 2, nothing written.""" # ---------------------------------------------------------------- small helpers def sha256_file(path): digest = hashlib.sha256() with open(path, "rb") as handle: for block in iter(lambda: handle.read(1 << 20), b""): digest.update(block) return digest.hexdigest() def sha256_text(text): return hashlib.sha256(text.encode("utf-8")).hexdigest() def clip(text, limit=TEXT_LIMIT): text = " ".join(text.split()) return text if len(text) <= limit else text[: limit - 3] + "..." def require_file(path, what): if not os.path.isfile(path): raise InputError("%s is not a file: %s" % (what, path)) def run_tool(script, args): """Run a scripts/quality tool by subprocess; return (exit code, stdout).""" path = os.path.join(QUALITY_DIR, script) require_file(path, script) proc = subprocess.run([sys.executable, path] + [str(a) for a in args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, errors="replace") return proc.returncode, proc.stdout, proc.stderr # ---------------------------------------------------------------- evidence kinds def parse_rchunks(path): """{arm label or None: [(first, rows, fnv1a64)]} from the PREFILL-R lines, split by `REPLAY-ARM start label=` lines.""" arms, current = {}, None with open(path, errors="replace") as handle: for line in handle: marker = re.search(r"REPLAY-ARM start label=(\S+)", line) if marker: current = marker.group(1) arms.setdefault(current, []) continue hit = re.search(r"PREFILL-R first=(\d+) rows=(\d+) fnv1a64=([0-9a-fA-F]+)", line) if hit: arms.setdefault(current, []).append((int(hit.group(1)), int(hit.group(2)), hit.group(3).lower())) return arms def parse_greedy(path): """{(request index, pass): [ids]} from the `DBG corpus N output ...` lines, by the parser q_pair uses.""" sys.path.insert(0, QUALITY_DIR) try: import q_lib except ImportError as exc: raise InputError("cannot import scripts/quality/q_lib.py: %s" % exc) finally: sys.path.pop(0) return {(run["index"], run["pass"]): run["output"] for run in q_lib.parse_port_log(path) if run["output"] is not None} def rchunk_reference(arms): lines = [] for label in sorted(arms, key=lambda x: "" if x is None else x): for first, rows, digest in arms[label]: lines.append("%s %d %d %s" % (label, first, rows, digest)) return sum(len(v) for v in arms.values()), sha256_text("\n".join(lines)) def greedy_reference(outputs): lines = ["%d:%d:%s" % (key[0], key[1], " ".join(str(i) for i in outputs[key])) for key in sorted(outputs)] return len(outputs), sha256_text("\n".join(lines)) def evidence_q_pair(baseline, candidate): code, out, err = run_tool("q_pair.py", [baseline, candidate]) if code == 2 and "no forced rows" in out: return {"kind": "q_pair", "status": "absent", "detail": "no forced rows in a log"} if code not in (0, 1): raise InputError("q_pair.py failed (exit %d): %s" % (code, clip(err or out, 300))) stats = re.search(r"common (\d+): identical (\d+), different (\d+), argmax flips (\d+)", out) if not stats: raise InputError("q_pair.py output not understood (log format drift?): %s" % clip(out, 300)) common, _, different, flips = (int(stats.group(i)) for i in range(1, 5)) dmax = None if different: found = re.search(r"d_top1 of the different rows: max (\S+?),", out) dmax = float(found.group(1)) if found else float("nan") return {"kind": "q_pair", "status": V_IDENTICAL if code == 0 else V_DIFFERS, "common": common, "different": different, "flips": flips, "d_top1_max": dmax, "exit": code, "detail": "q_pair exit %d: common forced rows %d, different %d, argmax flips %d%s" % ( code, common, different, flips, "" if dmax is None else ", max d_top1 %s" % dmax)} def evidence_rchunk(baseline, candidate): a, b = parse_rchunks(baseline), parse_rchunks(candidate) if not a or not b or not any(a.values()) or not any(b.values()): return {"kind": "r_chunk", "status": "absent", "detail": "no PREFILL-R lines in a log"} count, ref = rchunk_reference(b) same = a == b detail = "R-chunk fnv1a64 sequence: %d chunks, sha256 %s" % (count, ref[:16]) if not same: bad = None for label in sorted(set(a) | set(b), key=lambda x: "" if x is None else x): xs, ys = a.get(label, []), b.get(label, []) for index in range(max(len(xs), len(ys))): if index >= len(xs) or index >= len(ys) or xs[index] != ys[index]: bad = "arm %s chunk %d: baseline %s vs candidate %s" % (label, index, xs[index] if index < len(xs) else "-", ys[index] if index < len(ys) else "-") break if bad: break detail = "R-chunk sequences differ (%s)" % bad return {"kind": "r_chunk", "status": V_IDENTICAL if same else V_DIFFERS, "count": count, "sha256": ref, "detail": detail} def evidence_greedy(baseline, candidate): a, b = parse_greedy(baseline), parse_greedy(candidate) if not a or not b: return {"kind": "greedy_ids", "status": "absent", "detail": "no output id lines in a log"} count, ref = greedy_reference(b) same = a == b detail = "greedy ids: %d outputs, sha256 %s" % (count, ref[:16]) if not same: keys = sorted(set(a) | set(b)) bad = next(k for k in keys if a.get(k) != b.get(k)) detail = "greedy ids differ (request %d pass %d)" % bad return {"kind": "greedy_ids", "status": V_IDENTICAL if same else V_DIFFERS, "count": count, "sha256": ref, "detail": detail} def decide(evidence, tolerance): """(verdict, reasons) from the evidence list and the tolerance (or None).""" present = [e for e in evidence if e["status"] != "absent"] if not present: raise InputError("no comparable evidence: the logs share no q_pair forced rows, PREFILL-R lines or output id lines") differing = [e for e in present if e["status"] == V_DIFFERS] if not differing: return V_IDENTICAL, [] reasons = [e["detail"] for e in differing] if tolerance is None: return V_DIFFERS, reasons qp = next((e for e in present if e["kind"] == "q_pair"), None) if qp is None: return V_DIFFERS, reasons + ["tolerance cannot be evaluated: hashes and ids have no measure and q_pair has no forced rows"] if any(e["kind"] == "greedy_ids" for e in differing): return V_DIFFERS, reasons + ["greedy ids differ: the output changed, a tolerance does not cover it"] if qp["status"] == V_IDENTICAL: return V_WITHIN, reasons + ["q_pair rows identical (d_top1 0 <= %g)" % tolerance] if qp["common"] == 0: return V_DIFFERS, reasons + ["no common forced rows to measure"] if qp["flips"]: return V_DIFFERS, reasons + ["%d argmax flips: not covered by a d_top1 tolerance" % qp["flips"]] dmax = qp["d_top1_max"] if dmax is None or math.isnan(dmax): return V_DIFFERS, reasons + ["d_top1 of the differing rows is undefined"] if dmax > tolerance: return V_DIFFERS, reasons + ["max d_top1 %g exceeds tolerance %g" % (dmax, tolerance)] return V_WITHIN, reasons + ["max d_top1 %g <= tolerance %g" % (dmax, tolerance)] # ---------------------------------------------------------------- tool-call integrity TAG = re.compile(r"") FUNCTION = re.compile(r"\s*\s]+)>(.*)\s*\Z", re.S) PARAMETER = re.compile(r"\s]+)>\n?(.*?)\n?", re.S) def qwen_calls(text, malformed): """The calls of the `` blocks of a text as (name, ((parameter, value), ...)); problems go to malformed.""" calls, start, opened = [], 0, False for hit in TAG.finditer(text): if hit.group(0) == "": if opened: malformed.append("tool_call opened inside another one at offset %d" % hit.start()) opened, start = True, hit.end() continue if not opened: malformed.append("stray at offset %d" % hit.start()) continue opened = False body = text[start:hit.start()] func = FUNCTION.match(body) if not func: malformed.append("tool_call at offset %d has no well-formed ..." % (start - len(""))) continue inner = func.group(2) params = tuple((m.group(1), m.group(2)) for m in PARAMETER.finditer(inner)) if PARAMETER.sub("", inner).strip(): malformed.append("function %s has text or an unclosed parameter outside ..." % func.group(1)) continue calls.append((func.group(1), params)) if opened: malformed.append("unclosed at offset %d" % (start - len(""))) return calls def _collect_json(node, texts, calls, malformed): if isinstance(node, dict): if node.get("type") == "function_call": name, args = node.get("name"), node.get("arguments") try: parsed = json.loads(args) if isinstance(args, str) else args except ValueError: parsed = None if not isinstance(name, str) or not name or not isinstance(parsed, dict): malformed.append("function_call %r: arguments are not a JSON object" % (name,)) else: calls.append((name, tuple((k, json.dumps(v, sort_keys=True)) for k, v in sorted(parsed.items())))) return if node.get("type") in ("output_text", "text") and isinstance(node.get("text"), str): texts.append(node["text"]) return for value in node.values(): _collect_json(value, texts, calls, malformed) elif isinstance(node, list): for value in node: _collect_json(value, texts, calls, malformed) def session_calls(path): """(calls, malformed) of a session output file: Responses-style JSON or plain text.""" require_file(path, "session output") with open(path, encoding="utf-8", errors="replace") as handle: raw = handle.read() texts, calls, malformed = [], [], [] try: doc = json.loads(raw) except ValueError: doc = None if isinstance(doc, (dict, list)): _collect_json(doc, texts, calls, malformed) else: texts.append(raw) for text in texts: calls.extend(qwen_calls(text, malformed)) return calls, malformed def tool_call_integrity(candidate_session, baseline_session): if candidate_session is None: return {"verdict": "NOT_CHECKED", "reason": "no --candidate-session: no session output was supplied, so tool calls were not checked"}, True calls, malformed = session_calls(candidate_session) result = {"verdict": "PASS", "candidate_tool_calls": len(calls), "candidate_session_sha256": sha256_file(candidate_session), "calls_sha256": sha256_text(json.dumps(calls, sort_keys=True)), "matches_baseline": None} if malformed: result["verdict"], result["malformed"] = "FAIL", malformed[:10] if baseline_session is not None: base_calls, base_malformed = session_calls(baseline_session) result["baseline_tool_calls"] = len(base_calls) result["matches_baseline"] = base_calls == calls if base_calls != calls: result["verdict"] = "FAIL" result["mismatch"] = "tool-call sequence differs from the baseline session (%d vs %d calls)" % (len(calls), len(base_calls)) if base_malformed: result["baseline_malformed"] = base_malformed[:10] return result, result["verdict"] != "FAIL" # ---------------------------------------------------------------- the lossy class gate def lossy_gate(candidate, capture_dir, ref, control): if not os.path.isdir(capture_dir): raise InputError("--lossy needs the capture directory of the replay (req-*.json): %s is not a directory (use --capture-dir)" % capture_dir) args = [candidate, capture_dir, "--ref", ref] if control: require_file(control, "--control") args += ["--control", control] code, out, err = run_tool("q_tail_gate.py", args) verdicts = re.findall(r"VERDICT: (PASS|FAIL)", out) if code not in (0, 1) or not verdicts: raise InputError("q_tail_gate.py did not produce a verdict (exit %d): %s" % (code, clip(err or out, 300))) lines = [l.strip() for l in out.splitlines() if l.strip()] return code, lines # ---------------------------------------------------------------- record def read_record(path): if not os.path.exists(path): return {} try: with open(path, "r", encoding="utf-8") as handle: doc = json.load(handle) except (OSError, ValueError) as exc: raise InputError("record %s is not readable JSON: %s" % (path, exc)) if not isinstance(doc, dict): raise InputError("record %s is not a JSON object" % path) return doc def write_record(path, doc): tmp = "%s.tmp%d" % (path, os.getpid()) with open(tmp, "w", encoding="utf-8", newline="\n") as handle: json.dump(doc, handle, indent=2) handle.write("\n") os.replace(tmp, path) def baseline_identity(baseline, evidence): parts = ["log %s sha256 %s" % (os.path.basename(baseline), sha256_file(baseline))] parts.extend(item["detail"] for item in evidence if item["status"] != "absent") return clip("; ".join(parts)) def build_block(args): require_file(args.baseline, "--baseline") require_file(args.candidate, "--candidate") integrity, integrity_ok = tool_call_integrity(args.candidate_session, args.baseline_session) if args.lossy: code, lines = lossy_gate(args.candidate, args.capture_dir or os.path.join(os.path.dirname(os.path.abspath(args.candidate)), "capture"), args.ref, args.control) verdict = V_WITHIN if code == 0 else V_DIFFERS block = { "verdict": verdict, "tolerance": clip("q_tail_gate.py class gate: d_top1 p99 <= 0.22, max <= 0.43, flips <= 2.8% (Original envelope)" + ("; and each <= 1.25 x the run-to-run control" if args.control else "")), "basis": clip("q_tail_gate.py exit %d on %s: %s" % (code, os.path.basename(args.candidate), " | ".join(lines)), TEXT_LIMIT), "baseline": "log %s sha256 %s (identity only; the gate reference is pass %d of the replay log)" % ( os.path.basename(args.baseline), sha256_file(args.baseline), args.ref), "tool_call_integrity": integrity, "experimental": True, } else: evidence = [evidence_q_pair(args.baseline, args.candidate), evidence_rchunk(args.baseline, args.candidate), evidence_greedy(args.baseline, args.candidate)] verdict, reasons = decide(evidence, args.tolerance) given = args.tolerance is not None if verdict == V_IDENTICAL: tolerance = args.tolerance if given else 0 basis = args.basis if given else "exact comparison, no tolerance: " + "; ".join(e["detail"] for e in evidence if e["status"] != "absent") elif verdict == V_WITHIN: tolerance, basis = args.tolerance, args.basis else: tolerance = args.tolerance if given else "none recorded" basis = clip("; ".join(reasons) + ("" if not given else " (tolerance basis given: %s)" % args.basis)) block = {"verdict": verdict, "tolerance": tolerance, "basis": basis, "baseline": baseline_identity(args.baseline, evidence), "tool_call_integrity": integrity} if not integrity_ok and block["verdict"] != V_DIFFERS: block["verdict"] = V_DIFFERS block["basis"] = clip("tool-call integrity FAIL (%s); comparison was: %s" % (integrity.get("mismatch") or "; ".join(integrity.get("malformed", [])), block["basis"])) return block def parse_args(argv): parser = argparse.ArgumentParser(prog="quality_step.py", description="Write the non-lossy quality result of a baseline/candidate pair into an S0.1 record.") parser.add_argument("--baseline", required=True, help="baseline port smoke log") parser.add_argument("--candidate", required=True, help="candidate port smoke log (with --lossy: the replay log of q_tail_gate.py)") parser.add_argument("--record", required=True, help="S0.1 record to update (its quality block)") parser.add_argument("--tolerance", type=float, help="d_top1 tolerance (needs --basis)") parser.add_argument("--basis", help="text that justifies the tolerance") parser.add_argument("--lossy", action="store_true", help="route to the q_tail_gate.py class gate and mark the block experimental") parser.add_argument("--capture-dir", help="--lossy: capture directory of the replay (default: /capture)") parser.add_argument("--ref", type=int, default=0, help="--lossy: reference pass of the replay log") parser.add_argument("--control", help="--lossy: run-to-run control log for q_tail_gate.py") parser.add_argument("--candidate-session", help="session output of the candidate (Responses JSON or text) for the tool-call check") parser.add_argument("--baseline-session", help="session output of the baseline for the tool-call comparison") args = parser.parse_args(argv) if args.tolerance is not None and not (math.isfinite(args.tolerance) and args.tolerance >= 0): parser.error("--tolerance must be a finite number >= 0") if args.tolerance is not None and not (args.basis and args.basis.strip()): sys.stderr.write("error: --tolerance %g needs --basis (the reason the tolerance is acceptable)\n" % args.tolerance) sys.exit(2) if args.basis is not None and args.tolerance is None and not args.lossy: parser.error("--basis is the justification of a --tolerance; give both or neither") if args.lossy and args.tolerance is not None: parser.error("--tolerance is refused with --lossy: the class gate's rule is fixed in q_tail_gate.py") return args def main(argv): args = parse_args(argv) try: block = build_block(args) doc = read_record(args.record) existed = bool(doc) doc["quality"] = block write_record(args.record, doc) except InputError as exc: sys.stderr.write("error: %s\n" % exc) return 2 if not existed: sys.stderr.write("note: record did not exist or was empty: wrote a fragment holding only the quality block\n") print(json.dumps(block, indent=2)) code = 1 if block["verdict"] == V_DIFFERS else 0 print("verdict: %s (exit %d)" % (block["verdict"], code)) return code if __name__ == "__main__": sys.exit(main(sys.argv[1:]))