Skip to content

feat(sweep): ask a long list of outputs in balanced batches, then cut once (#132) - #747

Merged
amiddavid merged 4 commits into
mainfrom
feat/sweep-ask-batches
Oct 27, 2026
Merged

amiddavid merged 4 commits into
mainfrom
feat/sweep-ask-batches

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • A sweep that finds more than 12 old tool outputs now asks about all of them, not only the 12 largest.
  • The list is split into balanced batches and asked one after the other. The answers merge into one held answer. The next cold request does one recheck and one cut.
  • A list of 12 or fewer is one question, as today.

What we found

  • One question kept the 12 largest outputs and dropped the rest (sweep_over_ask_cap).
  • On a long session, most old outputs were never asked about, however old they were.
  • The cap was set for a reason: one reply holds a verdict for every output in the question, and a reply cut off in the middle parses as nothing. That reason is still true.

What changed

  1. Split. 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.
  2. Ask in sequence. Each batch is one question over the same cached prefix. They run under the thread's one claim and one question slot, so concurrency does not change.
  3. Judge each on its own. Each answer goes through the same checks as today, including the shared cache-read rule (prefixAskCacheOK).
  4. A failed batch fails open. An error, a refused cache read, a truncated reply, an unparseable reply: its outputs are left out of the held answer and the other batches still count. The next question may offer them again.
  5. Merge. All verdicts go into one held answer, keyed by tool-use id. No output is judged twice.
  6. New setting max_ask_batches (default 4, at most 8). Outputs beyond 12 x max_ask_batches (the smallest) are not asked. They are still counted as sweep_over_ask_cap.
  7. Counters. sweep_ask_batches, and sweep_batch_failed with the reason (sweep_batch_failed_by), in /stats and as events on the row. The answer cost is the sum of every batch.
  8. One function, askInBatches, so another path can reuse it. It enforces max_ask_batches itself.
  9. The keep-alive cost ceiling prices every batch (round 1). The keeper used to price one answer, so a 48-candidate sweep spent about 4x the approved ceiling. It now projects n x (prefix read + answer guess) for the planned n = ceil(offered / 12). If the ceiling admits fewer, the keeper lowers the count (the smallest outputs stay unasked, counted as sweep_over_ask_cap and sweep_batches_lowered). If not even one fits, the ordinary ping goes out.
  10. A panic in one batch is one failed batch (batch_panic). The batches before it are kept.
  11. A batch never starts after the sweep's deadline (sweep_batch_skipped). The keeper's 300 s bounds the whole sweep; each question keeps its own 90 s.
  12. A panic after a paid call keeps the thread asked (round 2). The recover erased the batch's usage, so the latch was given back and a repeating panic paid on every ping. A panicked batch now keeps the thread marked asked.
  13. A "no cap" policy admits every planned batch (round 2). Policy.Ceiling() is +Inf for a negative MaxUSDPerPing, and int(+Inf / cost) is MinInt64 on gc, which the clamp made zero batches.

The cold apply is not changed.

How it was tested

Eval box 1, foreground, -count=1. make lint passes. All packages pass, including proxy and dash. -race passes on components/offload, keepalive, config, components/all and proxy. No live calls.

Requirement Test
12 or fewer is one ask, as today TestTwelveOrFewerCandidatesMakeExactlyOneAsk, TestTwelveOrFewerCandidatesAreOneBatchInTheirOriginalOrder
16 gives 8+8, 23 gives 12+11, round-robin by size TestTheBatchesAreBalancedAndMixSizes, TestSweepAsksTwentyCandidatesAsTwoBalancedBatches
No output judged twice TestEveryCandidateIsInExactlyOneBatch, TestTheBatchesAreAskedInSequenceAndMergedIntoOneHeldAnswer
One merged answer, one cut TestOneMergedAnswerHoldsEveryVerdictUnderOneKey, TestTheMergedAnswerIsAppliedAsOneCutOnTheNextColdRequest
A failed batch keeps its outputs; the others apply TestABatchThatFailsFailsOpenAndTheOthersStillCount, TestAFailedBatchKeepsItsOutputsOnTheColdRequestAndTheOtherBatchApplies, TestIfEveryBatchFailsNothingIsHeldAndItIsAFailedAsk
Each batch judged by prefixAskCacheOK TestEachBatchIsJudgedByThePrefixAskCacheRuleOnItsOwn
The cost sums all asks TestTheHeldAnswerCarriesTheSumOfEveryBatchsCost, TestTheBatchesAreAskedInSequenceAndMergedIntoOneHeldAnswer
max_ask_batches and its cap TestMaxAskBatchesDefaultsToFourAndIsClamped, TestOnlyBatchTimesBatchesCandidatesAreOfferedAndTheSmallestAreCounted
One slot, one claim TestABatchedSweepHoldsOneQuestionSlot
The cost ceiling prices every batch and lowers the count TestTheSweepCeilingPricesEveryBatchAndLowersTheCount, TestAffordableSweepBatchesIsTheLargestCountTheCeilingAdmits, TestAnUnpricedModelKeepsThePlannedSweepBatches
The planned batch count; the keeper can lower the limit, never raise it TestThePlannedBatchCountIsCeilOfOfferedOverTwelve, TestACallerCanLowerTheBatchLimitButNotRaiseIt, TestAskInBatchesEnforcesTheOperatorsBatchLimitItself
A panic in one batch keeps the others; a batch never starts after the deadline TestAPanicInOneBatchKeepsTheOtherBatches, TestABatchNeverStartsAfterTheSweepsDeadline
A panic after a paid call keeps the thread asked; an ask that never left the process releases it TestAPanicAfterAPaidCallKeepsTheThreadAskedSoItIsNotPaidForAgainOnEveryPing, TestAnAskThatNeverLeftTheProcessStillReleasesTheLatch, TestAPanicInThePingQuestionLeavesAPlainPing
A no-cap policy admits every batch; a zero or NaN ceiling admits none TestAnInfiniteCeilingAdmitsEveryPlannedBatch, TestAZeroOrNegativeOrNaNCeilingAdmitsNothing, TestANoCapPolicyAsksEveryBatchEndToEnd
The held log reports offered and judged TestTheHeldLogReportsTheOfferedCountEvenWhenABatchFailed
/stats publishes the batch counters from one snapshot TestStatsPublishesTheBatchCountersFromOneSnapshot

Mutation 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

  • The batch size is the constant 12 here. A setting for it is easy to add if you want one.
  • How many batches pay for their cost is a measurement, not decided here. The default of 4 is a first guess.

Technical notes

  • splitAskBatches returns one batch in the original order when n <= 12, so the single-question path is unchanged.
  • The reply budget stays at the flat 16,000 tokens per batch.
  • A batch's items are absent from the held answer when it fails (not "kept"), so the next question may offer them.
  • Not in this PR: the warm path (feat(sweep): the warm path, an economic gate on a held answer (#491) #720) will call askInBatches after this merges.
  • The keeper's write > read stop judges the SUMMED usage (substitute.go, after the dispatch). A write-heavy batch can be masked by another batch's read. The per-batch prefixAskCacheOK write rule still gates each batch, so this weakens only the second-line stop.
  • A batch that panics keeps the asked latch 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.
  • The ceiling's answer guess is 4,000 output tokens per question. A real 12-verdict reply is about 7,000, so the ceiling under-prices one answer by about 1.8x. Read the per-ping ceiling with that tolerance, and remember it is now multiplied by the number of batches.
  • Three mutations survive. Removing the !(ceiling > 0) guard, or letting NaN or -Inf past it, leaves the tests green: on gc int(NaN) and int(-Inf) are negative and the n < 0 clamp already gives zero. The guard is kept because that conversion is implementation-defined.

Fixes #132

amiddavid added a commit that referenced this pull request Oct 27, 2026
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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Box results for head 41eeb178 (eval box 1, foreground, -count=1, after the rebase onto main 4f9f5d2d):

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 1bd627d1, plugin tests only). I did not re-run on that tip.

@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 41eeb178f6ca blocking

Verdict: blocking

Findings

  1. 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 at max_ask_batches: 8. An operator who set the ceiling for the one-question shape no longer bounds what one ping spends.
    • Proof: sweepOutputBudgetGuess = 4000 and projectedSweepUSD (substitute.go:302-313) return prefix*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) calls adjudicateWith once 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) in projectedSweepUSD or its caller, or carry the batch count on SweepPingInfo. Add a test: a sweep of 48 candidates against a ceiling that admits one answer must be refused or projected at 4 answers.

