Skip to content

feat(keepalive,dash): key cache attribution and keep-alive per thread - #426

Merged
amiddavid merged 9 commits into
mainfrom
feat/thread-key-423
Oct 11, 2026
Merged

amiddavid merged 9 commits into
mainfrom
feat/thread-key-423

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

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):

This branch main (control)
Keep-alive pings for the main thread 2 0
Main thread's next request: cache read 48,367 30,738
Main thread's next request: cache write 193 17,760

Closes #423.

What changed

  1. New package internal/thread. It finds the thread of a request, in this order:
    • Header. x-claude-code-agent-id names the subagent.
    • Prefix continuity. A request continues thread T when T's last message list is a prefix of the new message list. This is the rule the provider cache uses. It runs on the request as the agent sent it, before compaction.
    • Session. When there is no message list (for example a Responses request with previous_response_id), the thread is the session itself, as before.
  2. The first header-less thread of a session keeps the session's own key. So a single-thread session (Codex, Bob Shell, a Claude Code session with no subagents) behaves exactly 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 own p: id when the main agent arrives. Request bodies carry no timestamps, so order alone cannot be used.
  3. Dashboard (dash).
    • Idle gap, cold-start check and tail comparison are per thread.
    • New column requests.thread_id ('' = the main agent). The request API returns it.
    • A restart recovers recency per thread.
    • The SQL "previous turn" checks (splitMoved, afterOurMutation) use the previous turn of the same thread.
    • Reporting, savings and ?session= stay per session.
  4. Keep-alive (proxy).
    • One entry per thread. A subagent's request no longer replaces or clears the main thread's entry.
    • Ping rows carry the thread id.
    • Disarming a session override releases every thread of that session.
    • Session overrides still apply to all threads of their session.
  5. Changed prefix vs cold start, by shared mass. When a request matches no thread, the tracker measures how much of its message bytes a known thread already has as leading messages. At 50% or more, the request is that conversation with a changed prefix (a rewind, an edited turn, a fork). It keeps its own thread id, but the dashboard treats it as that thread's next turn, so a miss reads prefix_change or ttl_expiry, not cold_start.
  6. Summary keep-alive substitution (feat(offload): give cache_aware_summarizer a real trigger and feed the keep-alive #402) is per thread. cache_aware_summarizer registers its keep-alive candidate under session + thread. apply resolves the thread before the pipeline runs (apply.Opts.ThreadOf) and passes it on components.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.
  7. Fail open. A panic in thread identification uses the session key. The request is never blocked or changed.

What we found on the wire

With Claude Code 2.1.294 through a custom ANTHROPIC_BASE_URL (-p mode):

  • x-claude-code-agent-id is sent on every subagent request. It is absent on the main thread.
  • x-claude-code-request-class, -parent-agent-id and -agent-type were not sent. The code does not use them.
  • Claude Code also sends small auxiliary requests without the header, with a different first message. So "no header" does not mean "main thread". Prefix continuity gives each of these its own thread, and they no longer replace the main thread's keep-alive entry.

How it was tested

Unit tests (go test -race on the eval box, all green in internal/thread, dash, proxy, cmd/...). They cover issue tests 1–7:

  • Main thread idle 8.5 min while a subagent sends a request every minute: the miss is ttl_expiry. A control with session keying gives prefix_change.
  • A subagent's first request is cold_start.
  • A fork gets its own thread, with and without the header, whichever side speaks first.
  • Header path and fallback path give the same grouping.
  • An empty or malformed header falls back to prefix continuity.
  • The keeper holds 2 entries for 2 threads, and each ping carries its own thread's body (Anthropic and Responses routes).
  • OpenAI chat and Responses bodies group by prefix with no Claude Code header.
  • End to end through the handler, with and without the header: rows carry the thread, the keeper holds 2 entries.

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).

