Skip to content

fix(coref): price the turns left from billed growth (#232) - #757

Merged
amiddavid merged 4 commits into
mainfrom
fix/coref-turn-horizon
Oct 27, 2026
Merged

amiddavid merged 4 commits into
mainfrom
fix/coref-turn-horizon

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

What changed

  • N = (cut − billed prompt after the removal) ÷ billed growth per turn.
    • Cut: the summarizer's trigger fraction of the window (new Ctx.CutFrac), else the full window. It needs CtxWindowExact.
    • Billed prompt: PrevBilledInputThread (this thread only), less the removal scaled to billed units (ratio bounded to 1..8).
  • Fallback to the old estimate only when the billed size, the growth or an exact window is unknown. Coref counts it as the event horizon_fallback_<reason>.
  • Growth is tracked per thread, in memory. It restarts when the billed size shrinks. A repeated size is not a turn. The map holds at most 256 threads and drops entries older than 1 hour.
  • components.CutFracProvider: summarize and cache_aware_summarizer report their trigger fraction. Pipeline.Run sets Ctx.CutFrac from the enabled ones (smallest wins).
  • The comment on estimateTurnsRemaining no longer says "right to an order of magnitude".

How it was tested

  • New prefix_horizon_test.go. Tests cover:
    • the swing case: old horizons differ by more than 50x; new N is 200 for both shapes
    • the cut fraction and a size past the cut (N = 0)
    • each fallback reason
    • shrink restart and repeated size
    • per-thread keys, age limit, map bound
    • credit for the removal, and the ratio bound
    • the coref fallback event
  • Round 1 tests: components/cutfrac_pipeline_test.go (fakes and the real constructors), apply/billed_thread_test.go, a main thread with side requests, and two proxy tests for the write paths.
  • Full suite go test -count=1 ./...: pass. -race on components/offload: pass. make lint: pass.
  • No live run.

Mutation checks (each makes a test fail):

  • cut ignores CutFrac
  • Pipeline.Run: delete the fill loop, drop Enabled, take the largest, ignore a preset
  • growth fed from the session figure; per-thread record keyed by session only
  • no per-thread write in the enforced path; none in the observe path
  • no removal credit
  • no shrink restart
  • no exact-window check
  • a repeated size counts as a turn
  • no ratio bound
  • no age limit
  • no map bound

Round 1 changes

  • Billed input is now recorded per thread. New Store key cg:bint: + thread.Key(session, thread), written next to the unchanged session key cg:bin:. New Ctx.PrevBilledInputThread. Only the growth horizon reads it.
  • Readers of PrevBilledInput (session figure), all unchanged:
    • components/trigger.go:209 and :275 (FracResolvable, Fires: how full the session is)
    • components/offload/summarize.go:223 and extract_llm.go:689 (comments on the same trigger)
    • written at apply/apply.go:1437, read at apply/apply.go:689 and apply/responses.go:592
    • The session figure is right for them: they ask how full the context is, whoever answered last.
  • Reader of PrevBilledInputThread: components/offload/prefix_econ.go (noteThreadGrowth, cacheRewriteHorizon). feat(sweep): the warm path, an economic gate on a held answer (#491) #720's warm gate can use it the same way.
  • Written at proxy/proxy.go next to RecordBilledInput, in the enforced and the observe path.
  • Pipeline.Run's CutFrac fill now has tests. turnsRemainingAfter is removed (its removal credit lives in cacheRewriteHorizon). coref.md and data-dependence.md are updated. Stale comments are fixed.

Data dependence

  • In-memory growth state: 3 ints per thread, no content, not in the Store.
  • New Store record: one integer per thread (cg:bint:). Metadata only. Pinned like cg:bin:. Listed in docs/data-dependence.md.
  • No stored customer data is read.

Open questions

Technical notes

  • The fallback keeps today's behaviour exactly (no removal credit), so the existing guard tests for coref stay unchanged.
  • coref is in no shipped preset, so no preset user sees a change.

Fixes #232.
Part of #404.

🤖 Generated with Claude Code

… per turn (#232)

One horizon for every cache-rewrite gate: cacheRewriteHorizon.
N = (cut - billed prompt after the removal) / billed growth per turn.
The cut is the summarizer's trigger fraction (Ctx.CutFrac) or the
exact window. Growth is tracked per thread in a bounded, aged map.
The local-token estimate stays as a counted fallback.

Assisted-By: Claude Opus 5.5
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.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 95166ddd895e blocking

Verdict: blocking

Findings

  1. components/pipeline.go:88 — the new Ctx.CutFrac fill in Pipeline.Run has no test

    • What fails: the suite cannot detect a break in the new wiring. Delete the whole loop at pipeline.go:88-96, or drop comp.Enabled(c), or take the largest fraction instead of the smallest — every test still passes. TestHorizonCutFracIsTheCut (prefix_horizon_test.go:59) sets c.CutFrac by hand, so it tests cacheRewriteHorizon only. No test covers Summarize.CutFrac or CacheAwareSummarizer.CutFrac either. The PR's own mutation list ("cut ignores CutFrac") mutates the consumer, not the producer.
    • Proof: grep -rn "CutFrac" components/**/*_test.go matches only prefix_horizon_test.go:61, a hand-set field. No test builds a Pipeline with a summarizer and asserts c.CutFrac after Run.
    • Fix: add one test in components that builds a pipeline from summarize + cache_aware_summarizer (and a disabled one, e.g. DisallowCountChange for summarize), runs it, and asserts c.CutFrac equals the smallest fraction of the enabled ones, and 0 when none apply.
    • Why it matters: #720 will rebase onto this wiring and drop its own copy. A silent break here propagates into the warm sweep's horizon with no failing test anywhere.
  2. docs/components/coref.md:72 — the user doc still describes the old horizon, which this PR replaces

    • What fails: an operator reads how break_even prices T and gets the removed model. Line 72: "T estimated from how fast the transcript has been growing". Line 309 repeats it. Both now disagree with the code, which prices T from billed growth per turn (cacheRewriteHorizon, prefix_econ.go:270).
    • Proof: the PR rewrites the same claim in the code comments (coref.go:377, prefix_econ.go:27-28) but touches no file under docs/. grep "growing" docs/components/coref.md still hits lines 72 and 309.
    • Fix: update both sentences to the billed-growth wording, and name the horizon_fallback_<reason> events so an operator can see when the old estimate ran.

Non-blocking

  • components/component.go:422 — the doc says the pipeline hands CutFrac "to the components that run after it". The code sets it before any component runs, so a component ordered before the summarizer also reads it. The code is the better behavior (the cut is a pipeline property); fix the sentence.
  • components/offload/prefix_econ.go:262 — the doc says "else the whole window", but the code uses c.FillDenominator(), which is CompactionPoint when known. Using C is more correct; the sentence is wrong.
  • prefix_econ.go:301 — billedAfter starts from PrevBilledInput, one turn stale by construction, so N overcounts the turns left by about 1. Acceptable for an estimate; the staleness is documented on PrevBilledInput itself.
  • A summarizer gated by min_request_tokens or max_request_tokens can cut below CutFrac x C, which makes N overestimate. The PR body already scopes the cut to the trigger fraction; worth one sentence in the doc when finding 2 is fixed.
  • The PR does not state its data dependence, which CLAUDE.md asks of every PR. The new state (growthThreads) is in-memory metadata only: three ints per thread, no content, not in the Store. Say so in the PR description; docs/data-dependence.md needs no new row.

What I checked

  • Read the full diff (7 files) and the code around each change: component.go, pipeline.go, coref.go, prefix_econ.go, both summarizers, and the new prefix_horizon_test.go in full.
  • Traced the horizon math end to end: Trigger.Fires vs CutFrac vs FillDenominator all compare PrevBilledInput against the same denominator, so the cut point in cacheRewriteHorizon matches the summarizer's trigger.
  • Verified prefixRewritePays is byte-identical in behavior after the refactor: with billedGrowth{}, every path in prefixRewritePaysWith funnels to estimateTurnsRemaining with the same arguments, so the guard tests (prefix_econ_guard_test.go) still pin the old arithmetic.
  • Checked the fallback paths for nil c, unknown window, saved <= 0: each returns the documented result, no panic, and the break-even gate keeps its "no constraint when unresolvable" convention.
  • Checked the growth map: mutex-guarded, bounded at 256 with LRU eviction, 1 h age restart, keyed by thread.Key(Session, Thread) like the other offload registries (sweepPingCand, keepAliveCand), and session.Scoped makes the key tenant-safe. A lost or mixed entry reads as unknown growth and falls back — fail open.
  • Checked note's edge cases: duplicate size (no turn), shrink (restart), flat growth (fallback). The error direction of each is conservative for the gate.
  • Checked that both summarizer constructors return pointers, so the CutFracProvider type assertion in Pipeline.Run matches, and that Summarize.Enabled (!DisallowCountChange) is honored by the fill loop.
  • Confirmed the PR's claims: coref is in no preset (only config/markercap.go), and the fallback keeps coref's old behavior term for term.
  • Confirmed no existing test used the old breakEvenTurns signature, so the change compiles; test helpers (assistantMsg, toolResultMsg, bigReq) exist in the package.
  • Did not run builds or tests (not approved). Read the PR body only; no reviews or comments were read before this post.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 95166ddd895e blocking

Verdict: blocking

Findings

  1. components/offload/prefix_econ.go:230 — noteThreadGrowth feeds a per-THREAD entry from a per-SESSION billed figure.

    • What fails: a session with more than one thread shares one billed figure. thread.Key(c.Session, c.Thread) keys the growth map per thread, but c.PrevBilledInput is read and written per session: apply/apply.go:689 reads prevBilledInput(st, sessionID), and proxy/proxy.go:1753 records it from each response, whichever thread produced it (internal/thread's doc: one session holds "the main agent, each subagent, each fork"; Claude Code subagents and side requests share the session id). So each thread's entry notes sizes that belong to sibling threads. Two outcomes:
      • Sizes move down as well as up. note (prefix_econ.go:197) treats a smaller value as a restart. A side request (a title, a security monitor) that answers between two main-thread turns resets the main thread's growth run every time. Growth stays unknown, the horizon falls back to the local estimate, and defect #232 stays live on exactly this traffic.
      • The noted mixture grows slower than the thread itself. Growth is under-estimated, N is over-estimated, and break-even clears a rewrite that cannot pay back — the exact cache-write spend this gate exists to stop.
    • Proof: prefix_econ.go:226-255 (key at 230, note of c.PrevBilledInput at 253) against apply/apply.go:689 and apply/apply.go:1437-1442 (store key cg:bin: + session, no thread).
    • Fix: pick one scope. Record billed input per thread (key BilledPrefix by thread.Key), or note growth per session, or decline the billed horizon when the session has more than one live thread.
  2. components/pipeline.go:88 — the Ctx.CutFrac fill has no test.

    • What fails: nothing today; the new behavior is unguarded. The fill depends on a type assertion against POINTER-receiver methods (CutFrac on *Summarize, *CacheAwareSummarizer). A constructor that returns a value type, or a cut component disabled per request, silently leaves Ctx.CutFrac at 0 and the horizon silently prices the whole window. No test fails. The smallest-wins rule and the pre-set-value rule are likewise untested.
    • Proof: grep CutFrac components/**/*_test.go — only prefix_horizon_test.go:61 sets the field by hand. No test builds a pipeline with a CutFracProvider.
    • Fix: one test in components: two providers (0.9, 0.5) assert smallest wins; a disabled provider contributes nothing; a pre-set Ctx.CutFrac is respected.

Non-blocking

  • components/offload/prefix_econ_guard_test.go:115 — TestCorefHorizonIsNotCredited says coref "must not start" crediting the removal. The billed horizon now credits it (TestHorizonCreditsTheRemoval). The test passes only because it runs the fallback path. Scope its claim to the fallback, or it documents a rule this PR breaks.
  • components/offload/prefix_econ_guard_test.go:31 — "COREF'S PATH IS UNTOUCHED, term for term". Coref now calls prefixRewritePaysWith with growth. The test itself stays valid; the comment is stale.
  • components/component.go:420-424 — the doc says the value goes "to the components that run after it". Pipeline.Run fills it before any component runs. components/component.go:632-634 says "The warm sweep reads it" — that names #720's reader, not this PR's (coref's horizon).
  • components/offload/prefix_econ.go:123 — turnsRemainingAfter keeps the two-role split for a caller that no longer exists. Only estimateTurnsRemaining calls it, with both arguments equal. The removal credit it was built for moved into cacheRewriteHorizon.
  • components/pipeline.go:86-87 — CutFrac counts a summarizer that is enabled but will not cut on this deployment (no model resolved, cache_state declines). The horizon shrinks and coref forgoes rewrites. Safe direction; the doc should say so.
  • New per-thread in-memory state (three ints, no content) is metadata only. docs/data-dependence.md has no note for it, and the PR body does not walk the storage levels. The repo rule asks each PR to state its data dependence.

What I checked

  • The full diff d6edaad0..HEAD, both commits, and the code around every change: components/component.go, components/pipeline.go, components/offload/coref.go, prefix_econ.go, prefix_horizon_test.go.
  • The unchanged pieces the change leans on: trigger.go (Fires, FracResolvable), cachephase.go (FillDenominator — the cut point CutFrac * FillDenominator matches the trigger's frac(MinRequestFrac, FillDenominator)), prefix_econ_guard_test.go.
  • The billed figure's full path: apply/apply.go (prevBilledInput, RecordBilledInput, session derivation), proxy/proxy.go:1753, internal/thread (session vs thread keying).
  • Fallback equivalence: prefixRewritePays with no growth reproduces the old expression term for term; the guard test compares against a literal transcription of the original.
  • Constructor receivers: both summarizers register pointers, so the CutFracProvider assertion finds them.
  • The new tests' arithmetic, by hand (N = 200, 30, 0; restart and duplicate-size rules; map bound and age).
  • No builds or tests were run. Live tests are not approved.

…232)

Round 1 review of #757.
- Record billed input per thread (cg:bint:<thread key>) next to the
  session figure. Ctx.PrevBilledInputThread feeds the growth run, so a
  side request or subagent cannot reset or dilute the main thread.
- Test Pipeline.Run's CutFrac fill with fakes and the real summarizers.
- Document the billed-growth horizon in coref.md and data-dependence.md.
- Remove turnsRemainingAfter (its removal credit lives in
  cacheRewriteHorizon). Fix stale comments.

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

Copy link
Copy Markdown
Collaborator Author

Round 1 answers (head: see the push).

Blocking

  1. Per-thread growth from a per-session figure (R1): fixed. Billed input is now recorded per thread (cg:bint:), and Ctx.PrevBilledInputThread feeds the growth run. The session figure and all its readers are unchanged (listed in the PR body). Test: a main thread with side requests keeps a steady 4000 per turn. Mutations: growth fed from the session figure, per-thread key by session only, no write in the enforced path, no write in the observe path. Each fails a test.
  2. No test for the CutFrac fill (R1, R2): fixed. components/cutfrac_pipeline_test.go covers smallest wins, a disabled provider, a preset, none, and the real summarize and cache_aware_summarizer. Mutations: delete the loop, drop Enabled, take the largest, ignore a preset. Each fails a test.
  3. coref.md out of date (R2): fixed at both places. It names horizon_fallback_<reason> and the min/max_request_tokens caveat.

Non-blocking, all fixed: guard-test claim scoped to the fallback; stale "UNTOUCHED" comment; CutFrac doc says it is set before any component runs and names coref; FillDenominator wording; turnsRemainingAfter removed; pipeline.go note on an enabled summarizer that will not cut; Data dependence section added; docs/data-dependence.md updated.

Box 1 results (-count=1): all packages except components/offload pass; components/offload passes (25.8 s); -race passes on components, apply and components/offload; make lint passes.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 6a37ef8db94a blocking

Verdict: blocking

Findings

  1. proxy/proxy.go:1773 — in observe mode the per-thread billed record is written under the PRIMARY thread for every request, so finding R1-1 is fixed on the enforced path only.
    • What fails: an observe-mode tenant with a main thread plus subagents. Every request, whichever thread it ran on, writes its billed figure into the one key cg:bint:<sid>:
      • proxy/modes.go:41-44 — observe returns apply.Trace{}, so tr.Session is "".
      • proxy/proxy.go:1318-1324 — tr.ThreadResolved is false, so threadFor(r, tn.ID, "", orig, ...) runs.
      • proxy/thread.go:25-27 — a "" session short-circuits to thread.Result{ID: thread.Primary} before the agent header is read. So threadID is "" for every observe-mode request.
      • proxy/proxy.go:1773 — RecordBilledInputThread(tn.Shadow, sid, "", billed) keys the primary thread.
    • Two consequences, both in observe mode only:
      • A subagent's off-path run resolves its REAL thread (proxy/modes.go:161-188 → apply.BodyOpts on tn.Shadow, thread from the agent header / prefix continuity) and reads prevBilledInputThread(shadow, sid, <subagent id>) — a key nothing ever writes. PrevBilledInputThread stays 0 forever, so its horizon always falls back with no_billed_size.
      • Every thread's response overwrites the primary key, so the MAIN thread's growth run in observe is reset and diluted by subagent answers — the exact mixing round-1 finding 1 described. The commit's own claim ("a side request or subagent cannot reset or dilute the main thread") holds in sync mode only.
    • Severity: observe mode only. The enforced sync path is wired correctly (checked end to end below). No request, spend or reversibility is affected. But observe exists to measure this gate, and the repo has treated a permanent observe-mode zero as a defect before (the cg:bin: shadow record exists for exactly that reason, proxy/proxy.go:1759-1771).
    • Why the tests miss it: TestObserveModeRecordsBilledInputIntoTheShadowStore asserts only BilledThreadPrefix + sid — the primary key, which the observe write always uses.
    • Fix: in the observe branch, resolve the thread from the same facts the off-path run uses — h.threadFor(r, tn.ID, sid, body, ...) next to the SessionIDFor call — or record inside the off-path job, where apply has already resolved the real thread.

Earlier findings

  • My R1-1 (per-session figure into per-thread growth): fixed on the enforced path. Verified the whole chain: RecordBilledInputThread keys cg:bint: by thread.Key(session, threadID) (apply/apply.go:1445-1451); serve passes the same threadID the Ctx carried (proxy/proxy.go:1318-1324, 1754); both apply routes read it back (apply/apply.go:689, apply/responses.go:592); noteThreadGrowth and cacheRewriteHorizon read PrevBilledInputThread (prefix_econ.go:240, 268, 278, 281). TestSideRequestDoesNotResetMainThreadGrowth proves the mixing case. Not fixed in observe mode — new finding 1 above.
  • My R1-2 (no test for the CutFrac fill): fixed. components/cutfrac_pipeline_test.go covers smallest-wins, a disabled provider, a preset, none, and the real constructors through components.New. I checked each assertion against the code in Pipeline.Run; they pin the right outcomes.
  • Reviewer 2, finding 1 (CutFrac test): same as my R1-2, fixed. Checked myself; agree.
  • Reviewer 2, finding 2 (coref.md out of date): fixed. Both places (docs/components/coref.md:71-76, 313) now state the billed-growth horizon, name the horizon_fallback_<reason> events, and carry the min/max_request_tokens caveat.
  • All non-blocking items from both reviews: fixed. Guard-test comments scoped to the fallback; the stale "UNTOUCHED" comment; the CutFracProvider and CutFrac docs; the FillDenominator wording; turnsRemainingAfter removed; the pipeline note on an enabled summarizer that will not cut; the data-dependence section in the PR body; the docs/data-dependence.md row.

Non-blocking

  • When finding 1 is fixed, extend the observe-mode test with a subagent thread (a request carrying the agent-id header), so the write key is asserted for a non-primary thread, not only the primary one.
  • store/store.go:592-598 — the BilledThreadPrefix comment pins the key "for the same reason as BilledPrefix", then states the loss costs only a fallback. The sentence reads as an argument against pinning. Wording only; pinning one integer per thread is harmless.

What I checked

  • Last review: round 1, 95166ddd895e, 2026-10-27T17:25:55Z.
  • New commits read: 1 — 6a37ef8 "fix(coref): measure billed growth per thread, test the CutFrac fill (#232)".
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
  • New items since my last review: the author's round-1 answers (comment at 2026-10-27T18:07:26Z) — each claim checked against the code as above; commit 6a37ef8 — full diff read, plus the code around every change.
  • The fix's key wiring on the enforced path: apply (both routes), proxy (live and shadow stores), the growth map key and the store key all use thread.Key(session, thread). The session figure and its readers are unchanged.
  • The observe path traced end to end to establish finding 1: applyMode's zero Trace, threadFor's ""-session short-circuit, the shadow write key, and the off-path run's own thread resolution.
  • The new tests read line by line: billed_thread_test.go, cutfrac_pipeline_test.go, the cgllm_test.go additions, and the updated prefix_horizon_test.go. Their assertions match the code.
  • estimateTurnsRemaining after inlining turnsRemainingAfter: same arithmetic term for term; the guard tests still pin it against a literal recomputation.
  • The PR body's new Data dependence section and the docs/data-dependence.md row.
  • No builds or tests were run (not approved). The author's Box 1 results are taken as reported, not verified by me.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 6a37ef8db9 approve

Verdict: approve

Earlier findings

  • My finding 1 (CutFrac fill untested): fixed. components/cutfrac_pipeline_test.go builds a real Pipeline and asserts the fill: smallest wins, a disabled provider contributes nothing, a preset is kept, none is 0, and the real summarize / cache_aware_summarizer constructors feed it through the registry, including DisallowCountChange disabling summarize. That is the test I asked for. I checked the fake implements Component + Offload + CutFracProvider on value receivers, so the type assertion path is the real one.
  • My finding 2 (coref.md stale): fixed. Both places (now lines 72 and 313) price T from billed growth, name horizon_fallback_<reason> with the three reasons, and carry the min_request_tokens / max_request_tokens caveat.
  • Reviewer 1, finding 1 (per-session figure feeding per-thread growth): fixed, and I checked the fix myself. Billed input is now recorded per thread (cg:bint: + thread.Key(session, thread)), Ctx.PrevBilledInputThread feeds noteThreadGrowth and cacheRewriteHorizon, and the session figure and its readers are untouched. Verified end to end:
    • Write and read use the same resolution. The read (apply.go:690) keys on tr.Session + tr.Thread.ID from resolveThread inside BodyOpts; the write (proxy.go:1754) keys on tr.Session + threadID, and threadID = th.ID where th = tr.Thread whenever apply resolved the thread (proxy.go:1320-1325). Same tr, same key.
    • thread.Key(session, "") is the bare session, so single-thread traffic keys exactly as cg:bin: did. cg:bint: does not collide with cg:bin: under isPinPrefix's HasPrefix (7-char prefix with the colon vs. t).
    • Guards mirror RecordBilledInput exactly (nil store, empty session, tokens <= 0), so a no-op write can never store a figure that reads as known.
    • The Responses API path resolves the thread too (responses.go:520), so its read key matches.
    • Both stores get the record: the enforced path (tn.Store) and the observe shadow (tn.Shadow, proxy.go:1773), each covered by a test.
  • Reviewer 1, finding 2 (CutFrac fill untested): same fix as my finding 1.
  • All non-blocking items from both reviews: fixed. Guard-test claims scoped to the fallback, the stale "UNTOUCHED" comment, the CutFracProvider wording ("every component", set before any runs), the FillDenominator wording, turnsRemainingAfter removed with no dangling callers, the pipeline note on an enabled summarizer that will not cut, and the data-dependence statement (PR body section plus the docs/data-dependence.md row).

Findings

None.

Non-blocking

  • components/offload/prefix_econ.go:270 — the horizon's room is per thread, but the summarizer's cut gate reads the session figure. Trigger.Fires compares PrevBilledInput (whichever thread answered last) against CutFrac x FillDenominator, while N uses PrevBilledInputThread. In a mixed session the cut can land off the assumed point in main-thread terms. Side answers dilute the session figure, delay the cut, and make N an underestimate (safe). A large sibling thread answering last can fire the cut early and make N an overestimate (a rewrite with a shorter collection window than priced). Second-order; the doc already says T can be an overestimate. Worth one sentence if anyone measures break-even accuracy on subagent-heavy traffic.
  • store/store.go:262 — cg:bint: is pinned per thread, not per session. A subagent-heavy session now holds several pinned slots where cg:bin: held one. Over the pin cap a pin degrades to an evictable entry, and a lost key costs a fallback horizon, not correctness (the constant's comment says so). No change needed; noting the budget shift.
  • On a request where apply returns before resolving the thread, the write key comes from threadFor and the read key from apply's own zero-value resolution. The two can differ, the figure then reads unknown, and the horizon falls back. Fail open, rare, and the same asymmetry every other per-thread key in the proxy already has.

What I checked

  • Last review: round 1, 95166dd, 2026-10-27T17:24:57Z
  • New commits read: 1 — 6a37ef8d "fix(coref): measure billed growth per thread, test the CutFrac fill (#232)"
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review, and what I did about each:
    • Reviewer 1's round-1 review (17:25:55Z): read in full. Its finding 1 was outside my round-1 view; I verified the fix independently (see Earlier findings). Its finding 2 duplicated mine.
    • The author's round-1 answers (18:07:26Z): read in full. Every "fixed" claim was checked against the code, not taken on trust.
    • Commit 6a37ef8d: read the full diff and the code around every change — apply/apply.go, apply/responses.go, store/store.go, proxy/proxy.go, components/component.go, components/pipeline.go, components/offload/prefix_econ.go, and all five touched test files.
  • Verified the fallback is still byte-identical: estimateTurnsRemaining after inlining turnsRemainingAfter is the same expression, so the guard tests still pin the original arithmetic.
  • Verified the new tests' logic by hand: the per-thread store test (primary key = bare session, side key distinct), the side-request growth test (steady 4000 over 3 turns), and the CutFrac fill tests (all five assertions match the loop in Pipeline.Run).
  • Checked cache_aware_summarizer.Offload and summarize decline safely on the empty request the new pipeline test feeds them (summary_span_empty gate), so the test exercises the fill without depending on summarizer behavior.
  • Confirmed no other host records billed input (only the proxy), so hosts that never set PrevBilledInput also never set the thread figure — both read unknown and the horizon falls back, which is the pre-existing behavior for them.
  • Did not run builds or tests (not approved). The author reports the full suite, -race on three packages, and make lint pass; I verified the claims I could by reading.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Race check on 6a37ef8 (box 1, foreground): CGO_ENABLED=1 go test -race -count=1 ./proxy/... passes (498 s). No push.

…thread (#232)

Round 2 review of #757. Observe mode returns an empty Trace, so the
response path took the primary thread for the per-thread billed write.
A subagent's figure overwrote the main thread's, and the off-path run
read a key nothing wrote.

- serve resolves the thread with the same threadOf closure the request
  path hands to apply, so the key written is the key the run reads.
- The off-path run gets ThreadOf, so it reads the same key.
- Test: a subagent request (agent-id header) in observe mode.
- Reword the BilledThreadPrefix comment. Note in coref.md that the cut
  uses the session figure and N uses the thread figure.

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

Copy link
Copy Markdown
Collaborator Author

Round 2 answer (head 1cefbe9).

Blocking: observe-mode per-thread write used the primary thread. Fixed. The cause is as you wrote: observe returns an empty Trace, so serve saw no thread. serve now takes the same threadOf closure the request path gives apply and resolves the thread from the session id it derives for the Shadow store. The off-path run also gets ThreadOf, so it reads the key the response path wrote. I chose the first option (resolve in serve) over recording inside the off-path job, because the figure must exist before the next turn's run reads it.

Test: TestObserveModeRecordsBilledInputUnderTheRequestThread sends a request with the agent-id header and asserts the a:sub1 key exists and the primary key does not. Mutation (the write keeps threadID): the test fails on both assertions.

Non-blocking, fixed: BilledThreadPrefix comment reworded. coref.md now says the summarizer's cut fires on the session figure while N uses the thread figure, so in a mixed session the cut can drift.

Earlier question: -race -count=1 ./proxy/... at 6a37ef8 passed (498 s).

Box 1 at 1cefbe9, -count=1: all packages pass, make lint passes, -race passes on apply, components, components/offload and proxy. One proxy -race run failed TestALateFirstByteOnTheRealTransportNeverReachesTheClient (a 5 ms upstream-silence deadline, unrelated to this change). It passed 3 of 3 alone under -race, and the full proxy -race rerun passed (486 s).

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review, round 3 — approve

Reviewer 2
Verdict Approve
Head 1cefbe95590e
Reviewer Backend Context Session # Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 4 1cefbe95590e approve

What I checked

  • Last review: round 2, 6a37ef8db94a6ef97f43ced4aa4f9ff0d81d20ad, 2026-10-27T18:14:19Z.
  • New commits read: 1 — 1cefbe95 fix(coref): write the observe-mode billed record under the request's thread.
  • Read in full: 4 reviews, 3 comments, 0 inline comments (from the three saved conversation files).
  • Diff of 6a37ef8d..1cefbe95: 5 files — proxy/proxy.go, proxy/modes.go, proxy/cgllm_test.go, store/store.go, docs/components/coref.md.
  • Read around the diff: proxy/proxy.go (chat at 1195–1309, serve at 1626–1794), proxy/thread.go, apply/apply.go (SessionIDFor, 1397–1403), internal/thread/thread.go (recorder, mutex at 138), store/store.go.

Status of earlier findings

  1. My round-1, finding 1 — per-session growth fed a per-thread figure. Fixed in round 2 (6a37ef8d). The enforced path stays correct at 1cefbe95: serve writes cg:bint: under tr.Session + threadID, and the read uses the same two values. Still fixed.
  2. My round-1, finding 2 — no test for the CutFrac fill. Fixed in round 2 (components/cutfrac_pipeline_test.go). Unchanged by 1cefbe95. Still fixed.
  3. My round-1, finding 3 — coref.md out of date. Fixed in round 2. 1cefbe95 extends it correctly (see below). Still fixed.
  4. Reviewer 1, round 2, blocking — observe mode wrote the billed record under the primary thread. Fixed by 1cefbe95. I traced the fix end to end; details below.

An error of mine. My round-2 note 3 called this edge benign: the figure would read unknown and the horizon falls back. That was wrong. Reviewer 1 showed the real behavior: threadFor short-circuits on the empty session before it reads the agent header, so every observe request wrote the primary key. Subagent answers overwrote the main thread's figure, and subagent off-path runs read keys nothing wrote. A mixing defect, not a benign unknown. Reviewer 1 found it; my round-2 approve missed it.

The new commit, 1cefbe95

The fix is correct. The write key and the read key now agree on both halves:

  • Write (proxy/proxy.go:1772–1784): serve's observe branch derives sid from apply.SessionIDFor, then resolves the thread with threadOf(sid) and writes cg:bint: under thread.Key(sid, obsThread) into tn.Shadow.
  • Read (off-path run): proxy/modes.go now passes ThreadOf: info.threadOf, so apply resolves the thread with the same closure over the same request (r, orig).
  • Session halves agree by construction. SessionIDFor shares sessionIDFrom with BodyOpts (apply/apply.go:1391–1396), so serve and the off-path run derive the same session id.
  • Thread halves agree. Both calls run h.threads.Resolve on the same inputs — same session, same agent header, same body bytes (observe forwards the body untouched). The recorder is deterministic on those inputs, so both resolve the same thread.
  • The session == "" short-circuit is gone from this path. sid != "" is checked before threadOf(sid), so threadFor receives a non-empty session and reads the agent header.

The design choice is right. The author resolved the thread in serve's defer, not inside the off-path job, because the figure must exist before the next turn's off-path run reads it. Recording inside the async job could lose that race. I agree.

Concurrency is safe. Serve's defer and the off-path pool goroutine both call the recorder. The recorder holds a sync.Mutex (internal/thread/thread.go:138). The author's -race ./proxy/... run at 1cefbe95 passed (486 s, after one unrelated flake).

Scope of the hoist is sound. threadOf is assigned at proxy/proxy.go:1277, before applyMode, on every path through the panic-guarded closure — observe and bypassed included. A panic before line 1277 (in repairExpandErrors or AnchorPoint) leaves it nil; serve nil-checks it and writes the primary key. That is a fail-open edge on the panic path only: the figure is lost, the horizon falls back. Acceptable.

The test is sound. TestObserveModeRecordsBilledInputUnderTheRequestThread sends the agent-id header sub1 and asserts the a:sub1 key exists and the primary key does not. Serve's defer is the only cg:bint: writer in observe mode, so the absent-primary assertion cannot pass by accident. The stated mutation (keep threadID) fails both assertions. The existing Shadow-store test now polls for the record, which fixes the race the old fixed-sleep shape had.

store/store.go — comment rewording only. It now states the pin and the safe fallback. Matches the code.

docs/components/coref.md — the new sentence is accurate: the summarizer's cut fires on the session figure while T uses the thread figure, so in a mixed session the cut can drift. I verified this against prefix_econ.go in round 2; the doc now says it plainly.

Notes (non-blocking)

  1. threadOf captures r and is now called after the handler returns. The off-path run invokes the closure from its pool goroutine. threadFor reads only r.Header.Get(agentIDHeader); the header map is written once, at parse, before the handler starts, so no concurrent writer exists and -race passes. The capture in reqInfo predates this commit — the enforced path already held this closure. But the reqInfo rule says "never a pointer into request-scoped state", and this commit adds the first call after return. If threadFor ever grows a read of r.Context() or the body, this becomes a real hazard. One comment on the closure naming that constraint would settle it.

Verdict

Approve. The one new commit fixes the round-2 blocking finding correctly, on the write half and the read half, with a sound test. I have no new findings beyond the note above.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 4 1cefbe95590e approve

Verdict: approve

Findings

None.

Earlier findings

  • My R2-1 (observe mode wrote every thread's billed record under the primary key): fixed by 1cefbe95. I traced both halves of the fix:
    • Write (proxy/proxy.go:1772-1784): serve derives sid with apply.SessionIDFor, then resolves the thread with threadOf(sid) — the same closure the request path hands to apply — and writes cg:bint: + thread.Key(sid, obsThread) into tn.Shadow.
    • Read (proxy/modes.go:161-170): the off-path run now passes ThreadOf: info.threadOf, so apply calls the same closure (apply/opts.go:147-161) with its own derived session id.
    • The session halves agree by construction: SessionIDFor shares sessionIDFrom with BodyOpts (apply/apply.go:1377-1403), and both sides feed it the same header and the same body bytes (observe forwards the body untouched).
    • The thread halves agree: both calls run h.threads.Resolve on the same scope, agent header and body. A header thread gets "a:" + agentID whatever the tracker holds (internal/thread/thread.go:244), and a prefix thread matched once matches again on the same body, so the second resolve returns the same id.
    • sid != "" is checked before threadOf(sid), so threadFor never sees the empty session that caused the round-2 short-circuit to Primary.
  • An error of mine, round 2. My round-2 finding said the subagent's off-path run "resolves its REAL thread and reads a key nothing ever writes". The read half was wrong: at 6a37ef8d the observe job passed no ThreadOf, so the run's Trace stayed zero and it read the primary key too. Both halves were on the primary key. The defect was the mixing — every thread's answer overwrote the one key every thread read — which stands, and the commit message states it correctly. The fix repairs both halves, so the error changed nothing about the outcome.
  • My R1-1 (per-session figure into per-thread growth): still fixed. 1cefbe95 does not touch the enforced path's write (proxy/proxy.go:1754-1757) or any reader.
  • My R1-2 (no test for the CutFrac fill): still fixed. components/cutfrac_pipeline_test.go is unchanged by the new commit.
  • My R2 non-blocking items: both fixed. The observe-mode test now covers a non-primary thread (TestObserveModeRecordsBilledInputUnderTheRequestThread), and the BilledThreadPrefix comment no longer argues against its own pin.
  • Reviewer 2's round-3 note 1 (threadOf captures r and is now called after the handler returns): agree, checked myself. threadFor reads only r.Header.Get(agentIDHeader); the header map is written once at parse. The closure sat in reqInfo at base already (d6edaad0:proxy/modes.go:88); this commit adds the first call after return. Resolve holds a mutex (internal/thread/thread.go:138), so the concurrent calls are safe. I add nothing to their ask for one naming comment.

The new commit, 1cefbe95

  • The test is sound. TestObserveModeRecordsBilledInputUnderTheRequestThread sends x-claude-code-agent-id: sub1, asserts the a:sub1 key exists and the primary key does not. I checked the id derivation: "sub1" passes ValidHeaderID, and Resolve returns "a:sub1" for a header thread before any state is consulted. Serve's defer is the only cg:bint: writer in observe mode, so the absent-primary assertion cannot pass by accident. Keeping threadID in the write fails both assertions, as the author claims.
  • The existing Shadow-store test stays right. It asserts the bare BilledThreadPrefix + sid key. Its request has no agent header and is the session's first, and newID gives the first thread Primary (internal/thread/thread.go:295-298), so thread.Key(sid, Primary) is the bare session. The new polling loop replaces the old fixed sleep.
  • A late off-path job still resolves the same thread. I traced the reorder case: a job for turn N running after turn N+1's serve-side resolve finds no longestPrefix match (the recorded list is longer), but rewrittenTailParent accepts it — the shared run is th.n - 2, which passes its bound — and returns the same thread id. Header threads are state-free. So the write key and the read key stay equal even out of order.
  • threadOf nil is fail-open. A panic before the assignment at proxy/proxy.go:1277 leaves it nil; serve nil-checks and writes the primary key. That is the round-2 behaviour, on the panic path only. The figure is lost, the horizon falls back.
  • One caller. h.serve is called only from chat (proxy/proxy.go:1434); the new parameter reaches every path.
  • Docs. The coref.md sentence matches the code: the summarizer's cut fires on the session figure, T uses the thread figure. The store/store.go comment now states the pin and the safe loss separately. Both accurate.

What I checked

  • Last review: round 2, 6a37ef8db94a6ef97f43ced4aa4f9ff0d81d20ad, 2026-10-27T18:14:04Z.
  • New commits read: 1 — 1cefbe95 "fix(coref): write the observe-mode billed record under the request's thread (#232)".
  • Read in full: 5 reviews, 3 comments, 0 inline comments (from the three saved files).
  • New items since my last review, and what I did about each:
    • Reviewer 2's race-check comment (18:16:57Z): noted; no code claim to check.
    • The author's round-2 answers (19:06:51Z): every claim checked against the code above, not taken on trust.
    • Reviewer 2's round-3 review (19:14:12Z): read in full; their fix trace and their non-blocking note re-verified by me (see Earlier findings).
  • The full diff 6a37ef8d..1cefbe95 and the code around every change: proxy/proxy.go (chat 1195-1345, serve 1626-1800), proxy/modes.go, proxy/thread.go, proxy/cgllm_test.go (both observe tests line by line), apply/apply.go (SessionIDFor, sessionIDFrom, resolveThread in apply/opts.go), internal/thread/thread.go (Resolve, newID, longestPrefix, rewrittenTailParent, the mutex), store/store.go, docs/components/coref.md.
  • Confirmed at base d6edaad0 that the observe job passed no ThreadOf and that reqInfo.threadOf already existed — this corrects my round-2 read-half claim and scopes what the commit adds.
  • No builds or tests were run (not approved). The author's Box 1 results are taken as reported, not verified by me.

@amiddavid
amiddavid merged commit ccb62c7 into main Oct 27, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 27, 2026
@amiddavid
amiddavid deleted the fix/coref-turn-horizon branch October 27, 2026 19:25
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.

coref: the econ turn horizon swings two orders of magnitude on transcript shape (defect 1 fixed)

1 participant