Non-blocking

  • Stale text the PR contradicts. Four places still describe the old one-question shape:
    • docs/components/advanced-offload.md:534 — "max_calls because 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_calls reads "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.
  • 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() snapshots SweepBatchCounters() three times. The three fields can come from different moments. One call would keep them consistent.
  • extract_sweep_batch.go:125 — br.batches is written and never read. Tests read SweepBatchCounters() instead.
  • Per-batch recomputation. Each adjudicateWith re-runs coref.Index and flattenTranscript over 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-batch prefixAskCacheOK write 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+k into br.judged) against buildHeld's voted map: 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_batches clamps (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 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 41eeb178f6ca blocking

Verdict: blocking

Findings

  1. 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 to e.pol.Ceiling(). The real spend is about 4x that projection, and up to 8x with max_ask_batches: 8. The operator's per-ping $ cap is exceeded before any check notices; the after-the-fact pingUSD check (keeper.go:881, 889) only stops the NEXT ping.
    • Proof: fireSweepSubstitute runs dispatch once per ping (substitute.go:368) and askInBatches asks k batches inside that one dispatch (extract_sweep_batch.go:131-160). The PR's own test pins the multiplied read: TestTheBatchesAreAskedInSequenceAndMergedIntoOneHeldAnswer asserts res.CacheRead == 2*okUse.CacheRead for 20 candidates. projectedSweepUSD was 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 carries Offered) or export the per-sweep candidate limit, and price k x (prefix read + answer guess) in projectedSweepUSD.
  2. components/offload/extract_sweep_ping.go:603 — the cg.sweep.held log's offered field 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 new sweep_batch_failed counters describe gets a wrong inventory size.
    • Proof: res.Offered is set correctly from the collected list (line 567). Line 590 reassigns cands, drop := br.judged, br.drop. Line 603 then logs "offered", len(cands), which is now len(br.judged) — only the candidates of the batches that answered. Before this PR cands was never reassigned, so the field was right.
    • Fix: log res.Offered at line 603 (or capture the count before line 590).

