Skip to content

feat(analysis): add wait-cause and ping-budget analysis script - #425

Merged
amiddavid merged 11 commits into
mainfrom
feat/wait-cause-analysis
Oct 13, 2026
Merged

amiddavid merged 11 commits into
mainfrom
feat/wait-cause-analysis

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • This script measures why a Claude Code thread waits, and what a
    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).
  • It reads session transcripts and the dashboard DB. It also runs on
    the DB alone, the way the production proxy will need it.
  • A thread's own tool call predicts the end of its wait well: 97% of
    the time. A pending teammate message or background task predicts it
    less well: 53% and 24% of the time. See Results.
  • A learned budget beats today's fixed 2 pings by 3-6%. The data does
    not show that a per-tool budget beats one single learned number.
    See Results.
  • A third of one project's teammate waits never get a reply at all,
    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. Run
it with python3 -I.

Transcript mode. Reads Claude Code session transcripts together
with the dashboard DB. Give it one or more --projects-dir folders
(for example ~/.claude/projects/-Users-you-git-your-repo) and,
optionally, one or more --db paths:

python3 -I scripts/analysis/wait_causes.py \
  --projects-dir ~/.claude/projects/-Users-you-git-your-repo \
  --db ~/.local/state/context-guru/dashboard-8789.db

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:

