Repository navigation
feat(keepalive,dash): key cache attribution and keep-alive per thread - #426
Conversation
One Claude Code session holds many threads (main agent, subagents, forks), each with its own provider cache entry. The recorder and the keeper keyed on the session, so a subagent's requests reset the main thread's idle gap (its TTL expiries were labelled prefix_change) and replaced the main thread's keep-alive entry (the keeper pinged the newest subagent and let the main thread's cache expire). - internal/thread: find a request's thread from x-claude-code-agent-id (seen on the wire with Claude Code 2.1.294), else by prefix continuity on the message list as the agent sent it, else the session. The first header-less thread of a session keeps the session's own key, so single-thread traffic is unchanged. - dash: recency, cold start and tail comparison per thread; new requests.thread_id column; restart seeding per thread; the SQL "previous turn" definitions follow the same thread. - proxy: one keep-alive entry per thread; ping rows carry the thread; disarm releases every thread of the session. Fails open to the session. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
A request that matches no thread by prefix used to start a new thread, so its miss read cold_start even when it was the same conversation with a changed prefix (a user rewind, an edited earlier turn, a fork). The tracker now keeps each thread's full cumulative fingerprint. When a new thread's leading messages are at least half of its message bytes from a known thread, the result names that thread (Result.Inherits). The recorder then observes the request as that thread's next turn (ObserveThreadFrom): seen, with its gap measured from that thread. Its miss reads prefix_change, or ttl_expiry after a long gap. A subagent's first request shares nothing and stays a cold start. The new thread keeps its own id, so a fork and its parent are never merged and each keeps its own keep-alive entry. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Codex 0.160 re-serializes earlier reasoning items on resume, adding "content": null. The fingerprint skips reasoning items, which is what keeps the resumed session on its thread. Seen live in the PR #426 Codex run; this pins it. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
Summary
The design works. I found 2 problems that live traffic confirms and 2 smaller ones from reading the code. None blocks merge on its own, but problem 1 changes what thread_id = '' means in the dashboard.
What I ran
- Race tests on the eval box, at
e1e73b9:go vetclean,gofmtclean,go test -race ./...green in every package except 2 tests incontext-guru-plugin(TestInstallRefusesAnUnverifiedDownload,TestInstallReportsPATHFromTheSourceFallbackToo). Both also fail onmainon the same box. The cause is the box's root-owned/usr/local/bin/context-guru-proxy, not this PR. - Live check on the eval box: one proxy built from this branch, one from
origin/main, plain gateway,aws/claude-sonnet-5, keep-alive idle 30 s, K = 2. One session, sent in this order:- a small "generate a title" request, no header (like a Claude Code auxiliary request);
- main thread, 2 turns, no header;
- subagent
sub1, 2 turns, withx-claude-code-agent-id, then it stops; - 110 s idle.
| Row | Branch thread_id |
Branch | main (control) |
|---|---|---|---|
| auxiliary request | '' |
real request | real request |
| main thread, 2 turns | p:95c66e629d6c |
real requests | real requests |
| subagent, 2 turns | a:sub1 |
real requests | real requests |
| pings | 4 (2 main, 2 a:sub1) |
2 (subagent body only) |
Findings
- The first header-less request claims the primary id
'', even when it is an auxiliary request. Confirmed live: the title request got'', and the real main thread gotp:95c66e629d6c. The PR says''= main thread (column doc, API, issue text). That is only true when the main thread speaks first. Keep-alive still works, because each thread has its own entry, but any dashboard view that reads''as "the main agent" shows the wrong thread. See inline comment onnewID. - Every finished subagent now gets K pings. Confirmed live:
a:sub1got 2 pings after its last request, and nothing ever resumes it. Onmainthe same session sent 2 pings in total. The cost is K × (its prefix × cache-read rate) per finished subagent that passes the gates (turn ≥ 1, prefix floor). The config comment onKeepAliveMaxPingsalready names this waste ("a session that has ENDED looks exactly like one that is thinking"); this PR multiplies it by the number of subagents. The PR lists "noSubagentStopsignal" as an open question. I think it needs a number from the recorded traffic before merge, or a gate (for example, do not ping ana:thread). See inline comment onrecord. - The keeper bounds now count threads, not sessions (code reading, not measured).
maxKeepAliveSessions = 512andmaxKeepAliveTurnKeyskeep their old names and comments. One session can now hold many entries, andevictLockedhas no per-session fairness. See inline comment onkaThreadKey. newIDgives a compacted thread's id to the first thread withcompactingset, in slice order (code reading, not measured). With 2 threads compacting at the same time, the next unmatched request can take the wrong id. Rare. See inline comment.
Not filed
- A new header id whose body continues another thread is not flagged as
Disagree. That is the normal shape of a fork's first request, so a flag there would be noise. - Rolling deploy with old and new binaries writing one database. Old rows read as
'', as the PR says. The effect is short and limited to sessions that span the upgrade.
🤖 Generated with Claude Code
| // fingerprint, which differs from every other thread's (a fork has its parent's prefix but not | ||
| // its parent's full message list). | ||
| func (s *sessionState) newID(sums []uint64) string { | ||
| if !s.hasPrefixThread() { |
There was a problem hiding this comment.
Confirmed live (finding 1). The session's first header-less request gets Primary, whatever it is. In my run a "generate a title" request came first and got ''. The real main thread then got p:95c66e629d6c for all its turns and pings.
So thread_id = '' means "first header-less thread", not "main agent". Two options:
- change the docs (schema comment, API, PR text) to say that; or
- choose the primary by more than order, for example the thread with the most turns, or rename
''only in reporting.
The keep-alive is not affected: each thread keeps its own entry.
There was a problem hiding this comment.
Fixed in 2af908c, by changing the docs.
''now means "the session's first header-less thread". It is the main agent when the main agent speaks first. The package doc,Event.ThreadIDand the schema comment say so, and so does the PR text.- I did not choose the primary by turn count. That would change a live thread's key in the middle of its life. Its keep-alive turn count and its recency would reset, so its next miss would read
cold_start. - In every live Claude Code and Codex run I made, the main agent's request came first. Your order (title request first) can still happen, and after a proxy restart in the middle of a session it is likely. Keep-alive and attribution are correct in both cases; only a reader that takes
''to be the main agent is misled.
There was a problem hiding this comment.
Follow-up: now fixed in the code as well (commit bce2a19).
- Request bodies carry no timestamps. I checked live: Claude Code 2.1.294 messages have only
roleandcontent. - The request shape tells the main agent apart, using metadata only. The main agent declares tools (23 in Claude Code). The security-monitor and title requests declare none and use
stop_sequenceswithmax_tokens: 64. - New rule:
''goes to the first header-less thread that declares tools. A tool-less thread that came first moves to its ownp:id when the main agent arrives. - A client that never declares tools keeps its first thread as
'', as before. - Test:
TestTheMainAgentGetsThePrimaryEvenWhenAnAuxiliaryRequestComesFirst(your live order). It fails when the rule is removed. - Still open: after a proxy restart in the middle of a session, a header-less subagent that speaks before the main agent also declares tools, so it can take
''.
| return Primary | ||
| } | ||
| for _, th := range s.threads { | ||
| if th.compacting { |
There was a problem hiding this comment.
Code reading, not measured (finding 4). This returns the first thread with compacting set, in slice order. If 2 threads compact before either sends its next request, the next unmatched request can take the wrong thread's id. Rare. A fix: pick the compacting thread whose fingerprint or mass is closest, or the most recent one.
There was a problem hiding this comment.
Fixed in 2af908c. The successor is now the most recent compacting thread, because the agent sends the post-compaction request right after its own compaction request. New test: TestTwoCompactingThreadsTheLaterOneIsTheSuccessor. It fails when the code goes back to slice order (mutation checked).
|
|
||
| // kaThreadKey is the live-map key of one thread. The primary thread keys exactly as kaKey, so a | ||
| // single-thread session is tracked as it was before threads existed. | ||
| func kaThreadKey(tenant, session, threadID string) string { |
There was a problem hiding this comment.
Code reading, not measured (finding 3). With this key, maxKeepAliveSessions (512) and maxKeepAliveTurnKeys (20,000) now count threads. Their names and comments still say sessions, and the 512 comment says it is "reached only by a deployment with that many opted-in sessions idle at once". One busy session can now hold many entries, and evictLocked drops by deadline with no per-session fairness. Please update the comments, and say whether the bound needs to change.
There was a problem hiding this comment.
Comments updated in 2af908c. Both bounds now say they count threads. The bound does not change:
- An entry exists only for a thread past its first request, with a prefix over the floor.
- A finished thread's entry ends at the hard deadline, (K+1) × idle, about 14 min at the defaults.
maxKeepAliveBytes(128 MiB) binds before 512 entries do, at the sizes this traffic has.- No per-session fairness, on purpose.
evictLockeddrops the entry whose ping is least imminent, whichever session it is in.
| return | ||
| } | ||
| key := kaKey(tn.ID, session) | ||
| key := kaThreadKey(tn.ID, session, threadID) |
There was a problem hiding this comment.
Confirmed live (finding 2). A subagent that has finished still gets K pings. My run: subagent a:sub1 sent 2 turns and stopped; the branch then sent 2 pings for it (rows 7 and 9) and 2 for the main thread. main sent 2 pings in total for the same session.
Cost: K × (prefix × cache-read rate) for each finished subagent that passes the gates. On a session that starts many subagents this can be most of the keep-alive spend. Can you measure it on the recorded traffic (count of a: threads with turn ≥ 1 and prefix over the floor, times K)? If it is large, a simple gate is to skip ping entries for a: threads, or ping them only once.
There was a problem hiding this comment.
Measured, and I am not adding a gate. The numbers say a gate loses money on this traffic.
fix-summarizer session, recorded rows. Thread ids are not stored on old rows, so I used a heuristic: a "resume" is a later Sonnet row with 1–6 more messages.
Finished Sonnet threads (end_turn, prefix ≥ 20k) |
Count | Effect of K=2 pings |
|---|---|---|
| resumed within 4.7 min | 23 | none: the next request clears the entry before the first ping |
| resumed 4.7–14 min later | 8 | pings save a miss: |
| resumed later or never | 45 | wasted: |
So skipping a: threads would save ~$5.8 and lose ~$8.8. Many of these threads are agent-team teammates, which do resume. I wrote the numbers in a comment on pingable() in 2af908c.
A better rule would know what each thread waits for: a background task, a teammate or a human. That is the open question in #423 about the ping budget, and I think it belongs in its own change.
- Document what thread id '' means: the session's first header-less thread, which is the main agent only when it speaks first. Choosing it by turn count would re-key a live thread and reset its keep-alive turn count and recency. - A post-compaction request inherits the most recent compacting thread, not the first one in slice order. - Keeper bounds now count threads; say so, and why 512 still holds. - Record why a finished subagent thread is still pinged, with the numbers measured on recorded traffic. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
The first header-less thread took thread id '' even when it was an auxiliary request (PR #426 review, confirmed live). Request bodies carry no timestamps, but the shape tells them apart: Claude Code's main agent declares 23 tools, its security-monitor and title requests declare none. A tool-less thread now holds '' only until the first header-less thread with tools arrives; it then moves to its own p: id. A client that never declares tools keeps its first thread as the primary, as before. Metadata only: nothing is stored. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Re-check at
|
| Row | thread_id |
|---|---|
| title request (first, no tools) | '' |
| main thread, 2 turns | '' |
| subagent, 2 turns | a:sub1 |
| pings | 2 for '', 2 for a:sub1 |
So the main agent now gets '', as bce2a19 intends.
Nitpicks (optional)
- The title request's row keeps
''in the database. It was written before the move top:, so its stored row still reads as the main thread (row 1 in my run). Maybe one sentence in theEvent.ThreadIDdoc. - After the move, the main thread starts with the title request's counters (code reading, not measured). The keeper's turn count and the dashboard's "previous turn" are keyed by
''. So the main agent's first request counts as turn 1 and passes the first-request gate. Its previous turn is the title row. This is howmainbehaves today, so it is no regression. - The doc comment on
fingerprintIDsays "its first request". WhennewIDmoves the old holder, it passesholder.sum, which is the fingerprint of its last request. - A question, not a request:
th.toolsis set again on every request. If the main agent ever sends one request with no tools, a later header-less thread with tools takes'', and the main thread moves top:in the middle of its life. Claude Code and Codex always send tools, so this may never happen. - The
pingable()comment does not add up: 8 resumed + 45 never resumed = 53 of 76 threads. It does not say what happened to the other 23. - Style: the new
pingable()comment sits inside the function body and starts with an empty//line. Other comments in this file sit above the function. Also, 2 changed comment lines (maxKeepAliveTurnKeys,turns) are wider than the lines around them.
🤖 Generated with Claude Code
- Make a thread's tools flag sticky, so one tool-less request from the main agent cannot let a later thread take '' mid-life. - Say that a row keeps the thread id it was written with. - Fix the fingerprintID comment (first or last request). - Account for all 76 threads in the pingable() comment, and move it above the function; rewrap two over-wide comment lines. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Thanks. Nitpicks handled in 6af9b24:
|
Resolve the conflicts with #402 (cache_aware_summarizer keep-alive substitution) and make that substitution thread-aware. The substitution registry is keyed by session, but the keep-alive is now per thread, and a candidate's span is one thread's conversation. Without a fix, a subagent's ping could run the main thread's summary call (refreshing the wrong prefix), and a subagent's request or entry retirement could clear the main thread's candidate. The keeper now records which thread registered the candidate (noteCandidate, via offload.KeepAliveCandidateRegisteredSince). Only that thread's ping may use it, and only that thread's request or retirement clears it. A session with no recorded owner keeps the pre-#423 rule. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
Re-review at a18722f (merge of origin/main, with #402)
Result: the thread ownership of the summary candidate works when requests come one at a time. I found 1 bug that live traffic confirms, 1 race that a unit test reproduces, and 1 design question. The nitpicks in 6af9b24 are all done, thanks.
What I ran
- Race tests on the eval box:
go vetandgofmtclean, every package green exceptcontext-guru-plugin. That one failed because the test cannot write/tmp/context-guru-proxy-40219.log(Permission denied), a file another user owns on the shared box. Not this PR. - A unit test of my own for the race in finding 2 (below). It fails. I did not commit it; the code is in finding 2.
- Live check on the eval box: a proxy built from
a18722f, plain gateway,aws/claude-sonnet-5,cache_aware_summarizerwithcache_state: pre_expiry,pre_expiry_seconds: 280, keep-alive idle 30 s, K = 1. Two sessions, each with a main thread (2 turns, no header) and a subagentsub1(2 turns, with header). The sessions differ only in which thread sends its 2 turns last, so which thread registers the candidate last.
| Session | Thread that registered last | Main thread's ping | Subagent's ping | Ping row's thread_id |
|---|---|---|---|---|
| A | main | substituted (output 295) | ordinary, reason=other_thread |
correct |
| B | subagent | ordinary, reason=other_thread |
substituted (output 307) | '', should be a:sub1 |
Session A is the case the new test covers, and it works.
Findings
-
Bug, confirmed live: a substituted ping is booked with
thread_id = ''.recordSummarySubstitute(proxy/keepalive.go:1425) builds itsKeepAliveReportwithoutThread: j.thread.record1got that field in this PR; this second report came from #402 in the merge and did not. In session B the subagent's substituted ping shows up in the dashboard as a main-thread ping. The fix is one field. -
Race, reproduced in a unit test: a concurrent request of another thread can take ownership.
noteCandidateasks "did a candidate get registered after MY pipeline started?" (KeepAliveCandidateRegisteredSince(session, pipelineStartedAt)). That is not the same as "did MY pipeline register it". The subagent's pipeline starts first and registers nothing. Then the main thread's pipeline registers a candidate and callsnoteCandidate. Then the subagent's request callsnoteCandidateand takes the candidate. Claude Code runs the main thread and its subagents at the same time, so this order is normal. This is the failure the merge set out to prevent: the subagent's ping then runs the main thread's summary call. Test (in packageproxy, uses your helpers):func TestReviewConcurrentThreadDoesNotStealCandidate(t *testing.T) { k, _, _ := testKeeper(t, Limits{}) st := store.NewMemory(store.Options{MaxEntries: 400}) model := &fakeSummaryModel{out: "<summary>x</summary>"} const sess = "sess-review-race" subStart := time.Now() // the subagent's pipeline starts first and registers nothing time.Sleep(2 * time.Millisecond) mainStart := time.Now() kaCandidate(t, sess, st, model) // the main thread's pipeline registers k.noteCandidate("t1", sess, "", mainStart) k.noteCandidate("t1", sess, "a:S", subStart) // the subagent's request ends after that k.mu.Lock() owner := k.candThread[kaKey("t1", sess)] k.mu.Unlock() if owner != "" { t.Fatalf("the subagent took the main thread's candidate: owner = %q", owner) } }
Result:
owner = "a:S". A fix: let the pipeline run tell the proxy that IT registered the candidate (for example a flag on theCtxor theTrace, or a registration id it returns), instead of comparing times. -
Design question, seen live: one candidate per session, so the last thread to register wins. In session B the subagent's turn replaced the main thread's candidate, so the main thread's ping fell back to an ordinary ping. This fails open and costs no money, but the main thread loses the substitute whenever a subagent runs
cache_aware_summarizerafter it. Keying the offload registry by session + thread would fix this and finding 2 together. The cost: the thread id must be known when the pipeline runs, andthreadForruns after it today. If that is too big for this PR, a follow-up issue is fine.
🤖 Generated with Claude Code
| return | ||
| } | ||
| key := kaKey(tenantID, session) | ||
| registered := offload.KeepAliveCandidateRegisteredSince(session, pipelineStartedAt) |
There was a problem hiding this comment.
Finding 2 (race, reproduced in a unit test). This answers "was a candidate registered after my pipeline started", not "did my pipeline register it". A subagent request whose pipeline started before the main thread's registration and ends after it gets true here, and line 968 gives it the candidate. The test is in the review summary; it fails with owner = "a:S".
There was a problem hiding this comment.
All 3 are addressed in 2a87339. I took the larger fix: the registry is now keyed by session + thread.
thread_id ''on a substituted ping: fixed.recordSummarySubstitutenow setsThread: j.thread.- Race: fixed by design. I removed
noteCandidate,candThreadandKeepAliveCandidateRegisteredSince.cache_aware_summarizerregisters its candidate underthread.Key(session, Ctx.Thread).- Every lookup and clear uses the same key:
fireSummarySubstitute,ClearStaleKeepAliveCandidateand the 5 retirement sites. - The stale check still compares times, but only against requests of the same thread, so another thread's request can never take or clear a candidate.
- Your test case is in the new
TestKeepAliveSubstituteIsPerThread: a subagent request that starts before the main thread registers, then clears.
- One candidate per session: fixed. A subagent that registers later no longer replaces the main thread's candidate.
- To make this work, the thread must be known when the pipeline runs. New
apply.Opts.ThreadOf:applycalls it once, right after it resolves the session id, and puts the thread oncomponents.Ctx.ThreadandTrace.Thread. - The proxy resolves the thread after the pipeline only when
applyreturned early. The observe-mode shadow run gets no hook, so the tracker never sees a request twice.
- To make this work, the thread must be known when the pipeline runs. New
Still per session (filed as #430): the summarizer's checkpoint and its in-flight guard. Effect, seen in the test: once one thread commits a summary, the other thread's ping falls back to a plain ping (checkpoint_exists). That fails open and costs nothing, but it loses the substitute.
Tests: go test -race is green in internal/thread, apply, dash, proxy, components/... and cmd/....
New tests, each with a mutation check:
TestKeepAliveSubstituteIsPerThread: fails when the registry key ignores the thread.TestApplyModeResolvesTheThreadBeforeThePipeline: fails when theThreadOfwiring inapplyModeis removed. This test exists because during this work the wire really was missing for one run, and every other test still passed.apply:TestThreadOfRunsBeforeThePipelineOnBothEnvelopes, andTestThreadOfPanicFailsOpen.
Address the PR #426 re-review of the #402 merge. - Key cache_aware_summarizer's keep-alive candidate registry by thread.Key(session, thread) instead of by session. This removes the timestamp-based ownership (noteCandidate / candThread), which a concurrent request of another thread could win, and stops a later thread's registration from replacing another thread's candidate. - Resolve the thread inside apply, once the session id is known and before the pipeline runs (apply.Opts.ThreadOf), and expose it on components.Ctx.Thread, so the component can key by it. - Book a substituted ping with its thread (recordSummarySubstitute). The summarizer's checkpoint and in-flight guard are still per session; that is a follow-up. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
Re-review at 2a87339
Result: the 3 findings from my last review are fixed. Keying the candidate by thread removes the race by design, and substituted ping rows now carry the right thread. One gap remains on the Anthropic path. It fails open, but it keeps the "only the last thread gets a summary" effect from finding 3.
What I ran
- Race tests on the eval box:
go vetandgofmtclean, every package green exceptcontext-guru-plugin(TestRouteAddsGitignoreEntryByDefault). That failure is/tmp/context-guru-proxy-44619.log: Permission denied: on the shared box another user owns that/tmpfile. Not this PR. - Live check: sessions A and B again, same config as last time (
aws/claude-sonnet-5, plain gateway). A second run hit HTTP 429 from the gateway, so the numbers below are from the first run only.
| Session | Registered last | Main thread's ping | Subagent's ping |
|---|---|---|---|
| A | main | substituted (output 439), row '' |
plain ping, row a:sub1 |
| B | subagent | plain ping, row '' |
substituted (output 358), row a:sub1 ✅ |
- No ping used another thread's call. Every row has the right
thread_id. - But the thread that did NOT speak last always fell back.
/statsshowskeepalive_summary_substitute_failed: 2, notcheckpoint_exists. That is a different reason from the one #430 describes.
Finding: the PrefixAsk stash is still per session
On Anthropic, cache_aware_summarizer takes the PrefixAsk path: the summary call is the last forwarded body plus the instruction. That body comes from sentStash, which proxy.go:1646 fills with h.sent.put(session, …), one body per session. So the stash holds the body of whichever thread spoke last.
- The other thread's candidate checks
CoversSpan(session, …)against that body. The span hash does not match, so the call returnsErrStalePrefix, and the ping falls back to a plain ping. This is my reading of the code. It matches the live result, but I did not log the error itself (the "produced no summary" line logsreason=""). - So on Anthropic, only the thread that spoke last can ever get a substitute, which is the same effect as finding 3. It fails open, so it costs no money.
- The guard is the only thing that stops a summary of the wrong thread's conversation. An asker without
PrefixCoveragewould summarize the other thread's body.
Proposal: key sentStash by thread.Key(session, threadID) in put and in the 2 askers' Ask/CoversSpan (the component passes c.Session; it would pass the thread key, as the candidate now does). If you prefer to keep this PR's scope, add it to #430. #430 does not mention the stash today.
🤖 Generated with Claude Code
Address the PR #426 re-review at 2a87339. The sentStash that PrefixAsk reads was keyed by session, so only the thread that spoke last could use it: another thread's summary substitute failed its coverage check (keepalive_summary_substitute_failed), and extract_llm_sweep on one thread could ask against another thread's transcript. - Stash each forwarded body under thread.Key(session, thread). - cache_aware_summarizer and extract_llm_sweep ask, and check coverage, under the same thread key (PrefixAsker doc says so). - The stash now drops the oldest entries when full instead of all of them: per thread, a Claude Code session adds an entry on almost every turn, and a wholesale drop would keep throwing away the main thread. The entry bound is 256; the byte bound (96 MB) is unchanged. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Fixed in ec918bd. Thanks, your reading was right.
Still per session (#430): the summarizer's checkpoint and in-flight guard. So in your A/B run, the second thread may now fall back with |
Re-review at
|
| Session | First thread to come due | Its ping | The other thread's ping |
|---|---|---|---|
| A | subagent | substituted (output 489), row a:sub1 |
plain ping, row '' |
| B | main | substituted (output 421), row '' |
plain ping, row a:sub1 |
/stats:keepalive_summary_substituted: 2,keepalive_summary_substitute_failed: 0(was 2 at2a87339).- Each session's second thread fell back with
refresh_not_worth_it, notcheckpoint_exists. That is the same cause: the first thread's summary is stored under the session checkpoint (cache_aware_summarizer: key its checkpoint and in-flight state by thread, not session #430), so the second thread'spre_expirycandidate is priced as a refresh of it. Maybe worth one line in cache_aware_summarizer: key its checkpoint and in-flight state by thread, not session #430, so its test checks this reason too.
🤖 Generated with Claude Code
extract_llm_sweep and cache_aware_summarizer each guard a prefix ask against a stale cached prefix. Both guards hashed req.Input at their own position in the pipeline. CoversSpan, on the host side, hashes the stashed body from BEFORE the pipeline ran. The two spans match only when the guarded component is first in the pipeline. In housellm and xhigh the sweep runs ninth, after format, dedup, toon, cmdfilter, searchfold, textclean and extract_llm. Any of those components may rewrite a cached tool output on every turn (textclean strips terminal noise, for example). That rewrite makes the two hashes disagree even though the stash holds the correct bytes, so the sweep declines every ask as sweep_stale_prefix on real traffic. The summarizer has the identical failure whenever a component runs ahead of it, which no config check currently prevents. Fix: apply now takes a shallow copy of the normalized messages before Pipeline.Run starts and carries it on components.Ctx as RawInput. Both guards hash RawInput instead of req.Input. A Ctx built without going through apply (most component unit tests) leaves RawInput nil, and both guards fall back to req.Input, so their existing behaviour is unchanged. When RawInput is set but its length disagrees with req.Input's length at the guarded component's own position, an earlier component changed the message count and the two slices no longer share index coordinates; the guards decline rather than compare the wrong span. Added proxy/pr431_stale_prefix_coord_test.go: - extract_llm_sweep behind textclean no longer reports sweep_stale_prefix and still asks through the stash. - cache_aware_summarizer behind textclean asks exactly once, matching the existing first-in-pipeline case. - a genuinely changed cached span (not merely rewritten by an earlier component) still declines as stale, so the fix does not make the guard vacuously pass. On the eval box: go build, go vet and gofmt report nothing; go test ./components/... ./apply/... ./proxy/... and go test -race ./components/offload/... ./proxy/... both pass. Assisted-By: Claude Opus 5.5 <[email protected]> Rebased onto origin/main (#423/#426, the per-thread prefix-ask stash). That merge surfaced a second coordinate bug in the same guard: the sweep's new CoversSpan call compared against the plain session, while the Ask call three lines below it (already thread-aware on main) and the host's stash itself (keyed by thread.Key(session, thread)) both use the per-thread key. For any thread but the first, that mismatch made CoversSpan's missing-key convention report "covered" and the guard never fired. Fixed to use thread.Key(c.Session, c.Thread), same as the Ask call. The rebase also exposed a now-outdated assumption in an existing test, TestCacheAwareRealContentChangeInsideSpanStillDeclines: a genuine content edit inside the cached span breaks thread-prefix continuity, so #423's thread detector classifies the next turn as a new, unstashed thread before the stale-prefix hash check ever runs. The commission still declines (ErrNoPrefix instead of ErrStalePrefix) and still asks nothing, so the safety property holds; only which counter moves changed. Updated the test to check that either counter moved, with a comment on why. 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]>
…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]>
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]>
A tool-less side request (Claude Code's title suggestion, quota check, end-of-turn note) can share the main thread's recorded prefix and append its OWN extra message. Resolve matched it to the main thread by prefix, then unconditionally overwrote the thread's recorded tail with the side request's longer, now-diverged message list. The next REAL turn extends the ORIGINAL conversation, not the side request's tail, so it no longer matched by prefix and the main thread wrongly split into a new "p:" id. All per-thread state (prefix-ask stash, keep-alive candidate, summary checkpoint, wait-cause open-task state) was lost at that point. Seen live across a claude -p / --resume boundary (issue rossoctl#426 follow-up), but the same mismatch can happen within one interactive session whenever a side request interleaves with the main thread. First fix gave the side request the MAIN thread's id, just without moving its tail. That is not enough: every OTHER structure keyed by thread id (the keeper's live entry, the prefix-ask stash, wait-cause's open-task state) would still see the side request under the main thread's key, and keeper.arrive in particular DELETES a thread's live keep-alive entry on arrival — a side request arriving under the main id would clear the main thread's own entry, the rossoctl#426 bug in a new form. Give the side request its OWN thread instead, chained to the main thread via Inherits, and leave the main thread's tail, timestamp and tools flag untouched. The side request still never takes the primary id "": fingerprintID always returns a "p:" id. Edge case: if the main agent itself ever sends one genuinely tool-less request mid-conversation (not a side request, just its own next turn), the tracker cannot tell the two apart by content alone, and resolves it the same way: its own new thread, inheriting from the main thread. The chain still holds — the FOLLOWING tools-declaring request extends THAT thread's (now longest) tail, not the stale main thread, so attribution still reads one continuous conversation. Only the literal "" label does not survive; see TestAGenuineToolLessMainTurnStillChainsForward. Tests: - internal/thread: TestASideRequestDoesNotMoveTheMainThreadsTail (adapted to the new id), TestASideRequestNeverTakesThePrimaryID, TestAGenuineToolLessMainTurnStillChainsForward. - proxy: TestSentStashSurvivesASideRequest, TestKeeperSurvivesASideRequestsArrival, TestWaitCauseSurvivesASideRequest — each proves the specific structure named in the review (stash, keeper, wait-cause) survives a side request's arrival under its own, separate id. internal/thread (-race), proxy (-race), internal/waitcause (-race) and dash (-race) all pass. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
apply read one tracker record per session to set MaxCachedIdx and to decide ColdCache. Each thread has its own provider cache (rossoctl#423, rossoctl#426), so in a session with subagents both were wrong: - An idle main thread read as warm while a subagent of the same session was active, so the cold lift did not run. - The main thread's boundary came from the subagent's message count, so mask rewrote messages the main thread had cached. A subagent request after a longer main request read as a compaction and reset to -1. The record is now keyed by thread.Key(session, thread) on the chat and the Responses routes, with the tracker and with the store fallback. The primary thread keeps the bare session key, so single-thread sessions do not change. The alias clock and the TTL record are unchanged; both stay monotone toward warm. Refs rossoctl#484. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Summary
The proxy now keys cache-miss attribution and the idle keep-alive on session + thread, not on the session alone. A thread is the main agent, one subagent, or one fork. Each thread has its own provider cache entry.
Live result on a real Claude Code session (main thread idle 9.6 min while a background subagent worked):
main(control)Closes #423.
What changed
internal/thread. It finds the thread of a request, in this order:x-claude-code-agent-idnames the subagent.previous_response_id), the thread is the session itself, as before.''goes to the main agent, told apart by metadata: the first header-less thread that declares tools. Claude Code's auxiliary requests (security monitor, title) declare none. If one of them comes first, it moves to its ownp:id when the main agent arrives. Request bodies carry no timestamps, so order alone cannot be used.dash).requests.thread_id(''= the main agent). The request API returns it.splitMoved,afterOurMutation) use the previous turn of the same thread.?session=stay per session.proxy).prefix_changeorttl_expiry, notcold_start.cache_aware_summarizerregisters its keep-alive candidate under session + thread.applyresolves the thread before the pipeline runs (apply.Opts.ThreadOf) and passes it oncomponents.Ctx.Thread. Each thread's ping uses only its own candidate, and another thread's request cannot replace or clear it. The summarizer's checkpoint and in-flight guard are still per session: cache_aware_summarizer: key its checkpoint and in-flight state by thread, not session #430.What we found on the wire
With Claude Code 2.1.294 through a custom
ANTHROPIC_BASE_URL(-pmode):x-claude-code-agent-idis sent on every subagent request. It is absent on the main thread.x-claude-code-request-class,-parent-agent-idand-agent-typewere not sent. The code does not use them.How it was tested
Unit tests (
go test -raceon the eval box, all green ininternal/thread,dash,proxy,cmd/...). They cover issue tests 1–7:ttl_expiry. A control with session keying givesprefix_change.cold_start.Mutation check. Putting the session key back in the keeper fails 2 tests. Putting it back in the recorder fails 3 tests.
Live tests (laptop, Claude Code 2.1.294, one proxy built from this branch and one from
origin/main, plain gateway, Sonnet):Each run starts a background subagent that works for about 10 min (one request every ~100 s).
main(negative control)''for main,a:<id>for the subagent).p:thread and the grouping matched the header run exactly.main, the subagent's first request was labelledprefix_change(defect 3 of the issue). On the branch it is the first request of its own thread, so a miss there readscold_start(unit-tested; in this live run it happened to be a cache hit).Live test with Codex (0.160.0, Responses route,
azure/gpt-5.6-luna, OpenAI keep-alive idle set to 75 s; binary from the first commit):'', including acodex exec resumeand an upstream 502 retry. Noprevious_response_idwas ever sent, so prefix continuity always applied.reasoningitems with an added"content": null. The fingerprint skips reasoning items, so the thread held. A test now pins this (TestACodexResumeStaysOnItsThread).spawn_agent): Codex sends the parent's session id andprompt_cache_key, so only prefix continuity can split it. Branch: subagent on its ownp:thread, no cross-assignment.Replay on recorded traffic. Stored rows have no message bodies, so I replayed with the model as the thread (the same approximation the issue used). On the
fix-summarizersession (now 4,174 requests, 71prefix_changerows, $100.91):ttl_expirycold_startprefix_changeThe issue expected about 46 of 65 to move. 52 of 71 move.
Open questions
isAgentCompaction). If detection misses, the next request becomes a new thread and its miss readscold_start, notprefix_change.thread_idcolumn is written only when the dashboard is on.SubagentStopsignal. Measured onfix-summarizer: a gate on finisheda:threads would save ~$5.8 of pings and lose ~$8.8 of avoided misses, because teammates resume. So there is no gate. A better rule depends on what each thread waits for (the ping-budget question in Key cache attribution and keep-alive per thread, not per session #423).Technical notes
cache_control, thinking/reasoning blocks, and the content of tool results (kept by call id, because Claude Code clears old tool results in place). System prompt and tools are not part of it: a changed system prompt is a prefix change inside the same thread, and must be labelled so.[A-Za-z0-9_.:-]{1,128}. Thread ids:a:<agent id>,p:<12 hex>, or''.dash.Recorder.TEXT NOT NULL DEFAULT ''), no schema version bump. Old rows read as the main thread, which is how they were keyed.🤖 Generated with Claude Code