Skip to content

feat(sweep): ask at the keep-alive ping, hold the answer, recheck, shadow mode - #508

Merged
amiddavid merged 3 commits into
mainfrom
feat/sweep-cold-ask
Oct 25, 2026
Merged

amiddavid merged 3 commits into
mainfrom
feat/sweep-cold-ask

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Data dependence change

This PR changes the sweep's data dependence. Approved by David Amid on 2026-10-25. docs/data-dependence.md is updated (rows extract_llm_sweep and "Body stash", and the audit lists).

  • Held answer (cg:swh:, pinned). It is metadata. Per judged output it holds: the tool-use id, a short hash of the message, token counts, the keep-or-drop verdict. Per answer it holds: the conversation length when asked, the model name, the cost, and the wait cause. No tool-output text, no conversation text. (Checked against the heldAnswer and heldOutput structs.)
  • Two in-memory conversation copies per thread (content). The pipeline's view of the request and the request as the agent sent it. They are not in the Store. They are kept only for a thread the keep-alive can ping (new in this push: Ctx.CanKeepAlive), for at most 30 minutes, for at most 256 threads. There is no byte bound yet (PR C, item D). This is the same kind of copy as the cache_aware_summarizer turn copies (item 6 of the audit).
  • Removed dependence. The sweep no longer writes removals (cg:res:) for replay. The old row said it kept "its removals, the originals, and 'still needed' answers" and "pays full price" without the body stash. That is gone.
  • Level columns for the sweep: Off does nothing (a ping needs the body stash, and nothing is held with no Store). Metadata only: the held answer works, but the in-memory conversation copies are content, so the row's Kind stays content. Everything: works.
  • Body stash row: now notes the 2 extra copies per thread outside the stash.

Summary

Rebased onto main after #507 merged; main (#691, #692) merged in later (see the last commit) (squash 1953b47c). The PR base is main. One commit. Point 11 uses the shared askStripsThinkingShipped (no TODO left). See "Rebase" below.

  • The sweep asks its question at the keep-alive ping, in place of the ping.
  • It holds the answer per thread. Nothing applies it yet. A held answer changes no request.
  • Until the cold apply (PR C) exists, the ping asks only when shadow is on. Otherwise it stays plain and sweep_ask_needs_shadow counts why.
  • The in-request ask, econ_trigger and the full-price fallback are removed.

