Files
ai-agent/scripts/step-lag.py

437 lines
20 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""How late Claude reads what reports back while it works — and how much of
that one long response caused.
Claude Code hands the model a finished background task (``<task-notification>``)
or a follow-up the hub sent into the run's inbox only *between two steps*. A
step that streams for minutes (one 56 KB Write: 4 min 42 s in conv 01a20feb)
keeps both queued. This script reads Claude Code transcripts and measures it:
* every task end the CLI queued (``queue-operation enqueue`` of a completed /
failed notice): when the model got it (the queue's ``remove``, a user turn
carrying it, the Stop guard's relay, the hub's restart note) or that it
never did — and what the wait was spent on: the response streaming when it
ended, the tools that response then ran, the rest;
* every inbox follow-up, the same way;
* *Stop & send now* — an interrupt shortly after a follow-up was queued while
a step streamed: the response thrown away;
* the Stop guard's holds (``sidecar/logs/*.guard.log``): the task ends that
landed inside one and how long they waited behind it;
* the counterfactual of a step rule (no single Write/Edit over 15 KB —
weighed and dropped on 2026-11-25, these numbers):
a response carrying a bigger one is split in parts, so what reports back
waits at most one part's streaming; the cost is one more step per part,
each re-reading the context from the cache.
scripts/step-lag.py [--days 30] [--since ISO] [--until ISO] [--json OUT]
[--guard-logs DIR] [DIR ...]
DIRs default to ~/.claude/projects and ~/.claude-work/projects (main
threads; subagents' own transcripts are left out). Stdlib only.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import math
import os
import pathlib
import re
import statistics
import sys
from concurrent.futures import ProcessPoolExecutor
RULE_BYTES = 15_000 # the step rule: no single Write/Edit over ~15 KB
LONG_STEP_S = 20 # a step streaming longer than this is a "long response"
SNS_WINDOW_S = 60 # an interrupt this soon after a queued follow-up = Stop & send now
# (input, output, cache read) $/MTok — backend/conversations/pricing.py MODEL_PRICES
PRICES = {"opus-5-5": (4.0, 20.0, 0.20), "opus-5": (5.0, 25.0, 0.50),
"sonnet-5-5": (2.0, 10.0, 0.10), "sonnet-5": (2.0, 10.0, 0.20),
"fable-5-1": (10.0, 50.0, 0.25), "fable-5": (10.0, 50.0, 1.00),
"haiku-5-5": (1.0, 5.0, 0.10)}
INBOX = "[Follow-up from your user"
_BLOCK = re.compile(r"<task-notification>(.*?)</task-notification>", re.S)
def _tag(body: str, name: str) -> str:
m = re.search(rf"<{name}>(.*?)</{name}>", body, re.S)
return m.group(1).strip() if m else ""
def notices(text: str) -> list[tuple[str, str, str]]:
"""``(task id, status, summary)`` of each notification in ``text``."""
return [(_tag(b, "task-id"), _tag(b, "status"), _tag(b, "summary"))
for b in _BLOCK.findall(text or "") if _tag(b, "task-id")]
def ts(s) -> float | None:
try:
return dt.datetime.fromisoformat(str(s).replace("Z", "+00:00")).timestamp()
except ValueError:
return None
def prices(model: str | None) -> tuple[float, float, float]:
m = (model or "").removeprefix("claude-")
for k in sorted(PRICES, key=len, reverse=True):
if m.startswith(k):
return PRICES[k]
return PRICES["opus-5-5"]
def _texts(o: dict) -> list[str]:
if o.get("type") == "attachment":
p = (o.get("attachment") or {}).get("prompt")
return [p] if isinstance(p, str) else []
c = (o.get("message") or {}).get("content")
if isinstance(c, str):
return [c]
return [b.get("text", "") for b in c or [] if isinstance(b, dict) and b.get("type") == "text"]
def scan(path: str) -> dict:
"""One transcript → its steps, tool runs, queued items and interrupts."""
steps: list[dict] = [] # {sent, end, model, out, ctx, big: [bytes], blocks}
by_msg: dict[str, dict] = {}
tools: list[tuple[float, float, str]] = [] # foreground tool runs (call end → result, what)
tool_start: dict[str, tuple[float, str]] = {}
queued: list[dict] = [] # {kind, id, status, summary, at, read, how}
interrupts: list[float] = []
pending_send: float | None = None
try:
f = open(path, "rb")
except OSError:
return {}
with f:
for raw in f:
if raw.startswith(b'{"type":"api-request-blob"') or b'"isSidechain":true' in raw:
continue
try:
o = json.loads(raw)
except ValueError:
continue
t = o.get("type")
at = ts(o.get("timestamp")) if o.get("timestamp") else None
if t == "api-request" and at:
pending_send = at
elif t == "assistant" and at:
m = o.get("message") or {}
mid = m.get("id") or str(len(steps))
s = by_msg.get(mid)
if s is None:
u = m.get("usage") or {}
s = {"sent": pending_send, "end": at, "model": m.get("model"),
"out": u.get("output_tokens") or 0,
"inp": u.get("input_tokens") or 0,
"cr": u.get("cache_read_input_tokens") or 0,
"cw": u.get("cache_creation_input_tokens") or 0,
"ctx": sum(u.get(k) or 0 for k in ("input_tokens", "cache_read_input_tokens",
"cache_creation_input_tokens")),
"big": [], "writes": 0, "stop": m.get("stop_reason")}
by_msg[mid] = s
steps.append(s)
pending_send = None
s["end"] = max(s["end"], at)
for b in m.get("content") or []:
if isinstance(b, dict) and b.get("type") == "tool_use":
inp = b.get("input") or {}
if not inp.get("run_in_background"):
what = b.get("name") or "?"
if what == "Bash":
what = "Bash: " + str(inp.get("command") or "").strip().split("\n")[0][:50]
tool_start[b.get("id")] = (at, what)
if b.get("name") in ("Write", "Edit", "MultiEdit", "NotebookEdit"):
inp = b.get("input") or {}
n = len(json.dumps(inp.get("content") or inp.get("new_string")
or inp.get("edits") or ""))
s["writes"] += 1
if n > RULE_BYTES:
s["big"].append(n)
elif t in ("user", "attachment") and at:
c = (o.get("message") or {}).get("content")
if isinstance(c, list):
for b in c:
if isinstance(b, dict) and b.get("type") == "tool_result":
st = tool_start.pop(b.get("tool_use_id"), None)
if st is not None:
tools.append((st[0], at, st[1]))
for text in _texts(o):
if text.startswith("[Request interrupted by user"):
interrupts.append(at)
for tid, status, _ in notices(text):
_read(queued, tid, status, at, "turn")
if "Stop guard" in text:
for q in queued:
if q["read"] is None and q["kind"] == "task" and q["id"] in text:
q["read"], q["how"] = at, "guard"
if "<ai-agent-tasks-done>" in text:
for tid in re.findall(r"^- task ([\w-]+):", text, re.M):
_read(queued, tid, None, at, "note")
if INBOX in text and t == "user":
_read_followup(queued, text, at)
elif t == "queue-operation" and at:
c = o.get("content")
op = o.get("operation")
if not isinstance(c, str):
if op == "dequeue":
_dequeue(queued, at)
continue
if op == "enqueue":
for tid, status, summary in notices(c):
if status in ("completed", "failed"):
queued.append({"kind": "task", "id": tid, "status": status,
"summary": summary, "at": at, "read": None, "how": None})
if c.startswith(INBOX):
queued.append({"kind": "followup", "id": c[:200], "status": None,
"summary": None, "at": at, "read": None, "how": None})
elif op == "remove":
for tid, status, _ in notices(c):
_read(queued, tid, status, at, "remove")
if c.startswith(INBOX):
_read_followup(queued, c, at, "remove")
return {"path": path, "steps": steps, "tools": tools, "queued": queued,
"interrupts": interrupts}
def _read(queued, tid, status, at, how) -> None:
for q in queued:
if q["kind"] == "task" and q["id"] == tid and q["read"] is None and at >= q["at"] \
and (status is None or status == q["status"]):
q["read"], q["how"] = at, how
def _read_followup(queued, text, at, how="turn") -> None:
key = text[:200]
for q in queued:
if q["kind"] == "followup" and q["read"] is None and q["id"] == key and at >= q["at"]:
q["read"], q["how"] = at, how
return
def _dequeue(queued, at) -> None:
"""A dequeue names nothing: the oldest unread follow-up was read as a turn."""
for q in queued:
if q["kind"] == "followup" and q["read"] is None and at >= q["at"]:
q["read"], q["how"] = at, "dequeue"
return
# ── analysis ────────────────────────────────────────────────────────────────
def _streaming(steps, at):
"""The step streaming at ``at`` (sent before, blocks in after), or None."""
for s in steps:
if s["sent"] is not None and s["sent"] <= at < s["end"]:
return s
return None
def _parts(s) -> int:
return max(1, math.ceil(sum(s["big"]) / RULE_BYTES)) if s["big"] else 1
def _split_wait(s, at) -> float:
"""What reports back at ``at`` would wait for if the step were split in
equal parts by the rule: the end of the part streaming then."""
d = s["end"] - s["sent"]
part = d / _parts(s)
x = at - s["sent"]
return (math.floor(x / part) + 1) * part - x
def _step_cost(s) -> float:
pi, po, pc = prices(s["model"])
return (s["inp"] * pi + s["cr"] * pc + s["cw"] * pi * 1.6 + s["out"] * po) / 1e6
def analyse(scans: list[dict], since: float, until: float) -> dict:
items, sns, cost, extra, tps = [], [], 0.0, 0.0, []
split_steps = 0
for sc in scans:
steps = sc.get("steps") or []
for s in steps:
if s["sent"] is None or not (since <= s["end"] < until):
continue
cost += _step_cost(s)
d = s["end"] - s["sent"]
if d > 5 and s["out"] > 500 and s["stop"]:
tps.append(s["out"] / d)
if s["big"]:
split_steps += 1
pi, po, pc = prices(s["model"])
# each extra part: one more step re-reading the context
extra += (_parts(s) - 1) * (s["ctx"] * pc + 300 * po) / 1e6
for q in sc.get("queued") or []:
if not (since <= q["at"] < until):
continue
s = _streaming(steps, q["at"])
wait = (s["end"] - q["at"]) if s else 0.0
tool = None if s else next((x for x in sc.get("tools") or [] if x[0] <= q["at"] < x[1]), None)
cause = "stream" if s else "tool" if tool else "idle"
long_ = bool(s and s["end"] - s["sent"] > LONG_STEP_S)
big = bool(s and s["big"])
new_wait = _split_wait(s, q["at"]) if big else wait
items.append({**q, "path": sc["path"], "lag": (q["read"] - q["at"]) if q["read"] else None,
"stream": wait, "long": long_, "big": big, "saved": max(0.0, wait - new_wait),
"stepS": (s["end"] - s["sent"]) if s else None, "cause": cause,
"toolWait": min(tool[1] - q["at"], (q["read"] or tool[1]) - q["at"]) if tool else 0.0,
"tool": tool[2] if tool else None})
for i in sc.get("interrupts") or []:
if not (since <= i < until):
continue
f = [q for q in sc.get("queued") or [] if q["kind"] == "followup" and i - SNS_WINDOW_S <= q["at"] <= i]
cut = next((s for s in reversed(steps) if s["sent"] is not None and s["sent"] < i
and not s["stop"]), None)
if f and cut and i - cut["sent"] > LONG_STEP_S:
sns.append({"path": sc["path"], "at": i, "lostS": i - cut["sent"], "model": cut["model"]})
return {"items": items, "sns": sns, "cost": cost, "extra": extra, "tps": tps,
"splitSteps": split_steps}
def _q(xs, p):
xs = sorted(xs)
return xs[min(len(xs) - 1, int(p * len(xs)))] if xs else 0.0
def _m(s: float) -> str:
return f"{s / 60:.1f} min" if s >= 90 else f"{s:.0f} s"
def guard_holds(log_dir: pathlib.Path) -> dict[str, list[tuple[float, float]]]:
"""Each session's Stop-guard holds ``(start, end)`` from its guard log
(local time, as the guard writes it)."""
holds: dict[str, list[tuple[float, float]]] = {}
for f in log_dir.glob("*.guard.log"):
start = None
for line in f.read_text(errors="ignore").splitlines():
m = re.match(r"(\S+) stop-guard: (holding|relaying|still running|released)", line)
if not m:
continue
try:
t = dt.datetime.fromisoformat(m.group(1)).timestamp()
except ValueError:
continue
if m.group(2) == "holding":
start = t
elif start is not None:
holds.setdefault(f.name[:36], []).append((start, t))
start = None
return holds
def guard_report(r: dict, holds: dict) -> list[str]:
x = []
for i in r["items"]:
if i["kind"] != "task" or i["lag"] is None:
continue
for a, b in holds.get(pathlib.Path(i["path"]).stem, []):
if a <= i["at"] < b:
x.append(i)
break
slow = [i for i in x if i["lag"] > 60]
return ["## Stop-guard holds", "",
f"- {sum(len(v) for v in holds.values())} holds; {len(x)} task ends landed inside one, "
f"{len(slow)} of them waited > 60 s — **{_m(sum(i['lag'] for i in slow))}** in all "
f"(max {_m(max((i['lag'] for i in slow), default=0))})", ""]
def report(r: dict, days: float) -> str:
out = []
tps = statistics.median(r["tps"]) if r["tps"] else 100.0
for kind, name in (("task", "Background task ends"), ("followup", "Inbox follow-ups")):
xs = [i for i in r["items"] if i["kind"] == kind]
read = [i for i in xs if i["lag"] is not None]
lost = [i for i in xs if i["lag"] is None]
lags = [i["lag"] for i in read]
slow = [i for i in read if i["lag"] > 30]
behind_long = [i for i in xs if i["long"]]
behind_big = [i for i in xs if i["big"]]
out += [f"## {name}", "",
f"- {len(xs)} queued, {len(read)} read, **{len(lost)} never read** "
f"({sum(1 for i in lost if i['big'])} of them behind a big Write/Edit)",
f"- wait until read: median {_m(_q(lags, .5))}, p90 {_m(_q(lags, .9))}, "
f"max {_m(max(lags, default=0))}; {len(slow)} waited > 30 s, "
f"{_m(sum(lags))} in all",
f"- ended while one response was streaming > {LONG_STEP_S} s: {len(behind_long)} "
f"— {_m(sum(i['stream'] for i in behind_long))} of waiting on that response",
f"- … a response carrying a Write/Edit > 15 KB: {len(behind_big)} — "
f"{_m(sum(i['stream'] for i in behind_big))} of waiting; split by the rule: "
f"**{_m(sum(i['saved'] for i in behind_big))} sooner** "
f"({_m(statistics.mean([i['saved'] for i in behind_big]) if behind_big else 0)} each)",
""]
for cause, what in (("stream", "a response streaming"), ("tool", "a foreground tool running"),
("idle", "between turns (idle, held, or the run gone)")):
c = [i for i in read if i["cause"] == cause]
out.append(f"- ended during {what}: {len(c)}, {_m(sum(i['lag'] for i in c))} of wait "
f"(p90 {_m(_q([i['lag'] for i in c], .9))})")
tw: dict[str, list] = {}
for i in read:
if i["cause"] == "tool":
tw.setdefault(i["tool"].split(":")[0] if not i["tool"].startswith("Bash") else i["tool"],
[]).append(i["toolWait"])
worst = sorted(tw.items(), key=lambda kv: -sum(kv[1]))[:6]
if worst:
out.append("- foreground tools it waited behind most: " + "; ".join(
f"`{k}` {_m(sum(v))} ({len(v)}×)" for k, v in worst))
out.append("")
top = sorted(behind_big, key=lambda i: -i["stream"])[:5]
if top:
out.append("Worst waits behind one big response:")
for i in top:
out.append(f" - {_m(i['stream'])} behind a {_m(i['stepS'])} step "
f"→ {_m(i['stream'] - i['saved'])} split · "
f"{pathlib.Path(i['path']).stem[:8]} · {(i['summary'] or i['id'])[:70]}")
out.append("")
lost_s = sum(x["lostS"] for x in r["sns"])
po = 20.0
out += ["## Stop & send now mid-response", "",
f"- {len(r['sns'])} runs stopped within {SNS_WINDOW_S} s of a queued follow-up while "
f"a response streamed > {LONG_STEP_S} s: {_m(lost_s)} of response thrown away "
f"(≈ {lost_s * tps / 1000:.0f}k output tokens at the median {tps:.0f} tok/s, "
f"≈ ${lost_s * tps * po / 1e6:.2f} at Opus 5.5 output price)", "",
"## The rule's price", "",
f"- {r['splitSteps']} responses carried a Write/Edit > 15 KB in {days:.0f} days",
f"- splitting them: ≈ ${r['extra']:.2f} more (one more context re-read per part), "
f"{100 * r['extra'] / r['cost']:.2f} % of the ≈ ${r['cost']:.0f} these transcripts cost"
if r["cost"] else "- no cost data", ""]
return "\n".join(out)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("dirs", nargs="*")
ap.add_argument("--days", type=float, default=30)
ap.add_argument("--since")
ap.add_argument("--until")
ap.add_argument("--json")
ap.add_argument("--guard-logs", default=str(pathlib.Path.home() / "projects" / "ai-agent"
/ "sidecar" / "logs"))
a = ap.parse_args()
now = dt.datetime.now(dt.timezone.utc).timestamp()
until = ts(a.until) if a.until else now
since = ts(a.since) if a.since else until - a.days * 86400
dirs = [pathlib.Path(d) for d in a.dirs] or [pathlib.Path.home() / ".claude" / "projects",
pathlib.Path.home() / ".claude-work" / "projects"]
files = [str(p) for d in dirs if d.is_dir() for p in d.glob("*/*.jsonl")
if p.stat().st_mtime >= since]
with ProcessPoolExecutor(max_workers=max(1, (os.cpu_count() or 2) // 2)) as ex:
scans = [s for s in ex.map(scan, files, chunksize=4) if s]
r = analyse(scans, since, until)
days = (until - since) / 86400
print(f"# Step lag — {len(files)} transcripts, "
f"{dt.datetime.fromtimestamp(since):%Y-%m-%d} → {dt.datetime.fromtimestamp(until):%Y-%m-%d}\n")
print(report(r, days))
gl = pathlib.Path(a.guard_logs)
if gl.is_dir():
print("\n".join(guard_report(r, guard_holds(gl))))
if a.json:
pathlib.Path(a.json).write_text(json.dumps(
{k: v for k, v in r.items() if k != "tps"}, indent=1, default=str))
return 0
if __name__ == "__main__":
sys.exit(main())