#!/usr/bin/env python3 """Summarize collapse_sim.py runs: hit ratio and median time to first token per 30 s window, sessions in the system, resident working set against the KV pool, prefill computed per turn. python3 collapse_analyze.py runs/ctl runs/A runs/A2 runs/B --pool-tokens 68000 """ import argparse, json, statistics as st ap = argparse.ArgumentParser() ap.add_argument("prefixes", nargs="+") ap.add_argument("--pool-tokens", type=int, default=4250 * 16) ap.add_argument("--window", type=int, default=30) a = ap.parse_args() for p in a.prefixes: T = [t for t in map(json.loads, open(p + ".turns.jsonl")) if "error" not in t] M = [json.loads(l) for l in open(p + ".metrics.jsonl")] end = max(t["t"] for t in T) hit, ttft = [], [] for w in range(0, int(end) + 1, a.window): W = [t for t in T if w <= t["t"] < w + a.window] W1 = [t for t in W if t["k"] > 0] hit.append(round(100 * sum(t["cached"] for t in W1) / sum(t["prompt"] for t in W1)) if W1 else None) ttft.append(round(st.median(t["ttft"] for t in W), 2) if W else None) def phase(a0, a1): W = [t for t in T if a0 <= t["t"] < a1] mm = [m for m in M if a0 <= m["t"] < a1] if not W: return None ctx = st.mean(t["prompt"] for t in W) sess = st.mean(m["active"] for m in mm) return {"turns": len(W), "hit_pct": round(100 * sum(t["cached"] for t in W if t["k"] > 0) / max(1, sum(t["prompt"] for t in W if t["k"] > 0)), 1), "ttft_p50": round(st.median(t["ttft"] for t in W), 2), "turn_p50": round(st.median(t["lat"] for t in W), 2), "computed_per_turn": round(st.mean(t["prompt"] - t["cached"] for t in W)), "sessions_in_system": round(sess, 1), "queued_at_gate": round(st.mean(m["queued"] for m in mm), 1), "working_set_tokens": round(sess * ctx), "working_set_over_pool": round(sess * ctx / a.pool_tokens, 2)} print(json.dumps({"run": p, "hit_pct_per_window": hit, "ttft_p50_per_window": ttft, "before_burst_0_300": phase(0, 300), "burst_300_480": phase(300, 480), "after_burst_600_900": phase(600, 900), "end_900_1200": phase(900, 1200)}))