What changed

  1. Ask at the ping. No timer of its own. The time window and pre_expiry_seconds are removed.
  2. No minimum. min_inventory is now 1. The per-ping cost ceiling still applies.
  3. Hold per thread in the Store (cg:swh:, pinned). Each judged output keeps its tool_use_id and a SpanHash of the agent's message. The record also keeps the judged length and the wait cause (feat(dash,proxy): record wait cause and wake cause per request (#424 record half) #453, stored only).
  4. Recheck. recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request.
  5. Shadow mode (off by default, in no preset). Reports sweep_shadow_asked, _proposed, _valid, _dropped_<reason> as request events, and a cg.sweep.shadow log line.
  6. Evidence on by default.
  7. Plain ping where the question breaks the cache (extract_llm_sweep: the prefix ask re-writes the cache on Haiku 4.5 with thinking #422), counted as sweep_model_declined.
  8. Multi-list question. extract.Ask composes lists. An output in two lists is judged once. No second list is built.
  9. Removed settings. econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure, block_fallback and pre_expiry_seconds are ignored: the config still loads, one warning names the key and why, and RetiredKeys counts it. The sweep acts as if the key was absent. Other bad keys (model, strategy, ...) still fail the load.
  10. Removed code. The in-request ask and splice phase, the econ pricing in the sweep, askLedger (sweep_askcost.go), and the fallback ask.

How it was tested

  • Eval box 1 (after the rebase): all packages pass (go test ./... areas touched, go vet ./..., gofmt). Offload, waitcause and keeper tests also pass with -race.
  • Mutation checks (each made a test fail, then restored):
    • recheck hash check removed
    • recheck length check removed
    • recheck "reference after the question" loosened
    • model decline removed
    • ping fallback allowed (first survived; the test was vacuous; fixed)
    • cache-read-zero check removed
    • held key moved into the replay namespace
    • shadow recheck on warm requests
    • second ping asks again
    • list dedupe removed
    • summary no longer takes the ping first
    • shadow gate on the ask removed
  • Tests moved to the ping path: the adjudication tests now run through askOffload (register, then ask at the ping). Evidence tests moved to extract_sweep_evidence_test.go. The prefix_econ guard tests moved to prefix_econ_guard_test.go (coref still uses that code).
  • Tests deleted (they tested only a removed path):
    • Whole files: extract_sweep_econ_test.go (econ trigger, 5 tests), extract_sweep_afford_test.go (3), extract_sweep_fallbackcost_test.go (4), extract_sweep_intent_test.go (3), sweep_askcost_test.go (ask ledger, pressure and opportunity floors), econ_band_sim_test.go (2).
    • extract_sweep_test.go: TestSweepFiresOnlyInThePreExpiryWindow, TestSweepDoesNothingOutsideTheWindow, TestPreExpirySecondsWidensTheWindow, TestSweepFallsBackWhenTheCacheReadDidNotHappen, TestBlockFallbackDeclinesInsteadOfPaying, TestSweepDebugImpliesBlockFallbackUnlessExplicit, TestSweepFallsBackWithNoAsker, TestSweepDoesNotAttributeAReplyShapeToTheFallback, TestBlockFallbackDistinguishesAZeroReadFromAWrite, TestBlockFallbackDecliningAWritePublishesTheCorrectRejection, TestSweepRemovesSpentOutputsFromOneCachedAsk, TestSweepReplaysItsRemovalOnLaterTurns, TestSweepStaleGuardStaysOutOfTheWayWithNoKnownBoundary.
    • commitgate_sweep_test.go: TestSweepFreezesNoDecisionForADropThatDidNotHappen, TestSweepTellsAReserveRefusalApartFromNothingSpent, TestSweepReportsItsOwnEconomicsAndTheWiresSeparately, TestSweepReplayBooksWhatTheReplayedMessageActuallySaved. commitgate_freshpath_test.go: TestSweepBooksNothingForADropItCouldNotStash. These test the splice; PR C brings them back.
    • Subtests / entries: the extract_sweep_drop subtest in commitgate_irreversible_test.go and the extract_llm_sweep case in commitgate_test.go (now in gateExempt with a reason; PR C must add its case back).
    • sweep_askdump_test.go: two econ-block tests. prefix_econ_premium_test.go: the config-refusal and ask-declined-label tests. prefix_econ_prunecredit_test.go: the pruning test.
  • No test-only switch remains for a removed path.
  • New: TestRetiredKeysLoadWarnAndChangeNothing (each removed key loads, warns once, is counted, and the sweep equals the one built without it) and TestRecordedBenchmarkConfigsWithRetiredSweepKeysStillLoad (the deploy/harbor/cfg-iter02*.yaml files load and build). Mutations: stripping removed; counting removed.

Rebase

Main moved a lot since the first push (198 commits). Conflicts and how I resolved them:

  • proxy/keepalive.go: main moved the keeper into package keepalive. I took main's file and put my keeper changes in the new package:
    • keepalive/substitute.go: fireSweepSubstitute (with its recover), projectedSweepUSD, sweepWaitCause, and recordSubstitutePing (shared with the summary substitute).
    • keepalive/keeper.go: the call in fire() after the summary, three counters, the Stats fields, Options.OpenTasks and Record.ToolUseNames (the wait cause inputs). ToolUseNames is on Record, not Usage, so Usage stays comparable.
    • proxy/keepalive.go: passes ToolUseNames and wires OpenTasks to waitcause.Tracker.OpenCounts.
    • My keeper tests moved to keepalive/sweepsubstitute_test.go (the old proxy/keepalive_sweepsubstitute_test.go is deleted).
  • components/offload/extract_sweep.go:
  • extract_sweep_test.go: kept main's TestSweepAsksOnTheSnapshotItChecked and its fakeCoveredAsker, adapted to the ping path (the covered span is now the whole conversation). Main's two BlockFallback tests test the removed fallback and are deleted.
  • extract_sweep_fallbackcost_test.go: main changed only its imports (the cheapmodel move and dispatchtest). All four tests in it (TestSweepFallbackAskPricesItsOwnCall, TestSweepCountsBothLegsWhenItFallsBackAfterAsking, TestAFailedFallbackStillLandsInTheLedger, TestAFailedFallbackAfterAskingStillGrowsTheRow) test the removed fallback, so it stays deleted. Main added no new behavior to it.
  • refactor(offload): one helper for the role and opening of an appended question #507 (now squashed into main as 1953b47; its round-1 commit e118ae2): it made the sweep's in-request prefix ask decline on askStripsThinkingShipped (gate sweep_thinking_would_be_stripped, then the fallback), removed askBridge, and changed cheapmodel.insertAskMessage to use lastBridge. This PR removes that in-request ask and the fallback, so the conflict was in code I delete. I kept the askBridge removal and the cheapmodel change. The same rule runs at the ping through sweepModelDeclines and is counted as sweep_model_declined (TestModelsWhereTheQuestionBreaksTheCacheGetAPlainPing). No path uses the gate name sweep_thinking_would_be_stripped now, so it is not in the docs list. refactor(offload): one helper for the role and opening of an appended question #507's TestSweepDeclinesThePrefixAskWhenItWouldStripThinking drove the removed path; I replaced it with a pointer to that test.
  • internal/cheapmodel is now cheapmodel/: I updated my imports. refactor(offload): one helper for the role and opening of an appended question #507's TestSweepQuestionOpensWithTheSharedLine drove the removed in-request ask; it now asks through askOffload.
  • A new mutation re-run on the conflicted files (all fail a test): cache-read check removed, stale-prefix guard off, covered snapshot ignored, shared opening frame dropped, point 11 shared check off, keeper hook removed, summary-not-first, wait cause dropped, retired-key strip off, shadow gate off, ask recover off. One survived first (the keeper's own recover was masked by the offload one), so I added TestKeepAliveSurvivesAPanicInTheKeepersOwnQuestionCode.

Review round 1 (GLM, head 0211b4d) fixes

  • Data dependence: docs rewritten (above). registerPing now keeps a copy only when the keep-alive can ping the thread (TestWithKeepAliveOffNothingIsRegistered).
  • Concurrency: the collection slot is a non-blocking send before collect(), released on every exit (TestCollectionRunsAtMostSlotsAtOnce: 16 goroutines behind a barrier, collectPeak never above cap(sweepSlots); TestACollectionSlotIsReleasedWhenDispatchIsNeverCalled).
  • The result-cache miss is recorded in collect (TestCollectionRecordsTheResultCacheMiss).
  • sweep_concurrency_full and sweep_not_registered are counted and in /stats (TestAConcurrencyRefusalIsCounted).
  • advanced-offload.md: the "in-request ask remains" sentence, the dead counter names and the "read as a pair" text are gone; the benchmark-era enabling section is replaced.
  • Comment rot removed. retry removed from the wait-cause list (a failed response never reaches the keeper).
  • The shadow ask and the cold recheck are each reported once, under a mutex (TestTheShadowAskIsReportedOnceUnderConcurrentRequests, TestTheColdRecheckIsReportedOnceUnderConcurrentRequests).
  • A comment where the two ask timeouts meet.
  • Mutations (each fails a test): acquire the slot after collect; never release the slot; register without the keep-alive gate; no miss metric; no concurrency count; non-atomic report claim; non-atomic recheck claim; canPing ignoring policy.

Review round 1 fixes

  • Blocking: a panic in the ping question no longer reaches the keeper's goroutine. SweepPingSubstitute and the dispatch closure both recover. The panic is logged, counted (sweep_ping_panics, SweepPingCounters().Panics), and the ping stays plain. cand.asked stays true, so the next ping is plain too. fireSweepSubstitute has a last-line recover as well.
  • E: H1 now compares the full serialized request (model, params, all messages) over 4 growing requests on 3 cache phases (TestH1EveryRequestAfterAnAnswerIsByteIdenticalToTheSweepOff). The optionsfields wording is fixed.
  • C: the concurrency bound is checked before candidate collection.
  • B: the orphan fallbackAsk comment is removed.
  • New mutations: no recover in the ask; no recover in collect; slot check removed; verdict also stored as a replay record (fails H1); asked reset after a panic. Each fails a test.
  • sweep_ask_needs_shadow and sweep_ping_panics are now in /stats (the first was missing from the stats struct).

Acceptance tests (#404) for PR A

ID Test
A1 TestKeepAliveSendsTheSweepQuestionInPlaceOfTheNextPing (keepalive; the question replaces the ping, no ordinary ping is sent) and TestTheQuestionIsAskedAtThePingAndNotInTheRequest (offload; a request asks 0 times)
A2 TestNoKeepAliveNoQuestion (keepalive; keep-alive off, and a prompt under the 80k floor)
A3 TestTheQuestionIsAskedAtThePingAndNotInTheRequest (1 candidate asks), TestKeepAliveWithZeroCandidatesSendsAPlainPing (0 candidates: plain ping)
A4 TestKeepAliveSendsAPlainPingWhereTheQuestionWouldBreakTheCache (plain ping, sweep_model_declined +1), TestModelsWhereTheQuestionBreaksTheCacheGetAPlainPing (model table)
A5 Live, release integration check (not run on this PR)
H1 TestH1EveryRequestAfterAnAnswerIsByteIdenticalToTheSweepOff (also TestAHeldAnswerChangesNoRequest)
H3 TestHeldAnswerNeverReachesAnotherThread (p:, a:, a subagent thread), TestHeldAnswersAreKeptPerThread
R1 TestRecheckDropsAVerdictForEachReasonAndOnlyThen/R1_the_output_is_gone
R2 .../R2_the_content_changed
R3 .../R3_the_conversation_is_shorter_than_when_judged
R4 .../R4_a_later_turn_referenced_the_output
R5 .../R5_the_agent_expanded_it

Open questions

  • Unverified live, for the release integration check: CompletePrefixed does not forward Anthropic-Beta (the plain ping does). A prompt over 200k tokens may need context-1m-2025-08-07 on some gateways, and the question could then miss the cache or fail. The failure is safe (plain ping, or the write > read stop). The summarizer substitute has the same gap. A5 covers it.

  • internal/extract.BuildFallbackAsk and the unused pricing code in prefix_econ.go are pruned in PR C, not here. Coref keeps what it uses.

Technical notes

  • For PR C (review D, F). registerPing keeps a conversation copy per thread for up to 30 minutes (256 threads), now only where the keep-alive can ping; pruning runs only at the cap, and there is no byte bound (item D). applySweepDropReplay still reads cg:res: records that only extract_llm writes now; remove or namespace it in PR C.

  • Left for PR C (review round 2).

    • putHeld is not serialized with the claims (claimHeldReport, claimHeldSpend). The claims serialize with each other, but a putHeld from the ping can interleave with one. Fix this before PR C makes the held answer load-bearing (reviewer 1).
    • A refusal at the ask-level slot (inside ask) is counted under sweep_ask_failed, not sweep_concurrency_full. The collection-level refusal is counted correctly.
    • claimHeldSpend consumes the answer before the recheck runs, so a panic in the recheck loses the answer. That fails open (no drops); PR C should consume after the recheck.
  • Durability. cg:swh: has the same durability as cg:res: and cg:sum:: the Store is in memory, so a restart loses the held answer. That fails open: no drops.

  • Registration. The pipeline registers a conversation snapshot per thread. The keeper looks it up when a ping falls due. Candidates are collected at the ping, not per request.

  • For PR D. The summary substitute goes first at the ping; the sweep is tried only when it declines. I extracted recordSubstitutePing from recordSummarySubstitute so both book a substituted ping the same way.

  • Gate. The shadow check is in SweepPingSubstitute, with a TODO naming PR C. PR C removes it.

  • Haiku 4.5 with no thinking blocks is not skipped (extract_llm_sweep: the prefix ask re-writes the cache on Haiku 4.5 with thinking #422's measured case needs a thinking block before the last message).

Part of #404.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Review round 1 of 3

Verdict

Blocking. 1 blocking finding. The design matches the agreed decisions. H1 holds by code reading and by tests. One fail-open gap can crash the proxy.

What I ran

Synced head 6632593 to the eval box (~/rev508).

  • go vet on components, proxy, internal, config, store: clean. gofmt -l: clean.
  • go test ./components/... ./internal/... ./config/... ./store/...: all pass.
  • go test ./proxy -run 'Sweep|KeepAlive|PR431|OptionsFields': pass.
  • go test -race ./components/offload -run 'Sweep|Held|Recheck|Shadow|Ping|Retired': pass.
  • I did NOT run the full ./proxy/... suite.
  • Mutations I added (each should fail a test):
    • recheck "expanded" check removed: test fails (good)
    • recheck finds the output by index, not by tool_use id: test fails (good)
    • output hash made a constant: test fails (good)
    • ask reads the stash by session, not by thread key: test fails (good)
    • held answer stored under the session, not the thread key: test fails (good)
  • Panic probe (throwaway test, deleted): the asker panics inside dispatch. The panic escapes. See finding 1.
  • No live run against a main-branch control. I did not start a proxy. H1 and the cache checks below rest on code reading plus unit tests. Marked "unverified live".

Blocking findings

1. A panic in the ping-time question crashes the proxy. proxy/keepalive.go:580 (go k.fire(j)), components/offload/extract_sweep_ping.go (SweepPingSubstitute, collect, ask).

  • The question runs on the keeper's own goroutine. The pipeline's recover does not cover it. fire() has no recover. ask() has none.
  • This PR puts much more code on that goroutine: candidate collection, the co-reference index, Judge, buildHeld, JSON, Store writes.
  • Checklist item 5 says a panic must leave the ping a plain ping. It does not.
  • How I verified: test with a prefix asker whose Ask panics. dispatch(...) re-panics to the caller. In production the caller is a bare goroutine, so the process dies.
  • The summarizer's detached call has a recover for this exact reason (cache_aware_async.go:166, "a panic in a detached goroutine takes the process down").
  • Fix: wrap both SweepPingSubstitute (collect) and the dispatch closure in a recover. Return ok=false or a Substituted=false result. Count it and log it. Add a test that panics in Ask and in collect.
  • Note: after a panic cand.asked is already true, so the next ping stays plain. That is the right result. Keep it.

What I checked and found correct

  1. H1 (held answer changes no request).
    • The only code that changes req in Offload is applySweepDropReplay, and it needs a cg:res: hit.
    • The sweep no longer writes cg:res:. The held answer is in cg:swh: (pinned). Nothing reads it to change a request. shadowStep writes only to rep and the Store.
    • TestAHeldAnswerChangesNoRequest covers warm, cold and near-expiry requests and also checks that no cg:res: record exists.
    • Unverified live: no byte-diff against a main-branch control run.
  2. Cache safety of the question. CompletePrefixed appends one user message with no cache_control. It leaves tools and thinking alone. The question is fresh input, not a cache write. Any write or zero read makes adjudicateWith decline, and the keeper stops pinging on write > read. Matches the issue's measurement (19,595 read, 0 written). See non-blocking item A about headers.
  3. Per thread. Registration, the stash read, putHeld, getHeld and shadowStep all use thread.Key(session, thread). Mutation 4 and 5 above confirm tests catch a mix-up. A p: or a: thread has its own key and cannot read the main thread's answer.
  4. Recheck. Each reason is checked in order, one reason per verdict. The match is by tool_use id. "Referenced later" uses Idx+ConsumeLag >= Judged, and message indexes line up with flattenForCoref. Tests fail under mutation.
  5. Retired keys, config. All six load, warn once and are counted. The benchmark configs cfg-iter02*.yaml load and build. model, strategy and the other banned keys still fail the load.
  6. Removed code. No non-test reference remains to askLedger, the fallback ask or econ_trigger. The remaining preExpiryFor in proxy/keepalive.go belongs to the generic Trigger, not the sweep. The deleted tests all target removed paths.
  7. Decisions. Shadow gate (ask_needs_shadow), once-per-idle (already_asked, reset by the next request), summary-before-sweep, in-memory held answer, and the point 11 TODO all match.

Non-blocking

  • A. Header gap, unverified. The plain ping forwards Anthropic-Beta (pingHeaders). CompletePrefixed sends only anthropic-version and the credential. The same gap exists today for the in-request ask and the summarizer substitute. A beta that changes the cache key or the context limit (for example 1M context) could make the question miss the cache or fail. The failure is safe (plain ping, or write > read stop), but the ping would then be lost for that span. Consider a live check with a beta-header client, or file an issue.
  • B. extract_sweep.go (above flattenTranscript): a doc comment for fallbackAsk is left behind. The function is gone.
  • C. components/offload/extract_sweep_ping.go: SweepPingSubstitute runs candidate collection (hash of every output, co-reference pass) before the concurrency bound. With many due threads this runs unbounded. Move the slot check first, or collect inside ask.
  • D. registerPing keeps a conversation copy per thread for up to 30 minutes, up to 256 threads, even when keep-alive is off. Pruning runs only on insert at the cap. Memory is bounded but not small.
  • E. TestAHeldAnswerChangesNoRequest compares message text only, in a one-element loop. Compare the full serialized request. optionsfields_test.go says the retired key "is now refused"; it is ignored.
  • F. applySweepDropReplay still reads cg:res: records. Only extract_llm writes them now. Remove or namespace it in PR C.

@amiddavid
amiddavid force-pushed the feat/sweep-cold-ask branch from 6632593 to 101e62b Compare October 13, 2026 11:54
@OsherElhadad OsherElhadad mentioned this pull request Oct 21, 2026
14 of 31 tasks
amiddavid added a commit that referenced this pull request Oct 21, 2026
The sweep removal is temporary (restore with #508). Undo the docs and plugin
text edits. Keep the two config changes and the test. Add a short comment
at each of the two places.

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 21, 2026
fix(config): turn the sweep off in the xhigh preset for 0.5.3

xhigh no longer runs extract_llm_sweep. In 0.5.3 it is the same as high.
The sweep is still under work (#508) and returns to xhigh when #508 lands.
The name xhigh still loads. extract_llm_sweep stays registered, and housellm keeps it.

Update the preset comments, docs, README, and the plugin texts that said
xhigh adds the sweep. Add a test that xhigh has no sweep and equals high.

Closes #652

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

fix(config): limit the xhigh change to config only

The sweep removal is temporary (restore with #508). Undo the docs and plugin
text edits. Keep the two config changes and the test. Add a short comment
at each of the two places.

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

fix(config): keep the two preset-list guards green for xhigh

TestPresetDocsDoNotDrift and TestPluginPresetPipelinesAgreeWithConfig compare
the xhigh pipeline in docs/reference/presets.md and insights.py with config.go.
Change only those two lists. No prose changes.

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

style(config): gofmt the xhigh preset entry

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid
amiddavid force-pushed the feat/sweep-cold-ask branch from 101e62b to b1f4262 Compare October 25, 2026 08:56
@amiddavid
amiddavid changed the base branch from main to refactor/ask-instruction-role October 25, 2026 08:56
@amiddavid
amiddavid marked this pull request as ready for review October 25, 2026 08:57
@amiddavid
amiddavid force-pushed the feat/sweep-cold-ask branch from b1f4262 to cea7b42 Compare October 25, 2026 09:23
@amiddavid
amiddavid changed the base branch from refactor/ask-instruction-role to main October 25, 2026 09:25
@amiddavid
amiddavid force-pushed the feat/sweep-cold-ask branch from cea7b42 to 0211b4d Compare October 25, 2026 09:31

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

Who Backend How this review was produced Context Reviewer Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.309 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 0211b4dc9953 blocking

Verdict: blocking

Findings

1. The PR changes the sweep's data dependence, and docs/data-dependence.md does not say so

What fails. CLAUDE.md makes data dependence a hard boundary: every PR that adds or changes a feature states its data dependence, updates docs/data-dependence.md, and states a change in either direction at the top of the PR, with the row's "Decided by" confirmation. This PR changes the sweep's data dependence in three ways and does none of that:

  1. Two new full conversation copies per registered thread, in memory. registerPing (components/offload/extract_sweep_ping.go:228) copies the whole conversation twice — cand.input (the pipeline view) and cand.raw (c.RawInput) — and holds both for up to 30 minutes, over at most 256 threads, with no byte bound. The copies are taken on every request where the sweep runs, before anything decides whether keep-alive will ever ping this thread.
  2. A new pinned store namespace. cg:swh: (store/store.go, added to DefaultPinPrefixes) holds one full adjudication answer per thread, and pinning means the LRU cannot evict it.
  3. The old dependence is gone. The sweep no longer writes its removals to cg:res: for replay. Row 198 of docs/data-dependence.md says the sweep's storage is "its removals … the originals, and 'still needed' answers" and that it "pays full price to send parts of up to 12 outputs". After this PR that row describes behavior that no longer exists. Row 216 ("Body stash … 2 full bodies per thread") now under-counts: the sweep registry adds two more copies per thread that the row does not know about.

The PR body does not state the data-dependence change at the top, and no row's "Decided by" confirmed it.

Proof.

  • git diff 1953b47..HEAD -- docs/data-dependence.md is empty — the file is unchanged.
  • registerPing copies input and raw unconditionally from the Offload path (defer e.registerPing in Offload), gated only by the candidate registry's size and age, not by the keep-alive policy: a thread whose policy has KeepAlive: false still pays the copies. TestNoKeepAliveNoQuestion proves the question is skipped, not the registration.
  • Row 198 (docs/data-dependence.md:198) and row 216 (:216) both still describe the pre-#404 sweep.

Fix. Update docs/data-dependence.md: rewrite the extract_llm_sweep row for the ping-time question, the held answer in cg:swh:, and the in-memory conversation copies; correct the body-stash row's per-thread count. State the change at the top of the PR body, and get the row's "Decided by" confirmation before merge.

2. The pre-collection concurrency bound does not bound collection

What fails. The check at components/offload/extract_sweep_ping.go:351 reads len(sweepSlots) >= cap(sweepSlots) before collect() runs, and its comment says the bound is "BEFORE the work: collection hashes every output and runs the co-reference index, and with many threads due at once it would run unbounded". The bound does not hold. The slot is only taken later, inside ask (:440), as a non-blocking send. Between the length check and the send there is no synchronization, and the keeper dispatches every due ping at once: Sweep starts one goroutine per due job (keepalive/keeper.go:1168-1171), and fire releases the tenant's spare slot before it calls the substitutes (:1242), so nothing else limits how many run together.

So on one keeper tick with N due threads, all N goroutines can read len(sweepSlots) == 0, all N pass the check, and all N run collect() — per-output content-key hashing plus a co-reference index pass over the whole conversation, on full conversation copies, for each of N threads at the same time. Only the model call is bounded to 4. With shadow mode on and a busy proxy, this is an unbounded CPU and allocation burst on the keeper's tick, exactly what the comment says cannot happen. Fail-open holds — a thread that loses the race still gets its plain ping — so nothing breaks correctness; the defect is that the stated safety property is not enforced, and the test (TestTheConcurrencyBoundIsCheckedBeforeCollection) only covers the sequential case, so it cannot catch it.

Proof.

  • extract_sweep_ping.go:349-353: the check is a plain len() on the channel; sweepSlots (:196) is a buffered channel of 4, filled only by the non-blocking send inside ask (:440+), which runs after collect() has already finished.
  • keepalive/keeper.go:1168-1171: for _, j := range due { k.o.Go(func() { k.fire(j) }) } — all due jobs start at once, with no concurrency limit of their own.
  • keepalive/keeper.go:1242: release() drops the spare slot before fireSweepSubstitute, so the tenant limiter does not bound it either.

Fix. Take the slot before collect(), not after: acquire sweepSlots (non-blocking) at the top of the dispatch path, and release it when the ask declines or errors. Then len()-style admission is unnecessary and the bound is real. Alternatively bound collection with its own semaphore and leave the ask's slot as is — but then say so in the comment.

Non-blocking

  • Registry memory. The two conversation copies per thread (256 threads, 30 min, no byte cap) follow the pattern registerKeepAliveCandidate already set for the summarizer, and the PR's Technical notes acknowledge the cost. It still doubles the per-thread footprint. Worth a byte bound in a follow-up.
  • Ask.Add overwrites caller-set labels (internal/extract/ask.go:88). adjudicateWith passes items with Label: k already set; Add reassigns. Harmless with one list, because the items are matched by label after the fact. A second list (#490, #485) that reads labels before Add would be surprised. A doc line on Candidates() ("Label unset") already exists; the caller ignoring it is the nit.
  • markHeldReported get-then-put race. Two concurrent cold requests for one thread can both read Reported == false and both emit the shadow report. The store is keyed per thread, so one wins the final write. Double-counted metrics only; shadow mode is diagnostic. shadowStep could set Reported under a mutex or CAS-style.
  • The ask's timeout is effectively min of the passed timeout and llmCallTimeout inside adjudicateWith. The keeper passes CacheAwareSummarizerCallTimeout() (300 s); the inner cap may end the question earlier and report it as failed. Fail-open holds. Worth a comment so the two constants do not drift apart silently.

What I checked

  • The full diff of all 48 files against 1953b47c, including every deleted test and the new test files, plus the code around each change.
  • The ping-time stale-prefix guard. registerPing snapshots with MaxCachedIdx: len(req.Input)-1; PrefixCoveredAsker.AskCovered re-checks coverage on the same stash read, closing the check-then-ask race. A new request between registration and the ping makes the ask decline with ErrStalePrefix and the ping go out plain. Sound.
  • cg:swh: versus cg:res:. The replay loop reads only getResult hits in cg:res:; held answers live in cg:swh: and are never replayed. TestAHeldAnswerChangesNoRequest pins the byte-identity claim, and TestH1EveryRequestAfterAnAnswerIsByteIdenticalToTheSweepOff checks it over four growing requests and three cache phases. Sound.
  • Recheck reasons (conversation_shorter, output_gone, content_changed, referenced_later, expanded): each verified against the code, including the Idx + ConsumeLag >= Judged reference math and the raw-coordinate hash from rawSpanForHash. Sound.
  • Fail-open at every level. Panic recovery at the substitute, the dispatch closure, and fireSweepSubstitute; every "no" (no shadow, already asked, model declines, over budget, no inventory, concurrency, ask error, panic) falls through to the ordinary ping. Tests cover each. Sound.
  • asked lifecycle. CAS before the call; reset only when nothing left the process; left set on panic so the next ping is plain. Sound.
  • Registry cleanup. ClearKeepAliveCandidate/ClearStaleKeepAliveCandidate clear the sweep registration on retire, evict, shutdown, forget, and stale-entry paths. Sound.
  • Bookkeeping. recordSubstitutePing counts a substituted question once as the ping; deferred billing reuses the #455 mechanism idempotently; recordSweepKeep still writes the keep cache that admit reads at ping time. Sound.
  • Config. Retired keys (econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure, block_fallback, pre_expiry_seconds) are stripped with a warning and counted; banned keys still fail the load; the housellm preset keeps min_tokens: 1000 and gains the evidence: true default, which the PR intends; shadow is in no preset. TestRecordedBenchmarkConfigsWithRetiredSweepKeysStillLoad covers old configs.
  • Wiring. proxy/keepalive.go passes ToolUseNames and OpenTasks; waitcause.OpenCounts fails open on panic; ClassifyWaitingFor's call signature matches; sweep_ask_needs_shadow and sweep_ping_panics reach /stats.
  • Docs. docs/components/advanced-offload.md matches the new behavior (trigger, hold, recheck, shadow counters, retired keys, config table). docs/data-dependence.md does not — finding 1.
  • No tests were run (live tests not approved for this review); every claim above is from reading the diff and the surrounding 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.309 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 0211b4dc9953 blocking

Verdict: blocking

Findings

  1. components/offload/extract_sweep_ping.go:419 — the sweep's cache hit-rate now always reads 100%

    • What fails: after this PR, extract_llm_sweep records no missed result-cache lookup. The only remaining call is the replay hit (extract_sweep.go:545). So cache_hit_rate for this component (metrics/extract.go:507) is hits over hits, always 1.0. An operator reading /stats sees a perfect hit rate that no run produced.
    • Proof: the base recorded one miss per non-hit candidate while collecting (base extract_sweep.go:822, metrics.RecordExtractionCacheLookup(rep.Component, false)). This PR moved collection to the ping. The ping's collect still does the lookup — c.Store.Get(resultKey(c.Session, id)) at extract_sweep_ping.go:419 — but records no metric. Grep over the worktree: the sweep's only call left is the hit; extract_llm still records both sides (extract_llm.go:1045).
    • Fix: record the miss in collect, next to the getResult check.
  2. components/offload/extract_sweep_ping.go:351 — a question refused for a full concurrency bound is invisible in /stats

    • What fails: when all 4 slots are busy, SweepPingSubstitute returns concurrency_full and no counter moves. The keeper logs it at Debug only (keepalive/substitute.go:291). The Stats block this PR adds has no field for it.
    • Proof: every sibling reason increments a counter at its return — sweepPingNoCandidate (:336), sweepPingNeedsShadow (:342), sweepPingAlreadyAsked (:346), sweepPingModelDeclined (:356), sweepPingNoInventory (:367, :371). The summary substitute counts the same refusal (summarySubstituteConcurrencyFull, keepalive/substitute.go:143). The sweep path has no equivalent.
    • Fix: count it as the summary path does. Add a sweep_concurrency_full counter to SweepPingCounters() or the keeper Stats.
  3. docs/components/advanced-offload.md:242 — the doc says an in-request ask remains, and lists seven counters that no longer exist

    • What fails: two stale blocks.
      • Lines 240-242: "econ_trigger ... is off by default and is the only in-request ask that remains." False. This PR removes every in-request ask. Offload only replays frozen decisions, and TestSweepAsksNothingInsideARequestByDefault pins zero asks in a request.
      • Lines 554-566: the diagnostics list still names sweep_fallback_used, sweep_fallback_blocked, sweep_fallback_failed, sweep_fallback_no_model, sweep_inventory_below_min, econ_ask_not_repaid, prefix_rewrite_not_repaid. Lines 568-569 then tell the operator to read the last two as a pair.
    • Proof: grep for each of the seven names over components/, tests excluded: zero producers. The blockquote at lines 233-238 says the keys are gone and ignored. The two blocks contradict each other in one file.
    • Fix: delete the "remains" sentence and the seven dead names, or mark them as history the way the #491 blockquote does.

Non-blocking

  • Comment rot names removed machinery. extract_sweep.go:642-646 explains the named result by a defer foldFallback() that no longer exists. Lines 906-930 describe the removed FALL BACK / block_fallback: true choice, above code that now always declines. Line 1004 cites sweepIntent. extract_sweep_test.go:214-221 still explains the fallback model and effectiveBlockFallback. summarize.go:407 contrasts against the sweep's not_in_pre_expiry_window gate, which this PR removes.
  • extract_sweep_recheck.go:127 — r.Idx + r.ConsumeLag >= h.Judged compares positions on the cold request against the judged length. Messages inserted above a pre-question reference can misfile it as referenced_later. The error keeps content, so it is fail-safe.
  • The ping registry is bounded by thread count (256), not bytes. Each entry holds a copy of the conversation. The keep-alive registry uses the same convention (2048 bodies), so this is consistent.
  • advanced-offload.md:227 lists retry among the stored wait causes. A failed response never establishes a keeper entry (keeper.go:665 refuses non-2xx), so retry cannot be stored. Harmless.

What I checked

  • The full diff, 48 files, 1953b47c..0211b4dc. All four new sweep files in full: extract_sweep_ping.go, extract_sweep_hold.go, extract_sweep_recheck.go, extract_sweep_shadow.go. Also internal/extract/ask.go, keepalive/keeper.go, keepalive/substitute.go, internal/waitcause, proxy/keepalive.go, store/store.go, and the rewritten docs.
  • Fail-open. Every "no" at the ping leaves the ordinary ping. Panics are recovered at three levels: SweepPingSubstitute, ask, and fireSweepSubstitute. The in-request loop only replays frozen decisions. Tests pin that a held answer changes no request, across cache phases, and that nothing falls back to a full-price completion.
  • Namespace separation. Held answers live under pinned cg:swh:. Nothing replays them. The Spent tombstone stands in for the store's missing Delete.
  • Thread keys. Every keeper and lifecycle caller passes thread.Key(session, thread). The keep-alive clearers also clear the ping registry. TestRegistrationIsClearedByTheKeepAliveClearers pins it.
  • Retired keys. Each is ignored with one warning and a counter, and the config still loads (TestRetiredKeysLoadWarnAndChangeNothing). Banned keys are still refused. shadow: true is absent from the shipped presets.
  • internal/extract/ask.go. A one-list Prompt() equals BuildPrefixAsk byte for byte; the test pins it.
  • The reworked tests: the askOffload helper, the ping, recheck, evidence, keeper and proxy test files, and every deleted econ, fallback and commitgate test.
  • A grep for every symbol the PR removed (askLedger, econDecision, foldFallback, runFallback, fallbackAsk, and the rest). No live reference remains. Only comments name them.
  • Not run: Go builds and tests. Live tests were not approved for this review.

…adow mode

Part A of #404 (the cold path). The sweep asks its question in place of
the keep-alive ping and holds the answer per thread. Nothing applies a
held answer yet: it changes no request.

- Ask at the ping, no timer of its own. The time-window trigger and
  pre_expiry_seconds are removed (the key is refused with the reason).
- Ask with one candidate or more. min_inventory defaults to 1.
- Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a
  SpanHash of the agent's message for each judged output, the judged
  length and the wait cause (#453). Stored only; nothing decides on it.
- recheckHeld drops a verdict when the conversation is shorter, the
  output is gone or changed, a later turn referenced it (coref), or the
  agent expanded it. PR C calls it on the cold request.
- shadow: true (off, in no preset) reports asked, proposed, still valid
  at the cold request, and the reasons, as request_components events and
  a cg.sweep.shadow log line.
- evidence is on by default.
- Plain ping, counted as sweep_model_declined, where the question breaks
  the cache (#422).
- Ask only when shadow is on, until the cold apply exists (PR C). Counted
  as sweep_ask_needs_shadow.
- Remove econ_trigger, the in-request ask and the full-price fallback.
  The keys econ_trigger, econ_ignore_ask_cost, reward_premium,
  min_pressure and block_fallback are ignored with a warning and a count,
  so an old config still loads.
- extract.Ask composes the question from lists, so #490 and #485 can add
  theirs. An output in two lists is judged once.
- Recover from a panic in the ping question: the ping stays plain, the
  panic is counted, and the next ping is plain too. Check the concurrency
  bound before collecting candidates.

- Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper
  changes live in package keepalive (main moved the keeper there); the
  wait cause reaches it through Options.OpenTasks and Record.ToolUseNames.
  The question is framed with the shared opening line (resolveAsk.Frame)
  and asked through AskCovered when the asker supports it.

- Review round 1: keep the conversation copies only for a thread the
  keep-alive can ping (Ctx.CanKeepAlive). Take the collection slot before
  collecting and release it on every exit. Count the result-cache miss in
  collect, and count sweep_concurrency_full. Report the shadow ask and the
  cold recheck once, under a mutex. Rewrite the sweep rows of
  docs/data-dependence.md and drop the stale counters and prose from
  advanced-offload.md.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid
amiddavid force-pushed the feat/sweep-cold-ask branch from 0211b4d to 173180d Compare October 25, 2026 10:42
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 replies (head 0211b4d, fixed in 173180d)

Reviewer 1

  1. Data dependence: fixed in 173180d. docs/data-dependence.md rewritten: the extract_llm_sweep row (held answer, in-memory copies, the dropped cg:res: writes), the "Body stash" row (2 extra copies per thread), the audit lists and counts. A "Data dependence change" section is now at the top of the PR body. The held answer is metadata (ids, hashes, token counts, verdicts, conversation length, model, cost, wait cause). I checked this against the heldAnswer and heldOutput structs. The row's "Decided by" confirmation from David Amid is pending; I did not write it. registerPing now keeps a copy only when the keep-alive can ping the thread (new Ctx.CanKeepAlive, wired from keeper.canPing). Tests: TestWithKeepAliveOffNothingIsRegistered, TestNoAskerOrObserveModeRegistersNothing, TestCanPingFollowsTheKeepAlivePolicy. The row's Kind stays content because of the in-memory copies.
  2. Concurrency bound: fixed in 173180d. The slot is a non-blocking send taken before collect() and released on every exit (decline, error, panic, or a keeper that never calls dispatch). TestCollectionRunsAtMostSlotsAtOnce starts 16 goroutines behind a barrier and checks collectPeak <= cap(sweepSlots) and that no slot leaks. Mutation: acquire after collect, and the test fails.
  3. Non-blocking, markHeldReported race: fixed. A mutex-protected claim (claimHeldReport) makes the ask report once. I made the cold recheck's consume the same kind of claim (claimHeldSpend), since it had the same get-then-put race. Tests use a store that sleeps after Get, so a non-atomic claim fails every time.
  4. Non-blocking, the two ask timeouts: fixed. A comment at the meeting point in ask.
  5. Non-blocking, registry memory (no byte bound): not changed here. It is PR C's item D (brief). The PR body notes it.
  6. Non-blocking, Ask.Add relabels: not changed, by design. Add assigns one label sequence across all lists, so that a verdict's i names one item. Candidates() documents "Label unset". The sweep sets labels only because it builds the items before composing. With one list it is harmless, as the reviewer says.

Reviewer 2

  1. Cache hit rate: fixed in 173180d. collect records the miss with metrics.RecordExtractionCacheLookup(rep.Component, false). Test: TestCollectionRecordsTheResultCacheMiss (3 candidates give 3 lookups).
  2. concurrency_full invisible: fixed. Counted as sweep_concurrency_full in SweepPingCounters() and /stats. Test: TestAConcurrencyRefusalIsCounted. I also added sweep_not_registered.
  3. Stale docs: fixed. The "in-request ask remains" sentence, the seven dead counter names and the "read as a pair" text are removed from advanced-offload.md. I also replaced the benchmark-era enabling section, which told operators to set econ_trigger.
  4. Non-blocking, comment rot: fixed. extract_sweep.go (the named-result note, the FALL BACK block, the sweepIntent mention), extract_sweep_test.go (the fallback model and effectiveBlockFallback), and summarize.go:407. retry is removed from the wait-cause list (a failed response never establishes a keeper entry).
  5. Non-blocking, referenced_later misfile: not changed. The reviewer notes it is fail-safe: a misfiled reference keeps content, so it cannot cause a wrong drop.
  6. Non-blocking, registry bounded by threads, not bytes: not changed here. Same as reviewer 1's item (PR C, item D).

Verification

Box 1, foreground, -count=1: full suites pass (./proxy/..., ./dash/..., ./keepalive/..., components, config, internal, store, apply, cmd, metrics, modes, expand, schema, adapters, session, tenant, cheapmodel, dispatch, predictive, kvcache, proxyapp). go vet ./... and gofmt are clean. -race -count=1 passes for offload, waitcause, keepalive, apply, and the proxy keeper tests. Mutations (each fails a test): slot acquired after collect, slot never released, registration without the keep-alive gate, miss metric removed, concurrency count removed, report claim made non-atomic, recheck claim made non-atomic, canPing ignoring the policy.

)

The ping-time question and the held answer in cg:swh: (metadata only)
are approved, with the two in-memory conversation copies per thread
kept only while the keep-alive can ping the thread, for at most 256
threads and 30 minutes.

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

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 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 308425f17442 approve

Verdict: approve

Round-1 findings

My finding 1 (data dependence): fixed.

  • docs/data-dependence.md is rewritten. The extract_llm_sweep row now states the held answer (cg:swh:, pinned, metadata: ids, hashes, counts, verdicts, no text), the two in-memory conversation copies (30 minutes, 256 threads, only where the keep-alive can ping), and that cg:res: removals are no longer written. The "Body stash" row, the audit lists, the summary counts and the "storage off" list all match the new behavior.
  • The PR body now opens with a "Data dependence change" section that states the change and the approval.
  • The row's owner confirmed it: commit 308425f1 is authored and signed off by DAVID AMID and records "ping-time question and held answer approved 2026-10-25 (#508)" in the row.
  • The registration is also narrower now: registerPing keeps a copy only when c.CanKeepAlive() says the host's keep-alive can ping the thread (new components.Ctx.CanKeepAlive, wired from keeper.canPing through apply.Opts on both the chat and the responses path). A host with no hook keeps nothing. TestWithKeepAliveOffNothingIsRegistered and TestCanPingFollowsTheKeepAlivePolicy pin it.

My finding 2 (concurrency bound): fixed.

  • The slot is now a non-blocking send taken before collect() (extract_sweep_ping.go:364-372), released by a defer on every exit — a decline, an error, a panic, or the hand-off to the dispatch closure. The defer is registered after the panic-recover defer, so on a panic the slot is released before the recover runs. A keeper that declines after ok (the cost ceiling) and never calls dispatch holds no slot.
  • TestCollectionRunsAtMostSlotsAtOnce starts 16 goroutines behind a barrier and checks collectPeak <= cap(sweepSlots) and that no slot leaks; TestACollectionSlotIsReleasedWhenDispatchIsNeverCalled covers the never-dispatched case. The look-then-take race is gone.

My non-blocking items: the markHeldReported race is fixed (claimHeldReport/claimHeldSpend under heldMu, with tests on a store that sleeps after Get); the two-timeouts comment is in ask; the registry byte bound is deferred to PR C and stated in the PR body; the Ask.Add label point is rejected with a reason I checked and accept — Candidates() documents "Label unset", and one label sequence across lists is the design.

Reviewer 2's findings — agree, and checked myself: all three fixed. The miss is recorded in collect (metrics.RecordExtractionCacheLookup(rep.Component, false), with TestCollectionRecordsTheResultCacheMiss); sweep_concurrency_full and sweep_not_registered are counted and reach /stats through SweepPingCounters() and the keeper Stats; the stale doc blocks ("the only in-request ask that remains", the seven dead counter names, the "read as a pair" text) are gone from advanced-offload.md, and the benchmark-era enabling section now shows shadow: true. Their comment-rot and retry items are fixed too; the referenced_later misfile stays by the author's reasoning, which matches reviewer 2's own note that it is fail-safe.

Findings

None.

Non-blocking

  • ask's putHeld is not serialized with the claims (extract_sweep_ping.go:561 writes cg:swh: on the keeper's goroutine; claimHeldReport/claimHeldSpend do their get-then-put under heldMu, but the producer is outside that mutex). A claim that reads the old answer can overwrite a fresh answer written by a concurrent ask. Two overlapping asks for one thread (an old candidate's ask still in flight when a newer one runs) can also land out of order, and putHeld has no AskedAtMs comparison. In this PR the harm is bounded: a held answer changes no request, so the loss is shadow metrics and one wasted paid answer, and the next ping asks afresh. Fix before PR C makes the answer load-bearing: take heldMu in putHeld, or refuse to overwrite a strictly newer AskedAtMs.
  • spendHeld is now dead code (extract_sweep_hold.go:125) — claimHeldSpend replaced its only caller. Delete it, or note it as the PR C seam.
  • The Anthropic-Beta header gap on CompletePrefixed stays open. The PR body lists it under Open questions with A5 covering it. Agreed as non-blocking.

What I checked

  • Last review: round 1, 0211b4dc9953dccf50a77256c0e0b99021056e42, 2026-10-25T09:43:12Z.
  • New commits read: 2 — 173180de "feat(sweep): ask at the keep-alive ping, hold the answer, recheck, shadow mode" (the feature commit, rewritten in place: same parent 1953b47c, different tree) and 308425f1 "docs(data-dependence): record David's approval of the sweep change". The full new change is git diff 0211b4dc..308425f1: 20 files, +494/−153, read in full, plus the code around each change.
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt), plus the PR body in full.
  • New items since my last review, and what I did about each:
    • Reviewer 2's round-1 review: read in full; re-verified each of their three findings against the code before accepting the fixes (see above).
    • The author's reply comment (2026-10-25T10:43:08Z): checked every claim — the doc rewrite, the CanKeepAlive gate and its wiring, the slot fix and its two tests, the miss metric, the two new counters, the doc cleanups, the claim-based report and spend with their slow-store tests, and the timeout comment. All match the code.
    • The rewritten feature commit and the approval commit: read the full diff and the commit message; confirmed the approval commit is authored and signed by the row's "Decided by" owner.
    • The older comment of 2026-10-13 (review round 1 of 3, head 6632593): read in full. Its blocking panic finding and items B, C, D, E are fixed in code I verified in round 1 and re-checked here where the round-2 diff touched them; item A (the header gap) is the open question above; item F (applySweepDropReplay still reading cg:res:) is stated in the PR body as PR C work, and only extract_llm writes that namespace now.
  • The slot fix in detail: send-before-collect, defer-release, LIFO order against the panic-recover defer, and the dispatch closure taking its own slot in ask after the outer one is released. No leak path found.
  • canPing in the proxy: kill switch, audit sink, OpenAI exclusion, empty session, and the resolved policy without a campaign decision — the conservative direction is documented and tested. canKeepAliveFor recovers a panic in the hook to "cannot", so a broken host hook keeps nothing rather than failing the request.
  • The claim fixes: heldMu serializes the two claims against each other; both tests use a store that widens the get-then-put window, so a non-atomic claim would fail deterministically. The producer-side gap is the non-blocking note above.
  • The doc updates (advanced-offload.md, data-dependence.md) against the code: counter names (sweep_concurrency_full, sweep_not_registered, sweep_stale_prefix), the removed retry wait cause (a failed response never establishes a keeper entry, and sweepWaitCause passes failed=false), the level columns, and the audit lists. They match.
  • No tests were run (live tests not approved); every claim above is from reading the diff and the surrounding 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 resumed 2 of 2 2 of 2 308425f17442 approve

Verdict: approve

Findings

None.

Earlier findings, and their state

Mine, round 1:

  1. Cache hit-rate always 100% — fixed. collect now records the miss (extract_sweep_ping.go:463), where the old in-request loop recorded it. Test: TestCollectionRecordsTheResultCacheMiss. rep.Component is set, so the miss lands on the right component.
  2. concurrency_full invisible — fixed. sweep_concurrency_full is in SweepPingCounters() and the keeper Stats. Test: TestAConcurrencyRefusalIsCounted. The author also made the bound real: the slot is taken with a non-blocking send, not looked at.
  3. Stale docs — fixed. The "only in-request ask that remains" sentence, the seven dead counter names and the "read as a pair" text are gone. The enabling section no longer tells an operator to set econ_trigger. retry is now marked as impossible, with the reason.

Reviewer 1, round 1:

  1. Data dependence — fixed. I checked the rewritten docs/data-dependence.md row against the code: cg:swh: pinned, ids, hashes, counts and verdicts only; two in-memory conversation copies, gated by CanKeepAlive, 30 minutes, 256 threads. registerPing keeps nothing for a thread the keeper cannot ping. David Amid's approval is commit 308425f1.
  2. The concurrency bound did not bound — fixed. Agree with reviewer 1. The slot is taken before collect and released on every exit. TestCollectionRunsAtMostSlotsAtOnce (16 goroutines behind a barrier) and the slot-leak test cover it.

Non-blocking, both rounds: comment rot fixed in every file I named. The report and spend races fixed with claimHeldReport/claimHeldSpend. The two-deadlines comment added. The author rejected the Ask.Add relabel point: the reason is right — labels are one sequence across lists by design, and Candidates() documents it. The registry byte bound is deferred to PR C and recorded in data-dependence.md item 5. The referenced_later misfile stays: it is fail-safe and keeps content.

The comment of 2026-10-13 (head 6632593, before my round 1): its panic finding was already fixed at my round-1 head, and the three recover levels are still there. Its items C and D are fixed in 173180de. Item F (applySweepDropReplay reads cg:res:) is deferred to PR C. Item A (beta-header gap) is pre-existing and shared with the summarizer; it is not this diff.

The new code, checked as a first review

  • The CanKeepAlive hook. nil means "cannot", so a library caller keeps nothing — the safe direction. A panic in the hook reads "cannot". canPing follows the kill switch, the audit sink, the provider and the resolved policy. A learned campaign that would turn on later reads "cannot": the safe direction, nothing extra is kept. I checked resolvePolicy with a zero predDecision: the campaign branch is skipped, so no misleading state.
  • The slot change. The release defer is registered after the panic recover, so on a panic the slot is released first (LIFO) and the recover still runs. The slot covers collection only; ask takes its own. No leak when the keeper refuses at the cost ceiling and never calls dispatch.
  • The claims. claimHeldReport and claimHeldSpend do the read-check-write under one mutex. getHeld rejects spent records, so the tombstone stands. The winner of the spend keeps the answer it read, with its outputs. The tests use a store that sleeps after Get, so a non-atomic claim fails every time.
  • The counters. Every name the rewritten docs list has a producer or a Stats JSON tag. I checked each name by grep.
  • Fail open, re-checked. Every new "no" (no hook, hook says no, slot full, claim lost) leaves the request untouched and the ping plain.

Non-blocking

  • spendHeld (extract_sweep_hold.go:125) has no caller after the claim refactor. Dead code; claimHeldSpend carries its body.
  • The ask-level slot refusal (extract_sweep_ping.go:490) counts under sweep_ask_failed, not sweep_concurrency_full. The docs sentence names only the pre-collection refusal. Both paths leave a plain ping.
  • The docs say "Counted at the ping" for sweep_not_registered. A request counts it, in registerPing. Only the publication block is the keep-alive's.
  • claimHeldSpend marks the answer spent before recheckHeld runs. A panic in the recheck then loses the report. Content is untouched, so this is fail-safe.

What I checked

  • Last review: round 1, 0211b4dc9953dccf50a77256c0e0b99021056e42, 2026-10-25T09:43:49Z.
  • New commits read: 2 — 173180de "feat(sweep): ask at the keep-alive ping, hold the answer, recheck, shadow mode" and 308425f1 "docs(data-dependence): record David's approval of the sweep change (#508)". The branch was force-pushed: 0211b4dc is no longer on it, and 173180de re-authors the round-1 commit with the fixes folded in. So I read the tree diff 0211b4dc..HEAD in full: 1105 lines, 20 files. Anything silently dropped between the two heads would show there as a deletion.
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from the three saved files).
  • New items since my last review:
    • The author's reply comment, 2026-10-25T10:43:08Z. Read; every claim in it checked against the code above.
    • Commit 173180de. The fixes for both reviews; reviewed as a first review.
    • Commit 308425f1. The data-dependence row and the approval; checked against heldAnswer, registerPing and the registry bounds.
  • The changed files around each change: extract_sweep_ping.go (registerPing, SweepPingSubstitute, collect, ask), extract_sweep_hold.go (the claims), extract_sweep_shadow.go (in full), apply/apply.go, apply/opts.go, apply/responses.go, components/component.go, proxy/keepalive.go (canPing, resolvePolicy), proxy/modes.go, keepalive/keeper.go (Stats), and every new test in the diff.
  • Not run: Go builds and tests. Live tests were not approved for this review. The author's comment reports full suites and -race runs on the box; I did not verify them.

Main added #691 and #692. The only conflict was docs/data-dependence.md:
#691 added three sentences to the end of the "Keep-alive pings" row, and
this branch edits the "Body stash" row next to it. Main's keep-alive row
is kept as it is, and so is this branch's Body stash row.

Also, in the same commit, two small round-2 fixes:
- Delete spendHeld, which has no caller since the claim replaced it.
- Say that sweep_not_registered is counted at the request, not at a ping.

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

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Findings

None.

Earlier findings, and their state

Mine, round 1 and round 2: all fixed, and nothing in the new commits touches the fixes. The miss metric, the sweep_concurrency_full counter, the docs rewrite, the slot-before-collect, the claims, the CanKeepAlive gate — all still in place at this head.

My round-2 non-blocking items:

  1. Dead spendHeld — fixed. The merge commit deletes it. A grep over every Go directory finds no reference left. claimHeldSpend (extract_sweep_hold.go:126) carries the tombstone body.
  2. sweep_not_registered wording — fixed. advanced-offload.md now says it is counted at the request, not at a ping. This matches registerPing, where the counter moves.
  3. Ask-level slot refusal counts under sweep_ask_failed — not addressed. Still fail-safe: both paths leave a plain ping. Agreed with reviewer 1.
  4. claimHeldSpend marks the answer spent before recheckHeld runs — not addressed. A panic in the recheck loses the report only. Content is untouched. Fail-safe.

Reviewer 1's round-2 non-blocking items: the putHeld producer race is not addressed, and I agree it stays non-blocking here. A held answer changes no request in this PR. The loss is one shadow metric and one wasted paid answer. The next ping asks afresh. I add my voice to the warning: PR C must not build the cold apply on this seam. Take heldMu in putHeld, or refuse to overwrite a newer AskedAtMs, before any code reads a held answer to change a request. The Anthropic-Beta header gap stays the PR body's open question, under A5.

The new commit, checked as a first review

The branch moved by one merge, 8f069839. It brings in main's 86c118ba (#691, the plugin's Ping-header self-heal) and caac0b81 (#692, the dash ping-saving window), and folds in the two fixes above. I read the full tree diff 308425f1..HEAD: 1418 lines, 23 files.

  • The merge keeps both sides intact. I ran the two checks myself. git diff 86c118ba..HEAD over dash/, context-guru-plugin/ and codex-marketplace/ is empty, so #691 and #692 landed unchanged. git diff 308425f1..HEAD over every Go directory of this PR is the 8-line spendHeld deletion only.
  • The conflict resolution is right. The one conflict was docs/data-dependence.md. The merged file keeps main's keep-alive row with the three self-heal sentences (:216) and this branch's Body stash row with the sweep's two-extra-copies note (:217). Nothing was dropped from either side.
  • No semantic conflict with this PR. #692 changes dash read queries (kaSavedSince floors a ping's credit at the window start). The sweep writes no dash query and no ledger field they touch. #691 changes plugin install scripts and the manual Ping button's hold. The sweep's gate is CanKeepAlive, which follows keeper.canPing — the kill switch, the audit sink, the provider and the resolved policy — not the x-context-guru-ping header. A thread held for the button only keeps no sweep conversation copy unless the keeper can also ping it. The safe direction.
  • The folded docs fix reads well in place. The "Counted at the ping" paragraph now names sweep_concurrency_full, sweep_ping_panics, sweep_model_declined and sweep_ask_needs_shadow, and moves sweep_not_registered to its own request-counted sentence. Each name has a producer or a Stats JSON tag.

Non-blocking

  • The putHeld producer race, stated above: fix it before PR C makes the held answer load-bearing.
  • The ask-level slot refusal still counts under sweep_ask_failed, not sweep_concurrency_full. Both leave a plain ping.
  • claimHeldSpend still consumes before the recheck runs. A panic there loses the report, not content.

What I checked

  • Last review: round 2, 308425f174428909b83fbb48727d6ed3fe134d88, 2026-10-25T10:58:10Z.
  • New commits read: 1 — 8f069839 "Merge origin/main into feat/sweep-cold-ask" (parents 308425f1 and 86c118ba; brings #691 and #692 from main, resolves one conflict in docs/data-dependence.md, and folds in the two round-2 fixes). The full tree diff 308425f1..HEAD, 1418 lines over 23 files, was read in full, plus the code around each change: extract_sweep_hold.go, extract_sweep_shadow.go, the merged doc rows, and the #691/#692 files at the level needed to rule out interaction.
  • Read in full: 5 reviews, 2 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review, and what I did about each:
    • Reviewer 1's round-3 review (2026-10-25T11:27:49Z, approve): read in full. Their dispositions match mine. Their two merge checks I re-ran myself rather than trusting.
    • The merge commit: read the message, the stat, the full diff, and verified both parents' sides are intact in the tree.
    • No new issue comments arrived since the author's reply of 2026-10-25T10:43:08Z. The two comments on the PR are unchanged since round 2; I read them in full again.
  • Not run: Go builds and tests. Live tests were not approved for this review.

@amiddavid
amiddavid merged commit c7da735 into main Oct 25, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 25, 2026
amiddavid added a commit that referenced this pull request Oct 25, 2026
…ed run (#697)

fix(review): stop a reviewer that never ends, and never resume a failed run

On #507 a GLM reviewer repeated one word up to the 32k output limit, 4
turns in a row, about 21 minutes each. Nothing stopped it, and a later
round would have resumed that same session.

- Each reviewer run now has a wall-clock limit, OFFLOAD_REVIEW_TIMEOUT
  (default 1800 s, 0 = off). Past it, the script stops the run's whole
  process group and falls back to the next backend, unless the review is
  already on the PR. It does not limit tokens.
- A run that ends without posting drops its saved session
  (backend_forget_session, or backend_cleanup), so the next round starts
  fresh.
- Any .review-in-*.txt in a reviewer's own folder is allowed. A reviewer
  that also saved the PR body (.review-in-prbody.txt, #508) made the
  round exit 1 although both reviews posted.

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

fix(review): forget a session only after the backend ran

Round-1 review fixes for #697.

- Forget a saved session only when the backend started. A failure before
  it (worktree lock, prompt) keeps the session for the next round.
- Check OFFLOAD_REVIEW_TIMEOUT once at startup, before any worktree exists.
- Mark a stopped run with a file, not exit code 124. A backend that exits
  124 by itself is no longer labelled a timeout.
- Append to review.log, so an earlier diagnostic stays.
- claude: forgetting a session also removes its transcript.
- Fix the function counts in the backend headers and SKILL.md.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns

The sweep asked at the keep-alive ping and held the answer, and nothing used it.
This change applies it. The sweep now saves money.

- Cold apply (point 3): on the next cold request of a thread, rechecks the held
  answer and replaces each valid output with a shape descriptor and a <<cg:HASH>>
  marker. The original is stashed, so expand returns it byte for byte. Each drop
  writes a record (cg:swd:), and every later request of the thread replays the
  same bytes. A warm request with an unchanged conversation never changes (H1).
- Changed prefix (point 4): a rewind, an edited turn or a fork applies only the
  held drops after the first changed message. The ones before it stay held.
  Counted apart as sweep_applied_changed_prefix.
- Fail open: a store that cannot hold an original refuses that drop. A panic in
  the apply restores every message it touched, writes no record, and forwards the
  request unchanged.
- Dashboard (point 9): the answer cost is booked once, on the ping row the
  question replaced, in its own column (sweep_answer_usd). The expands of sweep
  markers come off the sweep's credit at the write rate.
- Quality signals (point 7): an expand of a sweep marker is charged to the sweep,
  and a later turn that uses something a dropped output introduced counts as a
  false drop. False-drop rate per thread and overall, in the Components tab and in
  /stats (keepalive.sweep_drops). Ids, hashes and counts only.
- The ping carries the forwarded body after a cold apply (point 15), by test.
- The shadow-only ask gate is gone. shadow stays a setting and applies nothing.
- xhigh runs the sweep again. The other presets are unchanged.
- From the #508 notes: registerPing no longer keeps a conversation copy for a
  thread with no candidate and prunes on every registration (D); the sweep reads
  its own cg:swd: record, not cg:res: (F); BuildFallbackAsk and the sweep-only
  pricing in prefix_econ.go are removed (coref keeps what it uses).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns

The sweep asked at the keep-alive ping and held the answer, and nothing used it.
This change applies it. The sweep now saves money.

- Cold apply (point 3): on the next cold request of a thread, rechecks the held
  answer and replaces each valid output with a shape descriptor and a <<cg:HASH>>
  marker. The original is stashed, so expand returns it byte for byte. Each drop
  writes a record (cg:swd:), and every later request of the thread replays the
  same bytes. A warm request with an unchanged conversation never changes (H1).
- Changed prefix (point 4): a rewind, an edited turn or a fork applies only the
  held drops after the first changed message. The ones before it stay held.
  Counted apart as sweep_applied_changed_prefix.
- Fail open: a store that cannot hold an original refuses that drop. A panic in
  the apply restores every message it touched, writes no record, and forwards the
  request unchanged.
- Dashboard (point 9): the answer cost is booked once, on the ping row the
  question replaced, in its own column (sweep_answer_usd). The expands of sweep
  markers come off the sweep's credit at the write rate.
- Quality signals (point 7): an expand of a sweep marker is charged to the sweep,
  and a later turn that uses something a dropped output introduced counts as a
  false drop. False-drop rate per thread and overall, in the Components tab and in
  /stats (keepalive.sweep_drops). Ids, hashes and counts only.
- The ping carries the forwarded body after a cold apply (point 15), by test.
- The shadow-only ask gate is gone. shadow stays a setting and applies nothing.
- xhigh runs the sweep again. The other presets are unchanged.
- From the #508 notes: registerPing no longer keeps a conversation copy for a
  thread with no candidate and prunes on every registration (D); the sweep reads
  its own cg:swd: record, not cg:res: (F); BuildFallbackAsk and the sweep-only
  pricing in prefix_econ.go are removed (coref keeps what it uses).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns

The sweep asked at the keep-alive ping and held the answer, and nothing used it.
This change applies it. The sweep now saves money.

- Cold apply (point 3): on the next cold request of a thread, rechecks the held
  answer and replaces each valid output with a shape descriptor and a <<cg:HASH>>
  marker. The original is stashed, so expand returns it byte for byte. Each drop
  writes a record (cg:swd:), and every later request of the thread replays the
  same bytes. A warm request with an unchanged conversation never changes (H1).
- Changed prefix (point 4): a rewind, an edited turn or a fork applies only the
  held drops after the first changed message. The ones before it stay held.
  Counted apart as sweep_applied_changed_prefix.
- Fail open: a store that cannot hold an original refuses that drop. A panic in
  the apply restores every message it touched, writes no record, and forwards the
  request unchanged.
- Dashboard (point 9): the answer cost is booked once, on the ping row the
  question replaced, in its own column (sweep_answer_usd). The expands of sweep
  markers come off the sweep's credit at the write rate.
- Quality signals (point 7): an expand of a sweep marker is charged to the sweep,
  and a later turn that uses something a dropped output introduced counts as a
  false drop. False-drop rate per thread and overall, in the Components tab and in
  /stats (keepalive.sweep_drops). Ids, hashes and counts only.
- The ping carries the forwarded body after a cold apply (point 15), by test.
- The shadow-only ask gate is gone. shadow stays a setting and applies nothing.
- xhigh runs the sweep again. The other presets are unchanged.
- From the #508 notes: registerPing no longer keeps a conversation copy for a
  thread with no candidate and prunes on every registration (D); the sweep reads
  its own cg:swd: record, not cg:res: (F); BuildFallbackAsk and the sweep-only
  pricing in prefix_econ.go are removed (coref keeps what it uses).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns

The sweep asked at the keep-alive ping and held the answer, and nothing used it.
This change applies it. The sweep now saves money.

- Cold apply (point 3): on the next cold request of a thread, rechecks the held
  answer and replaces each valid output with a shape descriptor and a <<cg:HASH>>
  marker. The original is stashed, so expand returns it byte for byte. Each drop
  writes a record (cg:swd:), and every later request of the thread replays the
  same bytes. A warm request with an unchanged conversation never changes (H1).
- Changed prefix (point 4): a rewind, an edited turn or a fork applies only the
  held drops after the first changed message. The ones before it stay held.
  Counted apart as sweep_applied_changed_prefix.
- Fail open: a store that cannot hold an original refuses that drop. A panic in
  the apply restores every message it touched, writes no record, and forwards the
  request unchanged.
- Dashboard (point 9): the answer cost is booked once, on the ping row the
  question replaced, in its own column (sweep_answer_usd). The expands of sweep
  markers come off the sweep's credit at the write rate.
- Quality signals (point 7): an expand of a sweep marker is charged to the sweep,
  and a later turn that uses something a dropped output introduced counts as a
  false drop. False-drop rate per thread and overall, in the Components tab and in
  /stats (keepalive.sweep_drops). Ids, hashes and counts only.
- The ping carries the forwarded body after a cold apply (point 15), by test.
- The shadow-only ask gate is gone. shadow stays a setting and applies nothing.
- xhigh runs the sweep again. The other presets are unchanged.
- From the #508 notes: registerPing no longer keeps a conversation copy for a
  thread with no candidate and prunes on every registration (D); the sweep reads
  its own cg:swd: record, not cg:res: (F); BuildFallbackAsk and the sweep-only
  pricing in prefix_econ.go are removed (coref keeps what it uses).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns

The sweep asked at the keep-alive ping and held the answer, and nothing used it.
This change applies it. The sweep now saves money.

- Cold apply (point 3): on the next cold request of a thread, rechecks the held
  answer and replaces each valid output with a shape descriptor and a <<cg:HASH>>
  marker. The original is stashed, so expand returns it byte for byte. Each drop
  writes a record (cg:swd:), and every later request of the thread replays the
  same bytes. A warm request with an unchanged conversation never changes (H1).
- Changed prefix (point 4): a rewind, an edited turn or a fork applies only the
  held drops after the first changed message. The ones before it stay held.
  Counted apart as sweep_applied_changed_prefix.
- Fail open: a store that cannot hold an original refuses that drop. A panic in
  the apply restores every message it touched, writes no record, and forwards the
  request unchanged.
- Dashboard (point 9): the answer cost is booked once, on the ping row the
  question replaced, in its own column (sweep_answer_usd). The expands of sweep
  markers come off the sweep's credit at the write rate.
- Quality signals (point 7): an expand of a sweep marker is charged to the sweep,
  and a later turn that uses something a dropped output introduced counts as a
  false drop. False-drop rate per thread and overall, in the Components tab and in
  /stats (keepalive.sweep_drops). Ids, hashes and counts only.
- The ping carries the forwarded body after a cold apply (point 15), by test.
- The shadow-only ask gate is gone. shadow stays a setting and applies nothing.
- xhigh runs the sweep again. The other presets are unchanged.
- From the #508 notes: registerPing no longer keeps a conversation copy for a
  thread with no candidate and prunes on every registration (D); the sweep reads
  its own cg:swd: record, not cg:res: (F); BuildFallbackAsk and the sweep-only
  pricing in prefix_econ.go are removed (coref keeps what it uses).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns (#404 PR C) (#695)

feat(sweep): apply the held answer on the next cold request, and book what it earns

The sweep asked at the keep-alive ping and held the answer, and nothing used it.
This change applies it. The sweep now saves money.

- Cold apply (point 3): on the next cold request of a thread, rechecks the held
  answer and replaces each valid output with a shape descriptor and a <<cg:HASH>>
  marker. The original is stashed, so expand returns it byte for byte. Each drop
  writes a record (cg:swd:), and every later request of the thread replays the
  same bytes. A warm request with an unchanged conversation never changes (H1).
- Changed prefix (point 4): a rewind, an edited turn or a fork applies only the
  held drops after the first changed message. The ones before it stay held.
  Counted apart as sweep_applied_changed_prefix.
- Fail open: a store that cannot hold an original refuses that drop. A panic in
  the apply restores every message it touched, writes no record, and forwards the
  request unchanged.
- Dashboard (point 9): the answer cost is booked once, on the ping row the
  question replaced, in its own column (sweep_answer_usd). The expands of sweep
  markers come off the sweep's credit at the write rate.
- Quality signals (point 7): an expand of a sweep marker is charged to the sweep,
  and a later turn that uses something a dropped output introduced counts as a
  false drop. False-drop rate per thread and overall, in the Components tab and in
  /stats (keepalive.sweep_drops). Ids, hashes and counts only.
- The ping carries the forwarded body after a cold apply (point 15), by test.
- The shadow-only ask gate is gone. shadow stays a setting and applies nothing.
- xhigh runs the sweep again. The other presets are unchanged.
- From the #508 notes: registerPing no longer keeps a conversation copy for a
  thread with no candidate and prunes on every registration (D); the sweep reads
  its own cg:swd: record, not cg:res: (F); BuildFallbackAsk and the sweep-only
  pricing in prefix_econ.go are removed (coref keeps what it uses).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
fix(sweep): serialise putHeld, claim before the cold apply, retry a panicked apply once

- putHeld takes heldMu and never overwrites a newer AskedAtMs, so a claim that read an old
  answer cannot overwrite a new one, and two asks of one thread cannot land out of order.
- The cold apply claims the held answer first. A panic in the apply or the recheck restores
  every message, is counted (sweep_apply_panic), and hands the answer back once. A second
  panic leaves it spent.
- The ask-level slot refusal counts as sweep_concurrency_full, not sweep_ask_failed.
- The cold test now uses the summary reserve's ColdApplyPhase.
- The sweep row carries the net saving and the cold-apply cache numbers for L1 and C2.
- docs/data-dependence.md: the sweep row now says it stashes originals for expand. PENDING.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
docs(sweep): fix the xhigh and housellm preset rows; record the data-dependence approval

presets.md: xhigh and housellm now describe the sweep as it is: it asks at the keep-alive
ping and removes content only on a cold request. The old max_calls and "adjudicates at
depth on an expired cache" text is gone.

data-dependence.md: Decided by records David Amid's approval of 2026-10-25 (#695).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
fix(sweep): round 1 review fixes for the false-drop signal and the commit window

- A marker shared by two threads lists every owner. An expand credits the thread that
  made it, and only a thread that carries the marker. With no thread known (the
  request-path repair), every owner is credited.
- The reference scan, the expand note and the commit take dropMu, so a flag is not lost.
- The commit is atomic in effect. A panic after the first record tombstones every record
  and marker owner this attempt wrote. Applied and sweep_applied_* are counted last.
- The change point is computed from the answer the claim returns.
- Shadow mode keeps replaying drops that already exist. It only stops new applies.
- Rename AppliedChangedPrefx; fix the stale selectAffordableDrops hint; document the
  next-warm imprecision.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
fix(sweep): release dropMu when the reference scan panics, and close the panic paths

- scanReferences held dropMu with a plain Unlock inside a function that recovers panics.
  A panic in the Store or the ledger left the lock held for good, and every later scan,
  expand note and commit blocked. The locked part is now a closure with a deferred unlock.
- The extraction savings metrics are booked after the commit, with the events and ledger.
- A panic at the held trim gives back the untrimmed answer, so the drops after the change
  point are not lost.
- An expand of a marker with no thread known counts once in the total.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
test(sweep): pin the sweep question against #710, #711 and #712

- A ping the sweep's question replaced uses no output-budget step (#712), so the next plain
  pings differ.
- A failed question is not a transport failure of a ping: it does not set #710's retry flag,
  the ordinary ping goes out in its place, and a question that billed asks once per idle period.
- A held answer and its drop records stay on their own thread key, so a thread that moves to
  another id (#711 prevents it for a resume) does not carry them.

Tests only.

Part of #404.

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