Non-blocking

  • askInBatches (extract_sweep_batch.go:122) does not enforce max_ask_batches itself. The cap lives only in collect (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 a sweepSlots slot and the keeper goroutine for up to 300 s. Fail open still holds.
  • keeper.go:1820-1822 calls SweepBatchCounters() three times for one Stats(). 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 askInBatches would keep the earlier answers.
  • Each batch re-runs coref.Index and flattenTranscript over the whole transcript, and writes a full-transcript dump when CG_SWEEP_ASK_DUMP is 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: adjudicateWith end to end (extract_sweep.go:598-1121), splitAskBatches, askInBatches, batchFailReason (extract_sweep_batch.go), collect and ask (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, < 1 reads as 4 in the constructor; the settings form (config/form.go:630) refuses < 1 instead — convergent, safe direction.
  • Docs: the new advanced-offload.md section 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.md row for extract_llm_sweep stays 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]>
@amiddavid
amiddavid force-pushed the feat/sweep-ask-batches branch from 41eeb17 to a78a96b Compare October 27, 2026 12:10
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 fixes are in head a78a96bd. One reply for every finding.

Blocking 1 (both reviewers): the keeper's cost ceiling priced one answer. Fixed.

  • SweepPingInfo now carries the planned batch count: ceil(offered / 12) (plannedAskBatches).
  • projectedSweepBatchesUSD projects n x (prefix read + answer guess).
  • affordableSweepBatches finds the largest n <= planned the ceiling admits. If it admits fewer than planned, the keeper lowers the count and passes it to the sweep (SweepPingWait.MaxBatches). The sweep asks that many, and the smallest outputs stay unasked (counted as sweep_over_ask_cap and sweep_batches_lowered). If not even one answer fits, the ordinary ping goes out, as before.
  • A caller may lower the limit but never raise it above max_ask_batches. An unpriced model keeps the plan (nothing to compare, as before).
  • Tests, with 48 candidates and a price of $0.0836 a question: TestTheSweepCeilingPricesEveryBatchAndLowersTheCount. A ceiling that admits one answer asks 1 batch; two asks 2; all four asks 4 and is not lowered; below one answer sends the ordinary ping. Plus TestAffordableSweepBatchesIsTheLargestCountTheCeilingAdmits, TestAnUnpricedModelKeepsThePlannedSweepBatches, TestACallerCanLowerTheBatchLimitButNotRaiseIt.
  • 8 mutations killed: the ceiling prices one answer again; the projection not multiplied; the limit not passed; refuse instead of lower; lowering not counted; the plan always 1; the keeper's limit ignored; the keeper's limit able to raise the bound.

Blocking 2 (reviewer 2): cg.sweep.held logged the judged count as offered. Fixed. It now logs offered (what was offered) and judged (what answered). TestTheHeldLogReportsTheOfferedCountEvenWhenABatchFailed: 20 offered, one batch of 10 fails, the line reads offered=20 judged=10. Mutation killed.

Non-blocking, all fixed

  • Per-batch recover. A panic in batch k is one failed batch (reason batch_panic); batches 1..k-1 are kept. TestAPanicInOneBatchKeepsTheOtherBatches (3 batches, batch 2 panics, 20 outputs held). The existing TestAPanicInThePingQuestionLeavesAPlainPing changed on purpose: a panic is now caught per batch, so with nothing paid the latch is given back and the next ping may ask. It used to stay marked asked because the panic escaped to the dispatch-level recover.
  • askInBatches enforces max_ask_batches itself (TestAskInBatchesEnforcesTheOperatorsBatchLimitItself: 60 candidates, no pre-cap, 2 asks, 36 counted over cap).
  • A batch never starts after the sweep's context ended (TestABatchNeverStartsAfterTheSweepsDeadline: the deadline passes in batch 1, batches 2 and 3 are skipped and counted as sweep_batch_skipped). This answers the 300 s versus 90 s point: the keeper's timeout bounds the whole sweep, each question keeps its own 90 s, and no batch starts once the outer one ends.
  • Stale text fixed: the config table now lists max_ask_batches; the max_calls sentence and banned-key reason; the cold-apply bound comment (up to 12 x 8 = 96); the "12 largest" comment; the timeout comment; the "cold sweep calls it" comment; the Counters list (sweep_ask_batches, sweep_batch_failed with _by, sweep_batch_skipped, sweep_batch_over_cap, sweep_batches_lowered).
  • Stats() reads the batch ledger once (TestStatsPublishesTheBatchCountersFromOneSnapshot). The unused br.batches is removed.
  • The keeper's write > read stop judges the summed usage. Noted in the docs and below. The per-batch prefixAskCacheOK still gates each batch.
  • Per-batch recomputation of the co-reference index and the dump (reviewer 1 and 2): left as is. It runs at ping time, off the hot path, and is bounded by max_ask_batches.

One thing I found while re-running after the rebase, not in the reviews: under -race, three batching tests saw 1 ask instead of 2. The cause is the new deadline rule, working as designed: those tests gave the whole sweep a 1 s budget, sized for one question, so on a slow machine the second batch was correctly skipped. They now use a 60 s budget. This is a test fix, and it is why the last commit exists.

Tests on box 1 (foreground, -count=1, head a78a96bd, rebased onto main 1bd627d1):

  • gofmt -l . prints nothing. make lint exits 0.
  • All packages pass, including proxy and dash.
  • -race passes on components/offload, keepalive, config, components/all and proxy.
  • Not repeated: dash under -race.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Box results for head a78a96bd (eval box 1, foreground, -count=1, rebased onto main 1bd627d1):

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 gofmt for three files, and three batching tests failed under -race only. Both are fixed in this head (the second is a test budget, described in the reply 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 2 of 2 a78a96bd68eb blocking

Verdict: blocking

Earlier findings

  • My round-1 finding (the keeper's cost ceiling priced one answer): fixed. SweepPingInfo.Batches carries ceil(offered/12); projectedSweepBatchesUSD prices n x (prefix read + answer guess); affordableSweepBatches lowers the count the ceiling admits and SweepPingWait.MaxBatches carries it down; askInBatches enforces 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.held logged the judged count as offered): fixed. The line now logs offered and judged (extract_sweep_ping.go:609), and TestTheHeldLogReportsTheOfferedCountEvenWhenABatchFailed pins 20 offered / 10 judged.
  • My non-blocking items: all fixed (stale text, the phantom "cold sweep" caller, the triple SweepBatchCounters() snapshot, the dead br.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

  1. components/offload/extract_sweep_batch.go:196 — a panic after a completed model call releases the asked latch, 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, so ask() sees no usage, sets Substituted=false, and stores asked=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 does drop, r = nil, sweepResult{} (extract_sweep_batch.go:201), discarding r.rec, which adjudicateWith sets 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 because in, out and the cache totals read zero (extract_sweep_ping.go:582-588). The sink does hold the call's usage — ask() reads sink.Model() and sink.CacheWrite1h() from it, and deferBilling books 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 panicked count on batchRun (or test the sweep_batch_failed_batch_panic event) and treat it like usage in the latch decision at extract_sweep_ping.go:585-588. Then update TestAPanicInThePingQuestionLeavesAPlainPing and the SweepReasonPanic comment to match. The per-batch recover itself is right and stays.

Non-blocking

  • extract_sweep_batch.go:130 — the comment says a panic's reason is panic; the code produces batch_panic (batchFailReason strips the sweep_ prefix from sweep_batch_panic). The tests assert batch_panic. Comment slip only.
  • sweepOutputBudgetGuess stays 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.
  • ResetSweepBatchForTest and NoteSweepBatchSkippedForTest are exported from the production file (extract_sweep_batch.go:271-277). The repo's precedent (SweepSlotsInUseForTest) keeps such helpers in a *_testing.go file.
  • Two names for one thing: the event is sweep_batch_skipped_deadline, the /stats field is sweep_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: collect caps at the operator's bound, askInBatches caps 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 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 a78a96bd68eb blocking

Verdict: blocking

Findings

  1. keepalive/substitute.go:337 — affordableSweepBatches turns the "no ceiling" sentinel (+Inf) into "zero batches", so every sweep question is refused.
    • What fails: a policy with MaxUSDPerPing < 0 means "no cap" (Policy.Ceiling(), types.go:250-258, returns math.Inf(1)). n := int(ceiling / one) divides +Inf by a positive cost. Go leaves that conversion implementation-defined; on gc (amd64, arm64) it yields math.MinInt64, a negative number. The clamp if n < 0 { n = 0 } then sets n to 0, fireSweepSubstitute sees allowed < 1, counts sweep_over_budget and 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 on allowed < 1. No test covers an infinite ceiling (TestAffordableSweepBatchesIsTheLargestCountTheCeilingAdmits uses finite ceilings only). Reachability: no shipped path sets a negative MaxUSDPerPing — the config loader refuses it (config/config.go:246) and so do the strategy bounds (proxy/keepalivestrategy.go:240) — but Policy is 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 with ceiling_usd=+Inf).
    • Fix: guard before dividing — if !(ceiling > 0) || math.IsInf(ceiling, 1) { return planned } in affordableSweepBatches. Low severity, one line.

Earlier findings, round 1

  • Reviewer 2, finding 1 (the per-ping ceiling priced one batch): fixed. plannedAskBatches = ceil(offered/12) is carried on SweepPingInfo.Batches (extract_sweep_ping.go:456), projectedSweepBatchesUSD prices n x (prefix read + answer guess), affordableSweepBatches lowers the count rather than refusing, SweepPingWait.MaxBatches carries it into askInBatches, and askInBatches itself enforces max_ask_batches with "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.held logged the judged count as offered): fixed. The line now logs offered (res.Offered) and judged (extract_sweep_ping.go:609). TestTheHeldLogReportsTheOfferedCountEvenWhenABatchFailed pins 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); askInBatches enforces the bound itself; stale comments fixed (config table, max_calls reason, cold-apply bound, "12 largest", timeout comment, "cold sweep calls it", Counters list); Stats() reads the ledger once; br.batches removed. 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_cap under-reports its own description. The /stats counter is fed only by askInBatches' trim (keeper lowering). The operator-config cap in collect feeds only the sweep_over_ask_cap gate. 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 feed collect's cap into sweepOverAskCapBatch too, 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 is sweep_batch_skipped_deadline while the /stats field is sweep_batch_skipped. Cosmetic.
  • directBatch (extract_sweep_batch_test.go) sets cand.e = e and immediately overwrites it with wide; 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-diff confirms 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-result ms set in the defer on both paths — correct), largestFirst, plannedAskBatches, SweepPingWait.MaxBatches plumbing through ask, fireSweepSubstitute and 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 the asked latch, so the next ping may ask — matches the code path (res.Substituted and 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, math import, 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 2 fixes are in head f5a53910. One reply for both findings and the non-blocking notes.

Blocking 1 (reviewer 1): a panic after a paid call released the asked latch. Fixed.

  • The per-batch recover erased that batch's result, so the sums read zero usage and ask() gave the latch back, though the model call had been paid for. A deterministic panic would then pay for the same question on every ping.
  • batchRun now counts panicked batches, and ask() treats a panic like usage in the latch decision: a panicked batch keeps the thread marked asked, so the next ping is plain. An ask that never left the process (no stashed prefix) still gives the latch back (TestAnAskThatNeverLeftTheProcessStillReleasesTheLatch).
  • The cost of a panicked batch is still booked: the sink saw the call, and deferBilling reads the sink. Only the per-batch result is erased.
  • TestAPanicInThePingQuestionLeavesAPlainPing is back to "the conversation stays asked after a panic", and the SweepReasonPanic comment now says what happens per batch.
  • New test, TestAPanicAfterAPaidCallKeepsTheThreadAskedSoItIsNotPaidForAgainOnEveryPing: one batch, the call is paid, then a panic in the code after it (a test-only hook after the parse). The latch stays set, the next ping is already_asked, and the asker is called once in all.
  • 4 mutations killed: panic ignored in the latch decision, the panic not counted, a latch that is never released, and the per-batch recover removed.

Blocking 2 (reviewer 2): an infinite ceiling refused every question. Fixed.

  • Policy.Ceiling() returns +Inf for a negative MaxUSDPerPing ("no cap"). int(+Inf / cost) is MinInt64 on gc, which the clamp made zero batches.
  • affordableSweepBatches now returns the planned count for +Inf, before the division. A ceiling of zero or less, or NaN, keeps the old meaning (every positive cost exceeds it, so nothing is admitted). Policy.Ceiling() resolves zero to the default, so a zero never arrives from a real policy; I checked that in the test.
  • Tests: TestAnInfiniteCeilingAdmitsEveryPlannedBatch, TestAZeroOrNegativeOrNaNCeilingAdmitsNothing, and TestANoCapPolicyAsksEveryBatchEndToEnd (48 candidates, a no-cap policy, all 4 questions asked, nothing lowered or refused).
  • 2 mutations killed: the infinite case not special-cased, and a zero ceiling treated as no cap.
  • Three mutations survive and I cannot kill them here. Removing the !(ceiling > 0) guard, or narrowing it so NaN or -Inf slip through, leaves every test green. On gc, int(NaN) and int(-Inf) are negative, and the existing n < 0 clamp turns them into zero anyway. So the explicit guard is redundant on this platform and a test cannot tell it from that accident. I kept the guard because that conversion is implementation-defined, and I said so in a comment on it.

Non-blocking, all fixed

  • Comments and docs now say batch_panic, not panic.
  • sweep_batch_over_cap: I fed collect's cap into the same ledger. It now counts every candidate left unasked by any limit (max_ask_batches, or the cost ceiling), the same candidates sweep_over_ask_cap counts per request. The Stats comment says so. The first version of my test did not catch this, so two mutations survived; I added assertions on the ledger and both are now killed.
  • ResetSweepBatchForTest and NoteSweepBatchSkippedForTest moved to extract_sweep_ping_testing.go.
  • The dead cand.e = e in directBatch is removed.
  • The docs say that the per-request event sweep_batch_skipped_deadline pairs with the /stats counter sweep_batch_skipped.
  • Technical notes now say the ceiling's 4,000-token answer guess under-prices one answer by about 1.8x, so operators should read the per-ping ceiling with that tolerance.

Tests on box 1 (foreground, -count=1, head f5a53910):

  • gofmt -l . prints nothing. make lint exits 0.
  • All packages pass, including proxy and dash.
  • -race passes on components/offload (361 s), keepalive (86 s), config, components/all and proxy (475 s).
  • Main has moved by two commits (387664ea, d08eff8b). I did not rebase. A trial merge of main into this branch had no conflicts, and I ran the full set above on that merged tree: it passes too. The pushed head is the unmerged branch.
  • Not repeated: dash under -race.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Box results for head f5a53910 (eval box 1, foreground, -count=1):

  • gofmt -l . prints nothing. make lint exits 0.
  • go test passes on every package, including proxy (114 s) and dash (101 s).
  • go test -race passes on components/offload (361 s), keepalive (86 s), config, components/all and proxy (475 s).
  • Not repeated: dash under -race (known 10 s insights handler timeout, noted on feat(sweep): apply the held answer on the next cold request, and book what it earns (#404 PR C) #695).
  • Main has moved by two commits since this branch's base (387664ea, d08eff8b). I did not rebase. A trial merge had no conflicts, and I ran all of the above on the merged tree too: it passes.

Mutation checks: 43 killed (17 first push, 18 round 1, 8 round 2). 3 survive and are explained in the PR body (the explicit ceiling <= 0 / NaN guard is redundant with the n < 0 clamp on gc).

@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 3 f5a539105d6e approve

Verdict: approve

Findings

None.

Earlier findings

  • My round-2 finding (a panic after a paid call released the asked latch): fixed. askInBatches now counts panicked batches on batchRun.panicked (extract_sweep_batch.go:180-182), and ask() treats a panic like usage in the latch decision: res.Substituted || in > 0 || out > 0 || br.panicked > 0 keeps 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, after ParseVerdicts), the latch stays set, the next ping is already_asked, and the asker is called once in all. The SweepReasonPanic comment and the changed TestAPanicInThePingQuestionLeavesAPlainPing now say the same thing as the code. The paid usage is still booked: deferBilling reads the sink, which saw the call.
  • Reviewer 2's round-2 finding (an infinite ceiling admitted zero batches): fixed. affordableSweepBatches returns the planned count for +Inf before 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, the Policy.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, where int(NaN) and int(-Inf) are negative and the n < 0 clamp 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_cap now counts every candidate left unasked by any limit (collect feeds the same ledger, extract_sweep_ping.go:513-515, with test assertions on the ledger); the test helpers moved to extract_sweep_ping_testing.go; the dead cand.e = e is gone; the docs pair sweep_batch_skipped_deadline with sweep_batch_skipped; the docs state the 4,000-token guess under-prices one answer by about 1.8x.

Non-blocking

  • sweepPanicAfterCallHook is a test seam inside the production adjudicateWith (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_cap widening, 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_panic on a fresh zero result (extract_sweep_batch.go:216-218), raised scans the gate list (extract_sweep.go:569-575), askInBatches counts it into br.panicked only for a batch that did not answer, and no other code raises that gate name. A panicking batch stays a failed batch with reason batch_panic; the other batches still count.
  • The latch decision in ask(): br.panicked comes 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: collect has one production caller (the ping ask, extract_sweep_ping.go:420) and caps at the operator's bound; askInBatches trims 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: +Inf returns 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. The math import is present.
  • The tests' fixtures and helpers exist: panicAfterPaidAsker, dynAsker, ErrNoPrefix, candidateFor, okUse, testKeeper, proxyPricer, registerSweep, sweepConversation, kaPolicy; the atomic import 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 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 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) returns planned for math.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". math is 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 asked latch): agree, and fixed. I checked it myself. askInBatches counts br.panicked when a failed batch raised sweep_batch_panic (extract_sweep_batch.go:180-182), and ask() 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). TestAPanicAfterAPaidCallKeepsTheThreadAskedSoItIsNotPaidForAgainOnEveryPing pins the whole story: one paid call, a panic after it, the latch stays, the next ping is already_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) and int(-Inf) are negative, so the existing n < 0 clamp 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_cap now counts collect's cap too (extract_sweep_ping.go:513-516), with no double count: collect trims 60→48 and askInBatches trims 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, and TestOnlyBatchTimesBatchesCandidatesAreOfferedAndTheSmallestAreCounted now asserts the ledger (12 and 36). Comments and docs say batch_panic. The sweep_batch_skipped_deadline event is paired with the sweep_batch_skipped counter in the docs. The dead cand.e = e is removed. ResetSweepBatchForTest and NoteSweepBatchSkippedForTest moved to extract_sweep_ping_testing.go, the repo's precedent.
  • Reviewer 1's round-2 non-blocking items: all fixed (the panic/batch_panic comment, 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 panicAfterPaidAsker fixture 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 SweepReasonPanic comment 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.panicked and its counting (r.raised("sweep_batch_panic") scans the gate slice set by askOneBatch's recover); the latch decision in ask() and the CAS that sets asked (line 531) with the single release point (line 598); affordableSweepBatches with both guards; collect's ledger add inside the trim branch; the moved test helpers; the hook var sweepPanicAfterCallHook (declared in extract_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_cap per request. No candidate is counted twice.
  • The new tests' premises: ask(cands, rep, 0, ...) takes the llmCallTimeout default (timeout <= 0); SweepPingSubstitute returns SweepReasonAlreadyAsked while asked is set; panicAfterPaidAsker returns 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.

@amiddavid
amiddavid merged commit 514b8be 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 added a commit that referenced this pull request Nov 10, 2026
…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]>
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.

extract_llm_sweep: one ask is capped at 12, so a large transcript is only partly swept

1 participant