Skip to content

contextguru plugin: follow context-guru's per-thread host contract (summarizer never fires; no subagent threads) #2130

Done

Description

@amiddavid

Summary

Cortex embeds context-guru, but it does not follow context-guru's per-thread host contract. Two results:

  1. The cache-aware summarizer never fires in Cortex, in any session. Long sessions grow to the client's own compaction point with no summary.
  2. Cortex sees every request in a session as the main thread. Subagents are never split out.

Found on Cortex v0.10.2, which embeds context-guru v0.7.7.

What we found

Gap 1: the summarizer never fires

  • Since fix(trigger): gate the window fraction on the request's own thread context-guru#1184 (in context-guru v0.7.4 and later), the summarizer's size trigger reads the billed input of the previous turn of this thread. It reads it from the store key cg:bint:<thread key>.
  • apply.RecordBilledInputThread writes that key. Cortex never calls it. It calls only apply.RecordBilledInput, which writes the session key cg:bin:. The cortex v0.10.2 binary does not contain RecordBilledInputThread at all.
  • So the per-thread figure is always 0. Trigger.FracResolvable then returns false, and the summarizer declines on every request.
  • Evidence from one laptop's Cortex state DB: 0 cg:bint: rows, 0 cg:sum: rows (no summary was ever stored), and 10 cg:bin: rows.
  • Effect seen: one Claude Code session reached 975k billed tokens of a 1M window through Cortex at preset ultrahigh. Cortex's context-guru saved 0.3% on it. Claude Code's own compaction then ran.
  • Setting ThreadOf (gap 2) does not fix this. Even on the main thread, the trigger reads cg:bint:, not cg:bin:.

Gap 2: no threads in a session

  • core/plugins/contextguru/plugin.go calls the context-guru pipeline with a session id: pctx.SessionID, or the A2A contextId.
  • It sets no apply.Opts.ThreadOf. The comment near line 371 says res.Trace.Thread.ID is empty, so accounting falls back to its own "main" rule.
  • It has the request headers in pctx.Headers.

Why it matters

  • Gap 1: on long sessions the summarizer is the component that saves the most. Without it, a session sends its full history on every turn. After an idle gap, it rewrites the whole cache. For the session above, one such turn cost about $4.70.
  • Gap 2: a subagent's requests share the session with the main agent.
    • context-guru treats them as one conversation. A subagent's shorter history then looks like the main agent dropped context.
    • Accounting cannot tell the main agent's cost from a subagent's.

