Repository navigation
fix(coref): price the turns left from billed growth (#232) - #757
Conversation
… 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]>
…232) Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| 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
-
components/pipeline.go:88 — the new
Ctx.CutFracfill inPipeline.Runhas 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) setsc.CutFracby hand, so it testscacheRewriteHorizononly. No test coversSummarize.CutFracorCacheAwareSummarizer.CutFraceither. The PR's own mutation list ("cut ignores CutFrac") mutates the consumer, not the producer. - Proof:
grep -rn "CutFrac" components/**/*_test.gomatches onlyprefix_horizon_test.go:61, a hand-set field. No test builds aPipelinewith a summarizer and assertsc.CutFracafterRun. - Fix: add one test in
componentsthat builds a pipeline fromsummarize+cache_aware_summarizer(and a disabled one, e.g.DisallowCountChangeforsummarize), runs it, and assertsc.CutFracequals 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.
- What fails: the suite cannot detect a break in the new wiring. Delete the whole loop at pipeline.go:88-96, or drop
-
docs/components/coref.md:72 — the user doc still describes the old horizon, which this PR replaces
- What fails: an operator reads how
break_evenprices 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.mdstill 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.
- What fails: an operator reads how
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 isCompactionPointwhen known. Using C is more correct; the sentence is wrong. - prefix_econ.go:301 —
billedAfterstarts fromPrevBilledInput, one turn stale by construction, so N overcounts the turns left by about 1. Acceptable for an estimate; the staleness is documented onPrevBilledInputitself. - A summarizer gated by
min_request_tokensormax_request_tokenscan cut belowCutFrac 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.mdneeds 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 newprefix_horizon_test.goin full. - Traced the horizon math end to end:
Trigger.FiresvsCutFracvsFillDenominatorall comparePrevBilledInputagainst the same denominator, so the cut point incacheRewriteHorizonmatches the summarizer's trigger. - Verified
prefixRewritePaysis byte-identical in behavior after the refactor: withbilledGrowth{}, every path inprefixRewritePaysWithfunnels toestimateTurnsRemainingwith 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), andsession.Scopedmakes 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
CutFracProvidertype assertion inPipeline.Runmatches, and thatSummarize.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
breakEvenTurnssignature, 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
left a comment
There was a problem hiding this comment.
| 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
-
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, butc.PrevBilledInputis read and written per session:apply/apply.go:689readsprevBilledInput(st, sessionID), andproxy/proxy.go:1753records 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.
- Sizes move down as well as up.
- Proof: prefix_econ.go:226-255 (key at 230, note of
c.PrevBilledInputat 253) against apply/apply.go:689 and apply/apply.go:1437-1442 (store keycg:bin:+ session, no thread). - Fix: pick one scope. Record billed input per thread (key
BilledPrefixbythread.Key), or note growth per session, or decline the billed horizon when the session has more than one live thread.
- What fails: a session with more than one thread shares one billed figure.
-
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 (
CutFracon*Summarize,*CacheAwareSummarizer). A constructor that returns a value type, or a cut component disabled per request, silently leavesCtx.CutFracat 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— onlyprefix_horizon_test.go:61sets the field by hand. No test builds a pipeline with aCutFracProvider. - Fix: one test in
components: two providers (0.9, 0.5) assert smallest wins; a disabled provider contributes nothing; a pre-setCtx.CutFracis respected.
- What fails: nothing today; the new behavior is unguarded. The fill depends on a type assertion against POINTER-receiver methods (
Non-blocking
components/offload/prefix_econ_guard_test.go:115—TestCorefHorizonIsNotCreditedsays 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 callsprefixRewritePaysWithwith 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.Runfills it before any component runs.components/component.go:632-634says "The warm sweep reads it" — that names #720's reader, not this PR's (coref's horizon).components/offload/prefix_econ.go:123—turnsRemainingAfterkeeps the two-role split for a caller that no longer exists. OnlyestimateTurnsRemainingcalls it, with both arguments equal. The removal credit it was built for moved intocacheRewriteHorizon.components/pipeline.go:86-87—CutFraccounts a summarizer that is enabled but will not cut on this deployment (no model resolved,cache_statedeclines). 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.mdhas 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 pointCutFrac * FillDenominatormatches the trigger'sfrac(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:
prefixRewritePayswith 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
CutFracProviderassertion 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]>
|
Round 1 answers (head: see the push). Blocking
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; 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; |
amiddavid
left a comment
There was a problem hiding this comment.
| 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
- 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 returnsapply.Trace{}, sotr.Sessionis"".proxy/proxy.go:1318-1324—tr.ThreadResolvedis false, sothreadFor(r, tn.ID, "", orig, ...)runs.proxy/thread.go:25-27— a""session short-circuits tothread.Result{ID: thread.Primary}before the agent header is read. SothreadIDis""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.BodyOptsontn.Shadow, thread from the agent header / prefix continuity) and readsprevBilledInputThread(shadow, sid, <subagent id>)— a key nothing ever writes.PrevBilledInputThreadstays 0 forever, so its horizon always falls back withno_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.
- A subagent's off-path run resolves its REAL thread (
- 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:
TestObserveModeRecordsBilledInputIntoTheShadowStoreasserts onlyBilledThreadPrefix + 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 theSessionIDForcall — or record inside the off-path job, where apply has already resolved the real thread.
- 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
Earlier findings
- My R1-1 (per-session figure into per-thread growth): fixed on the enforced path. Verified the whole chain:
RecordBilledInputThreadkeyscg:bint:bythread.Key(session, threadID)(apply/apply.go:1445-1451);servepasses the samethreadIDthe Ctx carried (proxy/proxy.go:1318-1324, 1754); both apply routes read it back (apply/apply.go:689, apply/responses.go:592);noteThreadGrowthandcacheRewriteHorizonreadPrevBilledInputThread(prefix_econ.go:240, 268, 278, 281).TestSideRequestDoesNotResetMainThreadGrowthproves 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.gocovers smallest-wins, a disabled provider, a preset, none, and the real constructors throughcomponents.New. I checked each assertion against the code inPipeline.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
CutFracProviderandCutFracdocs; theFillDenominatorwording;turnsRemainingAfterremoved; the pipeline note on an enabled summarizer that will not cut; the data-dependence section in the PR body; thedocs/data-dependence.mdrow.
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— theBilledThreadPrefixcomment 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, thecgllm_test.goadditions, and the updatedprefix_horizon_test.go. Their assertions match the code. estimateTurnsRemainingafter inliningturnsRemainingAfter: 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.mdrow. - No builds or tests were run (not approved). The author's Box 1 results are taken as reported, not verified by me.
amiddavid
left a comment
There was a problem hiding this comment.
| 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.gobuilds a realPipelineand asserts the fill: smallest wins, a disabled provider contributes nothing, a preset is kept, none is 0, and the realsummarize/cache_aware_summarizerconstructors feed it through the registry, includingDisallowCountChangedisablingsummarize. That is the test I asked for. I checked the fake implementsComponent+Offload+CutFracProvideron 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 themin_request_tokens/max_request_tokenscaveat. - 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.PrevBilledInputThreadfeedsnoteThreadGrowthandcacheRewriteHorizon, 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 ontr.Session+tr.Thread.IDfromresolveThreadinsideBodyOpts; the write (proxy.go:1754) keys ontr.Session+threadID, andthreadID = th.IDwhereth = tr.Threadwhenever apply resolved the thread (proxy.go:1320-1325). Sametr, same key. thread.Key(session, "")is the bare session, so single-thread traffic keys exactly ascg:bin:did.cg:bint:does not collide withcg:bin:underisPinPrefix'sHasPrefix(7-char prefix with the colon vs.t).- Guards mirror
RecordBilledInputexactly (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.
- Write and read use the same resolution. The read (
- 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
CutFracProviderwording ("every component", set before any runs), theFillDenominatorwording,turnsRemainingAfterremoved with no dangling callers, the pipeline note on an enabled summarizer that will not cut, and the data-dependence statement (PR body section plus thedocs/data-dependence.mdrow).
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.FirescomparesPrevBilledInput(whichever thread answered last) againstCutFrac x FillDenominator, while N usesPrevBilledInputThread. 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 wherecg: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
threadForand 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:
estimateTurnsRemainingafter inliningturnsRemainingAfteris 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.Offloadandsummarizedecline safely on the empty request the new pipeline test feeds them (summary_span_emptygate), 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
PrevBilledInputalso 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,
-raceon three packages, andmake lintpass; I verified the claims I could by reading.
|
Race check on 6a37ef8 (box 1, foreground): |
…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]>
|
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 Test: Non-blocking, fixed: Earlier question: Box 1 at 1cefbe9, |
amiddavid
left a comment
There was a problem hiding this comment.
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 —
1cefbe95fix(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
- My round-1, finding 1 — per-session growth fed a per-thread figure. Fixed in round 2 (
6a37ef8d). The enforced path stays correct at1cefbe95:servewritescg:bint:undertr.Session+threadID, and the read uses the same two values. Still fixed. - My round-1, finding 2 — no test for the CutFrac fill. Fixed in round 2 (
components/cutfrac_pipeline_test.go). Unchanged by1cefbe95. Still fixed. - My round-1, finding 3 — coref.md out of date. Fixed in round 2.
1cefbe95extends it correctly (see below). Still fixed. - 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 derivessidfromapply.SessionIDFor, then resolves the thread withthreadOf(sid)and writescg:bint:underthread.Key(sid, obsThread)intotn.Shadow. - Read (off-path run):
proxy/modes.gonow passesThreadOf: info.threadOf, soapplyresolves the thread with the same closure over the same request (r,orig). - Session halves agree by construction.
SessionIDForsharessessionIDFromwithBodyOpts(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.Resolveon 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 beforethreadOf(sid), sothreadForreceives 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)
threadOfcapturesrand is now called after the handler returns. The off-path run invokes the closure from its pool goroutine.threadForreads onlyr.Header.Get(agentIDHeader); the header map is written once, at parse, before the handler starts, so no concurrent writer exists and-racepasses. The capture inreqInfopredates 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. IfthreadForever grows a read ofr.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
left a comment
There was a problem hiding this comment.
| 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 derivessidwithapply.SessionIDFor, then resolves the thread withthreadOf(sid)— the same closure the request path hands to apply — and writescg:bint:+thread.Key(sid, obsThread)intotn.Shadow. - Read (
proxy/modes.go:161-170): the off-path run now passesThreadOf: info.threadOf, soapplycalls the same closure (apply/opts.go:147-161) with its own derived session id. - The session halves agree by construction:
SessionIDForsharessessionIDFromwithBodyOpts(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.Resolveon the same scope, agent header and body. A header thread gets"a:" + agentIDwhatever 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 beforethreadOf(sid), sothreadFornever sees the empty session that caused the round-2 short-circuit toPrimary.
- Write (
- 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
6a37ef8dthe observe job passed noThreadOf, 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.
1cefbe95does 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.gois unchanged by the new commit. - My R2 non-blocking items: both fixed. The observe-mode test now covers a non-primary thread (
TestObserveModeRecordsBilledInputUnderTheRequestThread), and theBilledThreadPrefixcomment no longer argues against its own pin. - Reviewer 2's round-3 note 1 (
threadOfcapturesrand is now called after the handler returns): agree, checked myself.threadForreads onlyr.Header.Get(agentIDHeader); the header map is written once at parse. The closure sat inreqInfoat base already (d6edaad0:proxy/modes.go:88); this commit adds the first call after return.Resolveholds 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.
TestObserveModeRecordsBilledInputUnderTheRequestThreadsendsx-claude-code-agent-id: sub1, asserts thea:sub1key exists and the primary key does not. I checked the id derivation:"sub1"passesValidHeaderID, andResolvereturns"a:sub1"for a header thread before any state is consulted. Serve's defer is the onlycg:bint:writer in observe mode, so the absent-primary assertion cannot pass by accident. KeepingthreadIDin the write fails both assertions, as the author claims. - The existing Shadow-store test stays right. It asserts the bare
BilledThreadPrefix + sidkey. Its request has no agent header and is the session's first, andnewIDgives the first threadPrimary(internal/thread/thread.go:295-298), sothread.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
longestPrefixmatch (the recorded list is longer), butrewrittenTailParentaccepts it — the shared run isth.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. threadOfnil is fail-open. A panic before the assignment atproxy/proxy.go:1277leaves 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.serveis called only fromchat(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.gocomment 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..1cefbe95and 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,resolveThreadinapply/opts.go),internal/thread/thread.go(Resolve,newID,longestPrefix,rewrittenTailParent, the mutex),store/store.go,docs/components/coref.md. - Confirmed at base
d6edaad0that the observe job passed noThreadOfand thatreqInfo.threadOfalready 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.
Summary
corefpriced the turns left as window ÷ local tokens per turn. A few large tool outputs moved it by 10x to 100x (coref: the econ turn horizon swings two orders of magnitude on transcript shape (defect 1 fixed) #232, defect 2).cacheRewriteHorizonprices it from the billed growth per turn on the thread. It is one function, so the warm sweep (feat(sweep): the warm path, an economic gate on a held answer (#491) #720) can call it later.What changed
Ctx.CutFrac), else the full window. It needsCtxWindowExact.PrevBilledInputThread(this thread only), less the removal scaled to billed units (ratio bounded to 1..8).horizon_fallback_<reason>.components.CutFracProvider:summarizeandcache_aware_summarizerreport their trigger fraction.Pipeline.RunsetsCtx.CutFracfrom the enabled ones (smallest wins).estimateTurnsRemainingno longer says "right to an order of magnitude".How it was tested
prefix_horizon_test.go. Tests cover: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.go test -count=1 ./...: pass.-raceoncomponents/offload: pass.make lint: pass.Mutation checks (each makes a test fail):
CutFracPipeline.Run: delete the fill loop, dropEnabled, take the largest, ignore a presetRound 1 changes
cg:bint:+thread.Key(session, thread), written next to the unchanged session keycg:bin:. NewCtx.PrevBilledInputThread. Only the growth horizon reads it.PrevBilledInput(session figure), all unchanged:FracResolvable,Fires: how full the session is)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.RecordBilledInput, in the enforced and the observe path.Pipeline.Run'sCutFracfill now has tests.turnsRemainingAfteris removed (its removal credit lives incacheRewriteHorizon).coref.mdanddata-dependence.mdare updated. Stale comments are fixed.Data dependence
cg:bint:). Metadata only. Pinned likecg:bin:. Listed in docs/data-dependence.md.Open questions
Ctx.CutFracis new public API oncomponents. feat(sweep): the warm path, an economic gate on a held answer (#491) #720 adds a same-named field and provider. Merge order may need a small rebase.Technical notes
corefis in no shipped preset, so no preset user sees a change.Fixes #232.
Part of #404.
🤖 Generated with Claude Code