Run Idle thread Pings for it Its next request: read / write
Branch, header sent main, 9.6 min 2 48,367 / 193
main (negative control) main, 9.6 min 0 30,738 / 17,760 (prefix re-written)
Branch, header stripped before the proxy main, 9.7 min 2 48,342 / 159
Branch, reverse case subagent, 9.9 min 2 28,147 / 1,117
  • Every ping row carries the idle thread's id ('' for main, a:<id> for the subagent).
  • With the header stripped, the subagent got a p: thread and the grouping matched the header run exactly.
  • On main, the subagent's first request was labelled prefix_change (defect 3 of the issue). On the branch it is the first request of its own thread, so a miss there reads cold_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):

  • Main conversation: all 16 requests on thread '', including a codex exec resume and an upstream 502 retry. No previous_response_id was ever sent, so prefix continuity always applied.
  • Resume: Codex re-serializes old reasoning items with an added "content": null. The fingerprint skips reasoning items, so the thread held. A test now pins this (TestACodexResumeStaysOnItsThread).
  • Subagent (spawn_agent): Codex sends the parent's session id and prompt_cache_key, so only prefix continuity can split it. Branch: subagent on its own p: thread, no cross-assignment.
  • Keep-alive: branch pinged each thread 3 times (subagent cr=7,907, main cr=8,980, all cw=0). Control pinged only the main thread's body; the subagent got no pings.
  • Not shown: the cache benefit on OpenAI, because its cache outlives the 170 s gap anyway; that needs a gap over 30 min.

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-summarizer session (now 4,174 requests, 71 prefix_change rows, $100.91):

New label Rows Cost
ttl_expiry 51 $80.59
cold_start 1 $0.27
stays prefix_change 19 $20.05

The issue expected about 46 of 65 to move. 52 of 71 move.

