Repository navigation
feat(sweep): ask a long list of outputs in balanced batches, then cut once (#132) - #747
Conversation
The gate's N was the warm turns so far. Now: - warm_expected_turns (default 0 = unset): N = max(expected - so far, 0). - Otherwise the session is assumed to run to its CUT: the summarizer's trigger fraction of the window when one is in the pipeline (handed to the sweep by the pipeline as Ctx.CutFrac), else the full window. N = (cut - billed prompt) / (billed growth per turn on the thread). - It falls back to the turns so far when the growth is unknown, the billed size is unknown, the window is only a guess, or the session is past the cut. warm_max_turns caps N; the wait-cause weight applies. - The decision log records the model (expected, cut, so_far_fallback), the cut, the growth per turn, the raw N and the reason for a fallback. - The cut model needs an exact window. A builder supplies one with a window: in the MODEL_PRICES table; prices.example.yaml shows how. Batching is in its own PR (#747). Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
|
Box results for head
Mutation checks: 17, all killed. Two first survived and I fixed the tests: the answer cost (no test priced the asks) and the batch order. Main has moved on since (to |
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 | 41eeb178f6ca |
blocking |
Verdict: blocking
Findings
- keepalive/substitute.go:305 — the keeper's cost ceiling prices one answer, but a batched sweep pays k answers.
- What fails: a thread with 48 candidates passes the per-ping ceiling check priced as ONE answer of 4,000 output tokens. The sweep then makes 4 model calls (default
max_ask_batches), each with a 16,000-token reply budget (PrefixAskMaxTokens, cheapmodel/cachecontrol.go:34). The answer spend runs about 7x the projection at the default, and up to 32x atmax_ask_batches: 8. An operator who set the ceiling for the one-question shape no longer bounds what one ping spends. - Proof:
sweepOutputBudgetGuess = 4000andprojectedSweepUSD(substitute.go:302-313) returnprefix*CacheRead + 4000*Output, once. The check at substitute.go:360 runs before dispatch.info.Offered(the candidate count, so k = ceil(Offered/12)) is already in hand there.askInBatches(extract_sweep_batch.go:122-148) callsadjudicateWithonce per batch, and each call is a full model call. The PR's own doc states it: "Each batch is one more question, so it costs one more answer." No test covers the projection against a batched sweep. - Fix: multiply the output term by the planned batch count. Compute k from
info.Offered(capped at 12 x max_ask_batches) inprojectedSweepUSDor its caller, or carry the batch count onSweepPingInfo. Add a test: a sweep of 48 candidates against a ceiling that admits one answer must be refused or projected at 4 answers.
- What fails: a thread with 48 candidates passes the per-ping ceiling check priced as ONE answer of 4,000 output tokens. The sweep then makes 4 model calls (default
Non-blocking
- Stale text the PR contradicts. Four places still describe the old one-question shape:
- docs/components/advanced-offload.md:534 — "
max_callsbecause one ask covers every candidate" sits one screen above the new Batches section that says the opposite. - docs/components/advanced-offload.md:523 — the config table omits
max_ask_batches, the one key this PR adds. - extract_sweep.go:208 — the banned-key reason for
max_callsreads "one call adjudicates every candidate". Now k calls do. - extract_sweep_apply.go:68 — "A cold apply drops at most maxAskItems outputs per question". Now up to 12 x max_ask_batches. The bound (512) still holds.
- docs/components/advanced-offload.md:534 — "
- extract_sweep_batch.go:127 — comment names a caller that does not exist. "the cold sweep calls it": no cold path calls
askInBatches. The ping ask is the only caller. - keepalive/keeper.go:1820-1822 —
Stats()snapshotsSweepBatchCounters()three times. The three fields can come from different moments. One call would keep them consistent. - extract_sweep_batch.go:125 —
br.batchesis written and never read. Tests readSweepBatchCounters()instead. - Per-batch recomputation. Each
adjudicateWithre-runscoref.IndexandflattenTranscriptover the whole conversation (evidence is on by default). An 8-batch sweep runs 8 full index passes. Ping time only, off the hot path. - The keeper's write>read stop now judges the sum.
u.CacheWrite > u.CacheRead(substitute.go:384) sees usage summed over batches, so a write-heavy batch can be masked by another batch's read. The per-batchprefixAskCacheOKwrite cap still gates each batch, so this weakens only the second-line stop. - docs/components/advanced-offload.md Counters list does not name
sweep_ask_batches,sweep_batch_failed,sweep_batch_failed_by. The Batches section above it does.
What I checked
- The full diff: extract_sweep.go, extract_sweep_batch.go (new), extract_sweep_ping.go, extract_sweep_test.go, extract_sweep_batch_test.go (new), docs/components/advanced-offload.md, keepalive/keeper.go.
- The code around each change: adjudicateWith (labels, gates, dump, stale-prefix guard, cache gate), collect, ask, buildHeld and the held-answer store, the cold apply, prefixAskCacheOK, sweep_askdump.go, keepalive/substitute.go's ceiling and stop guards.
- The drop-index remap (
base+kintobr.judged) againstbuildHeld'svotedmap: correct, no candidate judged twice. - Fail-open paths: a failed batch keeps its outputs out of the held answer; keeps are recorded only for answered batches; every-batch-fails holds nothing and resets
asked; the outer keeper timeout bounds all batches. - Reversibility: the cold apply still writes a marker plus stash per drop; the new tests expand every drop back byte for byte.
- Config:
max_ask_batchesclamps (0 to 4, over 8 to 8), field registration, hint text matches the code. - Concurrency: no new goroutines; the batch ledger maps are mutex-guarded; one question slot covers the whole sweep (test pins it).
- Docs: advanced-offload.md against the code, the data-dependence row for the sweep (unchanged by batching: same held-answer shape, metadata only).
- Live tests were not run (not approved). Go is not on this machine.
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 | 41eeb178f6ca |
blocking |
Verdict: blocking
Findings
-
keepalive/substitute.go:360 — the per-ping cost ceiling prices ONE batch; a batched sweep spends up to max_ask_batches times the approved cost.
- What fails: a thread with 48 candidates (default
max_ask_batches: 4) splits into 4 batches. Each batch reads the whole cached prefix again and pays its own answer. The keeper's pre-check projects the cost of ONE question (projectedSweepUSD= prefix x cache-read price + 4,000 output tokens, substitute.go:305-314) and compares it toe.pol.Ceiling(). The real spend is about 4x that projection, and up to 8x withmax_ask_batches: 8. The operator's per-ping $ cap is exceeded before any check notices; the after-the-factpingUSDcheck (keeper.go:881, 889) only stops the NEXT ping. - Proof:
fireSweepSubstituterunsdispatchonce per ping (substitute.go:368) andaskInBatchesasks k batches inside that one dispatch (extract_sweep_batch.go:131-160). The PR's own test pins the multiplied read:TestTheBatchesAreAskedInSequenceAndMergedIntoOneHeldAnswerassertsres.CacheRead == 2*okUse.CacheReadfor 20 candidates.projectedSweepUSDwas not changed and still prices one read plus one 4,000-token answer. - Fix: multiply the projection by the planned batch count. The offload side knows it: expose it on
SweepPingInfo(it already carriesOffered) or export the per-sweep candidate limit, and pricek x (prefix read + answer guess)inprojectedSweepUSD.
- What fails: a thread with 48 candidates (default
-
components/offload/extract_sweep_ping.go:603 — the
cg.sweep.heldlog'sofferedfield reports the judged count, not the offered count, when a batch failed.- What fails: 20 candidates, one batch of 10 fails. The log line says
offered=10. 20 were offered. An operator reading the sweep logs during exactly the partial-failure scenario the newsweep_batch_failedcounters describe gets a wrong inventory size. - Proof:
res.Offeredis set correctly from the collected list (line 567). Line 590 reassignscands, drop := br.judged, br.drop. Line 603 then logs"offered", len(cands), which is nowlen(br.judged)— only the candidates of the batches that answered. Before this PRcandswas never reassigned, so the field was right. - Fix: log
res.Offeredat line 603 (or capture the count before line 590).
- What fails: 20 candidates, one batch of 10 fails. The log line says
Non-blocking
askInBatches(extract_sweep_batch.go:122) does not enforcemax_ask_batchesitself. The cap lives only incollect(extract_sweep_ping.go:499). Safe today — the ping is the only caller and it pre-caps — but the function is documented as THE batching function that #720's warm path should call. A future caller that does not pre-cap silently ignores the operator's bound. Also that doc comment says "the cold sweep calls it"; no cold path calls it, only the ping.- Stale comments the change leaves behind: extract_sweep_ping.go:461 "The 12 largest, by the same cap" (now 12 x max_ask_batches); extract_sweep_apply.go:68-69 "a cold apply drops at most maxAskItems outputs per question" (now up to 96); extract_sweep_ping.go:525-529 "the shorter wins" — with k batches the wall bound is the keeper's outer timeout (300 s), not
llmCallTimeout(90 s), so a slow sweep can hold asweepSlotsslot and the keeper goroutine for up to 300 s. Fail open still holds. - keeper.go:1820-1822 calls
SweepBatchCounters()three times for oneStats(). The three fields can come from different snapshots while a sweep runs. Snapshot once into a variable. - A panic in batch 3 propagates to the dispatch-level recover, so the whole sweep becomes a plain ping and the verdicts batches 1-2 already paid for are lost (nothing held). Fail open holds; only money is lost. A per-batch recover in
askInBatcheswould keep the earlier answers. - Each batch re-runs
coref.IndexandflattenTranscriptover the whole transcript, and writes a full-transcript dump whenCG_SWEEP_ASK_DUMPis set. Ping-path CPU and dump disk grow k x. Bounded and background.
What I checked
- The full diff (7 files) and the code around every change:
adjudicateWithend to end (extract_sweep.go:598-1121),splitAskBatches,askInBatches,batchFailReason(extract_sweep_batch.go),collectandask(extract_sweep_ping.go),buildHeld/putHeld/claimHeldSpend(extract_sweep_hold.go),applyHeld(extract_sweep_apply.go), and the keeper side:fireSweepSubstitute,projectedSweepUSD,sweepAnswerUSD,Stats. - Fail open: a batch that fails keeps its outputs out of the held answer; the other batches still count; every-batch-failure holds nothing and the ping goes out. Verified against the code and the new tests.
- The merge: batch-local verdict labels and drop indexes are rebased correctly (
base := len(br.judged)), no candidate is judged twice, one held answer under one key, one cold apply. - Config: default 4, clamp to 8,
< 1reads as 4 in the constructor; the settings form (config/form.go:630) refuses< 1instead — convergent, safe direction. - Docs: the new
advanced-offload.mdsection and the field hint match the code (counter names, batch arithmetic 16 -> 8+8, 23 -> 12+11, cap 12 x max_ask_batches). - Data dependence: no new stored data. The held answer already carries cost and verdicts; the
docs/data-dependence.mdrow forextract_llm_sweepstays accurate. - Tests: read all 480 new test lines; every helper they use exists (
registered,deepCandidates,SweepPingSubstitute,getHeld,resetSweepLedgerForTest,SweepDropCounters,SweepSlotsInUseForTest); imports in the modified test files are still used. Coverage is good: split shapes, sequence, merge, fail-open per reason, one-cut cold apply, slot, cost. No tests run — live tests are not approved for this review.
… once (#132) One question used to keep the 12 largest candidates and drop the rest (sweep_over_ask_cap), so a long session was only partly swept: the outputs left out could never be offered, however old they were. The candidates are now split into k = ceil(n / 12) balanced batches (16 gives 8+8, 23 gives 12+11) and asked in sequence over the same cached prefix, under the one question slot and thread claim the caller already holds. The largest-first order is dealt round-robin so each batch mixes sizes. A list of 12 or fewer is one question, as before. - Each answer is judged on its own, and by prefixAskCacheOK on its own. - A batch that fails (error, refused cache read, truncated or unparseable reply) fails open: its outputs are left out of the held answer and the other batches still count. - All verdicts merge into one held answer keyed by tool_use id, so the next cold request does one recheck and one cut. - New max_ask_batches (default 4, at most 8). Candidates beyond 12 x batches are counted as sweep_over_ask_cap. - Counters: sweep_ask_batches, sweep_batch_failed (by reason). The answer cost sums every batch. - One function, askInBatches, so another path can reuse it. Fixes #132 Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
… 1 fixes (#132) BLOCKING. The keeper's per-ping cost ceiling priced ONE answer, but a batched sweep pays k: prefix read + answer, k times. A 48-candidate sweep spent about 4x the approved ceiling (up to 8x at max_ask_batches: 8). - SweepPingInfo carries the planned batch count, ceil(offered / 12). - The keeper projects n x (prefix read + answer guess), and if the ceiling admits fewer than planned it LOWERS the count: the sweep asks what the ceiling allows, the smallest outputs stay unasked and are counted (sweep_over_ask_cap, sweep_batches_lowered). If not even one answer fits, the ordinary ping goes out. - cg.sweep.held logged len(judged) as "offered" after a failed batch. It now logs offered and judged. Also: - A panic in one batch is one failed batch (reason batch_panic). The answers already paid for are kept. - askInBatches enforces max_ask_batches itself, and a caller may lower the limit but not raise it. - A batch never starts after the sweep's context ended, so k slow batches cannot run past the keeper's outer timeout (sweep_batch_skipped). - Stats() reads the batch ledger once. Unused br.batches removed. - Stale text fixed: the config table, the max_calls reasons, the cold-apply bound, the "12 largest" comment, the timeout comment, and the Counters list. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
A batch never starts after the sweep's context ended, so a 1 s outer budget sized for one question correctly skips the second batch on a slow machine. Under -race three batching tests saw 1 ask instead of 2. They now use a 60 s budget. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
41eeb17 to
a78a96b
Compare
|
Round 1 fixes are in head Blocking 1 (both reviewers): the keeper's cost ceiling priced one answer. Fixed.
Blocking 2 (reviewer 2): Non-blocking, all fixed
One thing I found while re-running after the rebase, not in the reviews: under Tests on box 1 (foreground,
|
|
Box results for head
Mutation checks: 35 in all (17 first push, 18 round 1), all killed. I re-ran four of them (the deadline, the cost ceiling, the held log, the per-batch recover) after the last test change, and all four were killed again. The first lint run after the rebase failed on |
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 | a78a96bd68eb |
blocking |
Verdict: blocking
Earlier findings
- My round-1 finding (the keeper's cost ceiling priced one answer): fixed.
SweepPingInfo.Batchescarriesceil(offered/12);projectedSweepBatchesUSDpricesn x (prefix read + answer guess);affordableSweepBatcheslowers the count the ceiling admits andSweepPingWait.MaxBatchescarries it down;askInBatchesenforces the bound itself and a caller can lower but not raise it. An unpriced model keeps the plan, as before. I checked the arithmetic, the refuse-below-one path, and the new tests (TestTheSweepCeilingPricesEveryBatchAndLowersTheCount,TestAffordableSweepBatchesIsTheLargestCountTheCeilingAdmits,TestAnUnpricedModelKeepsThePlannedSweepBatches,TestACallerCanLowerTheBatchLimitButNotRaiseIt). - Reviewer 2's finding 1 (same ceiling defect): fixed by the same change. Agree with reviewer 2, finding 1; nothing to add.
- Reviewer 2's finding 2 (
cg.sweep.heldlogged the judged count asoffered): fixed. The line now logsofferedandjudged(extract_sweep_ping.go:609), andTestTheHeldLogReportsTheOfferedCountEvenWhenABatchFailedpins 20 offered / 10 judged. - My non-blocking items: all fixed (stale text, the phantom "cold sweep" caller, the triple
SweepBatchCounters()snapshot, the deadbr.batches). Per-batch recomputation left as is with the reason "ping time, off the hot path, bounded by max_ask_batches". The reason is right; I accept it. The summed write>read stop is now documented in advanced-offload.md as a known limit of the second-line guard; the per-batch gate still holds. I accept.
Findings
- components/offload/extract_sweep_batch.go:196 — a panic after a completed model call releases the
askedlatch, so a deterministic panic re-pays the question on every ping.- What fails: a single-batch sweep (12 candidates or fewer) hits a bug that panics in verdict processing, after the model call returned and was paid for.
askOneBatch's recover zeroes the result wholesale, soask()sees no usage, setsSubstituted=false, and storesasked=false. The keeper sends the ordinary ping. The next due ping offers the question again, pays again, panics again. The cycle repeats for every ping while the thread stays registered (up to 30 minutes), one wasted model call each time. The round-1 code contained exactly this: the panic escaped to the dispatch-level recover and the conversation stayed marked asked — one paid call, then plain pings. - Proof:
askOneBatch's recover doesdrop, r = nil, sweepResult{}(extract_sweep_batch.go:201), discardingr.rec, whichadjudicateWithsets after the ask returns (extract_sweep.go:820-827) — so usage from a call that did happen is erased.ask()then releases the latch only becausein,outand the cache totals read zero (extract_sweep_ping.go:582-588). The sink does hold the call's usage —ask()readssink.Model()andsink.CacheWrite1h()from it, anddeferBillingbooks it — so the test comment's premise "no model call completed, so nothing was paid for" (extract_sweep_ping_test.go:683-685) does not hold for this class of panic. The code's own doc still promises the old policy:SweepReasonPanic(extract_sweep_ping.go:70-72) says "the conversation is marked asked so the next ping is plain too." - Fix: do not release the latch when a batch failed by panic. Carry a
panickedcount onbatchRun(or test thesweep_batch_failed_batch_panicevent) and treat it like usage in the latch decision at extract_sweep_ping.go:585-588. Then updateTestAPanicInThePingQuestionLeavesAPlainPingand theSweepReasonPaniccomment to match. The per-batch recover itself is right and stays.
- What fails: a single-batch sweep (12 candidates or fewer) hits a bug that panics in verdict processing, after the model call returned and was paid for.
Non-blocking
- extract_sweep_batch.go:130 — the comment says a panic's reason is
panic; the code producesbatch_panic(batchFailReasonstrips thesweep_prefix fromsweep_batch_panic). The tests assertbatch_panic. Comment slip only. sweepOutputBudgetGuessstays 4,000 output tokens per answer (keepalive/substitute.go:302) while the reply budget is 16,000 and a real 12-verdict reply is about 7,000. The k factor is fixed; the per-answer guess still under-prices one answer by about 1.8x realistic, 4x at the budget. Pre-existing guess, now multiplied; noting so the ceiling is read with the right tolerance.ResetSweepBatchForTestandNoteSweepBatchSkippedForTestare exported from the production file (extract_sweep_batch.go:271-277). The repo's precedent (SweepSlotsInUseForTest) keeps such helpers in a*_testing.gofile.- Two names for one thing: the event is
sweep_batch_skipped_deadline, the/statsfield issweep_batch_skipped. Both are documented; a reader must know they pair.
What I checked
- Last review: round 1, 41eeb17, 2026-10-27T10:58:10Z.
- New commits read: 2 — b3acb0c "fix(sweep): the keep-alive cost ceiling prices every batch, and round 1 fixes (#132)", a78a96b "test(sweep): give the batching tests a budget that fits k questions". (The PR was also rebased: my round-1 head 41eeb17 is now baa8c07 on base 1bd627d, same content. The plugin changes in 1bd627d are base movement, not this PR.)
- Read in full: 2 reviews, 3 comments, 0 inline comments (from the three files).
- New items since my last review, and what I did about each:
- Reviewer 2's round-1 review (posted 11:00:12Z, after mine): read in full; its finding 1 matches mine, its finding 2 (held log) I verified fixed.
- Author's reply comment (12:10:58Z): checked every claim against the code — ceiling fix, lowering, MaxBatches plumbing, per-batch recover, self-enforcing bound, deadline skip, stale text, Stats snapshot. All as described except the panic-latch behavior, which is finding 1.
- Author's box-results comments (10:51:55Z, 12:12:17Z): test and mutation results on the eval box. Not re-run here; live tests are not approved.
- Commit a78a96b (test budget 60 s): read; it exists because the new deadline rule correctly skipped batch 2 under a 1 s budget on a slow machine. The change is right, and it exposed nothing new.
- The new code in full:
askInBatches(cap, limit, deadline skip),askOneBatch(recover),largestFirst,plannedAskBatches, the ledger counters,SweepPingWait.MaxBatches/SweepPingInfo.Batches,projectedSweepBatchesUSD,affordableSweepBatches,fireSweepSubstitute's lower-or-refuse logic,Stats()'s single snapshot, and the new tests in both packages. - Fail open re-checked: a failed, skipped or panicking batch keeps its outputs out of the held answer; the other batches still count; the refuse path sends the ordinary ping; the unpriced path keeps the plan.
- No double count of
sweep_over_ask_cap:collectcaps at the operator's bound,askInBatchescaps at the lowered bound; only one of the two fires for the same candidates. - Live tests were not run (not approved). Go is not on this machine.
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 | a78a96bd68eb |
blocking |
Verdict: blocking
Findings
- keepalive/substitute.go:337 —
affordableSweepBatchesturns the "no ceiling" sentinel (+Inf) into "zero batches", so every sweep question is refused.- What fails: a policy with
MaxUSDPerPing < 0means "no cap" (Policy.Ceiling(), types.go:250-258, returnsmath.Inf(1)).n := int(ceiling / one)divides +Inf by a positive cost. Go leaves that conversion implementation-defined; on gc (amd64, arm64) it yieldsmath.MinInt64, a negative number. The clampif n < 0 { n = 0 }then sets n to 0,fireSweepSubstituteseesallowed < 1, countssweep_over_budgetand sends the ordinary ping. So the one policy that asks for no cap gets no sweep questions at all. The old check (cost > ceiling) handled +Inf correctly and sent the question. - Proof: types.go:254 (
MaxUSDPerPing < 0→math.Inf(1)); keepalive's own test pins the sentinel (types_test.go:13,{-1, math.Inf(1)}); substitute.go:337-344 does the division and the negative clamp; substitute.go:399-407 refuses onallowed < 1. No test covers an infinite ceiling (TestAffordableSweepBatchesIsTheLargestCountTheCeilingAdmitsuses finite ceilings only). Reachability: no shipped path sets a negativeMaxUSDPerPing— the config loader refuses it (config/config.go:246) and so do the strategy bounds (proxy/keepalivestrategy.go:240) — butPolicyis an exported library type and the sentinel is documented and tested in this package, so a host that uses it loses the sweep silently (a debug-level log withceiling_usd=+Inf). - Fix: guard before dividing —
if !(ceiling > 0) || math.IsInf(ceiling, 1) { return planned }inaffordableSweepBatches. Low severity, one line.
- What fails: a policy with
Earlier findings, round 1
- Reviewer 2, finding 1 (the per-ping ceiling priced one batch): fixed.
plannedAskBatches= ceil(offered/12) is carried onSweepPingInfo.Batches(extract_sweep_ping.go:456),projectedSweepBatchesUSDprices n x (prefix read + answer guess),affordableSweepBatcheslowers the count rather than refusing,SweepPingWait.MaxBatchescarries it intoaskInBatches, andaskInBatchesitself enforcesmax_ask_batcheswith "lower but never raise" semantics. Left-out candidates are counted. Tests cover 1/2/4 admitted and refusal below one. The fix is correct except for the +Inf edge in finding 1. - Reviewer 2, finding 2 (
cg.sweep.heldlogged the judged count asoffered): fixed. The line now logsoffered(res.Offered) andjudged(extract_sweep_ping.go:609).TestTheHeldLogReportsTheOfferedCountEvenWhenABatchFailedpins 20 offered / 10 judged. - My non-blocking items: all fixed — per-batch recover (
askOneBatch, a panic is one failed batch, earlier answers kept, test included);askInBatchesenforces the bound itself; stale comments fixed (config table,max_callsreason, cold-apply bound, "12 largest", timeout comment, "cold sweep calls it", Counters list);Stats()reads the ledger once;br.batchesremoved. The per-batch recomputation of the co-reference index was left as is with the reason "ping time, off the hot path, bounded by max_ask_batches" — I accept the reason; it matches my own round-1 assessment. - Reviewer 1's findings: agree, and all fixed — same ceiling fix, same non-blocking set (write>read sum now documented in the Batches section, per-batch cache rule still gates each batch: acceptable).
Non-blocking
sweep_batch_over_capunder-reports its own description. The /stats counter is fed only byaskInBatches' trim (keeper lowering). The operator-config cap incollectfeeds only thesweep_over_ask_capgate. 60 candidates, default config:sweep_gates.sweep_over_ask_cap= 12,sweep_batch_over_cap= 0. The Stats comment says "candidates left unasked because fewer batches were allowed", which reads as both. Either feedcollect's cap intosweepOverAskCapBatchtoo, or narrow the comment.- The panic reason is named "panic" in two comments and the docs, but the key is
batch_panic(extract_sweep_batch.go:138, advanced-offload.md Batches section). The skip event issweep_batch_skipped_deadlinewhile the /stats field issweep_batch_skipped. Cosmetic. directBatch(extract_sweep_batch_test.go) setscand.e = eand immediately overwrites it withwide; the first assignment is dead. Test-only.
What I checked
- Last review: round 1, 41eeb17, 2026-10-27T11:00:12Z.
- New commits read: 3 — baa8c07 (the reviewed feature commit rebased onto main 1bd627d;
git range-diffconfirms it is content-identical to 41eeb17, so I did not re-review it line by line), b3acb0c (the round-1 fixes), a78a96b (test budget + gofmt). - Read in full: 2 reviews, 3 comments, 0 inline comments (from the three files; the inline list is empty).
- New items since my last review: the author's fix reply (12:10:58, every claim checked against the code — all hold), box results for a78a96b (12:12:17), and the three commits above. The 10:51:55 box comment predates my round-1 review; I read it now.
- The full diff baa8c07..a78a96b and the final state of every touched file:
askInBatches(cap, deadline skip, panic recover, index rebasing),askOneBatch(named-resultmsset in the defer on both paths — correct),largestFirst,plannedAskBatches,SweepPingWait.MaxBatchesplumbing throughask,fireSweepSubstituteand both projection helpers,Stats(one snapshot), the docs section and Counters list. - The ceiling arithmetic: prefix 20,000 x 3.8e-7 + 4,000 x 19e-6 = $0.0836 per question; 0.10 admits 1, 0.20 admits 2, 0.40 admits 4, 0.02 refuses — matches the test and the code.
- The gate arithmetic when both caps fire: collect 60→48 (gate 12) plus keeper lowering 48→12 (gate 36) sums to 48 = 60−12 asked. No double count.
- The changed
TestAPanicInThePingQuestionLeavesAPlainPing: a caught batch panic with nothing paid resets theaskedlatch, so the next ping may ask — matches the code path (res.Substitutedand usage all zero →asked.Store(false)). - Fail open: a lowered, skipped or panicked batch leaves its outputs unasked and counted; the ping still goes out; the request path is untouched.
- Helpers used by the new tests all exist (
logging.New/With,mathimport,registerSweep,sweepConversation,testKeeper,proxyPricer,noPrice); no test was run — live tests are not approved.
…admits every batch (#132) BLOCKING. A panic in a batch can come AFTER its model call returned and was paid for. The per-batch recover erased that batch's result, so the sums read zero and ask() gave the asked latch back: a deterministic panic then paid for the same question on every ping. batchRun now counts panicked batches, and a panic keeps the thread marked asked. An ask that never left the process still gives the latch back. BLOCKING. A negative MaxUSDPerPing means "no ceiling" and Policy.Ceiling() returns +Inf. int(+Inf / cost) is MinInt64 on gc, which the clamp turned into zero batches, so the one policy that asks for no cap got no sweep. +Inf now admits every planned batch. A ceiling of zero or less, or NaN, keeps its old meaning: nothing is admitted. Also: - sweep_batch_over_cap now counts the candidates collect leaves unasked as well as the ones the cost ceiling leaves, matching its doc. - Docs and comments name batch_panic, and pair the per-request event sweep_batch_skipped_deadline with the /stats counter. - The test helpers move to extract_sweep_ping_testing.go. - A note that the ceiling's 4,000-token answer guess under-prices one answer by about 1.8x. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
|
Round 2 fixes are in head Blocking 1 (reviewer 1): a panic after a paid call released the
Blocking 2 (reviewer 2): an infinite ceiling refused every question. Fixed.
Non-blocking, all fixed
Tests on box 1 (foreground,
|
|
Box results for head
Mutation checks: 43 killed (17 first push, 18 round 1, 8 round 2). 3 survive and are explained in the PR body (the explicit |
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 3 | f5a539105d6e |
approve |
Verdict: approve
Findings
None.
Earlier findings
- My round-2 finding (a panic after a paid call released the
askedlatch): fixed.askInBatchesnow counts panicked batches onbatchRun.panicked(extract_sweep_batch.go:180-182), andask()treats a panic like usage in the latch decision:res.Substituted || in > 0 || out > 0 || br.panicked > 0keeps the thread marked asked (extract_sweep_ping.go:588). An ask that never left the process still gives the latch back (TestAnAskThatNeverLeftTheProcessStillReleasesTheLatch). The new test drives the exact case my finding described: the call is paid, then the code after it panics (sweepPanicAfterCallHook, afterParseVerdicts), the latch stays set, the next ping isalready_asked, and the asker is called once in all. TheSweepReasonPaniccomment and the changedTestAPanicInThePingQuestionLeavesAPlainPingnow say the same thing as the code. The paid usage is still booked:deferBillingreads the sink, which saw the call. - Reviewer 2's round-2 finding (an infinite ceiling admitted zero batches): fixed.
affordableSweepBatchesreturns the planned count for+Infbefore the division (substitute.go:351-352), so the "no cap" policy (MaxUSDPerPing < 0→Policy.Ceiling()=+Inf) keeps its sweep. A ceiling of zero or less, or NaN, admits nothing (substitute.go:353-355). Agree with reviewer 2, finding 1; I checked the guard, thePolicy.Ceiling()sentinel, and the three new tests, including the end-to-end no-cap run (4 asks, nothing lowered or refused). - The three surviving mutations: accepted. The
!(ceiling > 0)guard is redundant on gc, whereint(NaN)andint(-Inf)are negative and then < 0clamp zeroes them anyway. The author says so in the code comment, and the reason is right: the conversion is implementation-defined, and the guard keeps the answer right where it differs. A test on this platform cannot tell the guard from the accident. - Non-blocking notes from round 2, both reviewers: all fixed. Comments and docs say
batch_panic;sweep_batch_over_capnow counts every candidate left unasked by any limit (collectfeeds the same ledger, extract_sweep_ping.go:513-515, with test assertions on the ledger); the test helpers moved toextract_sweep_ping_testing.go; the deadcand.e = eis gone; the docs pairsweep_batch_skipped_deadlinewithsweep_batch_skipped; the docs state the 4,000-token guess under-prices one answer by about 1.8x.
Non-blocking
sweepPanicAfterCallHookis a test seam inside the productionadjudicateWith(extract_sweep.go:910-912). It is nil in production and unexported, so only same-package tests can set it, and the new test clears it with a defer. One nil check per ask. Acceptable; noting it because it sits in the path, not beside it.- A panic BEFORE the model call also keeps the latch set now, so a deterministic pre-call panic gives up sweeping for that thread (plain pings only).
ask()cannot tell the two apart, and keeping the latch is the safe side: it matches the round-1 behavior and cannot spend money. Checked and accepted.
What I checked
- Last review: round 2, a78a96b, 2026-10-27T12:19:07Z.
- New commits read: 1 — f5a5391 "fix(sweep): a panic after a paid call keeps the thread asked; no cap admits every batch (#132)".
- Read in full: 4 reviews, 5 comments, 0 inline comments (from the three files; the inline list is empty).
- New items since my last review, and what I did about each:
- Reviewer 2's round-2 review (12:20:21Z): read in full; its +Inf finding I verified fixed above.
- Author's round-2 reply (13:24:52Z): checked every claim against the code — the latch fix, the panic count, the booking from the sink, the +Inf guard, the zero/NaN guard, the
sweep_batch_over_capwidening, the helper move, the docs. All as described. - Author's box results (13:25:42Z): tests and 43 killed mutations on the eval box, with the 3 survivors explained. Not re-run here; live tests are not approved.
- Commit f5a5391: read the full diff and the final state of every touched file.
- The panic path end to end: the recover raises
sweep_batch_panicon a fresh zero result (extract_sweep_batch.go:216-218),raisedscans the gate list (extract_sweep.go:569-575),askInBatchescounts it intobr.panickedonly for a batch that did not answer, and no other code raises that gate name. A panicking batch stays a failed batch with reasonbatch_panic; the other batches still count. - The latch decision in
ask():br.panickedcomes only from the panic gate, so an ordinary failure with no usage (no stashed prefix) still releases the latch, as the new test pins. - No double count in
sweep_batch_over_cap:collecthas one production caller (the ping ask, extract_sweep_ping.go:420) and caps at the operator's bound;askInBatchestrims at the lowered bound. The two sets are disjoint (60 → 48 → 12 leaves 12 + 36 = 48 unasked), and the counter now counts both, matching its doc. - The ceiling guards:
+Infreturns the plan before the division; zero, negative and NaN return 0; an unpriced model keeps the plan;Policy.Ceiling()never returns zero or NaN, so the zero/NaN guard covers only a direct caller. Themathimport is present. - The tests' fixtures and helpers exist:
panicAfterPaidAsker,dynAsker,ErrNoPrefix,candidateFor,okUse,testKeeper,proxyPricer,registerSweep,sweepConversation,kaPolicy; theatomicimport is new and used. - Fail open re-checked: nothing in this commit touches the request path; a panicked, refused or lowered sweep still ends in an ordinary ping.
- Live tests were not run (not approved). Go is not on this machine.
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 | 3 of 3 | f5a539105d6e |
approve |
Verdict: approve
Findings
None.
Earlier findings
- My round-2 finding (the +Inf "no ceiling" sentinel became "zero batches"): fixed.
affordableSweepBatches(keepalive/substitute.go:348-352) returnsplannedformath.IsInf(ceiling, 1)before the division, and!(ceiling > 0)returns 0 for zero, negatives, -Inf and NaN — the old meaning of "every positive cost exceeds it".mathis imported. Tests:TestAnInfiniteCeilingAdmitsEveryPlannedBatch(planned 1, 2, 4, 8, plus the policy end to end),TestAZeroOrNegativeOrNaNCeilingAdmitsNothing,TestANoCapPolicyAsksEveryBatchEndToEnd(48 candidates, 4 asks, nothing refused or lowered). The exact one-line guard I proposed. - Reviewer 1's round-2 finding (a panic after a paid call released the
askedlatch): agree, and fixed. I checked it myself.askInBatchescountsbr.panickedwhen a failed batch raisedsweep_batch_panic(extract_sweep_batch.go:180-182), andask()treats it like usage in the latch decision (extract_sweep_ping.go:588:res.Substituted || in > 0 || out > 0 || br.panicked > 0). An ask that never left the process still gives the latch back (TestAnAskThatNeverLeftTheProcessStillReleasesTheLatch, ErrNoPrefix path).TestAPanicAfterAPaidCallKeepsTheThreadAskedSoItIsNotPaidForAgainOnEveryPingpins the whole story: one paid call, a panic after it, the latch stays, the next ping isalready_asked, one ask in all. The cost of a panicked batch is still booked from the detached sink (deferBilling), which saw the call. - The author's "3 surviving mutations" on the
!(ceiling > 0)guard: reason checked, and it is right. On gc,int(NaN)andint(-Inf)are negative, so the existingn < 0clamp already yields 0; a test on this platform cannot tell the guard from that accident. The guard keeps the answer right where the conversion is implementation-defined. I accept it, and the comment on the guard says exactly this. - My round-2 non-blocking items: all fixed.
sweep_batch_over_capnow countscollect's cap too (extract_sweep_ping.go:513-516), with no double count:collecttrims 60→48 andaskInBatchestrims within the survivors, so the counter sums to the candidates left unasked, the same set as the per-request gate. The Stats comment and the docs say so, andTestOnlyBatchTimesBatchesCandidatesAreOfferedAndTheSmallestAreCountednow asserts the ledger (12 and 36). Comments and docs saybatch_panic. Thesweep_batch_skipped_deadlineevent is paired with thesweep_batch_skippedcounter in the docs. The deadcand.e = eis removed.ResetSweepBatchForTestandNoteSweepBatchSkippedForTestmoved toextract_sweep_ping_testing.go, the repo's precedent. - Reviewer 1's round-2 non-blocking items: all fixed (the
panic/batch_paniccomment, the helpers' file, the event/counter pairing, and the 4,000-token guess now documented as under-pricing one answer by about 1.8x).
Non-blocking
- The
panicAfterPaidAskerfixture comment says the reply "carries a label the sweep indexes out of range", but the reply is a plain parseable verdict list and the panic comes from the test hook. The comment describes what the hook models, not what the fixture does. Test-only wording. - A panic before any model call (not after one) now also keeps the latch, where round 2 briefly released it. This is a return to the pre-PR behavior and the safe side for money; the
SweepReasonPaniccomment says so. Accepted.
What I checked
- Last review: round 2, a78a96b, 2026-10-27T12:20:21Z.
- New commits read: 1 — f5a5391 "fix(sweep): a panic after a paid call keeps the thread asked; no cap admits every batch (#132)".
- Read in full: 4 reviews, 5 comments, 0 inline comments (from the three files; the inline list is empty).
- New items since my last review, and what I did about each:
- Commit f5a5391: read the full diff and every touched file around the changes (details below).
- The author's reply (13:24:52Z): checked every claim against the code — the latch fix, the +Inf guard, the surviving-mutation explanation, the counter change, the doc changes. All hold.
- Box results for f5a5391 (13:25:42Z): 43 mutations killed, 3 survive as explained. Not re-run here; live tests are not approved.
- The new code in full:
br.panickedand its counting (r.raised("sweep_batch_panic")scans the gate slice set byaskOneBatch's recover); the latch decision inask()and the CAS that setsasked(line 531) with the single release point (line 598);affordableSweepBatcheswith both guards;collect's ledger add inside the trim branch; the moved test helpers; the hook varsweepPanicAfterCallHook(declared inextract_sweep_ping_testing.go, an always-compiled file per repo precedent, nil in production). - The over-cap arithmetic: collect 60→48 (12) plus a lowered ask 48→12 (36) sums to 48 unasked of 60, matching
sweep_over_ask_capper request. No candidate is counted twice. - The new tests' premises:
ask(cands, rep, 0, ...)takes thellmCallTimeoutdefault (timeout <= 0);SweepPingSubstitutereturnsSweepReasonAlreadyAskedwhileaskedis set;panicAfterPaidAskerreturns real usage so the panic is after a paid call. Helpers exist (dynAsker,okUse,candidateFor(t, cfg, session, asker, st, n),sweepAsker.cacheRead,store.NewMemory(store.Options{MaxEntries: ...})). - Fail open re-checked: a panicked batch fails open like any failed batch — its outputs stay unasked, the other batches still count, the ping goes out, and the request path is untouched. A no-cap policy asks the plan; a zero-or-NaN ceiling refuses and sends the ordinary ping.
- No test was run — live tests are not approved. Go is not on this machine.
…720) The sweep can now apply its cut on a warm cache, behind a cost gate (#491, #1030 item 2). Opt-in: warm: true in the extract_llm_sweep config, off by default; no shipped preset sets it. When on, it adds: the warm apply path with a gate that weighs the saving over the turns left against the rewrite cost; batching reuse (#747); the turns-left model; accumulation (refused drops carried in memory, the newer verdict wins); recheck reasons logged before the gate; a quote check against the body the model read; and the streamed-usage fix (#745). Behavior change: none by default. The warm path runs only when a config sets warm: true. On a flat-rate backend such as IBM Bob, the gate's rewrite cost is about 0, so cuts pass; the operator must add a price entry with cache_read == cache_write == input, or the gate uses Claude-class rates and stays strict. The PR body documents this. Owner's yes, 2026-11-10, in the integrator session: "approve both" (merge on main, opt-in, keep testing it through Bob users). Data dependence: the extract_llm_sweep row already covers the held answers and the carried drops (in memory, metadata only). Reviews: 2 offload reviews (GLM), round 11 (owner granted rounds up to 13), both approve at 8255b96. 8f90546 is a rebase onto main d407191 that changes only the column lists in dash/query.go and dash/store.go (#720's sweep_false_expands_warm after #1003's defer_cost_usd); git range-diff shows the other commits unchanged. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
Summary
What we found
sweep_over_ask_cap).What changed
k = ceil(n / 12)batches. 16 gives 8+8. 23 gives 12+11. The largest-first order is dealt round-robin, so each batch mixes big and small outputs.prefixAskCacheOK).max_ask_batches(default 4, at most 8). Outputs beyond12 x max_ask_batches(the smallest) are not asked. They are still counted assweep_over_ask_cap.sweep_ask_batches, andsweep_batch_failedwith the reason (sweep_batch_failed_by), in/statsand as events on the row. The answer cost is the sum of every batch.askInBatches, so another path can reuse it. It enforcesmax_ask_batchesitself.n x (prefix read + answer guess)for the plannedn = ceil(offered / 12). If the ceiling admits fewer, the keeper lowers the count (the smallest outputs stay unasked, counted assweep_over_ask_capandsweep_batches_lowered). If not even one fits, the ordinary ping goes out.batch_panic). The batches before it are kept.sweep_batch_skipped). The keeper's 300 s bounds the whole sweep; each question keeps its own 90 s.Policy.Ceiling()is+Inffor a negativeMaxUSDPerPing, andint(+Inf / cost)isMinInt64on gc, which the clamp made zero batches.The cold apply is not changed.
How it was tested
Eval box 1, foreground,
-count=1.make lintpasses. All packages pass, includingproxyanddash.-racepasses oncomponents/offload,keepalive,config,components/allandproxy. No live calls.TestTwelveOrFewerCandidatesMakeExactlyOneAsk,TestTwelveOrFewerCandidatesAreOneBatchInTheirOriginalOrderTestTheBatchesAreBalancedAndMixSizes,TestSweepAsksTwentyCandidatesAsTwoBalancedBatchesTestEveryCandidateIsInExactlyOneBatch,TestTheBatchesAreAskedInSequenceAndMergedIntoOneHeldAnswerTestOneMergedAnswerHoldsEveryVerdictUnderOneKey,TestTheMergedAnswerIsAppliedAsOneCutOnTheNextColdRequestTestABatchThatFailsFailsOpenAndTheOthersStillCount,TestAFailedBatchKeepsItsOutputsOnTheColdRequestAndTheOtherBatchApplies,TestIfEveryBatchFailsNothingIsHeldAndItIsAFailedAskprefixAskCacheOKTestEachBatchIsJudgedByThePrefixAskCacheRuleOnItsOwnTestTheHeldAnswerCarriesTheSumOfEveryBatchsCost,TestTheBatchesAreAskedInSequenceAndMergedIntoOneHeldAnswermax_ask_batchesand its capTestMaxAskBatchesDefaultsToFourAndIsClamped,TestOnlyBatchTimesBatchesCandidatesAreOfferedAndTheSmallestAreCountedTestABatchedSweepHoldsOneQuestionSlotTestTheSweepCeilingPricesEveryBatchAndLowersTheCount,TestAffordableSweepBatchesIsTheLargestCountTheCeilingAdmits,TestAnUnpricedModelKeepsThePlannedSweepBatchesTestThePlannedBatchCountIsCeilOfOfferedOverTwelve,TestACallerCanLowerTheBatchLimitButNotRaiseIt,TestAskInBatchesEnforcesTheOperatorsBatchLimitItselfTestAPanicInOneBatchKeepsTheOtherBatches,TestABatchNeverStartsAfterTheSweepsDeadlineTestAPanicAfterAPaidCallKeepsTheThreadAskedSoItIsNotPaidForAgainOnEveryPing,TestAnAskThatNeverLeftTheProcessStillReleasesTheLatch,TestAPanicInThePingQuestionLeavesAPlainPingTestAnInfiniteCeilingAdmitsEveryPlannedBatch,TestAZeroOrNegativeOrNaNCeilingAdmitsNothing,TestANoCapPolicyAsksEveryBatchEndToEndTestTheHeldLogReportsTheOfferedCountEvenWhenABatchFailed/statspublishes the batch counters from one snapshotTestStatsPublishesTheBatchCountersFromOneSnapshotMutation checks: 43 killed (17 in the first push, 18 in round 1, 8 in round 2). Each one made a named test fail. Round 2: the asked latch released after a panic, a panic not counted, a latch never released, the per-batch recover removed, an infinite ceiling not special-cased, a zero ceiling treated as no cap, and the over-cap count missing or doubled in the batching ledger. Three more guard-removal mutations survive and cannot be killed on this platform; see Technical notes.
Two mutations first survived in the first push and I fixed the tests: one on the answer cost (no test priced the asks) and one on the order. In round 1, one survived on the skipped-batch count in
/stats(nothing staged a skipped batch) and I added a test hook. One mutation run first used the wrong source tree and was discarded and re-run.Data dependence
Nothing changes. The held answer is the same metadata (ids, hashes, counts, verdicts). Batches add no stored data and no copy of the conversation.
Open questions
Technical notes
splitAskBatchesreturns one batch in the original order whenn <= 12, so the single-question path is unchanged.askInBatchesafter this merges.substitute.go, after the dispatch). A write-heavy batch can be masked by another batch's read. The per-batchprefixAskCacheOKwrite rule still gates each batch, so this weakens only the second-line stop.askedlatch set: its model call may already have been paid for, so a repeating panic must not pay on every ping. An ask that never left the process (no stashed prefix) still gives the latch back.!(ceiling > 0)guard, or letting NaN or-Infpast it, leaves the tests green: on gcint(NaN)andint(-Inf)are negative and then < 0clamp already gives zero. The guard is kept because that conversion is implementation-defined.Fixes #132