python3 -I scripts/analysis/wait_causes.py --db /path/to/dashboard.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 --json for machine-readable output. Add --self-test to run the
script'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.py and
scripts/analysis/README.md.

  • wake_cause: why a wait ended. One of tool_result,
    background, teammate, human, system, or retry. Read from
    the 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 failed
    prior call).
  • waiting_for: what the thread was waiting on when the wait
    started, 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, or retry. Read from the response that ends
    the turn before the wait: a tool call means own_tool (with the
    tool's name kept), except AskUserQuestion and ExitPlanMode, which
    wait on a human. No tool call means background if a background
    task is open, teammate if a teammate wait is open, else human.
  • Open background tasks and open teammate waits: tracked per
    thread from the request body, no LLM needed. See Technical notes for
    the exact shapes matched.
  • A price fit per model, from the DB's own billed cost, instead of
    a published list price (the list price overstated real cost here by
    up to 3.8x).
  • A learned ping-budget policy per issue Record why a thread waits, and set the keep-alive ping budget from it #424 section 4: a
    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.
  • A declared-but-never-called tools report, from the DB's own
    tool-declaration and tool-use tables.
  • An open-teammate-wait duration report: how long a wait for a
    teammate's reply stays open, including waits that never close.
  • Real keep-alive pings, read directly from the DB's ping rows
    (keepalive = 1), not inferred from a later real request's own
    ping 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-test builds a synthetic transcript and a synthetic sqlite
    database, 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_for value, the price fit, the DB-row match, the
    mislabel check, both policy-comparison splits, and the per-tool
    table's own reconciliation check.
  • Hit and miss counts were cross-checked against an independent count
    on both local projects. They match exactly.
  • The DB-fitted prices were cross-checked against an independent fit
    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.
  • The DB-row match rate was cross-checked against an independent
    match. Both give 99.8%.
  • 3 leaks in the waiting_for x wake_cause table were each traced to
    a 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 is
live traffic, so a re-run gives slightly different numbers.

Mislabel check (issue #423): how many DB prefix_change rows are
really a per-thread TTL expiry, not a compaction-driven miss.

Checked Mislabeled Their full cost
150 141 $134.99

waiting_for predicts wake_cause, on main threads, both
projects combined. Each row is what the thread was waiting on when
the wait started; the share is how often that same cause ended it.

Waiting for Gaps Ended by the same cause
own_tool 117 114 (97%)
Nothing open (human) 250 217 (87%)
An open teammate message 111 59 (53%)
An open background task 259 63 (24%)

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-guru main
threads; 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 of
a miss with no pings at all.

Waiting for Best N Cost at best N
own_tool 4 0.12x
An open background task 5 0.57x
An open teammate message 6 0.79x
Nothing open (human) 4 0.81x

Ping-budget policy comparison, learned on the first half of each
project's sessions by time, tested on the second half:

Project Test gaps Learned per tool Learned per cause One learned number Fixed 2 pings
context-guru 467 0.56x 0.55x 0.54x 0.58x
forever 14 0.44x 0.44x 0.56x 0.55x

forever's test half has only 14 gaps. That is too few to prove
anything, in either direction.

On context-guru, the 3 learned policies land close together and all
beat 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:

Project Learned per tool One learned number
context-guru 0.61 (0.55-0.68) 0.59 (0.53-0.62)
forever 0.63 (0.35-0.88) 0.52 (0.41-0.61)

Open teammate waits. How long a wait for a teammate's reply stays
open, on context-guru:

Count Share
Never gets a reply at all 91 32%
Gets a reply, 90th percentile wait — 3.0 hours

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:

Count Sessions Cost
Every ping row 360 25 $25.53
...falling inside a measured gap 274 — $22.01
...for a session that never returned 86 25 $3.52

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 a
session that did not return, $2.83).

Caveats

  • DB-only mode has no thread id, so a "thread" there is really a
    (session, model) pair. 2 subagents on the same model look like 1
    thread; a main thread that switches model looks like 2.
  • Model prices fall back to a small hardcoded table only when no --db
    is given, or the DB never billed that model.
  • The per-tool budget only applies when a tool has at least 20 waits
    of 4.67 minutes or more in the training half. Below that, the table
    reports n/a rather than a budget fit to too little data.
  • Both local projects' transcripts are live. A later re-run of this
    script will give slightly different numbers from the ones above.
  • The residual mismatch between waiting_for and wake_cause (as in
    the 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_for
    reports only the first one checked.
  • A real ping is matched to the gap it falls inside by thread id when
    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 as
    everywhere 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:

Start Finish
Backgrounded Bash: running in background with ID: X. <task-notification> naming X
Monitor: Monitor started (task X, <detail>), where <detail> is expires in <duration> unless the source ends first, or timeout <N>ms, or persistent — runs until TaskStop or session end The stated expiry passing, or a <task-notification> whose event text says [Monitor expired after ...] — not just any notification naming X: a Monitor sends one of these for every matching event while it keeps running
Async agent (Agent tool, run in background): Async agent launched successfully... agentId: X <agent-message from="X"> — not a <task-notification>
Background Skill (forked execution): the id is not in the text at all; it is the entry's own toolUseResult.agentId field A <task-notification> or an <agent-message from="X">
Any of the above A TaskStop(task_id=X) tool call, matched on its structured input, not by text

Open teammate waits: a SendMessage tool call opens one, matched
on its structured to field. 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 the
response'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's
own 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 + 5 minutes. A gap that ends inside
that window costs 0.1 * min(N, floor(gap / 4.67)), in units of x;
otherwise it costs 0.1*N + 1.15. No budget goes above 11 pings — past
that 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 the
gap 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 = 0 is a summary-substitute call (issue #458):
still a ping slot, priced from its own cost_usd, not the usual 0.1x
estimate.

amiddavid added a commit that referenced this pull request Oct 8, 2026
…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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 --db is 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.

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 human wakes are reviewer or teammate messages. The "teammate" cause is therefore undercounted, and this is the cause #424 most needs.
  • Other entries with isMeta: true also land in human: skill loads (Base directory for this skill:, 17), Check background task … (2) and <system-reminder> (2).
  • Proposed fix:
    • Match <cross-session-message as teammate.
    • Never classify an isMeta entry as human. Use its marker if it has one, otherwise a separate system cause.
  • #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_ms matches 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 teammate wake in each format (<teammate-message, <cross-session-message)
  • an isMeta entry
  • 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.

amiddavid added a commit that referenced this pull request Oct 8, 2026
… 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

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

  1. Prices. Added fit_model_prices(): fits 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 (exact same formula you used — my fit matches your table exactly: opus-5-5 $3.91, sonnet-5 $2.00, opus-5 $5.00, haiku-4-5 $1.00). PriceTable prefers that fit over a hardcoded fallback (now corrected to these same numbers, used only when no --db is given or the DB never billed that model), matched by substring so a Bedrock ARN model id still resolves. The report now opens with price_sources: which price priced which model, and from where (db_fit vs hardcoded_fallback). Every USD total in the PR body is recomputed with this.

  2. Teammate/human misclassification. TEAMMATE_RE now matches <cross-session-message as well as <teammate-message. An isMeta entry with no recognized marker (skill loads, system nudges, subagent hand-back notices) now gets its own system cause instead of falling through to human. On context-guru main threads this moved ~50 gaps from human into teammate and created an 18-gap system bucket — close to your 52-gap estimate (the small gap is almost certainly system entries that also would've landed in human under the old logic, now correctly going to system instead of teammate). Noted in the README that Record why a thread waits, and set the keep-alive ping budget from it #424's own wake_cause field needs the same marker list.

Should fix

  1. Simulation edge case. sim_cost_x now charges 0.1 * min(N, floor(g/4.67)) inside the window — N=0 can no longer be charged for a ping it never sends.

  2. Errors counted as misses. summarize_gaps_by_cause now counts hits, misses, and errors from their own properties (hits + misses + errors == gap count) instead of misses = len(gs) - hits, which folded every error into the miss count. The report now shows all three per cause.

  3. DB match on request-start vs response-arrival. Both the mislabel check and the OBSERVED column's real-ping lookup now match on ts + upstream_ms (an approximate response-arrival time) instead of raw ts, through a shared approx_response_ts() / DBIndex. On the validation session this raises the match rate from 96.2% to 99.75% (2817/2824, counting every thread, within a now-15-second window instead of 60) with a median residual of 0.13s — matches your 99.8% almost exactly.

  4. DB-only mode. db_only_report now uses the same cache_read/cache_write hit rule as transcript mode (not cache_miss_reason, which inherits whatever Key cache attribution and keep-alive per thread, not per session #423 hasn't fixed yet) and the row's own real keepalive_pings for the observed cost, split into OBSERVED/SIMULATED like transcript mode.

Minor

  1. Renamed mislabeled_usd to mislabeled_full_cost_usd and documented it as the mislabeled rows' full recorded cost_usd (matching the dashboard's prefix_change_cost_usd), not a miss premium.

  2. Extended --self-test: a retry gap (error call followed by a miss, asserting the error itself isn't double-counted), both teammate-message formats, an isMeta/system wake, a tiny synthetic sqlite DB exercising the price fit, the response-time match (DBIndex, mislabel_check), and db_only_report against deliberately mislabeled cache_miss_reason rows. All pass.

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 scripts/analysis/README.md (new sections: "Prices", "Matching a DB row to a transcript call", updated "Known approximations" and "Validation").

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Production validation: DB-only mode

Result: DB-only mode runs cleanly on a production multi-tenant dashboard DB. The run was read-only on the contextguru host's cg.db, with no API calls. It covered 134 sessions and 21,149 requests, Sep 9 to Oct 11.

What it found

Measure Value
Idle gaps over 4.67 min 1,504 (median 8.9 min, p90 89 min, max 8.5 days)
Of those, cache misses 1,175 (78%)
Keep-alive pings actually sent 11
Measured cost of those gaps 0.90x per gap, $770 in total

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:

Pings per gap Cost per gap Estimated USD Saving against measured
0 0.97x — —
2 0.56x about $480 about $290 (38%)
4 0.48x about $410 about $360
6 (best) 0.44x about $380 about $390 (51%)
10 0.47x — —

What this means

Other findings

  • 584 failed requests. Their median time before failing is 8.1 s, and 140 cache misses follow a failure.
  • Fitted prices differ by route for the same model: aws/claude-sonnet-5 is $1.52/MTok, and claude-sonnet-5 is $2.28/MTok. The script reads what the dashboard billed, so this reflects the production price data. It is worth checking whether that split is intended.

Not covered

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Production validation, second host (contextguru2)

Result: DB-only mode also runs cleanly on the contextguru2 production DB (read-only, run as root on the host, no API calls). This host has content capture on. The script does not read the content tables.

The two hosts side by side

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 contextguru2 hang 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. contextguru2 prices them at list (opus-5 $5.00/MTok, sonnet-5 $2.00, haiku-4-5 $1.00). contextguru prices them at about 0.76 times that, and gives aws/claude-sonnet-5 ($1.52) a different price from claude-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.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Production follow-up: why so few keep-alive pings on contextguru2

Result: most idle gaps without a ping happened INSIDE a keep-alive window, in sessions with more than one model. That is the session-level keep-alive keying that #426 fixed. Time windows and cost ceilings explain only a small part.

1. Correction to the numbers above: 351 pings, not 28

  • The DB holds 351 ping rows (keepalive = 1) in 75 sessions.
  • The script reported "28 real pings seen". DB-only mode counts only the pings recorded on the next real request (keepalive_pings), inside the gaps it measured. Pings for sessions that never came back are missed, and so is their cost.
  • This is a bug in this PR. DB-only mode must count ping rows directly, and add their cost_usd to the measured cost. It is being fixed before merge.

2. The keep-alive strategies on this host

There are 5 active strategies, all targeting all users:

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

  1. Deploy feat(keepalive,dash): key cache attribution and keep-alive per thread #426 (in this release). It removes the biggest cause.
  2. Raise the strategies to 2 pings. The simulation in the comment above shows 2 pings capture most of the saving.
  3. Consider covering evenings and weekends.
  4. Look into the 31 single-model gaps that got no ping inside a window.

amiddavid and others added 9 commits October 11, 2026 22:27
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]>
@amiddavid
amiddavid force-pushed the feat/wait-cause-analysis branch from fffcad2 to 8e2146a Compare October 11, 2026 20:02
@amiddavid

Copy link
Copy Markdown
Collaborator Author

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:

  1. They missed most pings. They counted only pings recorded on the next real request.
  2. They treated ping rows as requests. So a ping split a real idle gap into 2 short gaps, and the simulation looked better than it is.

Both are fixed in 8e2146a. The conclusion does not change: 2 pings per thread captures most of the saving.

Measure contextguru contextguru2
Ping rows (keepalive = 1) 227 in 27 sessions, $16.47 (earlier: "11") 351 in 75 sessions, $26.28 (earlier: "28")
Of those, for sessions that never came back 37, $1.41 91, $5.95
Idle gaps over 4.67 min 1,363 (median 10.8 min, p90 117 min) 810 (median 9.6 min, p90 126 min)
Cache misses among them 1,186 (87%) 625 (77%)
Measured cost, real pings included 1.02x per gap, $787 0.92x per gap, $408
Simulated, 0 pings 1.10x 1.12x
Simulated, 2 pings 0.63x, saves about $300 (38%) 0.59x, saves about $146 (36%)
Simulated, 4 pings 0.54x 0.55x
Simulated, 6 pings (best) 0.50x, saves about $400 (51%) 0.53x, saves about $174 (43%)
Failed requests / median time before failing 609 / 9 s 595 / 110 s
  • Keep-alive is on for part of the traffic on both hosts. It is not almost off, as I wrote before.
  • 2 pings capture most of the saving (36–38%), and the best budget adds only 7–13 points.
  • Together, the 2 hosts would have saved about $446 over this window with 2 pings per thread.
  • The breakdown by keep-alive window in the comment above still stands. It used its own query, which already excluded ping rows from the gaps.

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Turn gate on production: no gate recommended

Question: 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 turn_gate.py in DB-only mode (1b64f95), read-only, with this release's keep-alive defaults (#444): 2 pings, an 80,000-token floor, 270 s idle and a $0.50 per-ping ceiling. Net is the miss cost avoided minus the ping cost.

Turn contextguru pauses (pingable) net contextguru2 pauses (pingable) net
1 4 (1) −$0.63 15 (1) −$0.13
2–4 9 (0) $0.00 25 (4) +$0.59
5–9 18 (5) +$1.12 55 (17) +$2.74
10+ 439 (333) +$89.30 604 (444) +$136.71
Gate contextguru contextguru2 Together
Refuse turns under 5 +$0.63 −$0.45 +$0.18
Refuse turns under 10 −$0.49 −$3.19 −$3.68
  • The 80k floor already filters early turns: only 2 of 19 turn-1 pauses had a large enough prompt.
  • Turn 10 and later hold about $226 of the $230 net.
  • This matches the transcript-mode result on the local projects.

Caveats:

  • These production builds predate feat(keepalive,dash): key cache attribution and keep-alive per thread #426, so there is no thread id. Turns are counted per session and model, which is approximate.
  • contextguru now shows 39 ping rows, against 227 the day before. That host archives sessions older than 30 days (ARCHIVE_SESSION_AFTER=720h), and its data starts on Sep 9, so the oldest sessions most likely dropped out. Not confirmed.

@amiddavid
amiddavid merged commit 099239b into main Oct 13, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant