Skip to content

feat(sweep): the warm path, an economic gate on a held answer (#491) - #720

Merged
amiddavid merged 12 commits into
mainfrom
feat/sweep-warm
Nov 10, 2026
Merged

amiddavid merged 12 commits into
mainfrom
feat/sweep-warm

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

No behavior change unless warm: true. The warm path is off by default and in no preset. The default config behaves as main does.

State

Bob (IBM Bob, issue #1030, item 2)

  • Bob bills fresh input, cache read and cache write at one flat rate.
  • The gate already prices this. The rewrite cost is rewritten x ratio x (write - read). With cache_read == cache_write == input in the operator price entry, it is 0. Any cut with a positive saving passes. No separate apply_on_warm switch is needed.
  • A model with no price entry (for example premium-ide) gets the built-in Claude-class rates, where write is 12.5 x read. The rewrite is dear, so the gate refuses more and never less. It never assumes a flat rate.
  • On Bob, the operator must add a price entry with cache_read == cache_write == input. Without it, the gate prices Claude-class rates and stays strict.
  • warm_gate_price_model stays a diagnostic, unset by default and in no preset.
  • New tests: TestTheSameWarmCutPassesAtAFlatRateAndIsRefusedAtOpusRates, TestAModelWithNoPriceEntryIsGatedAtClaudeClassRatesNeverFlat.
  • Third test: TestTheGateSavingIsPricedAtTheReadRateNotTheWriteRate. At Opus rates a deep cut is refused over 60 turns; at a flat rate it passes.
  • Mutation checks (all killed):
    • Gate saving priced at write instead of read: the saving test fails.
    • Rewrite term (write - read) changed to write: the flat-rate/Opus test fails.
    • No-price-entry fallback made flat (write = read): both new tests fail.

Summary

  • Adds the warm path of the sweep. A session that never goes idle can now lose old tool outputs, behind an economic gate.
  • Off by default and in no preset. One setting turns it on: warm: true.
  • Rule decides when to ask. The model decides what to drop. The gate decides whether to apply.
  • The waiting answer lives in process memory only. It is never written to the Store.

What changed

  1. Trigger (rule). On a warm request, at most once every warm_every_n requests (30). Mass gate: the removable mass must be at least warm_min_mass_frac (0.20) of the conversation. Expected turns at the trigger = the warm turns run so far, capped. Every refusal is counted by reason (trigger_refusals). Only when outputs at least warm_min_age_turns (30) turns old and at least 1,000 tokens could pay back the rewrite even if all were dropped.
  2. Question. The same sweep question, run after the request is forwarded, in the background, from the ping registry's copy. It takes the thread's ping claim and the shared question slots. A thread never has two questions at once.
  3. File-read evidence. A file read also carries file_read=yes later_edits=N later_rereads=N. It comes from tool names and tool input paths only. No path reaches the question.
  4. Held in memory. Bounded: 256 threads, 30 minutes. A restart loses it. That drops nothing. No conversation copy of its own: the question reads the ping registry's existing copy, so it asks only on a thread the keep-alive can ping (80k floor). Otherwise it is counted as not_registered.
  5. Later warm request. Recheck, then the gate, then apply with the cold apply's own code (same markers, stash, drop records, replay). A refusal keeps the drops that passed the recheck, in memory only (item 15).
  6. Gate. Apply only if removed x read rate x expected warm turns > rewritten x (write rate - read rate). Sizes are billed. The rewrite follows how the provider reads the cache: it reads back only up to a cache entry written before the change. A drop farther than 20 content blocks (warmLookbackBlocks) from the last breakpoint reaches only system prompt + tools, so it rewrites the whole conversation. A drop inside the look-back rewrites only the tail. (In 6,968 recorded Opus calls every large cache drop read back exactly the fixed size.) Expected turns = the thread's warm run, capped at warm_max_turns (60), times a wait-cause weight read off the request (tool result 1.0, person 0.5, other 0.75).
  7. Cold or changed prefix. A waiting answer met by a cold request or a changed prefix uses the cold rules, with no gate.
  8. Money. A warm drop is credited at the read rate. The rewrite is charged on the request that paid it: the provider's cache-write tokens when reported, the billed estimate otherwise. Cold pricing is unchanged.
  9. Live-test numbers. Each applied warm sweep leaves a record (keepalive.sweep_warm.recent_sweeps) and events on the dashboard row: tokens removed, conversation before and after, rewrite, expected turns, expected net, and whether the drop was deep. The warm question is judged by prefixAskCacheOK against the turn's read (fix(cheapmodel): move the trailing breakpoint onto the appended question #725), with no write check of its own.
  10. Every decision is recorded in keepalive.sweep_warm.recent_decisions (last 50): D, R, N, weight, ratios, deep, saving and rewrite, reason. One INFO line each, no content.
    Turns left. warm_expected_turns (0 = unset): N = max(expected - so far, 0). Otherwise N = (cut - billed prompt) / (billed growth per turn), where the cut is the summarizer's trigger fraction of the window, else the full window; it falls back to the turns so far when the growth, the billed size or an exact window is missing. warm_max_turns caps N. The decision log records the model. The cut model needs an exact window: a builder supplies one with window: in MODEL_PRICES (see deploy/service/prices.example.yaml).
    Batching (more than 12 outputs, in balanced batches) is feat(sweep): ask a long list of outputs in balanced batches, then cut once (#132) #747, now merged. The warm ask calls the SAME askInBatches, with the same latch rule (a panic counts as usage) and the same per-batch cache-read rule. The gate decides ONCE over the merged answer, so there is one cut.
  11. Diagnostic warm_gate_price_model (unset, in no preset): prices the gate's decision with another model's rates, for a run on a model priced at $0. Gate only; the dashboard and /stats price the real model. Logged once and shown as keepalive.sweep_warm.gate_price_model.
  12. Counted apart. sweep_applied_warm, warm vs cold false-drop rate, gate accepts and refusals with reasons (keepalive.sweep_warm in /stats).
  13. Streamed usage fix (usage: a streamed litellm Anthropic response double-counts cache_read in billed input #745). A litellm gateway streams the TOTAL prompt in message_start and the true split in message_delta. The SSE merge took max() per field, so the read was counted twice and PrevBilledInput was about 2x too large (the warm gate's ratio_full read 2.9 to 4.6 where about 1.96 is right). A later event with an input count now replaces the whole input set. Output-only deltas (real Anthropic) change nothing. Issue usage: a streamed litellm Anthropic response double-counts cache_read in billed input #745 lists every consumer.
  14. Warm expands on the dashboard. New additive column requests.sweep_false_expands_warm (added with additiveColumns, no version bump). The dashboard's warm false-drop rate counts references and expands, as /stats does.
  15. Accumulation (new in this round). A gate refusal keeps the survivors' drop verdicts in the thread's held state. In memory only: never the Store. The next warm question's answer is merged by tool-use id. Each output counts once. The NEWER verdict wins, a newer keep included. Every apply attempt rechecks the whole merged set. A carried drop that fails the recheck leaves for good. The gate decides once on the surviving set. Accept: one cut, then the set is cleared. Refuse: the survivors stay.
    • Bounds: 30 minutes from the OLDEST question that still contributes (a refusal does not make it younger), 256 carried drops (oldest first), a shorter conversation clears the set, 256 threads.
    • A carried set that was already refused is not retried on each warm request. The trigger asks a new question, and the gate runs when its answer arrives.
    • The trigger does not count carried drops. It still prices every candidate as dropped.
    • The decision log records carried and new counts and tokens, and the recheck's losses by reason.
  16. Recheck reasons are booked before the gate (sweep_apply_dropped_<reason>), so a refusal shows them. An empty proposal is no_drop_proposed. no_valid_drop means the recheck threw out a whole proposal.
  17. A shrunk conversation voids the held answer (held_shrunk, decision conversation_shrunk). The gate does not run.
  18. sweep_batch_by_index: per batch position: asked, items, judged, fabricated.
  19. Quote check uses what the model read. A judge quote is now checked against the stashed body the question was appended to (new PrefixReadAsker), not the newest request. A quote from a message newer than that body is real and is no longer counted as fabricated. This changes only the counter, never a drop decision.

How it was tested

Eval box 1, -count=1, on the tree rebased onto main ccb62c7c. Every commit builds (checked one by one). make lint, gofmt and mkdocs build --strict clean. All packages pass. -race passes on offload (495 s), keepalive, config, components/all, cheapmodel, proxy. No live model calls.

Mutation checks for this round: 25 mutations, all killed. 13 on accumulation (newer wins, carry keeps only drops, tried flag, tried cleared on a new answer, expiry, cap, oldest-first, oldest age, shrink clear, retry every request, carry nothing, carry unrechecked, age reset on carry; two needed a stronger test first), 3 on the quote check (read text ignored, asker not used, proxy returns no text), 5 on the keeper publish (each carried_* field dropped in turn), 1 on carried_capped, and round 8: the shrink void without the same-answer check, and carried_expired counted for a never-refused answer (2 tests killed it, one of them an existing test I had to fix first), and the same split at read time (memHeld.get).

Requirement Test
Trigger once per N, never cold TestTheTriggerFiresOncePerNWarmRequestsAndNeverOnACold
Trigger not when it cannot pay TestTheTriggerAsksNothingWhenTheCandidatesCannotPayBack
Question after the forward; request identical to warm off TestTheQuestionRunsAfterTheForwardAndTheForwardedRequestIsUnchanged
Never in the Store; restart loses it TestTheWaitingAnswerIsNeverWrittenToTheStoreAndARestartLosesIt
Gate accepts / refuses, billed vs local TestTheGateAcceptsACaseThatPaysAndRefusesOneThatDoesNot, TestTheGateRatiosFollowTheBilledSizes
Expand byte for byte; replay stable TestAnAppliedWarmDropExpandsByteForByteAndLaterRequestsReplayIt
Changed prefix as #695 defines it TestAChangedPrefixBehavesAsTheColdApplyDefinesIt, TestAColdRequestAppliesAWaitingAnswerWithoutTheGate
Fail open, no lock held TestFailOpenInTheWarmPath (trigger panic, apply panic, store refuses)
Warm off changes nothing TestWithWarmOffNothingHappens, TestTheWarmSettingsHaveSafeDefaults, all of #695's tests unchanged
File-read evidence TestAFileReadThatTheAgentLaterEditedCarriesThatEvidence
One question per thread TestAWarmQuestionAndAPingQuestionNeverRunTogetherOnAThread
Credit and rewrite charge TestAWarmDropIsCreditedAtTheReadRateNotTheWriteRate, TestTheRewriteIsChargedOnTheWarmRequestThatPaidIt (dash)
A warm question and the ping never pay twice for one conversation TestAWarmQuestionStopsThePingFromAskingTheSameConversationAgain, TestAHeldPingAnswerStopsAWarmQuestionOnTheSameThread, TestAPingAnswerStillInTheStoreStopsAWarmQuestionAfterAReRegistration, TestAWarmQuestionThatNeverAskedLeavesThePingFree
Review round 1: rewrite counts the first output; eviction; counters; labels TestTheRewriteCountsTheFirstRemovedOutputsOwnReplacement, TestAThreadWithAWaitingAnswerIsNeverEvictedAndTheTableStaysBounded, TestWarmQuestionGatesAndLabelAreTheWarmPathsOwn, TestTheWarmStatsBlockShowsAnythingThatHappened
Warm asks only on a thread the keep-alive can ping; no own copy TestAThreadTheKeepAliveCannotPingNeverAsksAWarmQuestion
Warm false-drop rate counts expands; column is additive TestTheWarmFalseDropRateCountsExpandsAsWellAsReferences, TestTheWarmExpandColumnIsAdditive, TestAnExpandOfAWarmDropIsMarkedWarm
Rewrite model: deep drop = whole conversation; shallow = tail; gate refuses what the old model accepted TestADropAtDepthRewritesTheWholeConversation, TestADropNearTheTailRewritesOnlyTheTail, TestTheGateRefusesADeepDropTheOldModelAccepted
Mass gate; trigger reasons; warm run as estimate TestTheTriggerAsksNothingWhenTheRemovableMassIsTooSmall, TestTheMassSettingHasADefaultAndIgnoresNonsense, TestEveryTriggerRefusalIsCountedByReason, TestTheTriggerUsesTheWarmRunSoFarAsItsEstimateOfTurnsLeft
#725 cache-read rule TestTheWarmQuestionIsJudgedByTheSharedCacheReadRule
Live-test numbers per sweep TestEachWarmSweepRecordsItsNumbers
warm_gate_price_model (diagnostic): a skewed-price model gets another model's decisions; unchanged when unset; gate-only; unknown model counted; shown in /stats; a missing cache_write is not no_billed_size TestTheGatePriceModelGivesAZeroPricedModelRealDecisions, TestTheGatePriceModelChangesNothingWhenUnset, TestTheGatePriceModelDoesNotTouchTheDashboardPrice, TestAnUnknownGatePriceModelIsCounted, TestTheGatePriceModelShowsInTheStats, TestAMissingCacheWriteDoesNotMakeTheGateRefuseForNoBilledSize
Trigger uses the question's marker rule TestTheTriggerCountsAnOutputThatOnlyQuotesMarkerSyntaxAsRemovable
max_ask_items: default 12; clamp; 40 offers 40 and keeps the largest TestMaxAskItemsDefaultsToTwelveAndIsClamped, TestTheDefaultAskStillOffersTwelveAndKeepsTheLargest, TestFortyOffersFortyAndKeepsTheLargest
Reply budget scales; carried to the ask; on the wire; a floor TestTheReplyBudgetScalesWithTheCount, TestThePerVerdictBudgetCoversTheLongestRealisticVerdict, TestTheAskCarriesTheScaledReplyBudget, TestThePrefixCallSendsTheScaledReplyBudgetOnTheWire, TestTheReplyBudgetIsAFloorNotACeiling
A truncated reply is counted and fails open TestATruncatedReplyIsCountedAndFailsOpenWithManyItems
Every decision recorded, accept or refuse TestAnAcceptedApplyGateDecisionRecordsItsNumbers, TestARefusedApplyGateDecisionRecordsItsNumbersAndReason, TestEveryTriggerDecisionIsRecordedAcceptOrRefuse, TestTheDecisionLogKeepsTheLastFiftyAndOneInfoLineEach
Model audit TestEveryCallAfterASweepOnlyProxyOnANonClaudeModelCarriesTheRequestsModel, TestThePingKeepsTheRequestsModelAndEveryOtherField, TestANonClaudeModelOnARelayIsNotPingedUnlessNamed
Streamed usage: litellm shape reads as the true split; real Anthropic shapes unchanged (#745) TestStreamedUsageReadsTheTrueSplit (7 shapes), TestTheNonStreamedControlStillReadsTheTrueSplit
Turns left: expected, cut (with and without a summarizer), fallbacks, cap TestExpectedTurnsSetsTheTurnsLeft, TestTheCutModelRunsToTheSummarizersFractionOfTheWindow, TestTheCutModelRunsToTheFullWindowWithoutASummarizer, TestTheCutModelFallsBackToTheTurnsSoFarAndSaysWhy, TestTheCapAppliesToEveryTurnsModel
The pipeline hands the smallest enabled cut fraction to the sweep; the growth run restarts at a shrink TestThePipelineHandsTheSummarizersCutFractionToTheSweep, TestThePipelineHandsTheSmallestCutFraction, TestADisabledCuttingComponentIsNotCountedAsACut, TestTheGrowthRunRestartsWhenTheBilledPromptShrinks
The decision log records the turns model, cut, growth and raw N TestTheDecisionRecordsWhichTurnsModelProducedN, TestTheTriggerRecordsAndUsesTheSameTurnsModel
A warm sweep over many outputs asks batches, makes ONE gate decision and ONE cut TestAWarmSweepOverManyOutputsAsksBatchesAndMakesOneGateDecisionAndOneCut
12 or fewer outputs: one ask TestAWarmSweepOverTwelveOrFewerOutputsMakesOneAsk
A failed warm batch keeps its outputs; the others are gated TestAFailedWarmBatchKeepsItsOutputsAndTheOthersAreGated
A panic after a paid call keeps the thread asked (warm) TestAWarmPanicAfterAPaidCallKeepsTheThreadAsked
The warm ask honours max_ask_batches; its outer bound fits several batches TestTheWarmAskHonoursMaxAskBatches, TestTheWarmSweepOuterTimeoutFitsSeveralBatches
An old max_ask_items key gets a pointer to max_ask_batches TestAnOldMaxAskItemsKeyGetsAPointerToMaxAskBatches
Net sign TestTheNetOfAWarmDropIsPositiveWhenItPaysAndNegativeWhenItDoesNot (dash)
Refused drops are carried, merged with the next answer, and the gate decides on the merged set TestARefusedAnswersDropsAreCarriedAndMergedWithTheNextQuestionsAndTheGateDecidesOnTheMergedSet
Two answers that cannot pay alone are accepted together, with ONE cut, then cleared TestTwoRefusedAnswersThatCannotPayAloneAreAcceptedTogetherWithOneCut
Each output once; the newer verdict wins TestMergeHeldKeepsEachOutputOnceAndTheNewerVerdictWins
A newer keep overrides a carried drop TestANewerKeepOverridesACarriedDropInTheThreadsHeldState
A carried drop that fails the recheck leaves the set TestACarriedDropThatLaterFailsTheRecheckLeavesTheSet
Age limit counts from the oldest question; a refusal does not make the set younger TestTheMergedAnswerKeepsTheOldestContributingQuestionsAge, TestACarriedSetOlderThanTheLimitIsDroppedAndCounted, TestACarryOnRefusalDoesNotMakeTheAnswerYounger
Cap of 256, oldest go first TestTheCarriedSetIsCappedAndTheOldestGoFirst
A shorter conversation clears the set TestAConversationShrinkClearsTheCarriedSet
A carried set is not retried until a new question is merged in TestACarriedSetIsNotRetriedUntilANewQuestionIsMergedIn
No Store write for the carried set TestTheCarriedSetIsNeverWrittenToTheStore
A quote from the body the model read is not counted as fabricated TestAQuoteFromTheBodyTheModelReadIsNotCountedAsFabricated, TestAskReadReportsTheTextOfTheBodyItAskedOver (proxy)

Mutation checks (each made a named test fail; the last ones: rate ignores expands, expand never marked warm, column not read, keep-alive check removed, no-registry check removed, warm path takes its own copy; latch not set, held ping answer ignored, latch not given back, first output left out of the rewrite, held thread evicted, table grows past the bound, no-inventory not counted, warm gates in the ping counters, stats block ignores panics; deep drop counted as shallow, shallow counted as deep, mass gate removed, wrong mass default, turns taken from the cap, trigger and deep refusals unlabeled or uncounted, sweep record not kept, removed events not booked, turn read ignored): gate always accepts; billed ratios ignored; trigger every request; trigger on cold; worth test removed; age floor ignored; answer also written to the Store; question before the forward; thread claim removed; refused answer kept; no recover; warm drop recorded as cold; changed prefix gated; file evidence off; edit order ignored; held age ignored; credit at write rate; rewrite not charged. Three first survived and the tests were strengthened.

Data dependence

  • Everything the warm path adds is in memory only. Nothing is in the Store or on disk while an answer waits.
    • One waiting answer per thread: ids, hashes, counts, verdicts (metadata), 30 minutes at most. It also holds the drop verdicts a refused answer left behind: the same fields, at most 256 per thread, none older than 30 minutes since the question that judged them. Nothing new is stored: no text, no paths.
    • Per thread, a few numbers: the warm run length, the previous request's local token size, the request count since the last question, a last-touched time, and a pending flag with its time (5 minutes at most). At most 256 threads.
    • No conversation copy of its own. The question uses the ping registry's existing copy, which is already in the extract_llm_sweep row.
  • An applied warm drop writes the same records as a cold drop (cg:swd:, cg:swx:: metadata) and the same stash.
  • docs/data-dependence.md: "Decided by" reads warm path approved 2026-10-26 (sweep: apply a held answer on a warm request (proposal only, behind an economic gate) #491).
  • Approved by David Amid on 2026-10-26.

Which model each call uses

Result: with the pipeline [extract_llm_sweep] and keep-alive on, every call goes to the request's own model. No path can pick another model. (For a GLM-only run at $0.)

Call Where Model it uses
The forwarded request proxy request path the client's own body
Sweep question (cold, ping, or warm) proxy/prefixask.go:341 builds the client from models.Incoming; cheapmodel/anthropic.go:231 CompletePrefixed appends one message to the stashed forwarded body and sets only max_tokens and stream (line 245-ish): it never writes model the model in the stashed forwarded body (the request's)
Same, OpenAI Responses cheapmodel/openai_prefixed.go:20 same: sets input and max_output_tokens only
Keep-alive ping keepalive/keeper.go:1324 pingBodyN(j.raw, ...) the held forwarded body; keepalive/ping.go:73 changes only the output budget and stream
Manual ping keepalive/manual.go:129 same builder
Sweep substitute at a ping keepalive/substitute.go:258 the sweep's question above (the same client)
adjudicate internal/adjudicate declares a tool inside the same question; makes no call of its own
incomingModel proxy/proxy.go:849 builds cheapmodel.Anthropic{Model: <body.model>}: the request's model, by construction

Unreachable with this config

  • staticModel / pinCheapModel (proxy/proxy.go:904, proxy/dispatcher.go:113, CHEAP_MODEL): this is the only place a fixed model (for example claude-haiku-4-5) can enter. It is handed only to components that implement NeedsModel: summarize, cache_aware_summarizer, agentdiet (components/offload/*.go: NeedsModel() bool). extract_llm_sweep does not, and the pipeline runs only the components it names, so none of these run. The sweep component itself never calls Complete or c.Model.*.
  • The summary substitute at a ping needs a registered summarizer candidate (ClaimPing, components/offload/ping_claim.go). With no summarizer in the pipeline none exists.
  • Only two dispatch purposes exist (dispatch/dispatch.go:42-43): keepalive.ping and cheapmodel.complete. Both are covered above.
  • config/config.go presets name claude-haiku-4-5 for extract_llm and the summarizers. [extract_llm_sweep] alone uses none of them.

One setup trap, found by the audit (not a model leak). On an Anthropic route forwarded to a relay (not anthropic.com), keepalive/relay.go:21 relayServesClaude holds a thread only if the model name contains claude, opus, sonnet or haiku. A GLM model is not pinged and the sweep never gets a thread to ask on, so the run tests nothing (and costs nothing). Set CONTEXT_GURU_KEEPALIVE_MODELS=glm (a word in the model name). TestANonClaudeModelOnARelayIsNotPingedUnlessNamed pins this.

Tests

  • TestEveryCallAfterASweepOnlyProxyOnANonClaudeModelCarriesTheRequestsModel (proxy): a sweep-only proxy, keep-alive on, model glm-5-test. The upstream records the model of every body. It fails on any model but the request's, or any name with claude. It requires the sweep question to have run.
  • TestThePingKeepsTheRequestsModelAndEveryOtherField (keepalive).
  • Mutations killed: the question rewrites the model to claude-haiku-4-5; the ping rewrites it.

Open questions

  • The weights (1.0 / 0.5 / 0.75), the cap (60) and the two billed ratios are first guesses, to be tuned in the owner's live test.
  • Wait cause is read off the request, not from the dashboard's stored data.
  • Decided by the owner (accumulation, 2026-10-27): the newer verdict always wins. After a refusal the next question offers the carried outputs again, so a carried drop is judged again with each question. Each batch of up to 12 candidates is judged independently, and a newer keep is accepted. A carried drop therefore survives only if the next question does not cover its output or also drops it. This is by design: "if they seem to be needed so be it".

Technical notes

  • Look-back proxy (limit). The gate counts the look-back from the first drop to MaxCachedIdx, the end of the cached prefix, as a stand-in for the previous request's last cache breakpoint. It does not read the real breakpoint positions of the previous request. That is acceptable for now. If the real last breakpoint sits earlier than MaxCachedIdx, a drop the gate calls shallow may in fact be deep, and the gate then under-counts the rewrite (leans toward accept). The live test shows it: every applied sweep records deep and the rewrite it assumed, to compare with the provider's measured cache write.

  • Two ratios (dash: the per-family token factor can over-credit a single removal (10% and 24% on 2 sweeps) #696). One shared billed/local ratio cancels out of saving > rewrite. The sides differ: a removed output is plain tool text, but the rewritten tail also holds what the local count misses (thinking blocks, tool calls, images, the fixed prompt). So removed tokens use min(family factor, billed/local), and the rewrite uses billed/local. A missing or implausible billed size refuses.

  • applyHeldFrom is the cold apply over a source interface. The cold source is the Store. The warm source is a memory map whose put of a spent answer is a no-op.

  • All deferred unlocks follow feat(sweep): apply the held answer on the next cold request, and book what it earns (#404 PR C) #695's pattern.

  • Three -race timing flakes, none from this change: in dash, insights tests (TestTheInsightsDocumentIsScopedToOneProject, TestAnUnknownProjectIsEmptyRatherThanEverything) hit a 10 s handler timeout in the full run and pass alone (13.8 s; already noted on feat(sweep): apply the held answer on the next cold request, and book what it earns (#404 PR C) #695); and once in proxy (TestALateFirstByteOnTheRealTransportNeverReachesTheClient); it passes alone and on rerun.

Rebased onto main ccb62c7 (includes #747, batching, and #757's CutFrac, which this PR had also added: main's copy is kept). The docs build (mkdocs build --strict) passes. Part of #491.

Note for the live test (important). max_ask_items is not a setting on main. #747 made 12 the batch size, a constant, and added max_ask_batches instead. The older max_ask_items setting that this PR used to carry is removed (#747 owns the batching). A config with max_ask_items: 40 (for example glm-diag-40.yaml) is now rejected, with a pointer to max_ask_batches. To sweep a long list, use max_ask_batches (default 4, at most 8): 12 x 8 = 96 outputs at most.

@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.310 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 273d9e5b8fa3 blocking

Verdict: blocking

Findings

  1. components/offload/extract_sweep_warm.go:594 — a warm question does not set the registry candidate's asked latch, so the keep-alive ping pays for the same question again
    • What fails: a thread asks a warm question, then goes idle. The keeper pings it. SweepPingSubstitute reads the same registry entry, whose asked flag is still false, so the ping asks the same conversation a second time and putHeld writes a second (store-side) answer for the same outputs. One extra model call per idle span that follows a warm question, and two held answers that can both wait at once (the warm one in memory, the ping one in the Store).
    • Proof: runWarmQuestion builds a fresh copy of the registry candidate (cand := &sweepPingCandidate{e: reg.e, ...} at extract_sweep_warm.go:594). The copy's asked is a zero atomic.Bool, and nothing writes reg.asked. ask flips only the copy it was given (cand.asked.CompareAndSwap at extract_sweep_ping.go:540). The ping side checks the registry candidate itself (cand.asked.Load() at extract_sweep_ping.go:395), so it reads false. The thread claim (ClaimThread/ClaimPing) rules out the two questions running at once, but not the same question being paid twice in sequence. The asked field's own comment (extract_sweep_ping.go:226) names exactly this as its purpose: "so a second ping ... [does not pay] for the same answer twice".
    • Fix: in runWarmQuestion, set the registry candidate's latch when the warm question takes the copy (for example reg.asked.Store(true) under sweepPingMu next to the read, before the goroutine starts), so a later ping in the same idle span sends a plain ping. A test: hold a warm answer, then call SweepPingSubstitute for the thread and assert it declines with already_asked.

Non-blocking

  • extract_sweep_warm.go:102-113 — warmFor's eviction skips threads that are pending or asking, but not threads that hold a waiting answer. At 256 tracked threads, a thread's held answer can be evicted and lost silently: sweep_warm_held_expired does not count it, unlike age expiry. Fail-open (nothing is dropped), but the counter understates lost answers.
  • extract_sweep_warm.go:95-118 — when every entry is pending or asking, the eviction finds no victim and the map grows past maxWarmThreads. Bounded in practice by warmPendingMax (5 min), so transient.
  • extract_sweep_warm.go:427-441 (rewrittenAfter) — the loop starts at first+1, so it omits the marker bytes that replace the output at first itself, which the provider also rewrites. The rewrite is undercounted by one descriptor, so the gate is slightly more permissive. Small, but it points the wrong way for a gate whose stated bias is "refuse".
  • extract_sweep_warm.go:620-654 (askWarm) — when collection returns nothing or falls below min_inventory, the function returns without bumping rep.Gates or any counter. The ping path counts sweep_ping_no_inventory and bumps its gates (extract_sweep_ping.go:422-431); the warm path's early exits are invisible in /stats.
  • extract_sweep_ping.go:563-565 — the warm question's ask is labeled trigger: "ping" with the ping's gateReason, so the ask ledger and dump mislabel warm questions. Related: ask folds the warm question's gates into the ping's sweep_ping_gates counters (bumpSweepPingGates), so the two paths' gates are not told apart.
  • keepalive/keeper.go (sweepWarmStats) — the "did anything happen" test omits Panics, HeldExpired, Failed, ThreadBusy and ConcurrencyFull. A run where only those moved reports no sweep_warm block at all. Marginal, since each of those normally implies a counted predecessor.
  • dash/event.go:886-898 (sweepWarmRewriteUSD) — when the provider's CacheWrite is the smaller number, the whole row's cache-write is charged to the sweep, including the fresh suffix the request would have written anyway. Over-charges the sweep's rewrite; the direction is conservative (under-claims the saving), so noted only.
  • extract_sweep_warm.go:448 — _ = raw is a dead assignment; raw is never used after it. Leftover.

What I checked

  • Read the full diff (19 files, +2177/−56) and the code around every change: extract_sweep_warm.go in full, extract_sweep_apply.go (applyHeldFrom, NoteSweepExpand, scanReferences), extract_sweep_ping.go (registerPing, snapshotCandidate, collect, ask, SweepPingSubstitute), ping_claim.go (ClaimThread vs ClaimPing), keepalive/keeper.go stats wiring, dash/ (event pricing, schema migration, query/scan/insert column plumbing, SweepLedgerFor), proxy/proxy.go (ResolveWarmQuestion call site in the terminal defer), internal/extract/adjudicate.go, and both new test files.
  • Traced the warm state machine: trigger cadence (warm_every_n, cold reset), warmWorthAsking (upper-bound economics), the question after the forward (registry copy, thread claim, slots), the memory-only hold (warmHold/memHeld, 30-minute age), and the apply path (applyHeldFrom with warmGated: claim, recheck, gate, apply, panic restore). Verified the changed-prefix and cold-request cases route to the cold apply's own behavior with no gate, as the tests claim.
  • Verified the gate arithmetic (warmEcon, warmRatios, agentRates, cachedEnd, rewrittenAfter) and the refusal direction of every bound (maxBilledRatio, missing billed size, Turns weighting).
  • Verified no Store write carries the waiting answer (the memHeld source never touches the Store) and that fail-open holds: panics in the trigger, the apply and the question goroutine each recover with the request unchanged, and the apply's own panic restore gives the answer back.
  • Verified the dash column is additive (additiveColumns, default 0), the insert/scan counts match (35 placeholders ↔ 35 args), and old rows re-price unchanged (no sweep_applied_warm event on them). Checked that a row with sweep_applied_warm cannot also carry cold or changed-prefix sweep drops, so the read-rate credit and rewrite charge apply only to pure warm-apply rows.
  • Checked the data-dependence row and the recorded 2026-10-26 approval, and that /stats changes are additive only.
  • Did not run builds or tests (not approved on this machine); all conclusions are from reading the code.

@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.310 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 273d9e5b8fa3 approve

Verdict: approve

Findings

None. I found no wrong behavior, no data loss, no broken fail-open path, and no missing test for the new behavior.

Non-blocking

  • components/offload/extract_sweep_warm.go:448 — _ = raw is a dead assignment. raw is built at the top of warmStep and then discarded. The gate builds its own raw from applyHeldFrom. Delete the variable or use it.
  • keepalive/keeper.go (sweepWarmStats) — the nil test omits Panics. It checks Fired, Asked, GateAccept, GateRefuse, NotWorth, NoBilled, NotRegistered. A warm path that only panicked (for example the trigger-panic case the fail-open test produces) returns nil, so /stats shows nothing. Add Panics (and Held, Failed) to the test.
  • components/offload/extract_sweep_warm.go:95 (warmFor) — the bound can be exceeded. When every entry is pending or asking, no entry is evicted and the new one is inserted anyway, so warmThreads can pass maxWarmThreads. The growth is bounded by warmPendingMax (5 minutes) and by real traffic (each thread needs warm_every_n warm requests first), so I do not call it a defect.
  • components/offload/extract_sweep_warm.go:594 — a ping can repeat a warm question. runWarmQuestion builds a new sweepPingCandidate; it does not share the registry entry's asked flag. So a ping that falls due right after a warm question asks about the same conversation again. Cost: one extra answer per idle transition. The two answers do not conflict (the apply skips already-dropped outputs through HasPlaceholder).
  • components/offload/extract_sweep_ping.go:577 — warm-question gates land in the ping's counters. ask books its gates through bumpSweepPingGates, so keepalive.sweep_gates mixes ping and warm questions. Also, a warm collection that finds no candidates leaves no warm counter (the ping side counts no_inventory).
  • components/offload/extract_sweep_warm.go:350 (rewrittenAfter) — the rewrite omits the first message's own descriptor. The loop starts at first+1, so the descriptor that replaces the first dropped output is not counted. A small bias toward accept, against the stated "every doubt refuses" direction.
  • components/offload/extract_sweep_warm.go:142 — Held is documented as "answers now waiting", but it is cumulative. Nothing decrements it on apply, refusal or expiry. Same shape as the ping's sweep_held, so consistent, but the comment misleads.

What I checked

  • Read CLAUDE.md, docs/design.md, and the full diff of all 19 files: the warm step, the gate, the memory-held source, the ping changes, the apply changes, the dash schema, queries and pricing, the keeper stats, the proxy wiring, and both test files.
  • Fail open. Traced every failure path: a panic in the trigger (warmStep recover), a panic in the apply (applyHeldFrom restore and tombstones), a store that cannot stash (decline), a restart (answer lost, nothing dropped), a gate refusal (answer dropped, request unchanged), a host that never resolves (5-minute pending expiry). Each reverts the warm path only. The tests pin each one.
  • The economic gate. Checked the arithmetic (saving = removed x content ratio x read x turns; rewrite = rewritten x full ratio x write-minus-read), the ratio pairing (PrevBilledInput of the previous request against lastLocal of the same request), the bounds (maxBilledRatio, warmMaxTurns, weights), and the refusal direction of every doubt. The gate runs after the recheck and before the first message change, so a refusal touches nothing.
  • H1 and byte stability. A warm apply rewrites the prefix once, behind the gate; later requests replay the same bytes through replayDrops. Verified against the agent-raw versus pipeline-copy distinction: changePoint and buildHeld both use the agent's RawInput, so the warm apply's markers cannot fake a changed prefix for a store-held ping answer (I checked this because it looked like a real defect; it is not).
  • Concurrency. Checked warmMu/sweepPingMu/pingGuardMu lock orders (no reverse order exists), the claim-then-apply exclusivity, the asking/warmPending guards, the thread-claim exclusion with pings (ClaimThread shares pingGuardBusy), the slot handling (collect and ask each hold a slot, same as the ping), and eviction skipping asking threads.
  • Memory-only rule. The waiting answer lives in warmThreads only; memHeld.put never touches the Store; the test asserts no cg:swh: write and no answer payload in any Store write. Drop records and stashes are the same metadata-plus-stash shape as a cold drop.
  • Data dependence. docs/data-dependence.md row updated, with the 2026-10-26 approval recorded in the row's "Decided by" column.
  • Dash. Counted the insert columns against the placeholders (81 and 81); checked the additive migration, the read-rate credit for warm drops, the rewrite charge with the provider's own write as the cap, and the warm false-drop rate arithmetic (references plus expands over applied warm). The dash tests cover the credit, the charge, the rate and the migration.
  • Config. warm defaults to false, is in no preset, and the three knobs have safe defaults and Min: 1 validation.
  • I did not run builds or tests (not approved for this review); this is a code-reading review.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

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

R1-1 (blocking, reviewer 2 also): the warm question did not latch the registry candidate. Fixed.

  • runWarmQuestion now sets the registry candidate's asked latch under sweepPingMu, before the goroutine starts. A ping in the same idle span declines with already_asked.
  • The other way round: a ping answer held in the Store stops a warm question (already_asked counted). This also holds after a new request re-registers the thread with a fresh latch.
  • A warm question that never reached the provider (thread busy, slots full, model declined, no inventory) gives the latch back, so the ping may still ask.
  • Tests: TestAWarmQuestionStopsThePingFromAskingTheSameConversationAgain, TestAHeldPingAnswerStopsAWarmQuestionOnTheSameThread, TestAPingAnswerStillInTheStoreStopsAWarmQuestionAfterAReRegistration, TestAWarmQuestionThatNeverAskedLeavesThePingFree. Mutations killed: latch not set, held ping answer ignored, latch not given back.

Non-blocking, all fixed

  1. rewrittenAfter now starts at the first removed output and counts its replacement. TestTheRewriteCountsTheFirstRemovedOutputsOwnReplacement; mutation (start at first+1) killed.
  2. warmFor never evicts a thread that holds a waiting answer. When no thread can be evicted, the new thread is refused and counted (threads_full). The table never passes 256. TestAThreadWithAWaitingAnswerIsNeverEvictedAndTheTableStaysBounded; mutations (evict held, grow past the bound) killed.
  3. askWarm early exits are counted: no_inventory, with the collection's gates. TestWarmQuestionGatesAndLabelAreTheWarmPathsOwn; mutation killed.
  4. The ask is labeled trigger: "warm" with its own gateReason. Its gates go to a warm counter (keepalive.sweep_warm.gates), not sweep_ping_gates. Same test; mutation killed.
  5. The /stats "anything happened" test is now SweepWarmStats.Any() and covers every counter, including Panics, HeldExpired, Failed, ThreadBusy, ConcurrencyFull, Held. TestTheWarmStatsBlockShowsAnythingThatHappened; mutation killed.
  6. The comment on Held now says cumulative.
  7. The dead _ = raw and its raw variable are removed.

Left on purpose: sweepWarmRewriteUSD over-charges the rewrite when the provider's CacheWrite is smaller than the estimate. It errs on the conservative side: the dashboard under-claims the saving, never over-claims it. The provider's number includes the fresh suffix the request would have written anyway, and splitting that needs a per-message cache breakdown that the provider does not report. Not worth a guess that could lean the other way.

Tests on box 1 (head 0f12466b, -count=1, foreground): vet and gofmt clean; all packages pass. -race passes on offload, keepalive, config, components/all and proxy. In dash, a full -race run hits the known 10 s insights handler timeout (TestTheInsightsDocumentIsScopedToOneProject); it passes alone (13.8 s) and is noted on #695.

@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.310 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 0f12466b5bab approve

Verdict: approve

Findings

None. The round-1 blocking finding is fixed correctly, and the fix introduces no new defect I can show.

Earlier findings

Mine, round 1

  1. Blocking — the warm question did not set the registry candidate's asked latch. Fixed. runWarmQuestion now latches reg.asked under sweepPingMu before the goroutine starts (extract_sweep_warm.go:652-655), so SweepPingSubstitute declines with already_asked. The fix also closes the reverse direction I did not raise: a ping answer still waiting in the Store stops a warm question (extract_sweep_warm.go:666-671), which holds after a re-registration too. A question that never reached the provider gives the latch back (askWarm returns whether it asked; extract_sweep_warm.go:685-687). I traced each path: busy thread, slots full, model declined, no inventory all return false and unlatch; a sent question keeps the latch, which matches the ping's own policy after a failure. The give-back writes the detached reg object, so a registry entry replaced by a newer request is untouched. A panicking question keeps the latch — the same choice the ping path makes on panic (extract_sweep_ping.go:386), so consistent.
    2-8. Non-blocking — all fixed: rewrittenAfter now starts at first and subtracts removals at idx >= first, so the first output's descriptor counts; warmFor skips threads that hold an answer, refuses and counts a new thread when no victim exists (threads_full), and every caller handles the nil return; askWarm counts no_inventory and bumps the warm gates; the ask is labeled trigger: "warm" with its own gate reason, and warm gates go to keepalive.sweep_warm.gates through the new bumpSweepWarmGates; the /stats visibility test is SweepWarmStats.Any(), which covers every counter plus the gates map; the Held comment says cumulative; _ = raw and its variable are gone.

Reviewer 2, round 1 — no blocking findings. Their non-blocking list overlaps mine (dead assignment, Panics missing from the nil test, the bound, the repeated question, gate mixing, the first descriptor, the Held comment); I checked each fix myself as above. Their item on the nil test is fixed more completely than either of us asked: Any() covers all counters.

Rejected by the author, with a reason I accept: sweepWarmRewriteUSD charging the whole row CacheWrite when it is the smaller number. The reason: the error direction under-claims the saving, the provider reports no per-message cache breakdown, and any split would be a guess that could lean the other way. The reason is right — a fabricated split is worse than a conservative over-charge, and the direction agrees with the design's stated bias.

Non-blocking

  • warmHold (extract_sweep_warm.go:225-232) can silently drop an answer when the table is full of threads that all hold one, but sweepWarmHeld was already incremented by the caller in ask — /stats would count a phantom held answer. Needs 256 threads all holding answers at once, so marginal; threads_full fires in the same state and shows the pressure.
  • The warm-question lock order improved as a side effect (warmMu is now released before sweepPingMu is taken in runWarmQuestion); no path takes them in the reverse order, so no deadlock. Noted because the round-1 code held both.

What I checked

  • Last review: round 1, 273d9e5, 2026-10-25T23:44:01Z
  • New commits read: 1 — 0f12466b "fix(sweep): a warm question latches the registry, and review round 1 fixes (#491)" (4 files, +319/−47)
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review: reviewer 2's round-1 review (approve, 2026-10-25T23:45:33Z) — read in full, its non-blocking items checked against the fix; the author's round-1 reply (2026-10-26T00:29:32Z) — every claim in it checked against the code, including the two I could have disputed (the latch give-back semantics and the rejected sweepWarmRewriteUSD item).
  • Read the full diff 273d9e5b..HEAD and the changed code around it: runWarmQuestion's latch, release closure and store-held check; askWarm's new return value and counted early exits; warmFor's eviction and nil return with every caller (warmStep, warmHold, registerWarm); rewrittenAfter's new bounds; ask's warm labeling and gate routing; SweepWarmStats.Any, bumpSweepWarmGates, copyWarmGates, resetWarmForTest; the keeper's /stats wiring (additive fields only).
  • Checked the latch for races: the CAS runs under sweepPingMu before the goroutine; the give-back writes only the detached reg; release clears asking on the same thread object (an asking thread can no longer be evicted, so the map entry cannot have been reused); a registry entry replaced mid-question belongs to a newer conversation, so a later ping asking it is not a duplicate.
  • Checked warmFor's nil return cannot break the round-1 guarantees: warmStep returns before touching state, registerWarm declines, warmHold fails open (the waiting answer is lost, nothing is dropped), and the hasHeld and trigger blocks guard the reset.
  • Verified the new tests match the behavior they claim: latch set and ping declined, store-held stops the warm question including after re-registration, unasked latch returned, first-descriptor rewrite, bounded table with a held thread kept, warm gates and label, Any() coverage.
  • Did not run builds or tests (not approved on this machine); the author reports vet, gofmt, all packages and -race on the changed packages passing on the box, with one known unrelated dash timeout noted on #695.

@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.310 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 0f12466b5bab approve

Verdict: approve

Earlier findings

Reviewer 1, finding 1 (blocking) — the warm question did not latch the registry candidate. Fixed.

  • runWarmQuestion now takes the latch under sweepPingMu, before the goroutine starts (reg.asked.CompareAndSwap(false, true)). A ping in the same idle span reads the same registry entry and declines with already_asked.
  • The other direction is closed too: a ping answer held in the Store stops a warm question (getHeld check, already_asked counted). The check runs after sweepPingMu is released, so it adds no lock order.
  • The latch is given back only when no question was paid for: thread busy, slots full, model declined, no inventory, or ask's own "nothing left the process" branch. A dispatched question keeps it, also on a failed answer. That matches the comment, and it errs toward not paying twice.
  • Four new tests pin it, including the re-registration case (a fresh latch must still respect a Store-held answer). I traced each path in the code; the tests match the behavior.

Reviewer 1, non-blocking — all fixed except one, see below.

  1. warmFor evicting a held answer: fixed. Eviction now skips threads that hold an answer. When no thread can be evicted, the new thread is refused and counted (threads_full). The table never passes 256.
  2. The map growing past the bound: fixed, same change.
  3. rewrittenAfter omitting the first removed output's replacement: fixed. The loop starts at first and the others bound is >= first. Both call sites pass the first removal inside others, so the net count for the first output is its descriptor. The rewrite now leans the gate's way (refuse), not against it.
  4. askWarm early exits invisible: fixed. no_inventory is counted, and the empty-collection case bumps the warm gates map, the same split as the ping side.
  5. Warm questions labeled trigger: "ping" and booked in the ping's gate counters: fixed. The ask is labeled trigger: "warm" with its own gateReason, and its gates go to keepalive.sweep_warm.gates through bumpSweepWarmGates.
  6. The /stats nil test omitting counters: fixed. SweepWarmStats.Any() sums every counter and checks the gates map; sweepWarmStats uses it. The keeper struct adds threads_full, already_asked, no_inventory and gates, all additive.
  7. sweepWarmRewriteUSD over-charging when the provider's CacheWrite is smaller: rejected, and I accept the rejection. The error direction is conservative: the dashboard under-claims the saving, never over-claims it. The provider's number includes the fresh suffix the request would have written anyway, and splitting it needs a per-message cache breakdown the provider does not report. A guess could lean the other way. Not worth it.
  8. The dead _ = raw: fixed. The variable and the assignment are gone.

My round-1 non-blocking notes — all fixed by the same changes. The dead assignment (note 1), the nil test (2), the bound (3), the repeated question (4, same root as reviewer 1's finding 1), the mixed gates and missing no_inventory (5), the first descriptor (6), and the Held comment, which now says cumulative (7).

Findings

None. I found no wrong behavior and no new defect in the fix commit.

Non-blocking

  • components/offload/extract_sweep_warm.go (warmHold) — a paid answer lost at a full table shows only as threads_full. When every entry holds an answer, warmFor returns nil and warmHold returns, so an answer the model was already paid for is dropped. threads_full counts it, but that counter also counts plain tracking refusals, so the lost answer is not told apart from them. Fail-open either way: nothing is dropped, the request is unchanged.

What I checked

  • Last review: round 1, 273d9e5b8fa3cbf5b1451ed00dfa474e1ccbf665, 2026-10-25T23:45:33Z.

  • New commits read: 1 — 0f12466b "fix(sweep): a warm question latches the registry, and review round 1 fixes (#491)". Full diff read.

  • Read in full: 2 reviews, 1 comment, 0 inline comments. The inline list is empty.

  • New items since my last review: the author's fix-summary comment (every claim checked against the code, see above) and the fix commit itself.

  • The latch. Traced runWarmQuestion end to end: the CAS under sweepPingMu, the reg == nil and latched early exits, the getHeld Store check (nil Store safe, no lock held), and the goroutine's give-back. Checked the give-back against ask's own branches: a slots-full or nothing-left-the-process ask leaves the copy's asked false, so the registry latch is returned; a dispatched ask keeps it. Checked the races: reg is a pointer into the registry map, and a re-registration replaces the entry — a give-back then writes the stale entry only, and the fresh entry starts unlatched, so no ping is wrongly blocked or wrongly charged. A panic inside ask keeps the latch, the same as the ping path's panic recovery.

  • The eviction. Re-read warmFor, warmHold, warmStep and registerWarm with the nil returns. Every caller checks nil. A thread refused tracking simply gets no warm behavior; the request is unchanged.

  • The gate arithmetic. Re-checked rewrittenAfter at both call sites (warmWorthAsking and the gate proper): both build others with the first removal included, so the new >= bound is consistent. The rewrite is now larger by one descriptor, in the refuse direction.

  • The counters. Checked bumpSweepWarmGates/copyWarmGates locking, resetWarmForTest covering the three new counters and the gates map, and the keeper wiring (Any(), the new JSON fields, additive).

  • The author's test claims. Read the seven new tests. Each matches the behavior I verified in the code. I did not run them (tests are not approved for this review), so the "mutations killed" claims rest on the author's runs on box 1.

  • Did not run builds or tests; this is a code-reading review.

@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.310 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 3 ffaba1870590 approve

Verdict: approve

Earlier findings

All round-1 and round-2 items stay fixed after the rebase. The PR was rebased onto the new base 56f59a7 (the #724 and #725 fixes), and the warm-path series became one commit, b1e7d99, with the review fixes folded in. I re-checked each fix at HEAD:

  • The registry latch (round 1, blocking): the CAS under sweepPingMu, the Store-held stop, and the give-back are all present (extract_sweep_warm.go:789-821).
  • The held-thread eviction skip, the threads_full refusal, the warm gate counters, trigger: "warm", and SweepWarmStats.Any() are all present.
  • The first-descriptor rewrite (round 1, non-blocking) survives inside warmRewrite, which replaces rewrittenAfter: the loop starts at the drop and the subtraction bound includes it, so the first output's replacement still counts.

Reviewer 1, round 2, non-blocking — the phantom sweep_warm_held when warmHold refuses at a full table. Agree with reviewer 1; still open, and I have nothing to add. It needs 256 threads all holding answers, threads_full fires in the same state, and nothing is dropped. Non-blocking.

Rejected with a reason I accept (round 2): sweepWarmRewriteUSD charging the whole row CacheWrite when it is the smaller number. Unchanged, and the reason still holds.

Findings

None. I found no wrong behavior and no new defect in the two new commits.

Non-blocking

  • components/offload/extract_sweep_warm.go (warmWorthAsking) — the comment says "at the heaviest weight", but the trigger applies no wait-cause weight. Turns is the capped run count only; the weight lives in the gate's warmTurns. The unweighted trigger can refuse where the gate would accept, which is the safe direction, but the comment made me trace the code for a weight that is not there. Fix the comment.
  • No test-run report for the new heads. The last box-1 report in the PR conversation covers 0f12466b. Nothing covers 74c7cf8 and ffaba187. The author should run the suite and post the result before merge.

What I checked

  • Last review: round 2, 0f12466b5babfce24e0c013a014e44d50fcc7c91, 2026-10-26T00:35:10Z.

  • New commits read: 2 new since my last review — 74c7cf8 "fix(sweep): the warm gate prices the rewrite the way the provider reads the cache (#491)" and ffaba187 "feat(sweep): warm_gate_price_model, a diagnostic price for the warm gate (#491)". Full diffs read. The PR was also rebased onto a new base: git log --stat 0f12466b..HEAD lists 5 commits; 65485b8 (#724) and 56f59a7 (#725) are the new base, and b1e7d99 is the warm series with rounds 1-2 folded in. I read the rebase adaptation diff (0f12466b..b1e7d99) for the warm-path files in full.

  • Read in full: 4 reviews, 1 comment, 0 inline comments (the inline list is empty).

  • New items since my last review: reviewer 1's round-2 review (approve, 2026-10-26T00:33:11Z) — read, its two non-blocking notes checked; the rebase — every round-1/round-2 fix re-verified at HEAD (see above); the two new commits — reviewed as a first review below.

  • The rebase onto #725. The ask's cache judgment moved to prefixAskCacheOK (read the whole gate file): a read of zero, or a read below the turn's own read, refuses; a write alone refuses nothing. The warm path passes the turn's usage.CacheRead from the proxy through ResolveWarmQuestion into SweepPingWait.LastTurnRead, and ask feeds it to adjudicateWith. A lastTurnRead of 0 means unknown, so a failed forward or a missing usage cannot refuse a good question. The keeper fills the same field for the ping path from kaEntry.turnRead.

  • The rebase onto #721. carriesRealMarker replaces expand.HasPlaceholder in the candidate scan, the cold apply and the replay, so an output that only quotes marker syntax is still dropped. A real marker is skipped and counted (sweep_apply_already_marked). Checked the Store-nil case: it keeps the old safe answer.

  • 74c7cf8, the rewrite model. warmRewrite counts blocks from the first drop to the cached end. More than warmLookbackBlocks (20) makes the drop deep: the rewrite is the whole conversation from index 0, minus every removal, plus the first drop's replacement. Within the look-back it is the tail from the drop. Both call sites (the trigger and the gate) pass the first removal inside others, so the subtraction is consistent. A deep refusal is told apart (does_not_pay_deep). The model errs toward refuse: a deep drop prices a larger rewrite.

  • 74c7cf8, the mass gate. The trigger now asks only when the removable mass is at least warm_min_mass_frac (default 0.20, a value outside (0,1] reads as the default) of the conversation. Every trigger refusal is counted by reason (no_billed_size, no_candidate, below_mass, does_not_pay). The trigger's expected turns changed from the full cap to the run so far, capped — more conservative early in a thread's run, and the gate still uses its own weighted turns.

  • 74c7cf8, the records. noteWarmSweep runs only inside the applied-drops block and only when the warm gate passed, under the gate mutex, capped at 50. The thread label is a hash, not a session id. convBefore is taken before the recheck changes anything. The new events (sweep_warm_removed_tokens, sweep_warm_expected_turns, sweep_warm_deep) are additive; the dashboard reason text was updated for them.

  • ffaba187, the price model. warmGateRates copies the Ctx and swaps SelfRates, so the request's own rates are never mutated (the test pins this). An unknown model falls back to the built-in rates — agentRates(nil) is nil-safe — and is counted. The setting is a string field, unset by default, in no preset, logged once as a warning, and shown in /stats (gate_price_model), so a diagnostic run is visible. Any() treats it as activity, which is the point. The missing-cache_write case is a billed-size question, not a rates question, and the test pins that a missing write is not no_billed_size.

  • The keeper wiring. TriggerRefusals, Recent, GatePriceModel and PriceModelUnknown are additive JSON fields; sweepWarmStats copies them from SweepWarmCounters. The struct's mixed field alignment follows gofmt's comment-split groups, the same pattern as the pre-existing fields.

  • The data-dependence row. The rebase briefly dropped the "warm path approved 2026-10-26 (#491)" note from the row's Decided-by column; 74c7cf8 restored it. The row at HEAD is correct, and the new warmRecent records are numbers only (hash label, counts, dollars), so the row's memory-only claim still holds.

  • Did not run builds or tests (not approved for this review); this is a code-reading review.

@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.310 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 3 ffaba1870590 blocking

Verdict: blocking

The author rewrote the history: the PR is now three commits rebased onto a new base 56f59a7f (which brings #724 and #725 in). Two commits add real new behavior: the deep-drop rewrite model with the mass gate (74c7cf8b), and the warm_gate_price_model diagnostic (ffaba187). I read every new line. The logic is sound. But the branch fails its own lint gate.

Findings

  1. keepalive/keeper.go:1737-1743 — the new SweepWarmStats fields are not gofmt-formatted, so make lint fails and CI goes red
    • What fails: gofmt -l . lists keepalive/keeper.go. The Makefile's lint target runs exactly that and exits 1 (Makefile:54-56). CI runs make lint (.github/workflows/ci.yaml:38). The branch cannot pass its own checks.
    • Proof: the fields GatePriceModel, PriceModelUnknown, Recent and the re-padded GateAccept…Panics sit in one unbroken run of struct field lines (no blank line, no comment between them). gofmt aligns such a run to uniform columns. The actual bytes are not uniform: the name column is 18 (GatePriceModel string), 17 (PriceModelUnknown int64), then 16 for the five lines after; the tag column swings the same way (string json…`` with one space, int64 with two, then fifteen). I checked the bytes with `cat -t`: the padding is spaces, and the columns differ. Two references in the same file show what gofmt does produce: the same struct at `0f12466b` (which the author reported gofmt-clean) is uniform, and `SweepDropStats` at 1760-1776 re-aligns after each comment line, uniformly within each comment-free run. There is no tabwriter setting that yields non-uniform padding inside one run, so gofmt rewrites this block.
    • Why it went unseen: the author's reported test run (vet, gofmt, all packages, -race) covers head 0f12466b only. No comment or report covers the three new commits. I could not run gofmt myself (Go is not installed on this machine); the byte evidence above is the proof.
    • Fix: run make fmt (or gofmt -w keepalive/keeper.go) and push. Nothing else in the finding.

Earlier findings

Mine, rounds 1 and 2

  • Round 1 blocking (the asked latch) — fixed at 0f12466b, and the rebase keeps it. The delta since 0f12466b touches runWarmQuestion only to pass turnRead through; the latch, the give-back, and the store-held check are byte-for-byte the code I approved.
  • Round 1 non-blocking 2-8 — all still fixed. rewrittenAfter became warmRewrite (see below) and keeps the round-2 bounds: the loop starts at the first drop (or at 0 when deep), and every removal at idx >= start is subtracted, so the first output's own replacement counts. warmFor, the warm counters, the warm ask label and gates, Any(), the cumulative Held comment: unchanged.
  • Round 2 non-blocking (the phantom Held when warmHold drops a paid answer at a full table) — still open, still non-blocking. warmHold and the sweepWarmHeld.Add(1) after it are unchanged. Needs 256 threads all holding answers; threads_full fires in the same state.

Reviewer 2

  • Round 2 (approve, 2026-10-26T00:35:10Z, after my round-2 post) — read in full. No findings. Their one non-blocking item (a lost paid answer shows only as threads_full) is the same root as my round-2 note above; same status.
  • Their round-1 items — all fixed at 0f12466b, unchanged by the rebase.

Rejected by the author, reason still accepted: sweepWarmRewriteUSD charging the whole row CacheWrite. The code and the reason are unchanged since round 2.

The new commits, reviewed as a first review

  • The deep rewrite model (74c7cf8b). warmRewrite counts the content blocks from the first drop to the last breakpoint. More than warmLookbackBlocks (20) means deep: the provider can reach no entry after the fixed part, so the rewrite is the whole conversation from index 0. The model is refuse-biased (a deep drop costs more), matches the recorded evidence cited in the comment, and both call sites (the trigger and the gate) pass the same removal list. does_not_pay_deep is a refusal reason only; a deep drop that still pays is accepted. Tests pin deep, shallow, and the gate's refusal of a case the old model accepted.
  • The mass gate. warm_min_mass_frac (default 0.20, values outside (0,1] read as the default, off does not apply — it gates only the warm path). It runs after the candidate scan and before the rates, in the refuse direction, counted as below_mass. Tested at a refusing share and at the default.
  • The trigger's expected turns are now the thread's warm run so far, capped at warm_max_turns, unweighted. The weights are 0.5-1.0, so unweighted stays the upper bound; the trigger remains the optimistic test. Tested with a tail calibrated to pay at 60 turns and not at 3.
  • Trigger refusal reasons (TriggerReasons) are counted under sweepWarmGateMu, copied in SweepWarmCounters, reset in resetWarmForTest, and additive in /stats. Every refusal path in warmWorthAsking notes its reason.
  • Per-sweep records (WarmSweep). Booked in applyHeldFrom only inside the len(pending) > 0 block, so a refused or empty apply leaves no record. convBefore is read before the recheck (which mutates nothing), convAfter after the drops. Bounded at 50, locked, thread label is a hash (the test asserts no session id). Additive /stats fields.
  • warm_gate_price_model (ffaba187). Off by default, in no preset (I grepped: nothing outside the component references it). Only warmGateRates uses it; it copies the Ctx and sets SelfRates on the copy, so the request's own rates — what the dashboard prices with — are untouched (tested). An unknown model falls back to the built-in rates and counts price_model_unknown. It is logged once and shown as gate_price_model, so such a run is visible. Any() covers the new fields.
  • The warm question's cache rule. The proxy passes this request's usage.CacheRead (int64, so the conversion is safe) through ResolveWarmQuestion into SweepPingWait.LastTurnRead; the ping side gets the same field from the keeper's kaEntry.turnRead. Both land in askOpts.lastTurnRead and are judged by prefixAskCacheOK — the one rule from #725. A read of 0 always refuses; a read below the turn's read refuses; unknown (0) applies the zero rule only. The warm path adds no write check of its own, as the commit says.
  • carriesRealMarker in the cold apply and the replay, matching the ping's candidate scan. A quoted marker applies (and replays byte-identically, tested); a real marker is skipped and counted (sweep_apply_already_marked). The Store read is presence-only, and docs/data-dependence.md says so.
  • Dash. The three new EventN names flow through the existing generic events path; sweep_warm_rewrite_tokens already round-trips the same way. app.js adds their labels. Additive only.
  • Fail-open. No new early return mutates the request before the gate's refusal point. The gate refusal path, the trigger refusals, and the diagnostic fallback each leave the request unchanged. The panic restores are untouched.

Non-blocking

  • warmWorthAsking (extract_sweep_warm.go:635) still skips outputs with expand.HasPlaceholder, while collect uses carriesRealMarker. An output that only quotes marker text counts at the question but not in the trigger's mass and econ test. The direction is conservative (the trigger asks less), so a note only.
  • The round-2 phantom-Held note stays open (see Earlier findings).

What I checked

  • Last review: round 2, 0f12466b5babfce24e0c013a014e44d50fcc7c91, 2026-10-26T00:33:11Z
  • New commits read: 5 — the range crosses the rebase, so it holds the PR's three (ffaba187 "feat(sweep): warm_gate_price_model, a diagnostic price for the warm gate (#491)", 74c7cf8b "fix(sweep): the warm gate prices the rewrite the way the provider reads the cache (#491)", b1e7d99a "feat(sweep): the warm path, an economic gate on a held answer (#491)") and the two new base commits (56f59a7f #725, 65485b86 #724). I read the base commits for their interaction with the warm path (the prefixAskCacheOK rule and the deferral registry); their own behavior is main's, out of scope.
  • Read in full: 4 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review: reviewer 2's round-2 review (approve, 2026-10-26T00:35:10Z) — read in full; its one non-blocking item checked against the code (still open, same root as my round-2 note). No new author comment: the only comment (2026-10-26T00:29:32Z) predates my round-2 post, so the box results in it cover 0f12466b only, not the three new commits.
  • Read the full delta git diff 0f12466b..HEAD (2598 lines: the rebase's net change, including the #724/#725 base changes and all three PR commits) and the full-PR diff list against the new base (git diff --stat 56f59a7f..HEAD, 19 files — the same set I read in full in rounds 1 and 2; every line is either code I reviewed at 0f12466b or in the delta).
  • Verified the new hunks in their files: warmRewrite/contentBlocks, the mass gate, the trigger's turns and reasons, warmGateRates and the diagnostic's logging and /stats visibility, WarmSweep/noteWarmSweep placement and locking, resetWarmForTest coverage, ResolveWarmQuestion's new turnRead plumbing end to end (proxy usage.CacheRead → askWarm → SweepPingWait.LastTurnRead → askOpts → prefixAskCacheOK; and the ping side through kaEntry.turnRead and sweepWaitCause), carriesRealMarker at all three call sites, agentRates with a nil Ctx and with the copied Ctx, and the dash event flow.
  • Verified the gofmt finding at byte level (cat -t on the struct at HEAD, at 0f12466b, and on SweepDropStats and main's Ctx as references for what gofmt produces), and confirmed the gate: make lint runs gofmt -l . (Makefile:54-56) and CI runs make lint (ci.yaml:38).
  • Checked the new tests against the behavior they claim: deep and shallow rewrites, the gate refusing a deep drop the old model accepted, the mass gate at two shares, the setting's default, trigger reasons, the run-based turns estimate, the shared cache-read rule for warm and ping, the per-sweep record's fields and hashed thread, and the five price-model tests. I did not run them (tests are not approved on this machine), and no test run is reported for these three commits.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 3 notes, for head e4dd3ad5.

Blocking (reviewer 1): gofmt needed: keepalive/keeper.go. This was true of ffaba187. The fields I added to SweepWarmStats (GatePriceModel, PriceModelUnknown, Recent) were not aligned, and my earlier "gofmt clean" covered 0f12466b only. Fixed in b92fe988 (whitespace only). On this head, gofmt -l . over the whole repo prints nothing and make lint exits 0 on the eval box.

Reviewer 1: warmWorthAsking used expand.HasPlaceholder while collect uses carriesRealMarker. Fixed. The trigger now uses carriesRealMarker, so its mass test counts what the question would offer. Test: TestTheTriggerCountsAnOutputThatOnlyQuotesMarkerSyntaxAsRemovable (an output that only quotes marker syntax is removable; one that carries a real marker is not). Two mutations killed: the old rule back, and real markers ignored.

Comment "at the heaviest weight". Fixed. The trigger applies no wait-cause weight. The comment now says so, and that the weight is read off the request at the apply, where the gate uses it.

Reviewer 2's request for box results on this head. Eval box, -count=1, foreground, head e4dd3ad5:

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Follow-up for head e4dd3ad5: the warm_gate_price_model mutation checks were re-run on this exact tree. All 5 are killed: override ignored, request rates overwritten, unknown model not counted, override on when unset, stats hide the diagnostic.

@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.310 offload-review skill, @amiddavid's session resumed 2 of 2 4 of 4 e4dd3ad5248d approve

Verdict: approve

Earlier findings

Reviewer 1, round 3, finding 1 (blocking) — keeper.go was not gofmt-formatted at ffaba187. Fixed.

  • Fixed in b92fe988, whitespace only. At HEAD the whole SweepWarmStats run aligns to one column (TriggerRefusals after its comment, then GatePriceModel through Panics at a uniform name column). The author reports gofmt -l . prints nothing and make lint exits 0 on the eval box, for this head.
  • A correction to my own round-3 review: I wrote that the mixed alignment "follows gofmt's comment-split groups". That was wrong. Reviewer 1 proved it at byte level, and the author confirmed it. I could not run gofmt myself and guessed at the tabwriter's group rule; I should have flagged the uncertainty instead of explaining it away.

Reviewer 1, round 3, non-blocking — warmWorthAsking used expand.HasPlaceholder while collect uses carriesRealMarker. Fixed in e4dd3ad. The trigger's mass test now counts what the question would offer: an output that only quotes marker syntax is removable, one that really carries our marker is not. The new test pins both directions, with a real stash behind the marker for the second. The Store-nil case keeps the old safe answer, and warmStep requires a Store before the trigger runs, so the rule always has a Store to read.

My round-3 non-blocking — the stale "at the heaviest weight" comment. Fixed in e4dd3ad. The comment now says the trigger applies no wait-cause weight, and that the weight is read at the apply.

My round-3 non-blocking — no test-run report for the new heads. Answered. The author posted box results for e4dd3ad5: gofmt and lint clean, all packages pass (proxy 112 s, dash 96 s), -race on offload, keepalive, config, components/all and proxy, with the known dash insights timeout on #695 not repeated. The five warm_gate_price_model mutation checks were re-run on this exact tree.

Still open, non-blocking (reviewer 1, rounds 2 and 3): the phantom sweep_warm_held when warmHold refuses at a full table. Unchanged. I agree with reviewer 1's reading and add nothing.

Rejected with a reason I still accept: sweepWarmRewriteUSD charging the whole row CacheWrite. Unchanged.

Findings

None. I found no wrong behavior and no new defect in the new commit or the rebase.

Non-blocking

None new. The open phantom-Held note above is the only one left, and it is reviewer 1's.

What I checked

  • Last review: round 3, ffaba1870590c85918f387ae79bbd5d31168f4bf, 2026-10-26T09:44:11Z.

  • New commits read: 1 new — e4dd3ad "fix(sweep): the warm trigger uses the same marker rule as the question (#491)". Full diff read. The PR was also rebased again onto base 06b40ed (which brings #727 and the plugin bump); the round-3 commits were rewritten as d12e0bd, c6e2602c and b92fe988. I diffed each rewritten commit against its round-3 original: the differences are the #727 base files and, for b92fe988, the keeper.go gofmt realignment. No warm-path logic changed in the rewrite.

  • Read in full: 6 reviews, 3 comments, 0 inline comments (the inline list is empty). The first four reviews are the ones I read in full in rounds 2 and 3; their text is unchanged.

  • New items since my last review: reviewer 1's round-3 review (blocking, gofmt, 2026-10-26T09:50:48Z) — verified fixed, and my own round-3 claim about it corrected above; the author's two comments (2026-10-26T10:37:54Z and 10:39:25Z) — every claim checked against the code; the rebase; the new commit.

  • The rebase. The net diff ffaba187..HEAD on the warm-path files is exactly e4dd3ad's changes, the keeper struct realignment, and a base-only proxy stats line (CacheAnchorStats, #727). The new base touches cache_aware_summarizer, apply and expand; the warm path shares none of that code, and its own files are untouched by it.

  • e4dd3ad. One rule change and one comment fix. warmWorthAsking now calls carriesRealMarker(c, text) where it called expand.HasPlaceholder(text), and drops the now-unused expand import. The trigger and the question's candidate scan now agree, so the mass test cannot refuse a conversation the question would have offered. The direction of the old disagreement was conservative (the trigger asked less), so this is a correctness-of-measurement fix, not a fail-open change. The test covers both directions with the same quoted marker text, with and without a stash behind it.

  • The gofmt fix. Checked the struct bytes at HEAD: TriggerRefusals forms its own group after its comment, and the seven fields from GatePriceModel to Panics sit in one uniform run. This matches what gofmt produces for a comment-split group, and the author's box run confirms it.

  • Did not run builds or tests (not approved for this review); this is a code-reading review. The author's box results for this head cover the suite.

@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.310 offload-review skill, @amiddavid's session resumed 1 of 2 4 of 4 e4dd3ad5248d Approve

Verdict: approve

Both round-3 findings are fixed and verified at this head. The one new commit is correct. The two new base commits interact cleanly with the warm path. Nothing new is blocking.

Findings

None.

Earlier findings

Mine, round 3

  • Blocking: SweepWarmStats not gofmt-formatted — fixed in b92fe988, verified at e4dd3ad5. The comment-free run GatePriceModel…Panics now pads every name to column 18 and every type to column 20, and TriggerRefusals re-aligns to the Gates run above it. I checked the bytes with cat -t at this head. The fix is whitespace only; the fields and tags are unchanged. The author's box report (gofmt -l . empty, make lint exit 0) matches the bytes.
  • Non-blocking: the trigger used expand.HasPlaceholder while the question uses carriesRealMarker — fixed in e4dd3ad5, verified. See below.
  • Non-blocking: the "heaviest weight" comment — fixed in e4dd3ad5, verified. The comment now says the trigger applies no weight and that warmWeight is read at the apply, where the gate uses it. That matches the code: warmWorthAsking passes run unweighted, warmGate weighs it.

Mine, round 2

  • The phantom Held when warmHold drops a paid answer at a full table — still open, still non-blocking. warmHold and the sweepWarmHeld.Add(1) after it are unchanged. It needs 256 threads all holding answers, and threads_full fires in the same state.

Reviewer 2

  • Their round-3 review (approve, 2026-10-26T09:44:11Z) — read in full this round. Two non-blocking items, both now closed: the "heaviest weight" comment (fixed in e4dd3ad5) and the missing box report for the new heads (the author's 10:37:54Z comment reports gofmt, make lint, all packages, and -race on the changed packages at this exact head).
  • Their claim that the struct alignment "follows gofmt's comment-split groups" was wrong, and the fix in b92fe988 settles it. No action needed from them.

Rejected by the author, reason still accepted: sweepWarmRewriteUSD charging the whole row CacheWrite. The code is unchanged since round 2, and the reason still holds: it under-claims the saving, never over-claims it.

The new commits, reviewed as a first review

  • e4dd3ad5 — the warm trigger uses the same marker rule as the question. The trigger's candidate scan now calls carriesRealMarker(c, text) where it called expand.HasPlaceholder(text); the unused expand import is gone. The rule is the one already used by the question's scan, the cold apply, and the replay: no placeholder → not removable; a marker whose id is in the Store → removable is false; marker syntax that is only quoted → removable. The change closes the gap I noted in round 3: text that only quotes marker syntax now counts in the trigger's mass and econ test, exactly as it would count at the question. The direction of the old gap was conservative (ask less), and the new rule removes the divergence rather than flipping it.
    • The test (TestTheTriggerCountsAnOutputThatOnlyQuotesMarkerSyntaxAsRemovable) discriminates correctly. Both sides differ only in the marker rule: with no Store entry at the quoted id, all three tool outputs stay candidates and the trigger pays; with deadbeef… in the Store, all three are skipped and the trigger refuses with no candidate. I re-read carriesRealMarker at this head to confirm the Store lookup is the discriminator. The author reports both mutations killed on this tree (old rule back; real markers ignored), and the box run passes.
    • One line in the test's fixture closure takes a body parameter it never uses. Cosmetic; not worth a round.
  • b92fe988, c6e2602c, d12e0bd5 — the PR's three commits, rebased onto the new base. Content-identical to the three I reviewed in full in round 3 (ffaba187, 74c7cf8b, b1e7d99a), plus the gofmt whitespace in b92fe988. Proof: the full delta git diff ffaba187..HEAD touches the warm-path files only in the hunks above; there is no hidden conflict resolution.
  • 2b20ef29 (#727) and 06b40ed2 (#701) — new base commits, read for interaction. #701 is a version bump. #727 keeps and marks the last tool exchange after a cache_aware_summarizer splice (retreatPastLastToolExchange, CacheAnchorToolID, anchorCacheBreakpoint, the deferral dispatching counter, and the summary-header constants). None of it touches the sweep or warm-path files; the PR's own files change only as shown in e4dd3ad5. The one shared surface, proxy.go's stats handler, gains three additive apply.CacheAnchorStats() fields. No interaction defect found.

What I checked

  • Last review: round 3, ffaba1870590c85918f387ae79bbd5d31168f4bf, 2026-10-26T09:50:48Z
  • New commits read: 6 — e4dd3ad5 "fix(sweep): the warm trigger uses the same marker rule as the question (#491)", b92fe988 "feat(sweep): warm_gate_price_model, a diagnostic price for the warm gate (#491)" (rebased, gofmt fix folded in), c6e2602c "fix(sweep): the warm gate prices the rewrite the way the provider reads the cache (#491)" (rebased), d12e0bd5 "feat(sweep): the warm path, an economic gate on a held answer (#491)" (rebased), and the two new base commits 2b20ef29 "fix(offload): keep and mark the last tool exchange after a splice (#727)" and 06b40ed2 "chore(plugin): bump the plugins for v0.6.0 (Claude Code 0.6.0, Codex 0.2.5) (#701)"
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review: the author's two comments (2026-10-26T10:37:54Z and 10:39:25Z) — every claim checked against the code (gofmt bytes, the trigger rule, the comment, the box results). Reviewer 2's round-3 review (2026-10-26T09:44:11Z) was posted before my round-3 post but first read by me this round — both its items are closed as stated above.
  • Read the full delta git diff ffaba187..HEAD (1194 lines: the gofmt fix, the e4dd3ad5 trigger change and its test, and the two base commits) and confirmed the full-PR diff against the new base is the same 19-file set I read in full in rounds 1-3.
  • Verified the gofmt fix at byte level (cat -t on the struct at this head) and the gate it must pass (make lint → gofmt -l ., Makefile:54-56; CI runs make lint, ci.yaml:38). I could not run gofmt on this machine; the bytes and the author's box report agree.
  • Verified warmWorthAsking at this head (extract_sweep_warm.go:635-663): the carriesRealMarker call, the corrected comment, and the unused-import removal; and carriesRealMarker itself (extract_sweep_ping.go:674), unchanged from #725.
  • Checked the new test's two cases against carriesRealMarker's Store lookup, and the rig (newWarmRig, warmCfg: no warm_min_mass_frac, so the default 0.20 applies). I did not run it; the author's box report covers this exact head.
  • The author's 10:39:25Z comment re-ran the five warm_gate_price_model mutation checks on this tree; the code they cover is unchanged since round 3, where I read all five tests.

@amiddavid

amiddavid commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Box results for head 2b13baf5 (eval box 1, foreground, -count=1, on the head after the rebase onto main 3befbfb2):

What this head adds: max_ask_items, a record of every warm decision (accept or refuse), and the model audit ("Which model each call uses" in the PR body). Mutation checks on this head's changes: 19, all killed, including a question and a ping that rewrite the model. One caveat: a ping that rewrites the model was NOT caught by the end-to-end proxy test (the ping was not always sent in that run, because the sweep's question can stand in for it), so it is pinned by the unit test TestThePingKeepsTheRequestsModelAndEveryOtherField.

The audit finding to act on: a non-Claude model on a relay is not pinged unless named. Set CONTEXT_GURU_KEEPALIVE_MODELS=glm for the live run, or the sweep never gets a thread to ask on.

@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 5 of 7 2b13baf552cd Approve

Verdict: approve

The PR was rebased again, onto base 3befbfb2, and gained one new commit: 2b13baf5 (max_ask_items, a record of every warm decision, and a model audit). I read the new commit in full and checked the rebase. The behavior is sound and fail-open holds. Nothing blocking. Four small notes below.

Findings

None.

The new commit, reviewed as a first review

  • max_ask_items. A setting now (default 12, at most 64; below 1 reads as 12, above 64 as 64). The constructor clamps, and askItemsLimit clamps again at use, so a stale ExtractSweep cannot bypass it. collect caps the candidate list at it and keeps the largest outputs (stable sort by token count, sweep_over_ask_cap counts the rest). Tests cover the default, both clamps, the cap, and that the largest survive.
  • The reply budget. askReplyBudget(n) returns the flat 16,000 for n ≤ 12 and adds 224 tokens per verdict beyond 12, plus a 1,024 margin. It is set on the ask's context (cheapmodel.WithReplyBudget) inside adjudicateWith, so the ping question and the warm question both get it. Both clients honor it: Anthropic's CompletePrefixed and OpenAI's CompletePrefixedResponses call replyBudget(ctx, maxTok), which only raises, never lowers — the client's own default stays the floor. thinkingAdjustedMaxTokens runs after it, so a thinking agent's own max_tokens still caps the sum. A truncated reply keeps the old behavior: counted as sweep_reply_truncated, nothing held, nothing dropped. The wire test pins all four cases (default, scaled, thinking added on top, capped at the body's own limit).
  • Decision records (WarmDecision). warmWorthAsking and warmGate each record every exit, accepted or refused, through a deferred noteWarmDecision: D and R (local and billed), N, the weight, both ratios, deep, the two USD numbers, and the reason. Bounded at 50 under sweepWarmGateMu, reset in resetWarmForTest, copied in SweepWarmCounters, additive in /stats (recent_decisions). The thread is a hash label and the INFO log line carries numbers only — no content. I traced every return path in both functions: each refusal sets d.Reason, and the deferred record cannot be skipped. Tests cover an accepted and a refused apply, three trigger outcomes (accept, no_billed_size, below_mass), the 50 bound, and that the session id is not in the record.
  • Refused-apply events. A refused gate now books the decision's numbers on the row (sweep_warm_refused_*). Additive event names; app.js adds their labels; the generic EventN flow carries them.
  • Model audit. Two tests, no production change: a sweep-only proxy end to end on a non-Claude model (every upstream call must carry the request's model, no Claude name anywhere), and a unit test that the ping body keeps the model and every other field. The author's caveat — a non-Claude model on a relay is not pinged unless CONTEXT_GURU_KEEPALIVE_MODELS names it — is pinned by a second test, so the live run's setup is not a surprise. That caveat is operational, not a code defect.
  • Fail-open. Nothing in the commit mutates a request before a refusal point. The budget is a context value; a client that ignores it behaves as before. The decision record is written after the decision, in memory, and cannot fail a request.

The rebase and the base commits

  • The four earlier PR commits are content-identical after the rebase. Proof: git diff e4dd3ad5 97b2aa3c over the PR's own 17 files is empty except dash/schema.go, whose 9 added lines are #728's deferred-MCP index and column — base code, not the PR's. The new commit's own diff is the only PR-side change.
  • Six new base commits (#728, #730/#732, #731, #733, #735, #739) — read for interaction. None touches the sweep or warm-path files. #730/#732 adds Ctx.NoCacheBreakpoint and gates the #727 span retreat; the sweep shares none of that code. The shared dash/ui/app.js gains the PR's REASON_TEXT labels alongside the base commits' unrelated changes; additive, no conflict.
  • gofmt: byte-checked both structs the new commit touches (keepalive/keeper.go SweepWarmStats, extract_sweep_warm.go SweepWarmStats). Every comment-free run pads to uniform columns. The author's box report (gofmt -l . empty, make lint exit 0 at 2b13baf5) matches the bytes.

Earlier findings

Mine

  • Round 3 blocking (gofmt) — fixed at b92fe988, still clean at this head. Verified again by bytes.
  • Round 3 non-blocking (the trigger's marker rule) — fixed at e4dd3ad5, unchanged by this rebase (97b2aa3c is that commit).
  • Round 2 non-blocking (the phantom Held when warmHold drops a paid answer at a full table) — still open, still non-blocking. The sweepWarmHeld.Add(1) at extract_sweep_ping.go:644 is unchanged.

Reviewer 2 — their round-4 review (2026-10-26T10:41:15Z, approve) was posted before my round-4 post and first read by me this round. It approved and corrected their own round-3 gofmt claim. No round-5 review from them yet; nothing to cross-check.

Rejected by the author, reason still accepted: sweepWarmRewriteUSD charging the whole row CacheWrite. Unchanged since round 2; the reason still holds.

Non-blocking

  • extract_sweep.go:1256 — the max_ask_items hint says "160 tokens per output on top of the flat 16,000"; the code, the docs, and the commit message all say 224 (plus a 1,024 fixed margin, which the docs also omit). An operator sizing the setting from the /stats hint reads a number ~30% low. Fix the hint to 224.
  • The Fields entry declares Min: 1, but the hint says "below 1 reads as 12". Both are true on their own path and they disagree: the YAML path (newExtractSweep) reads 0 as 12, while the settings form (config/form.go validateValue) refuses 0 with "must be at least 1". The test covers the YAML path only. Not harmful — the form's refusal is clear — but the hint describes behavior the form does not have.
  • lastWarmDecision (extract_sweep_apply.go:897) can read another thread's decision. The gate's deferred record runs before it returns, so the newest decision is normally this gate's. But a concurrent trigger or gate on another thread can append in the window between the gate's return and the lastWarmDecision call, booking that thread's numbers on this row's events. Diagnostic-only mislabel, microseconds wide, decisions are rare. A noteWarmDecision returning the recorded decision (or the gate returning it) would close it.
  • docs/data-dependence.md does not name recent_decisions. The record is numbers plus a hash, in memory only, never in the Store, so the row's claim still holds — the same class as recent_sweeps, which the row also does not name. One clause in the warm-path sentence would close it.
  • The round-2 phantom-Held note stays open (see Earlier findings).

What I checked

  • Last review: round 4, e4dd3ad5248d16371e56e9b7507a7f61dbca9246, 2026-10-26T10:44:33Z
  • New commits read: 11 — 2b13baf5 "feat(sweep): max_ask_items, a record of every warm decision, and a model audit (#491)" (new), 97b2aa3c "fix(sweep): the warm trigger uses the same marker rule as the question (#491)" (rebased), 6d722ede "feat(sweep): warm_gate_price_model, a diagnostic price for the warm gate (#491)" (rebased), da35e41e "fix(sweep): the warm gate prices the rewrite the way the provider reads the cache (#491)" (rebased), cf34954c "feat(sweep): the warm path, an economic gate on a held answer (#491)" (rebased), and the six new base commits 3befbfb2 (#739), 8ff7f6aa (#735), 00cd7fd6 (#732/#730), ad87e369 (#733), f831e7ef (#728), e6e7f905 (#731). I read the base commits for their interaction with the warm path; their own behavior is main's, out of scope.
  • Read in full: 8 reviews, 4 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review: the author's comment (2026-10-26T23:42:55Z) — box results for this head, 19 mutation checks, and the keepalive-models caveat, each checked against the code; reviewer 2's round-4 review (2026-10-26T10:41:15Z, posted before my round-4 post, first read this round); the rebase; the new commit.
  • Read the new commit's full diff across all 15 files: the sweep config and askItemsLimit, adjudicateWith's budget, both cheapmodel clients' replyBudget hook, the WarmDecision record and its three mutators, the refused-apply events, the keeper wiring, the docs, and all five new or extended test files.
  • Proved the rebase clean: git diff e4dd3ad5 97b2aa3c over the PR's own files is empty except #728's base change in dash/schema.go. Confirmed the full-PR diff against the new base is the old 19-file set plus the 7 files of the new commit (26 files, +3861/−81), every line of which is code I reviewed in rounds 1-4 or in this round.
  • Byte-checked gofmt on both structs the commit touches (cat -t), and re-checked the round-2 phantom-Held line (extract_sweep_ping.go:644, unchanged).
  • Checked the hint and the Min against the two validation paths: newExtractSweep (YAML, clamps) and config/form.go validateValue (settings form, refuses below Min).
  • I did not run builds or tests (not approved on this machine); the author's box report covers this exact head (all packages, -race on the changed packages, gofmt and lint clean).

@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 5 of 7 2b13baf552cd approve

Verdict: approve

Earlier findings

All round 1-4 fixes are still present at this head. The PR was rebased onto base 3befbfb2 (#739), and the four warm-path commits were rewritten (cf34954c, da35e41e, 6d722ede, 97b2aa3c). I diffed e4dd3ad..97b2aa3c over every warm-path file: the only change is dash/ui/app.js (+9/−4), and I read that diff in full — it is all base content from #739 (a neverCalled helper, the skills filter, the history view's removal and its insights alias). No warm-path line changed in the rewrite. The round-1 latch (CAS at extract_sweep_warm.go:822, the Store-held stop at 834-835, the give-back at 854), the eviction skip, trigger: "warm", carriesRealMarker in the trigger, Any(), and the gofmt-realigned keeper struct are all present at HEAD.

Still open, non-blocking (reviewer 1, rounds 2-4): the phantom sweep_warm_held when warmHold refuses at a full table. Unchanged by this commit. I agree with reviewer 1's reading and add nothing.

Rejected with a reason I still accept: sweepWarmRewriteUSD charging the whole row CacheWrite when it is the smaller number. Unchanged.

Reviewer 1, round 4 (approve). Read in full. Nothing in it asks me for anything. Their cosmetic note (an unused body parameter in a test fixture) is not addressed by the new commit; it stays cosmetic.

Findings

None blocking. The new commit is correct in every path I traced (details under What I checked).

Non-blocking

  • components/offload/extract_sweep.go:1256 — the max_ask_items field hint says "160 tokens per output on top of the flat 16,000", but the code adds 224. askReplyBudget (extract_sweep.go:224) adds perVerdictReplyTokens = 224 per output beyond 12, plus askReplyOverhead = 1024. The documentation in docs/components/advanced-offload.md says 224 for every output beyond 12, which matches the code. The hint is operator-facing (config validation output) and contradicts both. One-line fix; no behavior involved.
  • components/offload/extract_sweep_apply.go:898 — lastWarmDecision() can return another thread's decision. The gate's defer records the decision, then applyHeldFrom reads the newest record globally. A warm apply on another session that records between those two statements puts its numbers on this row's sweep_warm_refused_* events. Applies run in-request, so concurrent warm applies are possible. Diagnostic numbers only: the refuse itself already happened, the request is unchanged, and the decision log itself is correct. A per-gate return value would close it; not worth blocking.
  • proxy/sweep_model_audit_test.go — dead code in the test's record closure. last := lastMessage(body); _ = last (the value is computed again inside the if above), and if strings.HasPrefix(s, "ping ") { questions += 0 } is a no-op. Cosmetic; the assertions are unaffected.

What I checked

  • Last review: round 4, e4dd3ad5248d16371e56e9b7507a7f61dbca9246, 2026-10-26T10:41:15Z.
  • New commits read: 1 new — 2b13baf5 "feat(sweep): max_ask_items, a record of every warm decision, and a model audit (#491)" (15 files, +819/−37). Full diff read, file by file. The PR was also rebased onto base 3befbfb2 (#739); the four warm-path commits were rewritten, and I verified the rewrite touches no warm-path file (see Earlier findings).
  • Read in full: 7 reviews, 4 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt; the inline list is empty).
  • New items since my last review: reviewer 1's round-4 review (approve, 2026-10-26T10:44:33Z) — read, nothing pending for me; the author's box-results comment (2026-10-26T23:42:55Z) — every claim checked against the code, including the mutation count and the audit caveat (below).

max_ask_items.

  • The setting: MaxAskItems is clamped twice — in newExtractSweep (below 1 reads as 12, above 64 as 64) and again in askItemsLimit at use. The constructor stores the clamped value (the test pins both). collect keeps the largest candidates and counts the rest as sweep_over_ask_cap; the default of 12 keeps the old behavior byte-for-byte (the cap constant became defaultMaxAskItems).
  • The reply budget: askReplyBudget(n) returns the flat 16,000 for n ≤ 12, else flat + (n−12)×224 + 1024. adjudicateWith sets it on the call's context through cheapmodel.WithReplyBudget, and I traced the chain both ways: the ping/warm ask builds its detached-sink context from c.Ctx, passes it into adjudicateWith, which adds the budget before the PrefixAsk call — so the warm question, the ping-standing question and the cold in-request sweep all carry it. replyBudget is a floor, never a ceiling-lower: a budget below the client's default is ignored, so the client never goes below its own default.
  • The clients: Anthropic.CompletePrefixed and the OpenAI Responses client apply replyBudget before thinkingAdjustedMaxTokens, so the documented ceiling (the sum capped at the agent's own max_tokens on a thinking body) still holds — the wire test pins 16000 default, 30000 scaled, 34000 with thinking added on top, and 9000 when the agent's own cap is smaller. Truncation still fails open: a cut reply parses as nothing, sweep_reply_truncated is counted, nothing held, nothing dropped (the test with a truncated array pins all three).
  • The measurement: 224 per verdict is backed by the test that bills a long-quote verdict at 1.7× the o200k count; the arithmetic holds (about 205 provider tokens).

The decision record.

  • WarmDecision holds numbers only: D and R (local and billed), N, the weight, both ratios, deep, saving and rewrite in USD, the reason, and a hashed thread label. No content. Same class as WarmSweep, which the data-dependence row already covers, so the row needs no change.
  • noteWarmDecision runs under sweepWarmGateMu, caps at 50, resets in resetWarmForTest, and writes one INFO line with the same numbers. warmGate records on every exit through a defer on the named returns, including no_valid_drop; warmWorthAsking does the same, with each refusal reason matching the noteWarmTrigger count beside it. Trigger decisions fire only on a trigger attempt (the warmEveryN cadence check returns first), not on every request.
  • SweepWarmCounters copies the list, Any() covers it, and the keeper's recent_decisions JSON field is additive.
  • A refused apply books the refused numbers as row events (sweep_warm_refused_removed_tokens, _rewrite_tokens, _expected_turns, _deep), read back from the newest decision — correct in a single-threaded run; the cross-thread window is the non-blocking note above.
  • The keeper struct bytes: I checked cat -t this time. GatePriceModel/PriceModelUnknown/Recent form one uniform run, the new comment starts a new group, and RecentDecisions through Panics form a second uniform run. That is what gofmt produces for comment-split groups, and the author's box report (gofmt -l . empty, make lint exit 0) covers this exact head.

The model audit.

  • pingBodyN changes only max_tokens (or max_output_tokens) and stream; the model and every other field of the held forwarded body stay. The unit test pins this for three model names, including the system and message content.
  • The end-to-end test drives a sweep-only proxy on glm-5-test with the keep-alive on, records the model of every upstream body, and fails on any model but the request's, on any Claude name, and when no sweep question ran. It allows the ping to be absent because the question stands in for it — I verified the author's caveat is exactly what the test can and cannot see, and the ping's model is pinned by the unit test instead.
  • The second test pins that a non-Claude model on a relay is not pinged unless CONTEXT_GURU_KEEPALIVE_MODELS names it (the variable is real; relay_test.go covers its parsing). The author's action item for the live run (set the variable, or no thread is ever pinged and the sweep never asks) follows from this and is correct.
  • The test's dead last/questions += 0 lines are the cosmetic note above.

The author's comment. Box results for this head: gofmt, lint, all packages, -race on offload, keepalive, config, components/all, cheapmodel and proxy, with the known dash insights timeout not repeated (noted on #695). The 19 killed mutations and the two model-rewrite checks match the tests I read. I did not run any of it (tests are not approved for this review); the conclusions above are from reading the code.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

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

This head adds the streamed-usage fix. Issue #745 has the root cause and every PrevBilledInput / input_tokens consumer with file:line.
Mutation checks: 5, all killed (max-merge back, an output-only delta wiping the tiers, cache write dropped on replace, replace never taking effect, output not kept at the larger count).

@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 6 of 7 21d9ea4c94f1 approve

Verdict: approve

Earlier findings

Nothing from rounds 1-5 was fixed by this commit, and nothing regressed. The new commit touches only proxy/usage.go and its new test; no warm-path file changed, and no rebase happened (21d9ea4c sits directly on 2b13baf5, base still 3befbfb2). I re-checked the round-1 latch, the eviction skip, and the round-4 marker rule at HEAD: all present.

Still open, non-blocking:

  • The max_ask_items hint says "160 tokens per output"; the code and docs say 224 beyond 12 (mine and reviewer 1's, round 5). Not fixed — the hint text at extract_sweep.go:1256 is unchanged.
  • The lastWarmDecision cross-thread window (mine and reviewer 1's, round 5). Unchanged.
  • The phantom sweep_warm_held when warmHold refuses at a full table (reviewer 1, rounds 2-5). Unchanged; I agree with reviewer 1's reading.
  • The dead lines in proxy/sweep_model_audit_test.go's record closure (mine, round 5). Unchanged.

Reviewer 1, round 5 — the Min: 1 disagreement with the hint. Agree, after checking it myself. The settings form refuses 0 with "must be at least 1" (config/form.go:633-635), while the YAML path clamps 0 to 12 and the hint says "below 1 reads as 12". Both paths are safe; the hint describes only the YAML path. Non-blocking.

Reviewer 1, round 5 — naming recent_decisions in docs/data-dependence.md. Fair. The record is numbers plus a hash, in memory only, so the row's claim holds — but one clause naming both recent_sweeps and recent_decisions would make that explicit. Non-blocking either way.

Rejected with a reason I still accept: sweepWarmRewriteUSD charging the whole row CacheWrite. Unchanged.

Findings

None. The new commit is correct, and it is in scope for this PR: PrevBilledInput is the input the warm gate's ratios read (warmRatios), so the double-count it fixes made this PR's gate refuse too much on a litellm gateway — the refuse direction, which is why nobody saw it sooner.

Non-blocking

  • proxy/usage.go:280-285 — the parseSSEUsage header comment still describes the old merge. It says the tiers "are merged across events, taking the maximum of each". After this commit the input tiers are replaced by the last event that carries an input count; only the output keeps max(). The big comment inside the loop states the new rule correctly, but the function header contradicts it. Update the header.
  • proxy/usage_stream_shapes_test.go — the case list runs 1, 2, 3, 4, 5, 7, 6. The last two cases are out of numeric order. Labels only; the assertions are unaffected.

What I checked

  • Last review: round 5, 2b13baf552cd3a04112c08d62c0dd42559b14860, 2026-10-26T23:49:40Z.
  • New commits read: 1 — 21d9ea4c "fix(usage): a streamed litellm response no longer counts cache_read twice (#745)" (2 files, +94/−4). Full diff read.
  • Read in full: 10 reviews, 5 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt; the inline list is empty).
  • New items since my last review: reviewer 1's round-5 review (approve at 2b13baf5, posted just before my round-5 post) — read in full; its two items I had not raised (the Min: 1 disagreement, the data-dependence naming) checked against the code myself, both agreed as non-blocking; the author's box-results comment (2026-10-27T01:19:46Z) — the reported mutation set (5) matches the failure modes the new code guards; the new commit — reviewed below.

21d9ea4c, the streamed-usage fix, reviewed as a first review.

  • The defect: a litellm gateway streaming an Anthropic-shaped response puts the total prompt in message_start's input_tokens and the true split in message_delta. The old field-by-field max() kept the total as fresh and added the delta's read, so billed input counted the read twice.
  • The fix: in parseSSEUsageWhy's event loop, an event whose usage block carries an input count (input_tokens or prompt_tokens, hasInputCount) now replaces the whole input set — fresh, read, write, 1h write — as one unit. An event without an input count (a real Anthropic message_delta, which is output-only) leaves the earlier values. Output keeps max().
  • I traced the rule against every shape the parser knows, through parseUsageWhy's field mapping:
    • Real Anthropic: tiers in message_start, output-only delta → replacement never fires after the start; same numbers as before.
    • litellm cache hit: the delta carries the true split → the start's total is replaced by 717 fresh + 6656 read. Billed 7,373, not 14,029.
    • litellm cache miss: the delta repeats the total with zero cache fields → same answer as the start.
    • A delta that repeats the same input fields → the same numbers replace themselves.
    • OpenAI Responses (input_tokens) and chat completions (prompt_tokens): the last event with a count wins, which is the final, cumulative one.
  • Guarded edges: a block that parses to all-zero or to an unparsed dialect returns before the merge (why != usageMissNone → continue), so a zero or foreign block can never wipe the tiers. A stream cut before the delta keeps the start's total as fresh with no cache — the same answer the old code gave, and the total is the true billed input anyway.
  • The tests: seven stream shapes plus a non-streamed control, with numbers shaped like the captured GLM stream. Each case's expected split matches what I derived from the parser by hand.
  • Consumers: CacheRead — which ResolveWarmQuestion passes as the turn's read for prefixAskCacheOK — is unchanged for both real Anthropic (start carries it) and litellm (the delta carries it; the old max took the same value). PrevBilledInput and the dashboard's fresh input become correct for litellm streams. No consumer relied on the double count.
  • The commit message's claim that the gate's full ratio and rewrite came out too high follows: warmRatios divides PrevBilledInput by the local size, so a 2x billed input inflated the full ratio toward the maxBilledRatio cap and the rewrite with it.

The author's comment. Box results for this head: gofmt, lint, all packages (proxy 124 s, dash 97 s), -race on offload, keepalive, config, components/all, cheapmodel and proxy; the known dash insights timeout not repeated (noted on #695). The five killed mutations each name a failure mode I checked in the code: the max-merge back, an output-only delta wiping the tiers, the cache write dropped on replace, replacement never taking effect, output not kept at the larger count. I did not run any of it (tests are not approved for this review); the conclusions above are from reading the code.

@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 6 of 7 21d9ea4c94f1 Approve

Verdict: approve

One new commit: 21d9ea4c, the streamed-usage fix for #745. It touches only proxy/usage.go and a new test file. I read it in full and traced it against every shape the parser knows. The fix is correct and loses no input the old merge kept. Nothing blocking.

Findings

None.

The new commit, reviewed as a first review

  • The bug. A litellm gateway streaming an Anthropic-shaped response puts the total prompt in message_start (input_tokens 7,373, no cache fields) and the true split in message_delta (input_tokens 717, cache_read_input_tokens 6,656). The old merge took the max of each field, so FreshInput stayed 7,373 while CacheRead became 6,656. Billed input is the sum of the three parts (proxy.go:1723), so it read 14,029 for a prompt of 7,373 — exactly the commit's claim, which I recomputed from the code. PrevBilledInput fed the warm gate about 2x too large, so the full ratio and the rewrite cost were too high and the gate refused too much.
  • The fix. In parseSSEUsageWhy, an event whose usage block carries an input count now replaces the whole input set (fresh, read, write, 1h write); output keeps max(). SSE lines are walked in order, so the last input-carrying event wins — the litellm delta, with the true split.
  • Why no input is lost. hasInputCount checks input_tokens and prompt_tokens — exactly the two fields the block parser's input-carrying branches read (usage.go:229 and :250). The parser's other accepted shape is output-only (output_tokens alone), whose input fields were zero under the old merge too, so replacing with it changes nothing; and an unrecognized dialect (Bedrock camelCase) is rejected as usageMissUnparsed before the merge and was already skipped. All-zero blocks are skipped as before. So the set of blocks that contributed input before and after is identical; only the combination rule changed.
  • The other shapes. A real Anthropic stream has the tiers in message_start and an output-only message_delta, so no later event carries an input count and message_start's values stay. A delta that repeats the same fields replaces them with the same numbers. A cache miss reports the total again with zero cache fields. All three are pinned by tests, plus a stream with no delta, a write-only cold turn, and output keeping the larger count.
  • The warm path's other input. CacheRead was already correct under the old merge (the delta's read beat message_start's zero), so turnRead and the ping-side cache rule are unchanged. Only FreshInput — and with it billed input and PrevBilledInput — changes, in the correct direction.
  • Tests. Seven stream shapes plus the non-streamed control, with synthetic numbers shaped like one captured GLM stream and no content. The author reports 5 mutations killed on this tree (max-merge back, an output-only delta wiping the tiers, cache write dropped on replace, replace never taking effect, output not kept at the larger count); each maps to a case I read.

Earlier findings

Mine, round 5 (all non-blocking, all still open). The new commit touches only proxy/usage.go, so none of them changed, and the author has not rejected any:

  • The max_ask_items hint says 160 tokens per output; the code, docs, and commit message say 224.
  • The Fields Min: 1 makes the settings form refuse 0 while YAML reads it as 12, against the hint's claim.
  • lastWarmDecision can read another thread's decision (microseconds-wide window, diagnostic only).
  • docs/data-dependence.md does not name recent_decisions (the row's claim still holds).
  • The round-2 phantom-Held note (a lost paid answer at a full table counts as a held answer) — unchanged at extract_sweep_ping.go:644.

Reviewer 2 — their round-5 review (2026-10-26T23:49:40Z, approve) was posted 36 seconds after mine and read in full this round. They independently raised the same hint and lastWarmDecision notes, plus dead code in the audit test's record closure. I checked each against the code and agree; nothing between us is pending.

Rejected by the author, reason still accepted: sweepWarmRewriteUSD charging the whole row CacheWrite. Unchanged.

Non-blocking

  • The five open notes above. Nothing new from this commit.
  • The new test's case numbering runs 1-5, 7, 6 (the last two are swapped in the table). Cosmetic only.

What I checked

  • Last review: round 5, 2b13baf552cd3a04112c08d62c0dd42559b14860, 2026-10-26T23:49:04Z
  • New commits read: 1 — 21d9ea4c "fix(usage): a streamed litellm response no longer counts cache_read twice (#745)" (2 files, +94/−4)
  • Read in full: 9 reviews, 5 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt)
  • New items since my last review: reviewer 2's round-5 review (2026-10-26T23:49:40Z, approve) — read in full, its three non-blocking notes checked against the code; the author's comment (2026-10-27T01:19:46Z) — box results for this head, the #745 pointer, and 5 mutation kills, each checked against the code and tests; the new commit.
  • Read the new commit's full diff and the whole of parseSSEUsageWhy, the block parser parseUsageWhy (every branch: input_tokens, Responses input_tokens_details, prompt_tokens, output-only, unparsed dialect), and hasInputCount, to confirm the replacement rule cannot skip a block the old merge counted.
  • Verified the billed-input arithmetic (FreshInput + CacheRead + CacheWrite, proxy.go:1723) against the commit's 14,029-vs-7,373 claim, and traced CacheRead's path to turnRead to confirm the ping-side rule is unchanged by the fix.
  • Confirmed the full-PR diff against the base is the round-5 file set plus proxy/usage.go and proxy/usage_stream_shapes_test.go (28 files, +3955/−85); every line is code I reviewed in rounds 1-5 or in this round.
  • I did not run builds or tests (not approved on this machine); the author's box report covers this exact head (all packages, -race on the changed packages, gofmt and lint clean).

@amiddavid

amiddavid commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

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

What this head adds: batching with one cut (#132), max_ask_batches, warm_expected_turns, and the turns-left model. See "Batching" and "Turns left" in the PR body.

Mutation checks on this change: 32, all killed (14 on batching, 18 on the turns-left model, the pipeline hand-off and the decision log). I counted them from my run log; an earlier draft of this comment said 40, which was wrong. Three first survived and were fixed:

  • "smallest first" in the batch order: no test checked which candidate led a batch. Added.
  • "a failed batch is put in the held answer as kept": no test checked the size of the held answer. Added.
  • "a disabled cutting component still counts": no test had one. Added.

Two things worth knowing

  • On the box, the tree under test is identical to the pushed head except for two plugin version files (plugin.json), which main gained from chore(plugin): bump the plugins for v0.6.1 (Claude Code 0.6.1, Codex 0.2.6) #740 after my last fetch. Go code is identical. I ran the plugin package on it too: it passes.
  • The branch is based on main 3befbfb2, not main's tip 161076c6. The difference is only those plugin version bumps.

A caveat on the cut model: it needs CtxWindowExact. On a model whose window is only a family guess (likely for a non-Claude model) it falls back to the turns so far, and the decision log says window_not_exact.

@amiddavid

amiddavid commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

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

What changed since 21d9ea4c: only the turns-left model (warm_expected_turns, the cut model, the pipeline hand-off of the summarizer's fraction) and its docs. Batching was moved out to #747, which fixes #132 for the cold sweep. When #747 merges, this PR rebases onto it and the warm path calls the same function.

Mutation checks on the turns-left model: 18, all killed. Sixteen on the model, the pipeline hand-off and the decision log, and two on the MODEL_PRICES window (a table window not treated as exact, and the cut model ignoring exactness).

The window. The cut model needs an exact window. An agent builder supplies one with window: in the MODEL_PRICES table (deploy/service/prices.example.yaml now has a commented example). A test goes through the real modelinfo table: a GLM entry with a window makes the cut model run, and the same model without one falls back with window_not_exact.

Note on the history: this was a force push (lease 6c27fc8d). The earlier head 6c27fc8d carried batching; it is kept only as a local backup branch and is not pushed.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review — round 11

Verdict: approve. No blocking finding this round. All four new commits are
test-only. No code path changed since round 10.

Reviewer Model Invocation State Seat Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session resumed 1 of 2 11 of 13 8255b96eb271 approve

What I checked

  • Last review: round 10, at 6298673807ab223d23d5cd76b5111bbfcd63eaa8, posted 2026-10-27T22:02:38Z.
  • New commits read: 12 in 62986738..8255b96e, each with sha and title below.
    • 4d1d93e6 feat(sweep): the warm path, an economic gate on a held answer (#491)
    • 4353bff7 docs: fix the prices link CI rejects, name the removed max_ask_items key, tidy comments (#491)
    • 4f679f21 fix(sweep): book why the recheck dropped a held answer, and void an answer for a shrunk conversation (#491)
    • 52c46ce8 feat(sweep): carry refused warm drops, and check quotes against what the model read (#491)
    • def9290a feat(sweep): count carried warm drops the cap evicts, and publish the carried counters (#491)
    • ce3056d5 test(keepalive): every carried counter must reach the sweep_warm stats (#491)
    • e123b395 fix(sweep): review round 8 fixes (#491)
    • 3b0894b2 fix(sweep): count a carried set that ages out at read time as carried_expired (#491)
    • 54a48062 test(sweep): the same warm cut passes at a flat rate and is refused at Opus rates (#491)
    • 43d51cda test(proxy): give the model audit the idle time the extra question slot needs (#491)
    • aebc8612 test: fit the warm credit tests to main's accountant pricing, and widen the audit window (#491)
    • 8255b96e test(sweep): pin the warm gate's saving to the read rate (#491)
  • Read in full: 18 reviews, 12 person comments, 0 inline comments.
  • New items since last review: reviewer 2's round-10 review (approve, 2026-10-27T22:02:35Z); two author comments with box results (2026-11-10T10:59:04Z and 2026-11-10T11:44:09Z).

The base moved, and the branch was rewritten again

The base moved from ccb62c7c to 77a910b0. That is about two weeks of main.
The eight old PR commits were rewritten onto it. Only four new commits sit on top.

I proved the rewrite content-neutral:

  1. I compared the old patch (git diff ccb62c7c 62986738, 6593 lines) with the new patch (git diff 77a910b0 3b0894b2, 6586 lines).
  2. The differences are only index hashes, hunk offsets, and context lines that come from the base side (dash/store.go columns).
  3. The PR's own token counts are identical in both patches.
  4. components/component.go declares CutFracProvider once in every rewritten commit. The round-9 duplicate is gone and did not come back.

The four new commits are test-only. No behavior change since round 10, so the
no-edge-case-change rule needs no new permission.

The four new commits

  1. 54a48062 — Two tests on warmGateRates. A flat rate (read == write) makes
    the rewrite cost zero, so the same deep cut passes. Opus rates refuse it. A model
    with no price entry is gated at Claude-class rates, never at a flat rate. This pins
    the flat-rate provider case (#1030) and the missing-price case. Both assertions
    match the code. Correct.
  2. 43d51cda — The model-audit test gets a wider idle window (Idle 2s→6s,
    sleep 6s→22s). The extra question slot needs the time. Test-only.
  3. aebc8612 — Two parts.
    • The dash warm-credit tests now use warmRow(e, removed) =
      e.ComponentSavedUSD(sweepPrice, SweepComponent, removed, removed). Main's #768
      moved the write-time saving into the accountant library, so the old
      write-time field is no longer booked. I read dash/event.go:959-972:
      ComponentSavedUSD prices unique tokens at uniqueRate and repeat tokens at
      repeatRate, times BilledTokenFactor, minus the warm rewrite charge. The tests
      still assert the read-rate credit, now through the stored-row rule. The re-fit
      keeps the meaning; it does not weaken the check.
    • The audit window widens again (Idle 6s→10s, sleep 22s→40s). The author's box
      comment says the 22s form failed once under -race. Deliberate, and the box run
      at the final head is green.
  4. 8255b96e — TestTheGateSavingIsPricedAtTheReadRateNotTheWriteRate. Input
    warmEconIn{Removed: 1000, Rewritten: 0, RatioContent: 1, RatioFull: 1, Read: 1, Write: 12.5, Turns: 1}. I read warmEcon (extract_sweep_warm.go:465):
    saving = 1000 × 1 × 1 × 1 = 1000, rewrite = 0. The assertion is 1000. With the
    write rate in place of the read rate the saving would be 12.5× larger, so the test
    is not vacuous. Correct.

All helpers exist and are used: warmGateRates (:975), warmEcon (:465),
TokenRates (components/component.go:1004, main's code), deepFixture (:919),
opusRates (:1222).

Box results

The author posted runs for b60a0bb0 and 8255b96e. The b60a0bb0 run had one
plugin-test failure that also fails on unmodified origin/main (fixed by #1035, now
in the base). The final head is fully green: -race offload 477s, proxy 615s, and
the new mutation killed. I did not run anything myself; live tests were not
approved this round.

New conversation items

  • Reviewer 2's round-10 review (approve) lists the same open items as mine. I
    checked each one at this head. I have nothing to add to their list.
  • The author's two box-result comments. Both checked above. The intermediate
    plugin failure is main's, not this PR's.

Earlier findings — status

Fixed in earlier rounds (checked, still fixed): the round-8 and round-9 items —
the duplicate CutFracProvider, the unpublished carried counters, the memHeld.get
expiry split (3b0894b2, mirrored in warmHold), the recheck reasons, the shrink
void, the quote check against the read body. All verified again in the rewrite.

Still open, all non-blocking (line numbers at this head):

  1. lastWarmDecision() cross-thread window — extract_sweep_apply.go:910. A
    concurrent request can read a decision a hair early. Worst case: one answer waits
    one extra turn, or one refusal is booked one turn late. Fail-open holds.
  2. Phantom sweepWarmHeld.Add(1) — extract_sweep_ping.go:660. warmHold can
    refuse at a full table, so the counter can over-count held answers.
  3. Dead lines in the audit test — proxy/sweep_model_audit_test.go:60-61
    (last := lastMessage(body); _ = last) and :153 (questions += 0). Style only.
  4. docs/data-dependence.md does not name recent_decisions. The doc states the
    warm path's data dependence; the recent-decisions cache is part of it. Doc gap
    only, no stored data involved.
  5. max_ask_batches declares Min: 1 while the hint says values below 1 become 4.
    Pattern nit, still open.
  6. PrevBilledInputThread opportunity — both reviewers call it an opportunity, not
    a defect. Unchanged.

Rejected with accepted reason (carried): sweepWarmRewriteUSD double-count
question — the accounting question was settled in an earlier round and the reason
was accepted.

Non-blocking notes

  • The audit test now sleeps 40 seconds (proxy/sweep_model_audit_test.go:143). This
    makes the proxy package slower on every -race run. The widening was deliberate
    and needed for a stable box run, so I do not block on it. A follow-up could make
    the window a test knob instead of a wall-clock sleep.
  • The four new tests are real pinning tests, not tautologies. The flat-rate and
    no-price tests guard the two ways warmGateRates could silently make the gate
    free. Good additions.

Verdict

Approve. The rewrite is content-neutral. The four new commits are test-only and
correct. Box results are fully green at the final head. The open items above are
non-blocking and unchanged from round 10.

@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.322 offload-review skill, @amiddavid's session resumed 2 of 2 11 of 13 8255b96eb271 approve

Verdict: approve

What changed this round

The branch rebased onto main 77a910b0 (about 130 commits of drift: the accountant pricing #930, IBM Bob #1030, per-model cache tiers, the dash schema work, #776, #768). The 8 PR commits were rewritten for the rebase. Four new commits sit on top, all test-only:

  • 54a48062 — the same warm cut passes at a flat rate and is refused at Opus rates; a model with no price entry is gated at Claude-class rates.
  • 43d51cda — the model audit gets the idle time the extra question slot needs (#776).
  • aebc8612 — the dash warm-credit tests read the legacy row rule; the audit window widens.
  • 8255b96e — the gate's saving is pinned to the read rate.

Findings

None.

Earlier findings

  • All earlier fixes stand at the new head. I compared the old PR diff (ccb62c7c..62986738) with the new one (77a910b0..8255b96e), normalized. Same 33-file set. Only 6 files differ, and each is rebase adaptation, not a behavior change: deploy/service/prices.example.yaml drops cache_read_frac (main moved to per-model tiers), proxy/prefixask.go no longer adds an import main already has, and the four dash files merge this PR's sweep_false_expands_warm columns into main's new column lists.
  • The rewritten history compiles. Each of the 12 commits declares CutFracProvider exactly once in components/component.go — main's #757 copy, with the PR's duplicate gone. This was the round-8 failure mode; it does not recur.
  • aebc8612's test change is a real adaptation, not a dodge. Main's #768 made Price book no saving at write time, so Components[0].SavedUSD is empty on a warm row now. The tests read Event.ComponentSavedUSD instead — the read-time rule dash/replaycap.go:469 really uses for stored rows with no priced_by. The rule still reads the row's own data: sweepWarmRewriteUSD takes the row's sweep_warm_rewrite_tokens and reported CacheWrite, and the rate comes from the row's own fields. Only the removed count is a constant, and it always was one. The flat-rate rewrite exemption (p.CacheWrite <= p.CacheRead) is in the production rule, so the new flat-rate test pins real behavior.
  • 54a48062 and 8255b96e pin the gate's arithmetic. Flat rate passes (rewrite cost 0 when write equals read), Opus rates refuse, no-price-entry models get built-in write-greater-than-read rates, and warmEcon's saving is Removed × RatioContent × Read × Turns. These match the gate code I read in rounds 8-10; nothing in the gate changed.
  • Still open, non-blocking and unchanged (line numbers at this head): the lastWarmDecision cross-thread window (extract_sweep_apply.go:910); the phantom sweep_warm_held when warmHold refuses at a full table (extract_sweep_ping.go:660); the dead lines in proxy/sweep_model_audit_test.go (_ = last at 61, questions += 0 at 153); docs/data-dependence.md not naming recent_decisions; the Min: 1-versus-hint pattern on max_ask_batches; the PrevBilledInputThread opportunity.
  • Rejected with a reason I still accept: sweepWarmRewriteUSD charging the whole row CacheWrite. Unchanged.

Non-blocking

  • The still-open items above. Nothing new from these commits.

What I checked

  • Last review: round 10, 6298673807ab223d23d5cd76b5111bbfcd63eaa8, 2026-10-27T22:02:35Z.
  • New commits read: 12 — the rewritten 8 (4d1d93e6 the warm path, 4353bff7 docs, 4f679f21 recheck reasons and shrink void, 52c46ce8 carry and quote check, def9290a carried counters, ce3056d5 keeper test, e123b395 round-8 fixes, 3b0894b2 carried_expired at read) and the new 4 (54a48062, 43d51cda, aebc8612, 8255b96e). The four new ones read hunk by hunk. The rewrite checked two ways: the endpoint diff comparison above, and a per-commit grep that each of the 12 declares CutFracProvider once.
  • Read in full: 20 reviews, 13 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt; the inline list is empty).
  • New items since my last review: reviewer 1's round-10 review (approve at 62986738, 2026-10-27T22:02:38Z) — read in full, no findings, its open list matches mine line for line; the author's box-results comment for b60a0bb0 (2026-11-10T10:59:04Z) — that head was discarded when the branch rebased again onto 77a910b0; its context-guru-plugin failures were on unmodified main and #1035 fixed them; the author's box-results comment for 8255b96e (2026-11-10T11:44:09Z) — fully green, -race on offload and proxy, one new mutation killed. I did not run any of it; the code read is my evidence.

On the box results. I read the two comments against the code, not as proof. The claims I could check myself — the flat-rate exemption in sweepWarmRewriteUSD, the read-time rule's callers, the four new tests' assertions against warmEcon and the gate — all hold at this head.

The base drift. Main's ~130 commits touch the same files this PR touches (pricing, dash schema, the sweep question's slot). I separated the PR's own work from the drift by the endpoint diff comparison, and read the four new commits, which are where the drift forced changes. The PR's behavior — warm path off by default, answers in memory only, gate refuses on doubt, everything reversible — is unchanged by the rebase.

Off by default and in no preset (`warm: true`).

- Trigger: on a warm request, at most once every warm_every_n requests,
  only when outputs at least warm_min_age_turns old and over the floor
  could pay back a rewrite if all were dropped, and their mass is at
  least warm_min_mass_frac of the conversation.
- The question is the sweep's own, run after the request is forwarded,
  from the ping registry's copy, under the thread's ping claim.
- The answer waits in process memory only. A restart loses it.
- On a later warm request: recheck, then the gate on the whole answer,
  then the cold apply's own code. A refused answer is dropped.
- The gate prices the rewrite the way the provider reads the cache:
  a drop deeper than the look-back rewrites the whole conversation.
- The turns left come from warm_expected_turns, or from the billed
  growth per turn up to the cut, or the turns so far.
- Every decision is recorded, accepted or refused.
- Counted apart: sweep_applied_warm, warm false-drop rate, gate accept
  and refuse with reasons. A warm drop is credited at the read rate and
  its rewrite is charged on the request that paid it.
- A streamed litellm response no longer counts cache_read twice (#745).

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…key, tidy comments (#491)

- The prices.example.yaml link in advanced-offload.md was relative and
  left docs/, so `mkdocs build --strict` failed. It is now an absolute
  GitHub URL, as the file does for summarizer_model_profiles.yaml.
- max_ask_items is a refused key with a pointer to max_ask_batches,
  so an older config gets a reason and not a bare "field not found".
  This is the one logic change: a new refusal message and a test.
- parseSSEUsage's header comment said it max-merges the input tiers. It
  now says the last event with an input count replaces them (#745).
- CutFracProvider no longer sits between Ctx and its doc comment.
- The streamed-usage test cases are in order, 1 to 7.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…nswer for a shrunk conversation (#491)

From the live GLM run t94, which applied nothing: 7 of 7 warm apply
decisions were refused, and nothing said why.

- The recheck's reasons (referenced_later, content_changed, output_gone,
  expanded, conversation_shorter) are booked BEFORE the warm gate, as
  sweep_apply_dropped_<reason> events and in the decision (proposed, and
  dropped by reason). They were booked after the gate returned, which a
  refusal never reaches, so 59 to 87% of the judge's drops disappeared
  with no reason.
- An answer where the judge proposed no drop at all is labeled
  no_drop_proposed. no_valid_drop is now only a proposal the recheck
  threw out in full.
- A held warm answer is dropped as soon as a request has FEWER messages
  than the answer judged (the agent compacted or started over), counted
  as held_shrunk and recorded as conversation_shrunk. A request of equal
  length keeps it.
- Fabricated quotes are counted per batch position, with the candidates
  and verdicts each position carried, in sweep_batch_by_index, so the
  next run can tell a batch effect from a model effect.

Logging and labels, except the shrunk-conversation drop.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…the model read (#491)

Warm sweep, accumulation and a quote-check fix.

- A gate refusal keeps the drops that passed the recheck, in memory only
  (never the Store). The next question's answer is merged by tool-use id.
  Each output counts once. The newer verdict wins, a newer keep included.
  Every apply attempt rechecks the merged set, and a carried drop that
  fails the recheck leaves for good. The gate decides once on the merged
  set. Accept means one cut, then the set is cleared.
- Bounds: 30 minutes from the oldest question that still contributes (a
  refusal does not make it younger), 256 carried drops (oldest first), and
  a shorter conversation clears the set.
- A carried set already refused is not retried on each warm request. The
  trigger asks a new question and the gate runs when its answer arrives.
- The decision log records carried and new counts and tokens, and the
  recheck's losses by reason. The reasons are booked before the gate, so a
  refusal shows them. An empty proposal is no_drop_proposed.
- A held answer judged on a longer conversation than the request has is
  dropped (held_shrunk, decision conversation_shrunk).
- sweep_batch_by_index: asked, items, judged and fabricated per batch
  position.
- A judge quote is checked against the stashed body the model read, not
  the newest request. New PrefixReadAsker. This changes only the
  fabricated-quote counter, never a drop decision.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
… carried counters (#491)

- New counter carried_capped: carried drops the 256 cap evicted in a merge.
- /stats keepalive.sweep_warm now publishes carried_merged,
  carried_overridden, carried_refused, carried_expired and carried_capped.
  The earlier commit counted them but the keeper did not publish them.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
#491)

Each of the 5 carried_* counters gets a distinct non-zero value and must
appear in keepalive.sweep_warm. A test-only seed hook in offload sets them.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
- The shrink void re-checks, under the second lock, that the held answer is
  still the one it decided on, so a fresh answer is never voided.
- carried_expired counts only a carried (refused) set that aged out. A
  never-refused answer that went stale counts as held_expired.
- Document why carryRefused marks a merged set tried.
- Fix two stale names in comments. The docs name carried_capped.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…_expired (#491)

memHeld.get counted every over-age answer as held_expired. It now splits by
the tried flag, as warmHold does: a carried (refused) set is carried_expired,
an answer never refused is held_expired.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…t Opus rates (#491)

IBM Bob bills fresh input, cache read and cache write at one rate (#1030).
The gate already prices that: write == read gives a rewrite cost of 0.
Pin it, and pin the no-price-entry fallback (Claude-class rates, never flat).

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…ot needs (#491)

Main (#776) sends the sweep question once, after the last planned ping.
With a 2 s idle window and a 6 s wait, that slot never came.
Use a 6 s idle window and a 22 s wait. The audit asserts the same things.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
…en the audit window (#491)

- dash: Price no longer books a saving at write time (#768). The three warm credit
  tests now read the legacy row rule (ComponentSavedUSD), which still values a stored
  row with no priced_by and carries the warm read-rate credit and rewrite charge.
- proxy: the model audit waits for the extra question slot (#776). Use a 10 s idle
  window and a 40 s wait. 3 of 3 runs pass on the box.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
The flat-rate test cannot see the saving side, because read == write there.
At Opus rates a deep cut does not pay over 60 turns. Priced at the write
rate it would pass. Mutation (saving at write) fails the new test.

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

Copy link
Copy Markdown
Collaborator Author

Box results for head 8f90546d (rebased on main d407191b)

The rebase resolved conflicts in dash/query.go and dash/store.go only. Main's #1003 column (defer_cost_usd) stays. sweep_false_expands_warm is added after it. git range-diff against the previous head shows only main's #1003 changes and that resolution.

Eval box 1, -count=1, foreground.

  • make lint: clean.
  • go test ./...: green. One run failed TestBodyOptsLoadsSessionStateFromDisk in apply. This PR does not touch apply. The test passes alone 3 of 3 and the whole package passes on rerun (load flake).
  • -race on dash: passes (859 s, -timeout 20m).

@amiddavid
amiddavid merged commit 54a51b5 into main Nov 10, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 10, 2026
amiddavid added a commit that referenced this pull request Nov 10, 2026
Bring in #720; no conflict, no hand resolution.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 10, 2026
Add a v3 configuration of the warm path. Off unless a v3 setting is
written; the default config is unchanged from #720.

- sweet spot: cut only when P >= fill(C) x C
- one cut per round: wait for growth after an accepted cut
- meaningful drop: D >= min_drop_frac x P, then #720's payback gate
- selector: judge (default), rule (no model call), hybrid (one cut)
- rules: file re-read or write, build/test/lint re-run
- protect_tools, protect_paths, protect_last_n
- counters under keepalive.sweep_warm.v3 and in the decision log

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.

1 participant