Open questions

  • Agent's own compaction without the header. The request after a compaction starts from a summary and matches no prefix. The tracker gives it the compacted thread's id when the compaction request was detected (isAgentCompaction). If detection misses, the next request becomes a new thread and its miss reads cold_start, not prefix_change.
  • No stored data needed. Thread identification uses only in-memory metadata: message hashes, byte counts and a tools flag. Nothing goes to the Store. The thread_id column is written only when the dashboard is on.
  • Thread state is in memory. After a restart, header-less threads get new ids; header threads keep theirs. Recency for both is recovered from the database.
  • Not changed here: 7 dashboard queries still look back per session where they mean one cache entry (KV-cache idle page, keep-alive replay, replay-savings projection, and others). Tracked in Dashboard queries: use the thread id where they ask about one cache entry #427.
  • A finished subagent still gets up to K pings. Thread entries end at the existing hard deadline, (K+1) × idle, and the proxy has no SubagentStop signal. Measured on fix-summarizer: a gate on finished a: 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

  • Fingerprint: FNV-64a, cumulative over messages. It skips 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.
  • Header ids are accepted only if they match [A-Za-z0-9_.:-]{1,128}. Thread ids: a:<agent id>, p:<12 hex>, or ''.
  • Bounds: 64 threads per session (oldest dropped), 20,000 sessions pruned by 2 h age, as in dash.Recorder.
  • New column is additive (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

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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 vet clean, gofmt clean, go test -race ./... green in every package except 2 tests in context-guru-plugin (TestInstallRefusesAnUnverifiedDownload, TestInstallReportsPATHFromTheSourceFallbackToo). Both also fail on main on 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:
    1. a small "generate a title" request, no header (like a Claude Code auxiliary request);
    2. main thread, 2 turns, no header;
    3. subagent sub1, 2 turns, with x-claude-code-agent-id, then it stops;
    4. 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

  1. 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 got p: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 on newID.
  2. Every finished subagent now gets K pings. Confirmed live: a:sub1 got 2 pings after its last request, and nothing ever resumes it. On main the 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 on KeepAliveMaxPings already 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 "no SubagentStop signal" as an open question. I think it needs a number from the recorded traffic before merge, or a gate (for example, do not ping an a: thread). See inline comment on record.
  3. The keeper bounds now count threads, not sessions (code reading, not measured). maxKeepAliveSessions = 512 and maxKeepAliveTurnKeys keep their old names and comments. One session can now hold many entries, and evictLocked has no per-session fairness. See inline comment on kaThreadKey.
  4. newID gives a compacted thread's id to the first thread with compacting set, 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

Comment thread internal/thread/thread.go Outdated
// 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() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.ThreadID and 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 role and content.
  • 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_sequences with max_tokens: 64.
  • New rule: '' goes to the first header-less thread that declares tools. A tool-less thread that came first moves to its own p: 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 ''.

Comment thread internal/thread/thread.go Outdated
return Primary
}
for _, th := range s.threads {
if th.compacting {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

Comment thread proxy/keepalive.go

// 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 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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. evictLocked drops the entry whose ping is least imminent, whichever session it is in.

Comment thread proxy/keepalive.go
return
}
key := kaKey(tn.ID, session)
key := kaThreadKey(tn.ID, session, threadID)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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: $1.1 each at 322k tokens, **$8.8 in total**
resumed later or never 45 wasted: 2 × $0.065 each, **$5.8 in total**

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

Copy link
Copy Markdown
Collaborator Author

Re-check at bce2a19

Result: the 4 findings are fixed. I have no blocking comments. All points below are nitpicks. Skip any you think are not worth the work.

What I ran

  • Race tests on the eval box: go vet and gofmt clean. go test -race ./... green, except TestResettingAProjectFallsBackToTheMachineWideInstall (reason=port_changed_since_plan). That test passed 3 of 3 times on a re-run, on this branch and on main. It is a port race on the shared box, not this PR.
  • Live check, same script as before. This time the main thread and the subagent declare tools; the first "generate a title" request does not.
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)

  1. The title request's row keeps '' in the database. It was written before the move to p:, so its stored row still reads as the main thread (row 1 in my run). Maybe one sentence in the Event.ThreadID doc.
  2. 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 how main behaves today, so it is no regression.
  3. The doc comment on fingerprintID says "its first request". When newID moves the old holder, it passes holder.sum, which is the fingerprint of its last request.
  4. A question, not a request: th.tools is 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 to p: in the middle of its life. Claude Code and Codex always send tools, so this may never happen.
  5. 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.
  6. 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Thanks. Nitpicks handled in 6af9b24:

  1. Done. The Event.ThreadID doc now says a row keeps the id it was written with.
  2. Not changed. This is how main behaves today, as you note, and the title request is a single turn.
  3. Done. The comment now says "first request" for a new thread and "last request" for a moved one.
  4. Done. The tools flag is sticky: once a thread has declared tools, it stays the main-agent candidate.
  5. Done. The comment now gives all 76: 23 resumed before the first ping (no ping sent), 8 inside the ping window, 45 never.
  6. Done. The comment moved above pingable(), and the two wide lines are rewrapped.

go test -race is green in internal/thread, dash and proxy.

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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 vet and gofmt clean, every package green except context-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_summarizer with cache_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 subagent sub1 (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

  1. Bug, confirmed live: a substituted ping is booked with thread_id = ''. recordSummarySubstitute (proxy/keepalive.go:1425) builds its KeepAliveReport without Thread: j.thread. record1 got 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.

  2. Race, reproduced in a unit test: a concurrent request of another thread can take ownership. noteCandidate asks "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 calls noteCandidate. Then the subagent's request calls noteCandidate and 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 package proxy, 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 the Ctx or the Trace, or a registration id it returns), instead of comparing times.

  3. 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_summarizer after 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, and threadFor runs after it today. If that is too big for this PR, a follow-up issue is fine.

🤖 Generated with Claude Code

Comment thread proxy/keepalive.go Outdated
return
}
key := kaKey(tenantID, session)
registered := offload.KeepAliveCandidateRegisteredSince(session, pipelineStartedAt)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

