#!/usr/bin/env python3 """Agreement gate of the request-end prefix checkpoints (docs/prefix-cache.md, "Request-end checkpoints"). Input: the full log of the replay smoke run with LELEKA_REPLAY_FORCE=1, LELEKA_TRACE_LOGPROBS=16, LELEKA_BRINGUP_TRACE=1 and LELEKA_REPLAY_ARMS=G=off,P=prompt,R=reply (arm index = "pass" of the corpus markers), and the capture directory the replay read. Every request of every arm decodes along the same recorded path; arm G (grid nodes only: the exact full read) is the reference. For each other arm the per-position deviation of the top-16 log-probabilities is summarised. Two yardsticks: * the Original's own envelope (docs/quality-gate.md section 1), measured on ~100-token prompts: d_top1 p99 <= 0.22, max <= 0.43, flips <= 2.8 %; * with `--control LOG`, the same measurement for a change that is NOT a checkpoint: the grid-only path with another chunk cut (a second replay run with LELEKA_REPLAY_CAPACITY changed, one arm G). A tail arm that deviates no more than that is within the rounding noise of any chunk-cut change (the prompt cells it resumes from were computed with other chunk boundaries), whatever the context length. Rule: p99, max and flip rate each <= 1.25 x the control's. Offline analysis only; no runtime use. usage: q_tail_gate.py REPLAY_LOG CAPTURE_DIR [--ref N] [--control LOG2] """ import glob, json, math, os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import q_lib TOL = {"d_top1_p99": 0.22, "d_top1_max": 0.43, "flip_rate": 0.028} SLACK = 1.25 def load_truth(capture_dir): truths = [] for path in sorted(glob.glob(os.path.join(capture_dir, "req-*.json"))): doc = json.load(open(path)) truths.append((doc["prompt_ids"], doc["generated_ids"])) return truths def forced_runs(log): by = {} for run in q_lib.parse_port_log(log): if run["forced"]: by.setdefault(run["index"], {})[run["pass"]] = run return by def deviations(ref_by, ref_pass, oth_by, oth_pass, truths): rows = [] for n, arms in sorted(ref_by.items()): other = oth_by.get(n, {}) if ref_pass not in arms or oth_pass not in other or n >= len(truths): continue prompt, generated = truths[n] path = list(prompt) + list(generated) ref = q_lib.valid_rows(arms[ref_pass]["windows"], path) oth = q_lib.valid_rows(other[oth_pass]["windows"], path) for r in q_lib.compare(ref, oth, first_pos=len(prompt) - 1): r["case"] = n rows.append(r) return rows def describe(name, rows): s = q_lib.summary(rows) rate = s["flips"] / s["n"] if s["n"] else float("nan") print(f"\n{name}: rows {s['n']}") print(f" d_top1 median {s['d_top1']['median']:.4f} p99 {s['d_top1']['p99']:.4f} max {s['d_top1']['max']:.4f}") print(f" dmax16 median {s['dmax']['median']:.4f} p99 {s['dmax']['p99']:.4f} max {s['dmax']['max']:.4f}") print(f" argmax flips {s['flips']} ({100 * rate:.2f}%)") return s, rate def main(): args = sys.argv[1:] opts = {} for flag in ("--ref", "--control"): if flag in args: i = args.index(flag) opts[flag] = args[i + 1] del args[i:i + 2] ref_pass = int(opts.get("--ref", 0)) log, capture = args[0], args[1] truths = load_truth(capture) by = forced_runs(log) passes = sorted({p for d in by.values() for p in d}) print(f"requests with rows: {len(by)} of {len(truths)}; arms (passes): {passes}; reference pass {ref_pass}") control = None if "--control" in opts: control_rows = deviations(by, ref_pass, forced_runs(opts["--control"]), 0, truths) control = describe("CONTROL (grid-only, another chunk cut) vs reference", control_rows) verdict = True for other in passes: if other == ref_pass: continue s, rate = describe(f"arm pass {other} vs reference", deviations(by, ref_pass, by, other, truths)) envelope = s["n"] > 0 and s["d_top1"]["p99"] <= TOL["d_top1_p99"] and s["d_top1"]["max"] <= TOL["d_top1_max"] and rate <= TOL["flip_rate"] print(f" Original envelope (p99 <= {TOL['d_top1_p99']}, max <= {TOL['d_top1_max']}, flips <= {100 * TOL['flip_rate']:.1f}%): {'within' if envelope else 'outside'}") ok = envelope if control: cs, crate = control ok = s["n"] > 0 and all([s["d_top1"]["p99"] <= SLACK * cs["d_top1"]["p99"], s["d_top1"]["max"] <= SLACK * cs["d_top1"]["max"], rate <= SLACK * crate]) print(f" against the control (x{SLACK}): {'within' if ok else 'worse'}") verdict = verdict and ok print(" VERDICT:", "PASS" if ok else "FAIL") sys.exit(0 if verdict else 1) if __name__ == "__main__": main()