364 lines
18 KiB
Python
Executable File
364 lines
18 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Re-measure what the fresh-context nudge assumes (backend runs/fresh.py
|
||
``ASSUMPTIONS``, docs/fresh-context.md).
|
||
|
||
Walks the transcript archive (the lab's, the workers', the guests') and the
|
||
live ``projects/`` trees for a window (``--days`` or ``--since``) and prints:
|
||
|
||
* the prompt cache's behaviour vs. the gap since the session's last API call —
|
||
how much of the context is read from cache, the TTL tier the CLI writes, and
|
||
what the first call costs warm vs. cold;
|
||
* how many API calls are left in the conversation after a cold follow-up (its
|
||
own turn's included), the later turns, and how many of those come back cold —
|
||
overall and per follow-up size (the scenarios the reply box weighs). Turns a
|
||
conversation scheduled for itself (Send later ``--to .`` wakeups — ``ai-agent
|
||
plugin scheduled-conversations add``, ``ai-agent later`` before — no reply box,
|
||
no nudge) are counted apart;
|
||
* every *fresh* compaction the ai-agent ran (Fresh & send, Auto fresh): what
|
||
it cost and took, the context it left, how long the conversation went on,
|
||
what it actually saved against continuing and what the estimate promised.
|
||
|
||
Pure stdlib; run it after a model launch or a Claude Code release that may
|
||
change caching, and update ``ASSUMPTIONS`` (and FRESH_ASSUMPTIONS in
|
||
frontend/src/lib/freshContext.ts) when the figures move.
|
||
|
||
scripts/fresh-context-calibration.py --days 30
|
||
scripts/fresh-context-calibration.py --since 2026-10-30T20:08Z --json out.json
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import glob
|
||
import json
|
||
import os
|
||
import statistics as st
|
||
import time
|
||
from datetime import datetime
|
||
|
||
DATA = "~/homelab/services/ai-agent/data"
|
||
ROOTS = (f"{DATA}/transcripts", f"{DATA}/workers/transcripts", "~/.claude/projects",
|
||
"~/.claude-work/projects", "~/.claude-guests/*/projects")
|
||
# The scheduled-conversations plugin's store (the core's own, carried over
|
||
# and renamed `.migrated` on 2026-11-26, for the turns scheduled before).
|
||
SCHEDULED = (f"{DATA}/plugins/data/_hub/scheduled-conversations/scheduled.json",
|
||
f"{DATA}/scheduled.json.migrated", f"{DATA}/scheduled.json")
|
||
# USD / Mtok: input, output, cache read — the newest of each family.
|
||
RATES = {"opus": (4.0, 20.0, 0.20), "fable": (10.0, 50.0, 0.25),
|
||
"sonnet": (2.0, 10.0, 0.20), "haiku": (0.10, 0.50, 0.01)}
|
||
HAIKU_LONG = (100_000, 5.0)
|
||
# The follow-up sizes the reply box weighs (runs/fresh.py ``ASSUMPTIONS``):
|
||
# API calls left after a cold reply, [lo, hi).
|
||
SIZES = [("quick", 1, 5), ("typical", 5, 90), ("big", 90, float("inf"))]
|
||
GAPS = [(0, 60), (60, 300), (300, 600), (600, 1800), (1800, 3600), (3600, 7200),
|
||
(7200, 86400), (86400, float("inf"))]
|
||
# The ai-agent's own compaction (runs/fresh.py INSTRUCTIONS) starts so.
|
||
FRESH_MARK = "Write this summary so the work continues seamlessly"
|
||
# What the estimate assumed before this run (to score it against reality).
|
||
OLD = {"scenarios": [(3, 0.07, 0.0), (33, 0.75, 0.22), (139, 0.18, 0.61)],
|
||
"summaryTokens": 12_000, "compactInputShare": 0.75, "compactOutputTokens": 8_000}
|
||
|
||
|
||
def family(model: str | None) -> str | None:
|
||
return next((f for f in RATES if f in (model or "")), None)
|
||
|
||
|
||
def ts(s: str) -> float:
|
||
return datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()
|
||
|
||
|
||
def q(xs: list, p: float):
|
||
xs = sorted(xs)
|
||
return xs[min(len(xs) - 1, int(p * len(xs)))] if xs else 0
|
||
|
||
|
||
def text_of(r: dict) -> str | None:
|
||
"""A user turn someone (or something) typed — None for tool results,
|
||
meta records, compaction summaries and slash-command plumbing."""
|
||
if r.get("type") != "user" or r.get("isMeta") or r.get("isCompactSummary"):
|
||
return None
|
||
c = (r.get("message") or {}).get("content")
|
||
if isinstance(c, list):
|
||
if any(isinstance(b, dict) and b.get("type") == "tool_result" for b in c):
|
||
return None
|
||
c = " ".join(b.get("text", "") for b in c if isinstance(b, dict))
|
||
c = (c or "").lstrip()
|
||
if not c or (c.startswith("<") and not c.startswith("<ai-agent-from")):
|
||
return None
|
||
return c
|
||
|
||
|
||
def walk(path: str) -> dict:
|
||
"""One transcript's main thread: its API calls, typed prompts, compaction
|
||
boundaries (with the cost-state on either side) and Read tool calls."""
|
||
calls, seen, prompts, bounds, reads = [], set(), [], [], []
|
||
cost_state, command = None, None
|
||
for line in open(path, encoding="utf-8", errors="replace"):
|
||
try:
|
||
r = json.loads(line)
|
||
except ValueError:
|
||
continue
|
||
if r.get("isSidechain"):
|
||
continue
|
||
t = r.get("type")
|
||
content = r.get("content") if t == "queue-operation" else (r.get("message") or {}).get("content")
|
||
if isinstance(content, str) and ("/compact" in content[:40] or "<command-name>/compact<" in content):
|
||
command = content
|
||
if t == "system" and r.get("subtype") == "compact_boundary":
|
||
md = r.get("compactMetadata") or {}
|
||
bounds.append({"t": ts(r["timestamp"]), "trigger": md.get("trigger"),
|
||
"pre": md.get("preTokens"), "post": md.get("postTokens"),
|
||
"ms": md.get("durationMs"), "fresh": bool(command and FRESH_MARK in command),
|
||
"calls": len(calls), "before": cost_state, "after": None})
|
||
command = None
|
||
elif t == "cost-state" and isinstance(r.get("modelUsage"), dict):
|
||
cost_state = {"total": r.get("totalCostUSD") or 0.0, "mu": r["modelUsage"]}
|
||
b = bounds[-1] if bounds else None
|
||
if b and b["after"] is None and b["calls"] == len(calls):
|
||
b["after"] = cost_state
|
||
elif t == "assistant":
|
||
m = r.get("message") or {}
|
||
for blk in m.get("content") or []:
|
||
if isinstance(blk, dict) and blk.get("type") == "tool_use" and blk.get("name") == "Read":
|
||
reads.append((ts(r["timestamp"]), (blk.get("input") or {}).get("file_path")))
|
||
u, mid, fam = m.get("usage"), m.get("id"), family(m.get("model"))
|
||
if not u or not mid or mid in seen or not fam:
|
||
continue
|
||
seen.add(mid)
|
||
cc = u.get("cache_creation") or {}
|
||
calls.append({"t": ts(r["timestamp"]), "fam": fam, "in": u.get("input_tokens", 0),
|
||
"read": u.get("cache_read_input_tokens", 0),
|
||
"write": u.get("cache_creation_input_tokens", 0),
|
||
"w1h": cc.get("ephemeral_1h_input_tokens", 0),
|
||
"w5m": cc.get("ephemeral_5m_input_tokens", 0),
|
||
"out": u.get("output_tokens", 0)})
|
||
elif (txt := text_of(r)) is not None:
|
||
prompts.append((ts(r["timestamp"]), txt))
|
||
calls.sort(key=lambda c: c["t"])
|
||
return {"calls": calls, "prompts": prompts, "bounds": bounds, "reads": reads}
|
||
|
||
|
||
def ctx(c: dict) -> int:
|
||
return c["in"] + c["read"] + c["write"]
|
||
|
||
|
||
def wr(fam: str) -> tuple[float, float]:
|
||
"""(cache write on the 1 h tier, cache read), USD per token."""
|
||
inp, _, read = RATES[fam]
|
||
return inp * 2 / 1e6, read / 1e6
|
||
|
||
|
||
def scheduled_turns() -> dict[str, list[float]]:
|
||
"""When each conversation's own scheduled turns (``--to .``) started."""
|
||
seen: dict[str, dict] = {}
|
||
for path in SCHEDULED:
|
||
try:
|
||
raw = json.load(open(os.path.expanduser(path), encoding="utf-8"))
|
||
except (OSError, ValueError):
|
||
continue
|
||
for s in (raw.values() if isinstance(raw, dict) else raw):
|
||
if isinstance(s, dict) and s.get("id"):
|
||
seen.setdefault(s["id"], s)
|
||
out: dict[str, list[float]] = {}
|
||
for s in seen.values():
|
||
if s.get("targetSessionId") and s.get("startedAt"):
|
||
out.setdefault(s["targetSessionId"], []).append(ts(s["startedAt"]))
|
||
return out
|
||
|
||
|
||
def old_estimate(C: int, fam: str, base: int) -> float:
|
||
"""What the reply box promised (old ASSUMPTIONS, Haiku compaction)."""
|
||
W, R = wr(fam)
|
||
F = base + OLD["summaryTokens"]
|
||
tier = HAIKU_LONG[1] if C > HAIKU_LONG[0] else 1.0
|
||
comp = (C * OLD["compactInputShare"] * 0.10 + OLD["compactOutputTokens"] * 0.50) * tier / 1e6
|
||
tot = 0.0
|
||
for n, share, k in OLD["scenarios"]:
|
||
cont = C * W + (n - 1) * C * R + k * C * (W - R)
|
||
fresh = comp + F * W + (n - 1) * F * R + k * F * (W - R)
|
||
tot += share * (cont - fresh)
|
||
return tot
|
||
|
||
|
||
def follow_ups(path: str, tr: dict, cut: float, until: float, sched: dict) -> list[dict]:
|
||
calls, prompts, bounds = tr["calls"], tr["prompts"], tr["bounds"]
|
||
if not calls:
|
||
return []
|
||
sid = os.path.basename(path)[:-6]
|
||
wakeups = sched.get(sid, [])
|
||
base = ctx(calls[0])
|
||
rows = []
|
||
texts_before: set[str] = set()
|
||
for i, (p, txt) in enumerate(prompts):
|
||
repeat = txt[:200] in texts_before
|
||
texts_before.add(txt[:200])
|
||
if not cut <= p < until:
|
||
continue
|
||
before = [c for c in calls if c["t"] < p]
|
||
after = [c for c in calls if c["t"] >= p]
|
||
if not before or not after:
|
||
continue
|
||
last, nxt = before[-1], after[0]
|
||
later = [lp for lp, _ in prompts[i + 1:]]
|
||
turn = [c for c in after if not later or c["t"] < later[0]]
|
||
later_cold = sum(1 for lp in later
|
||
if (pc := [c for c in calls if c["t"] < lp]) and lp - pc[-1]["t"] > 3600)
|
||
fresh = [b for b in bounds if b["fresh"] and last["t"] <= b["t"] <= nxt["t"]]
|
||
row = {"sid": sid, "path": path, "p": p, "gap": p - last["t"], "fam": nxt["fam"],
|
||
"base": base, "left": len(after), "turn": len(turn), "later": len(later),
|
||
"laterCold": later_cold, "fresh": bool(fresh),
|
||
"scheduled": repeat or any(abs(p - w) < 600 for w in wakeups),
|
||
"hit": nxt["read"] / max(1, ctx(nxt)), "w1h": nxt["w1h"], "w5m": nxt["w5m"]}
|
||
inp, _, read = RATES[nxt["fam"]]
|
||
wmult = 2.0 if nxt["w1h"] >= nxt["w5m"] else 1.25
|
||
row["first"] = (nxt["in"] * inp + nxt["read"] * read + nxt["write"] * inp * wmult) / 1e6
|
||
row["warm"] = (nxt["in"] * inp + (ctx(nxt) - nxt["in"]) * read) / 1e6
|
||
if not fresh:
|
||
row["C"] = ctx(nxt)
|
||
else:
|
||
b = fresh[-1]
|
||
row.update(C=b["pre"] or ctx(last) + last["out"], F=ctx(nxt), post=b["post"], ms=b["ms"])
|
||
ca, cb = b["after"], b["before"]
|
||
if ca and cb:
|
||
row["compactCost"] = ca["total"] - cb["total"]
|
||
tin = tout = 0
|
||
for model, cur in ca["mu"].items():
|
||
prev = cb["mu"].get(model) or {}
|
||
for k in ("inputTokens", "cacheReadInputTokens", "cacheCreationInputTokens"):
|
||
tin += cur.get(k, 0) - prev.get(k, 0)
|
||
tout += cur.get("outputTokens", 0) - prev.get("outputTokens", 0)
|
||
row["compactIn"], row["compactOut"] = tin, tout
|
||
# What it saved: every later call (up to the next compaction)
|
||
# would have replayed C − F more tokens — written again on the
|
||
# first call of a turn that came back to an expired cache (this
|
||
# one included), read from cache otherwise. (Not the call's own
|
||
# write share: the shared system-prompt prefix is often warm from
|
||
# other sessions, so a cold call can still read ~25K.)
|
||
W, R = wr(nxt["fam"])
|
||
nb = [x["t"] for x in bounds if x["t"] > nxt["t"]]
|
||
seg = [c for c in after if not nb or c["t"] < nb[0]]
|
||
cold_firsts = {id(nxt)}
|
||
for lp, _ in prompts[i + 1:]:
|
||
pc = [c for c in calls if c["t"] < lp]
|
||
fc = [c for c in calls if c["t"] >= lp]
|
||
if pc and fc and lp - pc[-1]["t"] > 3600:
|
||
cold_firsts.add(id(fc[0]))
|
||
rate = sum(W if id(c) in cold_firsts else R for c in seg)
|
||
row["saved"] = (row["C"] - row["F"]) * rate - (row.get("compactCost") or 0)
|
||
row["promised"] = old_estimate(row["C"], nxt["fam"], base)
|
||
seen = {f for t, f in tr["reads"] if t < p}
|
||
first40 = [f for t, f in tr["reads"] if t >= p][:40]
|
||
row["rereads"] = sum(1 for f in first40 if f in seen)
|
||
rows.append(row)
|
||
return rows
|
||
|
||
|
||
def scenario_table(s: list[dict], label: str) -> list[dict]:
|
||
out = []
|
||
if not s:
|
||
return out
|
||
left = [r["left"] for r in s]
|
||
print(f"\n{label} (n={len(s)}): calls left median {q(left, .5)} · mean {st.mean(left):.0f}"
|
||
f" · p25 {q(left, .25)} · p75 {q(left, .75)} · p90 {q(left, .9)};"
|
||
f" later turns mean {st.mean(r['later'] for r in s):.1f}"
|
||
f" · later cold mean {st.mean(r['laterCold'] for r in s):.2f}")
|
||
print(" scenario calls share avg calls median later cold")
|
||
for key, lo, hi in SIZES:
|
||
b = [r for r in s if lo <= r["left"] < hi]
|
||
if b:
|
||
span = f"{lo}+" if hi == float("inf") else f"{lo}–{hi - 1}"
|
||
row = {"key": key, "n": len(b), "share": len(b) / len(s),
|
||
"calls": st.mean(r["left"] for r in b), "median": q([r["left"] for r in b], .5),
|
||
"laterCold": st.mean(r["laterCold"] for r in b)}
|
||
out.append(row)
|
||
print(f" {key:9s} {span:9s} {row['share']:5.0%} {row['calls']:9.0f} {row['median']:6d}"
|
||
f" {row['laterCold']:10.2f}")
|
||
return out
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||
ap.add_argument("--days", type=int, default=30)
|
||
ap.add_argument("--since", help="ISO start instead of --days (e.g. the feature's deploy)")
|
||
ap.add_argument("--until", help="ISO end (default: now)")
|
||
ap.add_argument("--cold-min-context", type=int, default=125_000,
|
||
help="context floor for the remaining-calls figures")
|
||
ap.add_argument("--json", help="also write every follow-up row here")
|
||
args = ap.parse_args()
|
||
cut = ts(args.since) if args.since else time.time() - args.days * 86400
|
||
until = ts(args.until) if args.until else time.time() + 1
|
||
files: dict[str, str] = {}
|
||
for root in ROOTS:
|
||
for f in glob.glob(os.path.expanduser(root) + "/*/*.jsonl"):
|
||
if os.path.getmtime(f) < cut:
|
||
continue
|
||
b = os.path.basename(f) # the archive and the live tree hold copies
|
||
if b not in files or os.path.getsize(f) > os.path.getsize(files[b]):
|
||
files[b] = f
|
||
sched = scheduled_turns()
|
||
rows, autos = [], 0
|
||
for path in files.values():
|
||
tr = walk(path)
|
||
autos += sum(1 for b in tr["bounds"] if cut <= b["t"] < until and b["trigger"] == "auto")
|
||
rows += follow_ups(path, tr, cut, until, sched)
|
||
|
||
w1h, w5m = sum(r["w1h"] for r in rows), sum(r["w5m"] for r in rows)
|
||
span = f"since {args.since}" if args.since else f"last {args.days} days"
|
||
print(f"{len(rows)} follow-ups, {span} ({len(files)} transcripts)")
|
||
print(f"cache writes on follow-ups: 1 h tier {w1h / 1e6:.1f}M · 5 min tier {w5m / 1e6:.1f}M\n")
|
||
plain = [r for r in rows if not r["fresh"]]
|
||
print("gap since last call n median hit hit>0.8 med ctx 1st call $ warm $")
|
||
for a, b in GAPS:
|
||
s = [r for r in plain if a <= r["gap"] < b]
|
||
if s:
|
||
hi = "∞" if b == float("inf") else f"{b / 60:.0f}"
|
||
print(f"{a / 60:>6.0f}–{hi:<8} min {len(s):5d} {st.median(r['hit'] for r in s):8.2f}"
|
||
f" {sum(r['hit'] > 0.8 for r in s) / len(s):6.0%} {st.median(r['C'] for r in s) / 1e3:6.0f}K"
|
||
f" {st.median(r['first'] for r in s):9.3f} {st.median(r['warm'] for r in s):6.3f}")
|
||
cold = [r for r in rows if r["gap"] > 3600]
|
||
print(f"\ncold follow-ups (> 60 min): {len(cold)} ({len(cold) / max(1, len(rows)):.1%}),"
|
||
f" {sum(r['fresh'] for r in cold)} of them fresh, {sum(r['scheduled'] for r in cold)} scheduled wakeups")
|
||
for fam in RATES:
|
||
s = [r["first"] for r in cold if r["fam"] == fam and not r["fresh"]]
|
||
if len(s) >= 5:
|
||
print(f" {fam:6s} n={len(s):4d} first call $ p50 {q(s, .5):.2f} · p90 {q(s, .9):.2f}")
|
||
|
||
big = [r for r in cold if r["C"] >= args.cold_min_context]
|
||
floor = f"≥ {args.cold_min_context // 1000}K"
|
||
wake = [r for r in big if r["scheduled"]]
|
||
if wake:
|
||
cost = sum(r["first"] - r["warm"] for r in wake)
|
||
print(f"\nscheduled wakeups at {floor} (no reply box, never nudged): {len(wake)},"
|
||
f" ${cost:.2f} of cold re-writes beyond a warm read")
|
||
human = [r for r in big if not r["scheduled"]]
|
||
tables = {"human": scenario_table(human, f"after a typed cold follow-up at {floor}")}
|
||
tables["continued"] = scenario_table([r for r in human if not r["fresh"]], " … continued")
|
||
tables["fresh"] = scenario_table([r for r in human if r["fresh"]], " … fresh")
|
||
|
||
fresh = [r for r in rows if r["fresh"] and r["C"] >= 60_000]
|
||
if fresh:
|
||
print(f"\nfresh compactions: {len(fresh)}"
|
||
f" ({sum(1 for r in fresh if r['gap'] <= 3600)} on a warm cache)"
|
||
f" · automatic compactions in the window: {autos}")
|
||
priced = [r for r in fresh if r.get("compactCost") is not None]
|
||
print(f" compaction $ median {st.median(r['compactCost'] for r in priced):.3f}"
|
||
f" · sum {sum(r['compactCost'] for r in priced):.2f}"
|
||
f" · s median {st.median(r['ms'] for r in fresh) / 1e3:.0f} (p90 {q([r['ms'] for r in fresh], .9) / 1e3:.0f})")
|
||
print(f" re-reads {st.median(r['compactIn'] / r['C'] for r in priced):.2f} of the context"
|
||
f" · writes {st.median(r['compactOut'] for r in priced) / 1e3:.1f}K tokens")
|
||
print(f" after it the next call replays median {st.median(r['F'] for r in fresh) / 1e3:.0f}K"
|
||
f" = injected {st.median(r['base'] for r in fresh) / 1e3:.0f}K"
|
||
f" + summary {st.median(r['F'] - r['base'] for r in fresh) / 1e3:.1f}K"
|
||
f" (postTokens {st.median(r['post'] for r in fresh) / 1e3:.1f}K)")
|
||
print(f" re-reads of files read before it, first 40 Reads: {sum(r['rereads'] for r in fresh)} in all")
|
||
print(f" saved ${sum(r['saved'] for r in fresh):.2f} realised"
|
||
f" vs ${sum(r['promised'] for r in fresh):.2f} the old estimate promised"
|
||
f" (median ${st.median(r['saved'] for r in fresh):.2f} vs ${st.median(r['promised'] for r in fresh):.2f})")
|
||
if args.json:
|
||
with open(args.json, "w", encoding="utf-8") as fh:
|
||
json.dump({"rows": rows, "scenarios": tables, "autoCompactions": autos}, fh, indent=1)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|