All 3 are addressed in 2a87339. I took the larger fix: the registry is now keyed by session + thread.

  1. thread_id '' on a substituted ping: fixed. recordSummarySubstitute now sets Thread: j.thread.
  2. Race: fixed by design. I removed noteCandidate, candThread and KeepAliveCandidateRegisteredSince.
    • cache_aware_summarizer registers its candidate under thread.Key(session, Ctx.Thread).
    • Every lookup and clear uses the same key: fireSummarySubstitute, ClearStaleKeepAliveCandidate and 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.
  3. 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: apply calls it once, right after it resolves the session id, and puts the thread on components.Ctx.Thread and Trace.Thread.
    • The proxy resolves the thread after the pipeline only when apply returned early. The observe-mode shadow run gets no hook, so the tracker never sees a request twice.

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 the ThreadOf wiring in applyMode is removed. This test exists because during this work the wire really was missing for one run, and every other test still passed.
  • apply: TestThreadOfRunsBeforeThePipelineOnBothEnvelopes, and TestThreadOfPanicFailsOpen.

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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 vet and gofmt clean, every package green except context-guru-plugin (TestRouteAddsGitignoreEntryByDefault). That failure is /tmp/context-guru-proxy-44619.log: Permission denied: on the shared box another user owns that /tmp file. 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. /stats shows keepalive_summary_substitute_failed: 2, not checkpoint_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 returns ErrStalePrefix, 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 logs reason="").
  • 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 PrefixCoverage would 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Fixed in ec918bd. Thanks, your reading was right.

  • sentStash is per thread now. h.sent.put(thread.Key(session, threadID), …).
  • cache_aware_summarizer and extract_llm_sweep ask, and check coverage, under thread.Key(c.Session, c.Thread). The PrefixAsker doc says the argument is the thread key.
  • This also fixes an older problem: extract_llm_sweep on a subagent turn could ask its question against the main thread's transcript.
  • Stash bound. Per thread, one Claude Code session adds a stash entry on almost every turn (each auxiliary request is its own thread). The stash used to drop everything when full, which would keep throwing away the main thread's body. It now drops the oldest entries first. The entry bound is 256; the byte bound (96 MB) is unchanged.
  • Tests, each mutation-checked:
    • TestCacheAwareAsksUnderTheThreadKey
    • TestSweepAsksUnderTheThreadKey
    • TestSentStashDropsTheOldestThreadNotTheActiveOne
  • go test -race is green in internal/thread, apply, dash, proxy, components/... and cmd/....

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 checkpoint_exists instead of failed, once the first thread's summary has committed.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Re-review at ec918bd

Result: the sentStash finding is fixed. I have no more findings for this PR.

What I ran

  • Race tests on the eval box: go vet and gofmt clean. Every package green except 2 tests in context-guru-plugin (TestInstallRefusesAnUnverifiedDownload, TestInstallReportsPATHFromTheSourceFallbackToo). Those 2 also fail on main on this box (its root-owned /usr/local/bin/context-guru-proxy), so the cause is the box, not this PR.
  • Code check: every caller of the stash and of PrefixAsk.Ask / CoversSpan now uses thread.Key(session, thread). The oldest-first eviction keeps bytes consistent.
  • Live A/B, same setup as before (aws/claude-sonnet-5, plain gateway, cache_aware_summarizer with cache_state: pre_expiry):
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

🤖 Generated with Claude Code

@amiddavid
amiddavid merged commit addcd1e into main Oct 11, 2026
4 checks passed
@amiddavid
amiddavid deleted the feat/thread-key-423 branch October 11, 2026 08:12
amiddavid added a commit that referenced this pull request Oct 11, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 11, 2026
…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]>
amiddavid added a commit that referenced this pull request Oct 11, 2026
…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]>
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 to AIMikav/context-guru that referenced this pull request Nov 9, 2026
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]>
amiddavid added a commit to AIMikav/context-guru that referenced this pull request Nov 9, 2026
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]>
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.

Key cache attribution and keep-alive per thread, not per session

1 participant