Repository navigation
feat(analysis): add wait-cause and ping-budget analysis script - #425
Conversation
…d cost The miss/hit rule used cache_read == 0 as "miss". Real traffic often comes back with some cache_read but a cache_creation that dwarfs it — most of the prefix still had to be rewritten, which is a miss in every way that matters for cost. The old rule missed almost all of these, so the reported miss cost was far too low (e.g. forever's in-process teammate threads showed 294 gaps at 0.01x/gap; the real number is 294 misses at ~1.15x/gap). Fix is_cache_hit to: cache_read > 0 AND cache_creation < half of cache_read. Cross-checked against an independent count on both local projects (same gap/dedupe rule): exact match on misses and hits for every (project, thread-kind) bucket. Also, per review on PR #425: - Split the cost report into OBSERVED (what really happened, including real keep-alive pings already sent, pulled from the DB's keepalive_pings via a session+cache_read+timestamp match) and SIMULATED (the hypothetical N=0..12 ping-budget curve, where N=0 is always 1.15x for a gap over 5 minutes by construction). These were previously conflated under one "miss cost" column, which is why a simulated best-N could appear to cost more than the observed column. - Report hits vs misses per cause, so a reader can see whether "gap over the threshold means a miss" holds on that traffic. - Split the "subagent" thread kind into "subagent" (a plain Task-tool subagent) and "team_thread" (an in-process agent-team teammate, identified by meta.json's taskKind). These behave very differently — a team_thread's wait is on peer coordination, not a bounded task, which is why e.g. forever's team_thread-teammate gaps run 11-145 minutes median/p90 rather than minutes. This was previously folded into one "subagent" bucket under a "teammate" wake cause, which is a different thing (the wake cause, not the thread kind) and was confusing. - Add --self-test: a tiny synthetic transcript (one main thread, one subagent thread) with known gaps, known hits/misses, and known causes, asserting the exact observed and simulated numbers. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
Review
Result: the method is right, but 2 defects change the published numbers. The USD totals are too high, and about 1 in 7 reviewer or teammate wakes is counted as "human". Please fix both and re-run before merge.
What I ran
python3 -I scripts/analysis/wait_causes.py --self-test: passes.- The script on the real local data: both projects' transcripts and
dashboard-8789.db, opened read-only. - Independent checks of each finding below, on the same data. There are no API calls; the script is offline.
Must fix
1. The USD prices are wrong, so every USD total is too high.
MODEL_BASE_INPUT_PRICE_PER_TOKEN uses list prices. The dashboard DB prices the same traffic differently. I fitted cost_usd = b × (fresh + 0.1·cache_read + 1.25·cache_write + 5·output) on the DB rows:
| Model | Script | DB | Script ÷ DB |
|---|---|---|---|
claude-opus-5-5 |
$15.00 | $3.91 | 3.8× |
claude-sonnet-5 |
$3.00 (fallback, not in the table) | $2.00 | 1.5× |
claude-opus-5 |
$3.00 (fallback) | $5.00 | 0.6× |
claude-haiku-4-5 |
$1.00 | $1.00 | 1.0× |
- Example: "context-guru main, human: $430" is mostly opus. At the DB price it is about $115.
- Proposed fix:
- When
--dbis given, use per-model prices from the DB (the same fit is enough). - When the DB has no price for a model, fall back to the table, and correct the table.
- Print the price source for each model in the report.
- When
2. Messages from other Claude sessions are counted as human.
These messages use <cross-session-message from=… from-name=…>, not <teammate-message. TEAMMATE_RE misses them.
- 52 of the 377 main-thread
humanwakes are reviewer or teammate messages. The "teammate" cause is therefore undercounted, and this is the cause #424 most needs. - Other entries with
isMeta: truealso land inhuman: skill loads (Base directory for this skill:, 17),Check background task …(2) and<system-reminder>(2). - Proposed fix:
- Match
<cross-session-messageasteammate. - Never classify an
isMetaentry ashuman. Use its marker if it has one, otherwise a separatesystemcause.
- Match
- #424 needs the same marker list, so it should be noted there too.
Should fix
3. The simulation charges one ping too many at the window edge.
sim_cost_x charges 0.1 × floor(g / 4.67) even when that is more than N.
- Example: N=0 with a 4.8-min gap costs 0.1x, but N=0 sends no pings.
- Fix:
0.1 × min(N, floor(g / 4.67)).
4. Failed calls are counted as misses but cost nothing.
misses = len(gs) - hits counts an isApiErrorMessage call as a miss, while observed_cost_x_usd gives it no miss premium. Count errors in their own column.
5. The DB match uses the request start, while the transcript has the response arrival.
On fix-summarizer:
- The script's rule (start time, 60 s window) matches 2,709 of 2,817 calls (96.2%).
- Matching on
ts + upstream_msmatches 2,810 (99.8%).
This affects the observed ping counts and the mislabel check.
6. DB-only mode ignores keepalive_pings.
The production DB has this column, so the measured cost there can include real pings. Also use the same hit rule (cache read and cache write) in both modes, not cache_miss_reason. Otherwise production numbers depend on the label defect that #423 fixes.
Minor
7. Name what mislabeled_usd measures. It is the full cost of the mislabelled rows, not their miss premium. Name it that way in the output, as the dashboard's prefix_change_cost_usd does.
8. Extend the self-test to cover:
- a
retry - a
teammatewake in each format (<teammate-message,<cross-session-message) - an
isMetaentry - the DB match
- DB-only mode
After the fixes
Please re-run the analysis and update the results tables in the PR body. Finding 2 moves gaps from human to teammate. Finding 1 changes every USD total. The conclusions in the body may change with them.
… DB match) Fix all 8 findings from the PR #425 review. Must fix: - Finding 1: price per model was a published list price, overstating cost by up to 3.8x (claude-opus-5-5: $15/MTok listed vs $3.91/MTok actually billed). Add fit_model_prices(), fitting cost_usd = price * (fresh + 0.1*cache_read + 1.25*cache_write + 5*output) per model by least squares on the DB's own billed rows, and a PriceTable that prefers that fit over the (now corrected) hardcoded fallback table. Report which price priced which model (price_sources). - Finding 2: a message from another Claude session arrives as <cross-session-message ...>, not only <teammate-message ...>; both now match the "teammate" wake cause. An isMeta entry (skill load, system nudge, subagent hand-back notice) with no recognized marker now gets its own "system" cause instead of falling through to "human" — 52 of 377 context-guru main-thread "human" wakes were really reviewer/teammate messages. Should fix: - Finding 3: sim_cost_x capped the in-window ping term at min(N, floor(gap/interval)) — N=0 no longer gets charged for a ping it never sends at the window's edge. - Finding 4: an upstream error call is neither a hit nor a miss; summarize_gaps_by_cause now counts hits/misses/errors from their own properties instead of misses = len(gs) - hits, which folded errors into the miss count. - Finding 5: DB-row matching (DBIndex, mislabel_check) now matches on an approximate response time (ts + upstream_ms), not raw ts (a request-start time) — raises the match rate on the validation session from 96.2% to 99.8% and tightens the window from 60s to 15s. - Finding 6: db_only_report now uses the same cache_read/cache_write hit rule as transcript mode (not the cache_miss_reason label, which depends on the ttl_expiry/prefix_change distinction #423 is still fixing) and the row's own real keepalive_pings for the observed cost. Minor: - Finding 7: renamed mislabeled_usd to mislabeled_full_cost_usd and documented that it is the mislabeled rows' full recorded cost, not just their miss premium. - Finding 8: extended --self-test to cover a retry gap, both teammate wake formats, an isMeta/system wake, a tiny synthetic sqlite DB (price fit, response-time match, mislabel_check), and db_only_report against deliberately mislabeled rows. Also split "subagent" into "subagent" (plain Task-tool) and "team_thread" (in-process agent-team teammate, via meta.json's taskKind) in an earlier pass, kept here for the same reason: a team_thread's wait is on peer coordination, not a bounded task. Re-ran on both local projects and both dashboard DBs; results and tables in the PR body are updated to match. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Thanks for the review — all 8 findings fixed, pushed to this branch, and the PR body's results tables are updated. Point by point: Must fix
Should fix
Minor
Re-ran on both projects' transcripts and both dashboard DBs; the PR body's results tables, "Takeaway", and open questions are updated to match. Full writeup of each fix is in |
Production validation: DB-only modeResult: DB-only mode runs cleanly on a production multi-tenant dashboard DB. The run was read-only on the What it found
x = the prompt's base input price. One ping costs 0.1x. A miss costs 1.15x more than a hit. Simulated ping budget, on the same gaps:
What this means
Other findings
Not covered
|
Production validation, second host (
|
| Measure | contextguru |
contextguru2 |
|---|---|---|
| Idle gaps over 4.67 min | 1,504 | 965 |
| Median / p90 gap | 8.9 / 89 min | 6.6 / 79 min |
| Cache misses among them | 1,175 (78%) | 626 (65%) |
| Keep-alive pings sent | 11 | 28 |
| Measured cost | 0.90x per gap, $770 | 0.75x per gap, $411 |
| Simulated, 2 pings | 0.56x, saves about $290 (38%) | 0.49x, saves about $141 (34%) |
| Simulated, best (6 pings) | 0.44x, saves about $390 (51%) | 0.45x, saves about $166 (40%) |
| Failed requests | 584, median 8.1 s before failing | 596, median 110 s before failing |
| Misses after a failure | 140 | 92 |
What this adds
- Both hosts point the same way. 2 pings per thread captures most of the saving (34–38%), and 6 pings adds only a few points more. Together, the 2 hosts would have saved about $430 over this window with 2 pings.
- Failures on
contextguru2hang about 14 times longer before they fail (110 s against 8 s). That looks like the long gateway hangs seen elsewhere, and it is worth its own look. - The 2 hosts price the same models differently.
contextguru2prices them at list (opus-5 $5.00/MTok, sonnet-5 $2.00, haiku-4-5 $1.00).contextguruprices them at about 0.76 times that, and givesaws/claude-sonnet-5($1.52) a different price fromclaude-sonnet-5($2.28). The script uses what each dashboard billed. If the hosts are meant to use the same price source, one of them is wrong, and all its dollar figures (savings included) are off by that factor.
Production follow-up: why so few keep-alive pings on
|
| Day | Window (Israel time) | Pings | Floor | Ceiling per ping |
|---|---|---|---|---|
| Sunday | 09:00–19:00 | 1 | 2,000 tokens | $30 |
| Monday | 08:00–19:00 | 1 | 2,000 tokens | $20 |
| Tuesday | 09:00–19:00 | 1 | 2,000 tokens | $20 |
| Wednesday | 09:00–21:00 | 1 | 2,000 tokens | $20 |
| Thursday | 09:00–18:00 | 1 | 2,000 tokens | $20 |
- Each strategy sends 1 ping, not 2.
- No strategy covers Friday, Saturday, or evenings and nights.
- With a ceiling of $20 or more and a floor of 2,000 tokens, neither limit blocks a ping in practice.
3. Every idle gap of 280 s to 1 h, by cause
The gaps are grouped by session and model, because this build has no thread id. The window is checked at the moment the ping would fire (the previous request plus 275 s).
| Pinged? | Window | Session | Next call | Gaps |
|---|---|---|---|---|
| no | in | multi-model | miss | 302 |
| no | in | multi-model | hit | 102 |
| no | in | single-model | miss | 31 |
| no | out | multi-model | miss | 93 |
| no | out | multi-model | hit | 21 |
| yes | in | multi-model | hit / miss | 52 / 25 |
| yes | in | single-model | hit | 11 |
- 404 of the 549 gaps without a ping (74%) were inside a window, in a multi-model session. In those sessions, the keeper's single entry per session is taken over or reset by another thread's request, so the idle thread never gets its ping. feat(keepalive,dash): key cache attribution and keep-alive per thread #426 fixes this.
- Only 114 gaps (21%) were outside every window. Adding evening and weekend hours would cover those.
- The 102 "no ping, hit" gaps are probably not real idle gaps: requests from another thread on the same model fall between them, and this build cannot tell the threads apart.
- 31 single-model gaps inside a window got no ping and missed. These are not explained yet.
- Pinged gaps: 63 hits and 25 misses. With 1 ping, a gap longer than about 9 minutes misses anyway.
What to change after this release
- Deploy feat(keepalive,dash): key cache attribution and keep-alive per thread #426 (in this release). It removes the biggest cause.
- Raise the strategies to 2 pings. The simulation in the comment above shows 2 pings capture most of the saving.
- Consider covering evenings and weekends.
- Look into the 31 single-model gaps that got no ping inside a window.
Add scripts/analysis/wait_causes.py, a reusable offline analysis for issue #424. It measures, per thread (main and subagent) and per wake cause, the gap distribution, the unmitigated cache-miss cost, and a keep-alive ping-budget simulation (N = 0-12). It reads Claude Code session transcripts for exact thread boundaries and exact wake causes, and cross-checks the dashboard DB for prefix_change mislabels and upstream failures. It also runs DB-only, with no transcripts, which is how it must run against the production proxy. Validated against the known fix-summarizer session (6c456ae0-469f-44a1-92c1-f6ea03192715): numbers are close to the issue's own rough pass, with differences explained in the script's README (exact per-thread attribution vs. a DB-row proxy that had no thread id). Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…d cost The miss/hit rule used cache_read == 0 as "miss". Real traffic often comes back with some cache_read but a cache_creation that dwarfs it — most of the prefix still had to be rewritten, which is a miss in every way that matters for cost. The old rule missed almost all of these, so the reported miss cost was far too low (e.g. forever's in-process teammate threads showed 294 gaps at 0.01x/gap; the real number is 294 misses at ~1.15x/gap). Fix is_cache_hit to: cache_read > 0 AND cache_creation < half of cache_read. Cross-checked against an independent count on both local projects (same gap/dedupe rule): exact match on misses and hits for every (project, thread-kind) bucket. Also, per review on PR #425: - Split the cost report into OBSERVED (what really happened, including real keep-alive pings already sent, pulled from the DB's keepalive_pings via a session+cache_read+timestamp match) and SIMULATED (the hypothetical N=0..12 ping-budget curve, where N=0 is always 1.15x for a gap over 5 minutes by construction). These were previously conflated under one "miss cost" column, which is why a simulated best-N could appear to cost more than the observed column. - Report hits vs misses per cause, so a reader can see whether "gap over the threshold means a miss" holds on that traffic. - Split the "subagent" thread kind into "subagent" (a plain Task-tool subagent) and "team_thread" (an in-process agent-team teammate, identified by meta.json's taskKind). These behave very differently — a team_thread's wait is on peer coordination, not a bounded task, which is why e.g. forever's team_thread-teammate gaps run 11-145 minutes median/p90 rather than minutes. This was previously folded into one "subagent" bucket under a "teammate" wake cause, which is a different thing (the wake cause, not the thread kind) and was confusing. - Add --self-test: a tiny synthetic transcript (one main thread, one subagent thread) with known gaps, known hits/misses, and known causes, asserting the exact observed and simulated numbers. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
… DB match) Fix all 8 findings from the PR #425 review. Must fix: - Finding 1: price per model was a published list price, overstating cost by up to 3.8x (claude-opus-5-5: $15/MTok listed vs $3.91/MTok actually billed). Add fit_model_prices(), fitting cost_usd = price * (fresh + 0.1*cache_read + 1.25*cache_write + 5*output) per model by least squares on the DB's own billed rows, and a PriceTable that prefers that fit over the (now corrected) hardcoded fallback table. Report which price priced which model (price_sources). - Finding 2: a message from another Claude session arrives as <cross-session-message ...>, not only <teammate-message ...>; both now match the "teammate" wake cause. An isMeta entry (skill load, system nudge, subagent hand-back notice) with no recognized marker now gets its own "system" cause instead of falling through to "human" — 52 of 377 context-guru main-thread "human" wakes were really reviewer/teammate messages. Should fix: - Finding 3: sim_cost_x capped the in-window ping term at min(N, floor(gap/interval)) — N=0 no longer gets charged for a ping it never sends at the window's edge. - Finding 4: an upstream error call is neither a hit nor a miss; summarize_gaps_by_cause now counts hits/misses/errors from their own properties instead of misses = len(gs) - hits, which folded errors into the miss count. - Finding 5: DB-row matching (DBIndex, mislabel_check) now matches on an approximate response time (ts + upstream_ms), not raw ts (a request-start time) — raises the match rate on the validation session from 96.2% to 99.8% and tightens the window from 60s to 15s. - Finding 6: db_only_report now uses the same cache_read/cache_write hit rule as transcript mode (not the cache_miss_reason label, which depends on the ttl_expiry/prefix_change distinction #423 is still fixing) and the row's own real keepalive_pings for the observed cost. Minor: - Finding 7: renamed mislabeled_usd to mislabeled_full_cost_usd and documented that it is the mislabeled rows' full recorded cost, not just their miss premium. - Finding 8: extended --self-test to cover a retry gap, both teammate wake formats, an isMeta/system wake, a tiny synthetic sqlite DB (price fit, response-time match, mislabel_check), and db_only_report against deliberately mislabeled rows. Also split "subagent" into "subagent" (plain Task-tool) and "team_thread" (in-process agent-team teammate, via meta.json's taskKind) in an earlier pass, kept here for the same reason: a team_thread's wait is on peer coordination, not a bounded task. Re-ran on both local projects and both dashboard DBs; results and tables in the PR body are updated to match. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Issue #424 added a waiting_for field, known when a wait STARTS (unlike wake_cause, known only once it ends) — this is the field a keep-alive ping budget would actually be set from. Add it to the analysis script. - Merge an API response's content across every transcript entry that shares its message_id (a tool_use block can land in a different split entry than the usage), so Call now carries stop_reason and tool_use_names. - classify_waiting_for (ThreadWaitState): a failed call means retry; a tool_use means own_tool (with the tool name kept), except AskUserQuestion and ExitPlanMode, which wait on the human; a no-tool_use response means background if a background task is open, teammate if a teammate wait is open, else human. - Track open background tasks and open teammate waits per thread, from the real tool_result/user-entry shapes found in both local projects' transcripts (grepped before writing any regex, per the task): backgrounded Bash and Monitor close via <task-notification>; an async agent (Agent tool, run_in_background) closes via <agent-message from="X">, NOT a task-notification, which is the one place the finish signal differs by start kind; a Monitor also closes on its own stated expiry elapsing; any of them close on a TaskStop(task_id=X) tool call, matched structurally, not by regex. A teammate wait opens on a SendMessage tool_use (matched on the tool name and its JSON `to` field) and closes on <teammate-message teammate_id="X"> or <cross-session-message from-name="X">. - Report, per thread kind: a waiting_for x wake_cause cross-tab, the same observed/simulated cost columns wake_cause gets but grouped by waiting_for (the table a ping-budget policy needs), and an own_tool breakdown by tool name. - Extend --self-test with a dedicated waiting_for session covering all five values with known expected classifications. Re-ran on both local projects and both dashboard DBs; README documents the method, the real transcript shapes it was built from, and how the resulting cross-tab compares to issue #424's own (self-described rough) one. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Add issue #424 section 4 to wait_causes.py: per project and per tool (main and team_thread threads), learn the wait and simulate the hierarchical ping-budget policy the issue proposes, plus report declared-but-never-called tools. - Per-tool wait stats: call count (every tool_use block, anywhere), wait count (the gap after a response whose LAST tool_use is that tool, every gap including the short ones, no threshold), median/p75/ p90 wait, share over 5 min, and the best N (over only this tool's waits of GAP_THRESHOLD_MIN or more). iter_calls_and_gaps now also returns a ToolWait per consecutive call pair, independent of the threshold-filtered Gap list. - Policy comparison: learn on the first half of each project's sessions by time, evaluate on the second half (otherwise this only measures overfitting). Four policies, each capped at N=11 (issue #424: "never go above the break-even point"): - hierarchical: AskUserQuestion/ExitPlanMode use the human budget; else the tool's own budget when it has >=20 training waits; else its waiting_for group's budget; else a default of 2. - a single global best N. - the waiting_for-only policy (the hierarchical policy's own fallback step, with no per-tool step at all). - today's fixed 2 pings. - Unused tools: declared built-in tools (the DB's tool_declarations, kind='tool') never called (the DB's tool_uses), for the project's sessions. Needs --db — checked directly that a transcript carries no declared-tools list of its own. Fixed a real correctness bug while building this: the DB's own tool_uses table can under-cover a project (dashboard DBs here cover only a handful of forever's many sessions), so a tool the TRANSCRIPTS show as called is now unioned into the "called" set before subtracting from "declared" — without this, forever's unused-tools list wrongly included SendMessage and AskUserQuestion, tools with hundreds of real calls. - Extend --self-test: per-tool stats on the existing waiting-for fixture, a hand-constructed train/test policy scenario (asserts exact costs for all 4 policies), split_sessions_by_time's train/test split, and the unused-tools DB-undercoverage fix. Re-ran on both local projects and both dashboard DBs; README documents the method and the policy-comparison numbers. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…s-tab Investigate and fix all 3 leaks the review found in the context-guru main-thread waiting_for x wake_cause cross-tab, each traced to a real session/timestamp/entry before fixing. Root cause of most of the drop in all 3 rows: waiting_for was computed lazily, only when the NEXT call was flushed. By then every entry between the two calls -- including the very teammate reply or task notification about to END the gap -- had already been applied to the tracked open-tasks/open-teammates state, so a background task or teammate wait that was genuinely open at the START of the gap looked already closed by the time it was checked. Fixed by snapshotting waiting_for the moment each call finishes, in iter_calls_and_gaps, before anything later can mutate ThreadWaitState. Also: - wake_cause: AskUserQuestion/ExitPlanMode's human answer travels back as a bare tool_result (the API's only way to return a tool's result); classify_wake_cause now applies the same exception waiting_for already had, so this is wake_cause=human, not tool_result (was 15/15 of a leak, now 0). - Monitor-start detection: found 2 more real detail-clause shapes besides "expires in <dur>" -- "persistent -- runs until TaskStop or session end" (no expiry) and "timeout <N>ms" (ms, not a duration string) -- neither matched the old regex at all. - A Monitor's own mid-watch event notification was being treated as a finish signal, same as a one-shot task's completion -- it isn't; only its "[Monitor expired after ...]" terminal notice is (49 of 70 real Monitor-event notifications in both projects were mid-watch, not final). - A background Skill launch (forked execution)'s id is not in its text at all -- it is the entry's own toolUseResult.agentId field. - The 11 residual human/teammate leak cases were checked by hand against every SendMessage sent earlier in that session: none had an outstanding unanswered send, confirming they are unpredictable peer-initiated follow-ups, not a bug. Added: TeammateWait, reporting how long open teammate waits stay open (review: "check that the open-teammate rule does not keep a wait open forever ... report how long"). On both projects, 129 of 1,474 (9%) never see a reply within the thread's own transcript. Extended --self-test with a dedicated regression session asserting each of the 4 fixes, plus teammate-wait-duration coverage (a closed and a never-closed case). Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Fix the per-tool table per review, and report the hierarchical-policy result honestly instead of letting a small test set hide it. Per-tool table (summarize_tool_waits): - Lead with waits_ge_threshold (count, median, p75, p90, hits, misses) as the PRIMARY columns, since the keep-alive only ever acts after GAP_THRESHOLD_MIN of idle time -- a tool's typical sub-minute wait tells the policy nothing. Keep the all-waits median and the share-over-5-min as secondary columns, clearly labeled. - best_n is "n/a" below MIN_TOOL_WAITS_FOR_OWN_BUDGET (20) qualifying waits -- it was previously computed from as few as 0-1 waits (Write, Edit), which is not a real signal. - Reconcile own_tool_breakdown with the per-tool table exactly: both now key on the response's LAST tool_use only. own_tool_breakdown previously counted every tool_use block in a multi-tool response, which could inflate a tool's count past what the per-tool table showed for the same traffic (Write: 4 vs 1). --self-test now asserts own_tool_breakdown[tool] == tool_waits[tool].waits_ge_threshold for every tool except AskUserQuestion/ExitPlanMode. Policy comparison: - forever's main-thread time-ordered test split has only 14 gaps -- flag any test set below MIN_MEANINGFUL_TEST_GAPS (50) with a CAVEAT line instead of reporting it as a result. - On context-guru (453 test gaps, the only split with enough data), state plainly that the hierarchical policy LOSES: 0.562x/gap against a single global best N=5 at 0.539x/gap and fixed 2 pings at 0.579x/gap. - Added repeated_split_policy_comparison: 5 random (not time-ordered) session-level splits, reporting each policy's mean and spread. This confirms the loss is not an artifact of the one time-ordered split: global best N wins on both projects across all 5 splits. - Diagnosed why, by inspecting which test gaps cost the most under the hierarchical policy vs. global-N: a cause-specific N (Bash's own N=2, teammate's own N=3) is tuned to that cause's typical SHORT wait, so it systematically misses that same cause's rare long tail; the pooled global N, forced to also fit the longer human/background populations, ends up accidentally well-suited to those same outliers too. Written up in the README's Validation section. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…inly No code change: the per-tool table reconciliation and the 5-random- split check were already fixed and verified in 8e80c83 (re-confirmed here with 0 mismatches across every tool on fresh data). This commit only tightens the wording per review, in scripts/analysis/README.md: - forever's 14-gap test split is now stated outright to prove nothing, with no wording anywhere that calls it a tie or a win. - context-guru's result is stated as: the 3 learned policies cluster closely (0.544-0.565x/gap) and all beat fixed 2 pings (0.580x) by roughly 3-6%, but the best of the three is the single global N, not the per-tool hierarchical policy -- this data does not show that per-tool learning beats one global N. - The open-teammate-wait finding is now stated as something issue #424 needs to act on, not just report: a third of context-guru's teammate waits never close within the visible transcript, and the ones that do can run for hours (p90 ~3.1-3.3h) -- #424 must define an assumed timeout for an open teammate wait, since none exists today (unlike a Monitor's stated expiry). Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Fix a bug found on production data (contextguru2): DB-only mode reported "28 real pings seen" when the DB actually held 351 ping rows (keepalive=1) across 75 sessions. Root cause: both modes counted pings via keepalive_pings, a column the Go proxy writes once -- on whichever real request a ping run ends with. That misses every ping whose session never sent another real request at all: there is no "next real row" to carry a count, so the ping just disappears from the total. It also priced every ping at a fixed 0.1x estimate, never the ping's own real cost_usd. Fix: - DBRow gains max_tokens and thread_id (the latter optional -- #423's column, not present on either local DB yet; read_db_rows() detects its absence via PRAGMA table_info and fails open to the (session_id, model) fallback the rest of this script already uses). - DBIndex.pings_for() and a new pings_in_range() read ping ROWS directly, matched to the gap they fall inside by timestamp (thread_id when the DB has one, else session_id+model), and sum their REAL cost_usd instead of estimating 0.1x * count. Used by both run_transcript_mode and db_only_report, so a ping is counted the same way in both. - ping_rows_summary(): every ping row in the DB, regardless of whether it falls in a measured gap -- count, sessions, total cost, and the max_tokens=0 "summary-substitute" (issue #458) subset, still counted as a ping slot, priced from its own cost_usd. - DBIndex.ping_orphans() / db_only_report's own matching: ping rows never attributed to a gap, reported separately as "pings for sessions that did not return" (count, sessions, cost) instead of silently vanishing from the total. - is_keepalive_substitute_strategy(): documents the extraction_calls strategy suffixes ('/keepalive_substitute_billed', '/keepalive_substitute') that must be excluded from any future "LLM spend" total built from that table, so a substitute ping's cost (already counted once here, from requests.cost_usd) is never added twice. This script does not read extraction_calls today, so nothing calls this yet. On both local DBs: 360 real ping rows (not 28), 305 attributed to a measured gap in DB-only mode (256 in transcript mode's exact per-thread gaps), the rest reported as pings for sessions that did not return ($2.83-$5.05 of $25.53 total, depending on mode). Extended --self-test: a synthetic DB with a ping row inside a gap, a summary-substitute ping also inside it, and an orphan ping after the session's last request, in both modes. Asserts the counts and the cost exactly. Rebased onto origin/main (issue #423/#453 and other work landed there since this branch was last pushed); no conflicts, this PR only touches scripts/analysis. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
fffcad2 to
8e2146a
Compare
Corrected production numbers, with the ping fix (8e2146a)This replaces the numbers in my 2 earlier production comments. The earlier DB-only runs had 2 errors:
Both are fixed in 8e2146a. The conclusion does not change: 2 pings per thread captures most of the saving.
|
Answers whether a "no keep-alive ping before turn K" gate would lose value. Reuses wait_causes.py's transcript parser and cost model under the shipped keep-alive defaults (2 pings, 20k prefix floor). Transcript mode only; the docstring sketches the DB-only mode production needs. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Lets turn_gate.py run against the production dashboard DB, which has no transcripts and no exact per-thread turn index. Mirrors wait_causes.py's own DB-only approach: - Group real request rows (keepalive=0, status=200) by `thread_id` where the DB has that column, else by (session_id, model) as an approximate thread proxy. Pings never form a turn boundary. - Turn index is 1-based row order within a group; also switched transcript mode to the same 1-based convention, so both modes report into the same turn buckets. - Gaps use the previous request's own response-arrival time (ts + upstream_ms, wait_causes.py's approx_response_ts), not its raw request start, to the next request's start. - Simulated ping cost is now gated by the keeper's 3 live checks (issue #444's defaults): a prefix floor (80,000 tokens), a minimum idle time before the first ping (270s), and a per-ping USD ceiling ($0.50) -- configurable via --prefix-floor/--idle-sec/--ping-ceiling-usd. A pause that fails a gate is still counted, with zero simulated cost. - Added real keep-alive ping attribution (keepalive=1 rows, priced from their own cost_usd) per turn bucket, reusing wait_causes.py's DBIndex, plus a USD column alongside the existing x-unit cost/avoided/net, and a gate-at-5/gate-at-10 net-change comparison against today's baseline. - Extended --self-test with DB-only fixtures and gate coverage. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Turn gate on production: no gate recommendedQuestion: should the keeper refuse pings for threads with fewer than 5 or 10 turns? Result: no gate. On both production hosts, pinging turns 5–9 pays, a gate at 10 loses money, and a gate at 5 changes almost nothing. The run used
Caveats:
|
Summary
keep-alive ping budget would cost. It answers issue Record why a thread waits, and set the keep-alive ping budget from it #424's main
questions and its section 4 (learn the wait per tool).
the DB alone, the way the production proxy will need it.
the time. A pending teammate message or background task predicts it
less well: 53% and 24% of the time. See Results.
not show that a per-tool budget beats one single learned number.
See Results.
within the visible transcript. Issue Record why a thread waits, and set the keep-alive ping budget from it #424 needs a timeout rule for
this case; none exists today.
Depends on issue #423 for exact per-thread keying. Until #423 lands,
the production dashboard DB has no thread id, so some of this script's
checks (the per-thread cache-miss mislabel check, and the real
keep-alive pings pulled into the "observed" cost column) match a DB row
to a transcript event by session, cache size, and timestamp, not by an
exact thread id.
What the script does
scripts/analysis/wait_causes.py. Python standard library only. Runit with
python3 -I.Transcript mode. Reads Claude Code session transcripts together
with the dashboard DB. Give it one or more
--projects-dirfolders(for example
~/.claude/projects/-Users-you-git-your-repo) and,optionally, one or more
--dbpaths:Each transcript file is one thread: the main session, a plain
subagent, or an in-process agent-team teammate. This mode gives exact
threads and exact wake causes.
DB-only mode. The way the production proxy must run this, since it
has no transcripts. Give it only
--db:There is no thread id and no wake cause here yet. The script says so,
and groups rows by session and model as an approximate stand-in for a
thread.
Add
--jsonfor machine-readable output. Add--self-testto run thescript's own test suite on a built-in synthetic transcript and a
synthetic database; it needs no live data.
What changed
New files:
scripts/analysis/wait_causes.pyandscripts/analysis/README.md.wake_cause: why a wait ended. One oftool_result,background,teammate,human,system, orretry. Read fromthe transcript entries between two API calls, by string match (a
<teammate-message>or<cross-session-message>, a<task-notification>, plain text, a bare tool result, or a failedprior call).
waiting_for: what the thread was waiting on when the waitstarted, from issue Record why a thread waits, and set the keep-alive ping budget from it #424 section 4. One of
own_tool,background,teammate,human, orretry. Read from the response that endsthe turn before the wait: a tool call means
own_tool(with thetool's name kept), except
AskUserQuestionandExitPlanMode, whichwait on a human. No tool call means
backgroundif a backgroundtask is open,
teammateif a teammate wait is open, elsehuman.thread from the request body, no LLM needed. See Technical notes for
the exact shapes matched.
a published list price (the list price overstated real cost here by
up to 3.8x).
per-tool budget, with a fallback to a per-cause budget, with a
fallback to a fixed default. Compared against a single learned
budget, a cause-only budget, and today's fixed 2 pings.
tool-declaration and tool-use tables.
teammate's reply stays open, including waits that never close.
(
keepalive = 1), not inferred from a later real request's ownping count. The earlier method missed every ping whose session
never sent another real request — a production check found 351 real
ping rows where it surfaced 28. Each ping is matched to the gap it
falls inside by timestamp, and priced from its own real
cost_usd.Pings that fall inside no measured gap are reported separately, as
pings for a session that did not return.
How it was tested
--self-testbuilds a synthetic transcript and a synthetic sqlitedatabase, with known gaps, known hits and misses, known wake causes
and waiting-for values, and known DB rows. It asserts the script's
exact output against hand-worked numbers. It covers every wake cause
and every
waiting_forvalue, the price fit, the DB-row match, themislabel check, both policy-comparison splits, and the per-tool
table's own reconciliation check.
on both local projects. They match exactly.
of the same formula. They match exactly:
claude-opus-5-5$3.91/MTok,
claude-sonnet-5$2.00/MTok,claude-opus-5$5.00/MTok,claude-haiku-4-5$1.00/MTok.match. Both give 99.8%.
waiting_forxwake_causetable were each traced toa real session, timestamp, and transcript entry, then fixed. See
Caveats and Technical notes.
Results
All numbers below are from both local Claude Code projects
(
context-guru,forever) and their dashboard databases. The data islive traffic, so a re-run gives slightly different numbers.
Mislabel check (issue #423): how many DB
prefix_changerows arereally a per-thread TTL expiry, not a compaction-driven miss.
waiting_forpredictswake_cause, on main threads, bothprojects combined. Each row is what the thread was waiting on when
the wait started; the share is how often that same cause ended it.
own_toolhuman)A thread's own tool call is a reliable signal. A pending teammate
message is a fair signal. A pending background task is a weak signal:
most of the time something else (usually the human) ends the wait
first.
Cost per cause, at its own best ping budget (
context-gurumainthreads; the project with enough data to show a stable number). Cost
is in units of
x, the prompt's own base price; 1.15x is the cost ofa miss with no pings at all.
own_toolhuman)Ping-budget policy comparison, learned on the first half of each
project's sessions by time, tested on the second half:
forever's test half has only 14 gaps. That is too few to proveanything, in either direction.
On
context-guru, the 3 learned policies land close together and allbeat the fixed default by 3-6%. The best of the 3 is the single
learned number, not the per-tool budget. This data does not show
that learning a budget per tool beats one learned number for
everything.
A second check, over 5 random session splits instead of 1 time-ordered
split, gives the same ranking on both projects:
Open teammate waits. How long a wait for a teammate's reply stays
open, on
context-guru:About a third of this project's teammate waits never close within the
visible transcript. Issue #424 needs its own rule for how long to keep
pinging a teammate wait that may never close — nothing like a
Monitor's stated expiry exists for this case today.Real keep-alive pings, read directly from the DB's ping rows, both
local databases combined:
A ping for a session that never returns is invisible to the OLD
method (reading a later real request's own ping count): on the same
data, it reported 28 real pings seen in DB-only mode. Reading ping
rows directly, this script now reports all 360 (305 inside a measured
gap in DB-only mode's coarser
(session, model)grouping; 55 for asession that did not return, $2.83).
Caveats
(session, model)pair. 2 subagents on the same model look like 1thread; a main thread that switches model looks like 2.
--dbis given, or the DB never billed that model.
of 4.67 minutes or more in the training half. Below that, the table
reports
n/arather than a budget fit to too little data.script will give slightly different numbers from the ones above.
waiting_forandwake_cause(as inthe Results table above) is not all unpredictable. Some of it is a
design choice open to Record why a thread waits, and set the keep-alive ping budget from it #424: a thread can have more than one thing
pending (a teammate wait AND a background task), and
waiting_forreports only the first one checked.
the DB has one (issue Key cache attribution and keep-alive per thread, not per session #423, not populated on either local database
yet), else by
(session, model)— the same approximation aseverywhere else in this script that falls back to that pair. A
session with more than one thread sharing a model can attribute a
ping sent for one thread to a different thread's gap.
Technical notes
Open background tasks, matched by text, found by reading real
transcript entries rather than assuming a shape:
Bash:running in background with ID: X.<task-notification>namingXMonitor:Monitor started (task X, <detail>), where<detail>isexpires in <duration> unless the source ends first, ortimeout <N>ms, orpersistent — runs until TaskStop or session end<task-notification>whose event text says[Monitor expired after ...]— not just any notification namingX: aMonitorsends one of these for every matching event while it keeps runningAgenttool, run in background):Async agent launched successfully... agentId: X<agent-message from="X">— not a<task-notification>Skill(forked execution): the id is not in the text at all; it is the entry's owntoolUseResult.agentIdfield<task-notification>or an<agent-message from="X">TaskStop(task_id=X)tool call, matched on its structured input, not by textOpen teammate waits: a
SendMessagetool call opens one, matchedon its structured
tofield. A<teammate-message teammate_id="X">or
<cross-session-message from-name="X">closes it.Matching a DB row to a transcript call. The DB has no thread id
(issue #423), and its timestamp is the request's start, not the
response's arrival, which is all a transcript has. Matching on the
request start plus the DB's own
upstream_ms(an estimate of theresponse's arrival) finds 99.8% of calls within 15 seconds, against
96.2% within 60 seconds for the request start alone.
Price fit.
cost_usd = price * (fresh_input + 0.1*cache_read + 1.25*cache_write + 5*output_tokens), solved per model from the DB'sown billed rows by least squares through the origin. Used instead of
a published list price, which overstated billed cost here by up to
3.8x for one model.
Ping-budget simulation: a ping fires every 4.67 minutes. N pings
keep the cache warm for
4.67*N + 5minutes. A gap that ends insidethat window costs
0.1 * min(N, floor(gap / 4.67)), in units ofx;otherwise it costs
0.1*N + 1.15. No budget goes above 11 pings — pastthat point, the cost of pinging and still missing exceeds the cost of
never pinging at all.
Reading real pings. A ping row (
keepalive = 1) is matched to thegap it falls inside by timestamp, not by reading a later real
request's own ping count — that column is written once, on whichever
real request ends a run of pings, so a ping whose session never sends
another real request has no such row to be counted on at all. A ping
with
max_tokens = 0is a summary-substitute call (issue #458):still a ping slot, priced from its own
cost_usd, not the usual 0.1xestimate.