Skip to content

feat(dash,proxy): record wait cause and wake cause per request (#424 record half) - #453

Merged
amiddavid merged 7 commits into
mainfrom
feat/wait-cause-record
Oct 11, 2026
Merged

amiddavid merged 7 commits into
mainfrom
feat/wait-cause-record

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR adds the RECORD half of issue #424. The proxy now writes why each
thread waits and why it wakes up, on every request. It does not choose a
keep-alive ping budget. It does not change keep-alive or compaction
behaviour. The keep-alive still sends a fixed 2 pings per thread (PR #426).

Part of #424.

What changed

New package internal/waitcause. It reads two things, by string match and
structural tool_use reads only — no LLM:

  • waiting_for: what a thread is about to wait on, set on the row whose
    OWN response ends a turn. One of own_tool (with the last tool's name
    kept in wait_tool), human, background, teammate, retry,
    unknown.
  • wake_cause: what ended a wait, set on the row that starts the next
    turn. One of tool_result, background, teammate, human, system,
    retry, unknown.
  • open_background / open_teammate / monitor_expiry_ms: the open
    background-task count, open-teammate-wait count, and the latest known
    Monitor expiry, as of that request's own body.

All six are new nullable columns on requests (additive, no schema version
bump — same pattern as thread_id and keepalive_strategy_id). A row from
before this feature existed reads NULL, not a guessed value.

waiting_for and wake_cause are also new dimensions of /api/breakdown,
so a dashboard user can split cost and request count by them. No new panel.

No second body parser. internal/waitcause builds its signals from
apply.NormalizeMessages(provider, orig) — the same normalization the
compaction pipeline itself already uses for all three providers the issue
names (Anthropic Messages, OpenAI chat, OpenAI Responses). Where a Claude
Code marker does not apply — another agent, another provider, a shape this
package does not recognise — the fields read "unknown", never a guess.

The open-task/open-teammate state survives the agent compacting its own
history.
An item (a Monitor, a backgrounded Bash, a pending SendMessage)
stays "open" until its own finish signal, a TaskStop, a stated Monitor
expiry, or a cap for one with none — never merely because its start marker
scrolled out of a since-compacted body.

Fails open. Every exported waitcause function recovers internally
from a panic and returns the zero value. A bug here can only degrade this
data; it can never block, change, or slow the request.

Off the request path, entirely. The actual body rescan
(waitcause.Tracker.Observe) never runs on the path that forwards the
request, and never runs inline in finish() either — both were measured
to add real latency (see "A real latency regression" below). It runs as a
closure (dash.Event.WaitCause) the dashboard's own WRITER goroutine
invokes right before the insert, the same place and for the same reason
Event.Redact() already runs there.

How it was tested

Unit tests (internal/waitcause, go test -race, all green): every
value of waiting_for and wake_cause, on Anthropic Messages, OpenAI chat
and OpenAI Responses bodies. Both teammate marker forms
(<teammate-message>, <cross-session-message>). An async-agent/Skill
finish (<agent-message from="X">) and a <task-notification>, both as
wake_cause=background. A Monitor's mid-watch notice (not a finish) vs.
its expired notice (a finish) vs. its own stated expiry elapsing with no
notice at all. A backgrounded Bash, an async agent, and an anonymous
backgrounded Skill launch (its real id lives only in a transcript field no
API body carries). TaskStop. The AskUserQuestion / ExitPlanMode
exception, both for waiting_for and for the bare tool_result that
answers them. The retry rule (same thread, non-200 previous status, same
message count) and its two negatives (success, or a grown conversation).
An item surviving a compacted body with no start marker (fix 6, see
below). A trailing role:"system" noise entry hiding the real signal
behind it (found live — see "A real defect" below), for all three cases
(tool_result, human, the AskUserQuestion exception). The full teammate
lifecycle in one test — own_tool/SendMessage opens the wait,
waiting_for=teammate once the turn ends with nothing else to do, and a
<teammate-message> reply gives wake_cause=teammate and closes
open_teammate back to 0
(TestTeammateReplyClosesAnOpenWaitAndWakesTheThread). A sibling block
beside a tool_result in the same wire message (#457/#460, see "Open
questions"): mid-turn user text gives human, a <task-notification>
sibling gives background, and a <system-reminder>-only sibling does
NOT give human. Fail-open on a malformed body and on a nil tracker.

Added latency (BenchmarkObserveLargeBody, on the eval box): ~11
ms
for a 783 KB body (2,000 turn pairs) — the full per-request rescan.
This is real work, which is exactly why it does NOT run on the request
path or in finish() — see the two latency fixes below.

go test -race -count=1 on internal/waitcause, apply, proxy,
dash, cmd/... on the eval box: all green, no cache. The existing
keep-alive tests pass unchanged (-run 'KeepAlive|Keepalive|Keeper'),
and TestDashboardAddsNoRequestLatencyWithContentCapture (the test that
caught the first latency regression — see below) now passes with ~1 ms
added, well inside budget. Also ran, specifically, the tests this
package's new dependency on apply.NormalizeMessages touches:
TestXHighPresetCommitsACacheAwareSummary,
TestCacheAwarePipelineOrderMinimalTextCleanCase,
TestSweepGuardUsesRawCoordinatesNotPipelinePosition,
TestCacheAwareStalePrefixThroughARealOversizedTurn, and apply's
TestResponsesSetsRawInputBeforeThePipelineRewrites — none dropped to 0
summary/ask calls.

Live traffic during development (not a release gate for this PR).
Per policy, an individual PR does not carry its own live test; a merged-
main integration check covers that, run separately. Before that policy
was set for this PR, a proxy built from this branch — pointed at the real
provider gateway, not Context Guru — drove a real Claude Code session
through it in a scratch config, specifically to shake out shapes a unit
test would not have thought to write. It found both real defects below.
That exploration is also why waiting_for=teammate's CLOSE path
(a genuine <teammate-message> reply) is unit-tested here
(TestTeammateReplyClosesAnOpenWaitAndWakesTheThread, covering the whole
open → waiting_for=teammate → wake_cause=teammate → closed lifecycle in
one test) rather than claimed from a live run: this environment's actual
backgrounded-Agent hand-back turned out to use a DIFFERENT signal
(<agent-message from="X">, see the first defect below) than the
agent-team <teammate-message> tag the issue's own design was written
against, and reaching a genuine peer-session <teammate-message> close
live would need a fuller agent-team setup than a scratch sandbox gives
cheaply. The live teammate-reply CLOSE case is checked in the
merged-main integration run
, not here.

A real defect, found live, not assumed in advance — and fixed. A
backgrounded Agent's hand-back wakes the thread with ONLY an
<agent-message from="X">...</agent-message> tag (plus the harness's own
boilerplate) — no <task-notification>, no plain text. classifyWake had
no case for this tag at all, so it fell through to "plain text" and
reported wake_cause=human instead of background. Fixed by reusing the
same <agent-message from="X"> pattern already used to CLOSE an open
background task, now also as a wake_cause=background signal — confirmed
fixed live (re-ran the identical scenario; the row that read human
before now reads background), with a regression test
(TestObserveWakeCauseAgentMessageIsBackground).

A second real defect, found earlier in the same live test, also
fixed.
This org's Claude Code build appends a bare
{"role":"system","content":"<total_tokens>...tokens left</total_tokens>"}
entry after every turn, including right after the real tool_result or
human text that is the actual wake signal — confirmed by
schema.SessionHead's own doc comment in this repo, which names the
Claude Agent SDK as the source. The first version of classifyWake read
only the last message and misread the Bash-finishing wait as
wake_cause=human. Fixed by skipping trailing role=="system" entries
structurally (isNoiseEntry) rather than guessing from content — the role
itself is a stronger signal than a <system-reminder> string match.
Confirmed fixed live and covered by regression tests.

Open questions

  • Resolved. The gap this PR found in apply.NormalizeMessages
    (apply.normalize's Anthropic branch dropped any OTHER content block
    sitting beside a tool_result in the same user message — mid-turn
    user text, a system-reminder, a task notification) got its own issue
    and PR, per this repo's rule that a defect on main affecting every
    component does not ride a feature branch: apply.normalize drops text blocks that share a user message with a tool_result #457, fixed by fix(apply): keep sibling text blocks beside a tool_result in the normalized view #460
    (fix/normalizer-siblings), now merged to main and rebased onto
    here. apply.normalize now keeps the sibling as its own synthetic
    role=user message, in wire order — this PR's own pinning test
    (apply/normalize_siblingblock_test.go, which asserted the OLD,
    dropped behaviour) is deleted rather than flipped: fix(apply): keep sibling text blocks beside a tool_result in the normalized view #460's own
    apply/normalizer_siblings_test.go already covers the normalizer
    directly. internal/waitcause gets three new tests instead, for what
    THIS package needs to get right now that the sibling reaches it: a
    tool_result plus mid-turn user text gives wake_cause=human, a
    tool_result plus a <task-notification> sibling gives
    wake_cause=background, and a sibling that is ONLY a
    <system-reminder> block does NOT read as human — the synthetic
    sibling message is always role=user (never role=system), so
    isNoiseEntry's role check does not catch it; classifyWake's
    content-based hasSystemMarker check already does, independent of
    role, and that is what these new tests pin.
  • The response-side tool_use extraction (responseToolUseNames, new field
    on Usage) is best-effort on a streamed response: it reads whatever the
    sniffer's bounded head+tail window holds (see newSniffer), so a
    tool_use far into a very long streamed response can fall outside it. That
    under-reports own_tool; it never invents one.
  • The open-teammate 56-minute cap, the matching cap for a background task
    with no stated expiry, and the per-thread persistent state are all new,
    small, in-memory-only (never persisted, never logged — no names, no task
    ids, only counts and labels reach the database). Bounded the same crude
    way internal/thread bounds its own maps, but has not run under the
    kind of long-lived-thread load that package has.
  • A background Skill launch's real id is not in any API body at all (only
    in a transcript's own toolUseResult.agentId), so it is tracked
    anonymously (oldest-matches-first, now persistent across compaction
    too). This is the same imprecise, documented choice
    scripts/analysis/wait_causes.py (feat(analysis): add wait-cause and ping-budget analysis script #425) makes for the same case.
  • A backgrounded Agent teammate's hand-back (seen during development)
    is not the same code path the issue's own <teammate-message>/
    SendMessage design was written against (that is a peer Claude
    session, not a backgrounded subagent) — see the first defect above.
    waiting_for=teammate and the SendMessage-open path are unit-tested
    here; the live, merged-main integration run is where a genuine peer-
    session <teammate-message> close gets checked end to end.

Technical notes

  • Full per-request rescan, not incremental state, for the open-task/
    open-teammate counts: the body already carries the whole conversation,
    so a fresh scan is self-correcting from anything an earlier request
    missed (a restart, a dropped event) where incremental state would stay
    wrong forever. What DOES persist across requests, per thread: the
    open-background/open-teammate sets themselves (fix 6, so compaction
    can't silently close them), a small map from a stable id to the
    wall-clock time this process first saw it open (needed because the body
    itself carries no timestamps at all), a bounded set of already-applied
    close signals (so replaying the same historical signal — every request
    resends the whole conversation — can't repeatedly pop an unrelated
    anonymous Skill entry), and the previous request's status and message
    count, for the retry rule.
  • Marker shapes (Monitor start/expiry text, task-notification blocks,
    teammate/cross-session message tags, background Bash/async-agent/Skill
    start text, <agent-message from="X">) are exactly
    scripts/analysis/wait_causes.py's (feat(analysis): add wait-cause and ping-budget analysis script #425), verified there against real
    Claude Code transcripts, plus the two fixes this PR's own live test
    found (the <agent-message> wake and the role:"system" noise entry).
    The proxy sees the API request body, not a transcript, so there is no
    isMeta flag: system-injected text is told apart by content
    (<system-reminder, Base directory for this skill:, …) for a
    user-role entry, and structurally (the role itself) for a bare
    role: "system" entry.
  • Usage.ToolUseNames is new, filled at the same point Usage.StopReason
    already is (responseStopReason), off the same buffered/sniffed bytes,
    for Anthropic Messages (buffered and streamed content_block_start),
    OpenAI chat (buffered tool_calls and streamed delta.tool_calls), and
    OpenAI Responses (buffered output[].function_call).
  • The body scan runs on the dashboard's writer goroutine, not on the
    request path, and not inline in finish().
    First version: the scan
    ran inline in finish(), which runs on the handler's own defer, BEFORE
    the handler returns — so it delayed the NEXT request on a keep-alive
    connection by exactly the scan's own cost, which
    TestDashboardAddsNoRequestLatencyWithContentCapture caught (added
    ~97ms against a ~34ms budget). Fixed by building a closure around
    everything the scan needs and handing it to dash.Event.WaitCause,
    invoked by the writer right beside Event.Redact() for the identical
    reason. Tracker.RecordOutcome (this request's own status/message
    count, for the next request's retry check) is folded into the same
    closure so it still runs strictly after Observe reads the previous
    state, in the writer's own FIFO order — the one trade-off is that a row
    DROPPED under a full capture channel also skips RecordOutcome for it,
    which can miss a retry label; fail-open, same as everywhere else here.
  • proxy/keepalive_test.go: one test's u == (Usage{}) struct-equality
    check stopped compiling once Usage gained a slice field; changed to an
    equivalent field-by-field zero check, no behaviour change.
  • Keep-alive ping rows carry no wait-cause label, by construction, not
    by a special-case check: a ping's dash.Event is built entirely in
    dashEmitter.KeepAlivePing (cmd/context-guru-proxy), which never sets
    Event.WaitCause — there is no *waitcause.Tracker reference anywhere
    on that path for either a plain ping (record1) or the
    cache_aware_summarizer's keep-alive-substitute ping (feat(offload): give cache_aware_summarizer a real trigger and feed the keep-alive #402,
    recordSummarySubstitute), both of which reach the identical
    KeepAlivePing call. Pinned by
    TestDashEmitterKeepAlivePingCarriesNoWaitCause and
    TestDashEmitterSummarySubstitutePingCarriesNoWaitCause.

🤖 Generated with Claude Code

amiddavid added a commit that referenced this pull request Oct 11, 2026
…ross compaction

Two more fixes to #453, both decided by the user.

1. internal/waitcause no longer carries its own per-provider body parser
   (messageEntries, blocksOf's old gjson-based version). It now builds
   its wait signals from apply.NormalizeMessages(provider, orig) — the
   same normalization the compaction pipeline itself uses for all three
   dialects (Anthropic Messages, OpenAI chat, OpenAI Responses). Role-
   based system-noise detection (isNoiseEntry) now reads
   bschemas.ChatMessageRoleSystem directly instead of guessing from
   content.

   Found in the process, and deliberately NOT fixed here (a defect on
   main affecting every component gets its own issue and PR, not a fix
   riding a feature branch — the user is tracking it separately):
   apply.normalize's Anthropic branch drops any OTHER content block
   sibling to a tool_result in the same user message. Pinned by
   apply/normalize_siblingblock_test.go, written to fail once that
   normalizer gap is fixed.

2. The open-background-task and open-teammate state now survives the
   agent compacting its own history. Previously every request did a
   fresh rescan of the current body with no memory of earlier requests,
   so a Monitor's own start marker scrolling out of a compacted body
   read as "closed" even though the task was still running. The
   Tracker's per-thread state is now the source of truth (threadState.
   openBackground / openTeammates), updated by applying each request's
   open/close signals onto it rather than rebuilt from scratch; an item
   leaves only on its own finish signal, a TaskStop, a stated Monitor
   expiry, or a cap for one with none (noExpiryCap, matched to the
   existing teammateWaitCap). Every write is naturally safe to repeat
   against the same historical signal (every request resends the whole
   conversation) except the Skill-anonymous close fallback, which is
   explicitly guarded by a bounded appliedCloses set.

Also fixes a real latency regression the user's own test caught:
TestDashboardAddsNoRequestLatencyWithContentCapture failed because the
body rescan (waitcause.Tracker.Observe, ~11ms on a 783 KB body) was
running inline in finish(), which runs on the handler's own defer
before it returns — delaying the NEXT request on a keep-alive
connection by that amount. The scan now runs as a closure
(dash.Event.WaitCause) invoked by the dashboard's writer goroutine,
right beside Event.Redact() and for the identical reason. RecordOutcome
is folded into the same closure so it still runs strictly after Observe
reads the previous state, in the same order requests arrived.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid
amiddavid force-pushed the feat/wait-cause-record branch from 189f458 to 043f82c Compare October 11, 2026 15:31
amiddavid added a commit that referenced this pull request Oct 11, 2026
…ot human

Found live, in #453's own live test: a backgrounded Agent's hand-back
wakes the thread with ONLY an `<agent-message from="X">...</agent-message>`
tag (plus the harness's own boilerplate explaining what it is) — no
`<task-notification>`, no plain human text. classifyWake had no case
for this tag at all, so it fell through to hasPlainText and reported
wake_cause=human instead of background.

Fixed by reusing agentMessageFromRE (already used to CLOSE an open
background task in scanOpenState) as a presence check in classifyWake
too, in the same bucket as <task-notification>: both are a background
task's own finish signal arriving with nothing typed by a human.

Confirmed fixed live: the same scenario that showed wake_cause=human
before this fix now shows wake_cause=background. Regression test added
(TestObserveWakeCauseAgentMessageIsBackground).

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
…424 record half)

Add internal/waitcause, which reads the request body and the response's own
stop reason and tool calls, by string match and structural tool_use reads
only, no LLM. It writes waiting_for, wait_tool, wake_cause, open_background,
open_teammate and monitor_expiry_ms on every request, so a later change can
choose a keep-alive ping budget from real production data.

This is RECORD only. It never reads these fields back, never changes the
keep-alive ping budget (still a fixed 2 per thread, PR #426), and never
changes compaction behaviour. Fails open throughout: a panic or a shape this
package does not recognise leaves every field "unknown"/0 and never touches
the request or its timing.

Also adds waiting_for and wake_cause as /api/breakdown dimensions.

Found during the live test and fixed here: a trailing bare {"role":"system"}
entry some Claude Code builds append after every turn (even right after the
real tool_result or human text) was hiding the actual wake signal behind it;
classifyWake now skips trailing role=="system" entries structurally rather
than guessing from content.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Issue #424's RECORD half scanned the pristine body (waitcause.Tracker.
Observe, ~11ms on a 783 KB body) before forwarding the request upstream.
Move it to finish(), after the response has already gone out, by stashing
the body (one slice-header copy) with noteWaitBody instead of scanning it
inline. The request path's own cost is now independent of body size — see
BenchmarkNoteWaitBodyLargeBody alongside internal/waitcause's own
BenchmarkObserveLargeBody.

Also adds a test pinning that keep-alive ping rows (plain, and the
cache_aware_summarizer's #402 summary-substitute) never get a waiting_for
or wake_cause: both reach dash.Event construction through dashEmitter.
KeepAlivePing, which holds no *waitcause.Tracker at all, so there was
never a path from a ping to this package's state.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
…ross compaction

Two more fixes to #453, both decided by the user.

1. internal/waitcause no longer carries its own per-provider body parser
   (messageEntries, blocksOf's old gjson-based version). It now builds
   its wait signals from apply.NormalizeMessages(provider, orig) — the
   same normalization the compaction pipeline itself uses for all three
   dialects (Anthropic Messages, OpenAI chat, OpenAI Responses). Role-
   based system-noise detection (isNoiseEntry) now reads
   bschemas.ChatMessageRoleSystem directly instead of guessing from
   content.

   Found in the process, and deliberately NOT fixed here (a defect on
   main affecting every component gets its own issue and PR, not a fix
   riding a feature branch — the user is tracking it separately):
   apply.normalize's Anthropic branch drops any OTHER content block
   sibling to a tool_result in the same user message. Pinned by
   apply/normalize_siblingblock_test.go, written to fail once that
   normalizer gap is fixed.

2. The open-background-task and open-teammate state now survives the
   agent compacting its own history. Previously every request did a
   fresh rescan of the current body with no memory of earlier requests,
   so a Monitor's own start marker scrolling out of a compacted body
   read as "closed" even though the task was still running. The
   Tracker's per-thread state is now the source of truth (threadState.
   openBackground / openTeammates), updated by applying each request's
   open/close signals onto it rather than rebuilt from scratch; an item
   leaves only on its own finish signal, a TaskStop, a stated Monitor
   expiry, or a cap for one with none (noExpiryCap, matched to the
   existing teammateWaitCap). Every write is naturally safe to repeat
   against the same historical signal (every request resends the whole
   conversation) except the Skill-anonymous close fallback, which is
   explicitly guarded by a bounded appliedCloses set.

Also fixes a real latency regression the user's own test caught:
TestDashboardAddsNoRequestLatencyWithContentCapture failed because the
body rescan (waitcause.Tracker.Observe, ~11ms on a 783 KB body) was
running inline in finish(), which runs on the handler's own defer
before it returns — delaying the NEXT request on a keep-alive
connection by that amount. The scan now runs as a closure
(dash.Event.WaitCause) invoked by the dashboard's writer goroutine,
right beside Event.Redact() and for the identical reason. RecordOutcome
is folded into the same closure so it still runs strictly after Observe
reads the previous state, in the same order requests arrived.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
…ot human

Found live, in #453's own live test: a backgrounded Agent's hand-back
wakes the thread with ONLY an `<agent-message from="X">...</agent-message>`
tag (plus the harness's own boilerplate explaining what it is) — no
`<task-notification>`, no plain human text. classifyWake had no case
for this tag at all, so it fell through to hasPlainText and reported
wake_cause=human instead of background.

Fixed by reusing agentMessageFromRE (already used to CLOSE an open
background task in scanOpenState) as a presence check in classifyWake
too, in the same bucket as <task-notification>: both are a background
task's own finish signal arriving with nothing typed by a human.

Confirmed fixed live: the same scenario that showed wake_cause=human
before this fix now shows wake_cause=background. Regression test added
(TestObserveWakeCauseAgentMessageIsBackground).

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
…ecycle

Per policy, no live tests on an individual PR; the live teammate-reply
scenario moves to the merged-main integration check. Replaces it with a
unit test that exercises the same lifecycle: own_tool/SendMessage opens
the wait, waiting_for=teammate once the turn ends with nothing else to
do, and a <teammate-message> reply gives wake_cause=teammate and closes
open_teammate back to 0.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
…lings

#460 (fix/normalizer-siblings) merged, closing #457: apply.normalize now
keeps a sibling block beside a tool_result in the normalized view, as
its own synthetic role=user message in wire order, instead of dropping
it. apply's own normalizer_siblings_test.go
(TestNormalizeKeepsSiblingTextBlocksInOrder and friends) already covers
the normalizer directly, so the pinning test this PR added before #460
existed (apply/normalize_siblingblock_test.go, which asserted the OLD,
dropped behaviour) is deleted rather than flipped — keeping it would
either duplicate #460's own coverage or assert the wrong thing.

internal/waitcause gets three new tests instead, for what THIS package
needs to get right now that the sibling reaches it: a tool_result plus
mid-turn user text gives wake_cause=human, a tool_result plus a
<task-notification> sibling gives wake_cause=background (both read off
the LAST normalized entry, which is now the sibling, not the
tool_result), and a sibling that is ONLY a <system-reminder> block does
NOT read as human — apply.normalize's synthetic sibling message is
always role=user, so isNoiseEntry's role check does not catch it;
classifyWake's content-based hasSystemMarker check already does, and
this pins that it keeps doing so.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid
amiddavid force-pushed the feat/wait-cause-record branch from ce5aa5b to d33080b Compare October 11, 2026 17:32
@amiddavid
amiddavid merged commit 3ea2d7b into main Oct 11, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 11, 2026
OsherElhadad pushed a commit that referenced this pull request Oct 11, 2026
Behind --dashboard-lifecycle-signals (default off), a request_lifecycle side table
stores the gap from the previous response end on the same thread, the granted cache
TTL tier, the incoming tool_result count/bytes/error flag, and the keep-alive ping
ordinal. The thread id, previous stop reason and tool names are the requests columns
from #426 and #453 and are no longer duplicated. The body is read through
apply.NormalizeMessages on the dashboard writer goroutine; stale thread state is
evicted by age, amortised to once a minute; Lifecycles is scoped by tenant.

Signed-off-by: Osher-Elhadad <[email protected]>
amiddavid added a commit that referenced this pull request Oct 11, 2026
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 added a commit that referenced this pull request Oct 13, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 13, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are refused with a reason.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 13, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 13, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.
- Recover from a panic in the ping question: the ping stays plain, the
  panic is counted, and the next ping is plain too. Check the concurrency
  bound before collecting candidates.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.
- Recover from a panic in the ping question: the ping stays plain, the
  panic is counted, and the next ping is plain too. Check the concurrency
  bound before collecting candidates.

- Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper
  changes live in package keepalive (main moved the keeper there); the
  wait cause reaches it through Options.OpenTasks and Record.ToolUseNames.
  The question is framed with the shared opening line (resolveAsk.Frame)
  and asked through AskCovered when the asker supports it.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.
- Recover from a panic in the ping question: the ping stays plain, the
  panic is counted, and the next ping is plain too. Check the concurrency
  bound before collecting candidates.

- Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper
  changes live in package keepalive (main moved the keeper there); the
  wait cause reaches it through Options.OpenTasks and Record.ToolUseNames.
  The question is framed with the shared opening line (resolveAsk.Frame)
  and asked through AskCovered when the asker supports it.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.
- Recover from a panic in the ping question: the ping stays plain, the
  panic is counted, and the next ping is plain too. Check the concurrency
  bound before collecting candidates.

- Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper
  changes live in package keepalive (main moved the keeper there); the
  wait cause reaches it through Options.OpenTasks and Record.ToolUseNames.
  The question is framed with the shared opening line (resolveAsk.Frame)
  and asked through AskCovered when the asker supports it.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.
- Recover from a panic in the ping question: the ping stays plain, the
  panic is counted, and the next ping is plain too. Check the concurrency
  bound before collecting candidates.

- Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper
  changes live in package keepalive (main moved the keeper there); the
  wait cause reaches it through Options.OpenTasks and Record.ToolUseNames.
  The question is framed with the shared opening line (resolveAsk.Frame)
  and asked through AskCovered when the asker supports it.

- Review round 1: keep the conversation copies only for a thread the
  keep-alive can ping (Ctx.CanKeepAlive). Take the collection slot before
  collecting and release it on every exit. Count the result-cache miss in
  collect, and count sweep_concurrency_full. Report the shadow ask and the
  cold recheck once, under a mutex. Rewrite the sweep rows of
  docs/data-dependence.md and drop the stale counters and prose from
  advanced-offload.md.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
…adow mode (#508)

feat(sweep): ask at the keep-alive ping, hold the answer, recheck, shadow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.
- Recover from a panic in the ping question: the ping stays plain, the
  panic is counted, and the next ping is plain too. Check the concurrency
  bound before collecting candidates.

- Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper
  changes live in package keepalive (main moved the keeper there); the
  wait cause reaches it through Options.OpenTasks and Record.ToolUseNames.
  The question is framed with the shared opening line (resolveAsk.Frame)
  and asked through AskCovered when the asker supports it.

- Review round 1: keep the conversation copies only for a thread the
  keep-alive can ping (Ctx.CanKeepAlive). Take the collection slot before
  collecting and release it on every exit. Count the result-cache miss in
  collect, and count sweep_concurrency_full. Report the shadow ask and the
  cold recheck once, under a mutex. Rewrite the sweep rows of
  docs/data-dependence.md and drop the stale counters and prose from
  advanced-offload.md.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>

docs(data-dependence): record David's approval of the sweep change (#508)

The ping-time question and the held answer in cg:swh: (metadata only)
are approved, with the two in-memory conversation copies per thread
kept only while the keep-alive can ping the thread, for at most 256
threads and 30 minutes.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
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