Proposal

  1. Call lifecycle.Prepare and lifecycle.Finish (refactor(lifecycle): a library Prepare for the steps before each request (1/2, #1305) context-guru#1358 and Feat: List the programs Cortex is not reading #1359, in context-guru v0.7.9). Finish writes both billed keys. It also keeps Cortex in step with later changes to the steps after each response.
    • If Cortex must stay on v0.7.7 for now, call apply.RecordBilledInputThread next to apply.RecordBilledInput, with the thread id the request was served under.
  2. Set ThreadOf with context-guru's library calls. No context-guru change is needed:
// Sketch, from the example at the ThreadOf field in context-guru's apply/opts.go (main).
orig := body // the request as the agent sent it, saved before the pipeline runs
agentID, _ := thread.HeaderAgentID(agent.Identify(pctx.Headers).SubagentID())
opts.ThreadOf = func(session string) thread.Result {
    // agentall is github.com/rossoctl/context-guru/agent/all.
    res, _ := tracker.ResolveSession(tenant, session, agentID, orig, agentall.IsClientCompaction(pctx.Headers, orig))
    return res
}
  • Same thread on both sides: once ThreadOf is set, make the finish-side calls with Trace.Session and Trace.Thread.ID. lifecycle.Finish does this. If Trace.ThreadResolved is false after the call, call the same function with Trace.Session, so the finish side still has a thread.

  • Signals: agent.Identify reads a subagent id from:

    • Claude Code: x-claude-code-agent-id;
    • Codex: thread-id, with x-codex-parent-thread-id;
    • OpenCode: x-opencode-parent-session-id.
  • Fallback: with no subagent header, thread.ResolveSession uses prefix continuity. A request that continues a thread's history goes on that thread. With no headers at all, Cortex gets the same result as today: one main thread per session.

  • Header strip: a host must strip every x-context-guru-* header before it forwards a request. Check that Cortex does.

How to check the fix

  • After a few turns of a long session, the Cortex context-guru state DB has cg:bint: rows.
  • On a session above 90% of the client's compaction point, the summarizer stores a cg:sum: row, and the next request is much smaller.

Open questions

  • Does Cortex want per-thread accounting, or only the main thread's?
  • Does the Cortex request context keep the original client headers, or does a gateway rewrite them first?

Suggested order: gap 1 first (lifecycle.Prepare and Finish), because users feel it: no summary ever fires. Then ThreadOf.

Technical notes

  • The contract is described at the ThreadOf field in context-guru's apply/opts.go.
  • context-guru's docs/client-coverage.md lists the Cortex thread gap: subagent thread "none: primary only".
  • agent.Client.SubagentID() comes from fix(keepalive): read Codex and OpenCode subagents, stop reading human for other clients context-guru#1318 (merged). The sketch follows the ThreadOf example in apply/opts.go on context-guru main. Check it against the version Cortex pins.
  • The log field tokensBefore counts message text only, so it is about 2.5 to 3.4 times lower than the billed input. That is by design. The summarizer's trigger uses the billed figure, which is why gap 1 matters.

Activity

  1. amiddavid commented on Nov 26, 2026

    @amiddavid
    Author

    Evidence from one laptop: both gaps lower the saving figures

    Summary. On one laptop with Cortex v0.10.2, context-guru v0.7.7 and preset ultrahigh, the fleet dashboard showed about 20% less cache saving than usual. Context rewrite was almost 0: $0.55, 0.4% of baseline in 24 h. Both gaps in this issue explain it.

    Gap 1 is still live

    The context-guru state DB has:

    • 65 cg:bin: rows (session keys);
    • 0 cg:bint: rows (thread keys);
    • 0 cg:sum: rows: the summarizer did not store a summary in any session.

    Gap 2 causes cache breaks

    • The accountant splits threads by the agent header: 67 sessions, 105 threads, 38 not main.
    • The context-guru engine keys its state by session only: 65 cg:len: rows.
    • cg:len:<session> is the previous turn's message count. The engine changes only messages after this boundary, because the messages before it are in the provider cache (apply.prevLen, modes.Boundary).
    • In a session with several threads, each thread overwrites the boundary of the others. Two agent-team sessions from the log show this:
    Session Requests Requests >10% smaller than the one before
    A (agent team) 743 169
    B (agent team) 916 212
    C (no teammates) 238 10

    The sizes alternate between threads, for example 129k, 20k, 24k, 129k, 24k, 129k tokens. Sessions A and B are 40% of all requests in the log.

    Why the boundary error costs money

    1. Short thread after a long one. modes.Boundary reads the drop in size as a client compaction and sets the boundary to 0. The whole history of the short thread is then open to change, also the part in its cache.
    2. Long thread after a short one. The boundary is the short thread's message count. Most of the long thread's cached history is open to change.
    3. A rewrite inside a cached prefix breaks the cache. The next request writes the full prefix to the cache again.

    The accountant has the correct threads, so it books each of these as a break caused by a change. That changes both rows of "Net saved by source":

    • Context rewrite: the dashboard counts a caused break against Context rewrite, so the breaks cancel what the rewriters save.
    • Cache management: a keep-alive ping or a 1-hour cache write saves money only when the next request reads the same prefix. After a break the cost stays and the rescue does not come.

    The context-guru proxy resolves threads, so its own dashboard does not have this error.

    What this means for the fix order

    • Gap 1 (lifecycle.Prepare/Finish, or RecordBilledInputThread) lets the summarizer fire.
    • Gap 2 (ThreadOf) gives each thread its own cg:len: boundary. This fix stops the breaks. Without it, agent-team and subagent sessions lose cache savings on every change of thread.

    How to check after the fix

    • The state DB has cg:len: and cg:bint: keys per thread, not per session.
    • On the savings dashboard, the cache breaks for agent-team sessions drop.

    Technical notes

    • I took the size of each request from the tokensBefore field of context-guru compacted request log lines, grouped by session=.
    • I counted threads from accountant-state.json (keys <session>\x00<thread>).
    • I did not measure the dollar cost of the breaks. Prometheus has it, in the cache-breaks-by-cause panel.
  2. boazdavid commented on Nov 26, 2026

    @boazdavid
    Contributor

    Both gaps this issue described are fixed on main:

    • Gap 1 (summarizer never fires): lifecycle.Finish is now called from finishEngine (core/plugins/contextguru/windows.go:128), so the per-thread billed-input key the summarizer's trigger reads is written.
    • Gap 2 (no threads in a session): the plugin now sets apply.Opts.ThreadOf (core/plugins/contextguru/plugin.go:730, threadOfFor(pctx)), driven by the engine's own thread resolver.

    Landed via the "feat(contextguru): Split a session into threads with the engine's resolver" and "fix(contextguru): Run lifecycle.Finish so the summarizer can fire" commits (merged in PR #2129), with context-guru bumped to v0.7.9.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions