Repository navigation
fix(keepalive): the sweep question takes the last ping, never ping 1 (#776) - #779
Merged
Merged
Conversation
…776) The sweep question took ping 1 of an idle span. It reads the turn's cache entry but does not renew one that ends at a text turn. After a text turn the entry then expired, and the plain ping 2 wrote the whole conversation again: 22 of the 80 misses in #776 ($50.18 in 3.9 days on one laptop), which #777 could not fix. Ping 1 is now always plain. The question takes the last planned ping of the span. A one-ping plan (the 1-hour tier's default) sends no question, so the question is never the only ping. The summarizer's substitute, the already_asked latch, the cost ceiling and the batch rules are unchanged. Owner decision 2026-10-30. Fixes #776 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Owner decision 2026-10-30: the sweep must not contradict the caching strategy. Where the question cannot renew the cache, it runs as an extra request after the strategy's last ping. - After a turn that ends at a text turn (the last non-system message is not a tool_result; roles and block types only), every planned ping is plain. The question goes out once at the slot after the last planned ping, 30 s before the hold ends. No ping follows it, and it sends nothing if the copy is gone or there is no candidate. - After a tool_result turn the question may take ping 1, as on main: it renews the entry (#777). - This replaces the "plain ping 1, question on the last ping" rule of the first commit, which is reverted. New counters: keepalive_sweep_extra_asked, keepalive_sweep_extra_skipped. Refs #776 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
The owner asked for the rule in the development docs, so a later change that breaks it is caught. - docs/design.md: a new section, "Keep-alive: the cache strategy comes first". It names the summarizer's substitute as a known gap. - CLAUDE.md, Hard boundaries: one bullet that points at it. - RELEASING.md, Part B: the live check confirms that after a text turn every planned ping is plain and reads the full prefix. - A guard test for the sweep on 1-, 2- and 3-ping plans. Refs #776 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Owner decisions 2026-10-30: "summerizer as well so a)" and "a1 it is". - After a text turn the summarizer's keep-alive substitute no longer takes a planned ping. Every planned ping is plain, and the summary goes out once as the extra request after the last one. - A cache_state any summary uses the sweep's slot: 30 s before the normal hold deadline. - A cache_state pre_expiry summary (the medium preset) runs only in its pre-expiry window. Its slot is the middle of that window: 268 s after the last ping at the 5-minute defaults, 32 s before expiry. - The one exception to the hold limit: only for a span that ended at a text turn and still has a pre_expiry summary waiting, the deadline timer re-arms once, to 15 s past the slot (43 s longer at the defaults), never past the cache expiry. Every other span keeps the limit. Counted as keepalive_hold_extensions. - One request in the extra slot. The summary owns it before the sweep. A declining pre_expiry summary is not followed by the sweep. - A missed extra slot is never sent late. - OpenAI is out of scope: its cache has no text-turn rule. - docs/design.md: the known gap is gone. The guard covers every substitute kind. Refs #776 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
After a text turn the summary now waits for the extra slot after the last planned ping. These two tests are about a planned ping dispatching the summary, so their last real turn now ends at a tool_result. Refs #776 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
commented
Oct 30, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.314 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 79d6119c4609 |
blocking |
Verdict: blocking
Findings
- keepalive/keeper.go:1288 — the extra request skips the route-breaker and dead-credential re-check
- What fails: a text-turn span that spent its planned pings waits for its extra slot. Another thread's pings trip the route breaker (or a 401 on the shared credential marks it dead) before that slot. At the slot, the keeper dispatches the sweep question or the summary call on the tripped route or with the dead credential. The call is wasted spend, and it runs on a route the breaker had refused.
- Proof: the ordinary ping branch re-checks both marks right before it dispatches (keeper.go:1318-1322), and its comment says the check exists because a breaker "can trip or land WHILE an entry is sitting idle waiting for its next ping". The extra branch at keeper.go:1288 dispatches without either check, and nothing in
fireExtra→fireSummarySubstitute/fireSweepSubstitute(substitute.go) checks them — theoffloadpackage cannot see the keeper's breaker. An entry whose own ping tripped the route is stopped (e.stopped), soextraWaiting()is false; the exposed case is another thread's trip or dead-credential mark on the same route or credential, exactly the case the ordinary branch guards. - Fix: in the extra branch of
Sweep, before appending the job, apply the same check as keeper.go:1318-1322 — sete.stopped = trueandcontinueinstead of dispatching. Add a test: trip the route (or mark the credential dead) after the last planned ping, and assert no extra question goes out.
Non-blocking
- keepalive/keeper.go:103-104 and 296-298 — the hold-limit comments now overstate the invariant. Both still say the credential and conversation are held for at most (K+1) x Idle. The extension adds a documented exception. The blocks around the credential hold are the file's security statement; update them to name the exception and its bound (15 s past a pre_expiry slot, capped at the cache's own expiry).
- The extension past the deadline is 43 s only at the defaults.
extendHoldLockedre-arms toslot + 15 s, capped at the cache expiry. With a short Idle on a 5-minute cache (say Idle 60 s), the slot sits well past the deadline and the extension is bounded by the cache expiry, minutes past (K+1) x Idle. This matches the rule as written in docs/design.md ("15 s past the slot... never past the cache's own expiry"), but the headline number is defaults-specific. Consider stating the general bound in design.md. - keepalive/keeper.go:1812-1813 —
SweepExtraSkippedcounts more than its description.fireExtraalso counts it when a summary declined and no sweep candidate existed, and when the claim came backPingPlain(thread busy). The Stats comment says "the claim gave the sweep no question". Naming or doc mismatch only. - docs/design.md:278 —
keepalive.endsAtTextTurnreads like a published metric. No such metric exists; it is the internal functionendsAtTextTurn(keeper.go:2152). Say "an internal flag on the held entry" or similar. - RELEASING.md:153 — the new bullet has no number while the sibling checks are numbered 1-9.
- Short-Idle schedules can overlap the extra with the last ping.
extraSlot(false)isstartedAt + Idle - 30 s. If a strategy band admits Idle under about 30 s, the slot is in the past, and the extra can be dispatched on the first tick after the last ping dispatches, while that plain ping is still in flight (the claim guard does not cover plain pings). Only reachable if such short Idle is configurable.
What I checked
- Read the full diff (17 files) and the surrounding code in full: keeper.go, substitute.go, manualhold.go, ping_claim.go, cache_aware_keepalive.go, ping.go, types.go.
- Traced the timing arithmetic. At the shipped defaults (Idle 240 s, K 2, TTL 300 s): sweep/any slot at 210 s after the last ping, pre_expiry slot at 268 s, extension to 283 s, capped at the 300 s expiry. Matches docs/design.md and
TestTheExtraSlotAtTheShippedDefaults. Also checked Idle 280 s (tests), Idle 60 s, one-hour threads (Idle 3540 s), and a HeadTTL1h schedule not granted the tier. - Checked the latch and release paths:
extraAskedis set under the lock before dispatch, so one extra per span; a missed slot is never sent late; the eager release and the deadline timer agree at (K+1) x Idle; the extension re-arms once and the second firing always retires;evictLocked,Forget,RetireSession,ArriveandShutdownall still release the extended entry. - Checked lock ordering and deadlocks:
extraReadyLockedandpreExpiryExtraWaitingLockedrun underk.muand touch only leaf mutexes inoffload;endsAtTextLocked,fireExtraand both substitute calls takek.muon the ping goroutine only;ClaimPingis never called underk.mu. - Checked
endsAtTextTurnagainst body shapes: trailing system reminder, tool_result last, text after tool_result in one turn, string content, assistant last, no messages, OpenAI exclusion (endsAtText forced false, andeligibleadmits no other breakpoint-less provider). - Checked that planned pings stay plain after a text turn for every substitute kind (
fireSubstitutegates all three claim choices), and that the guard test table covers sweep, pre_expiry and any at MaxPings 1-3. - Checked fail-open: the extra sends the question or nothing, never an ordinary ping; a declined summary with a pre_expiry state leaves the slot empty rather than asking the sweep late;
fireSweepSubstitutekeeps its panic recovery. - Checked data dependence:
endsAtTextTurnreads roles and block types from the already-held body (metadata only, no new storage); docs/data-dependence.md needs no new row. - Checked the wrote-guard interaction: a span whose pings write instead of read is stopped, so the extra never fires on a long-dead cache except through the pre-existing stale-anchor case (a transiently failed last ping moves
startedAtwithout refreshing; the pre_expiry extra can then write). This anchor logic is pre-existing on main for substitutes at pings, so I did not raise it as a finding. - Did not run builds or tests (not approved for this review). Did not read the PR body, other reviews or comments, per the round-1 rule — so I could not verify that the behavior change is named at the top of the PR as RELEASING.md requires; the diff itself names it in CLAUDE.md, docs/design.md and RELEASING.md, and records the owner's "a1" decision of 2026-10-30 for the hold extension.
amiddavid
commented
Oct 30, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.314 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 79d6119c4609 |
blocking |
Verdict: blocking
Findings
- keepalive/keeper.go:1288 — the extra request skips the route-breaker and dead-credential re-check that every planned ping gets
- What fails: a span whose route tripped, or whose held credential was marked dead, after its last planned ping still sends its one extra request (the sweep question or the summary). The proxy dispatches one request against a route the breaker refuses, with a credential it knows is dead, on the user's held credential.
- Proof: the planned-ping branch runs
routeIsTrippedLocked/credIsDeadLockedright before it builds the job, and its comment (keeper.go:1315-1317) says the re-check exists because the breaker "can trip or land WHILE an entry is sitting idle waiting for its next ping". The extra branch at 1288-1298 builds and queuespingJob{extra: true, ...}with no such check. The extra slot sits idle a fullIdleperiod after the last ping, so the same exposure holds. The substitutes that ride a planned ping pass this check;fireExtra's own comment claims the extra goes out "under the same claim, ceilings and latches as a substitute that takes a ping", but the breaker check is not among them. - Fix: in the extra branch, run the same two checks under the lock. On a trip, set
e.stopped = trueandcontinue, so the release branch owns the entry and the extra is simply not sent. A test can mirror the existing breaker tests with a text-turn body and a spent plan.
Non-blocking
Stats.SweepExtraSkipped(keeper.go:1812) counts every nothing-sent exit offireExtra, including a summary that declined and a question whose dispatch failed. The doc on the field says "the claim gave the sweep no question to send". Widen the doc, or split the counter, so a rise still means one thing.- The hold extension is granted from the registration's
cache_statealone (extendHoldLocked). Apre_expirycandidate thatKeepAliveSubstitutewould refuse (a checkpoint exists and no refresh tail) still gets the entry held up to ~43 s longer, and nothing is sent. Bounded and fail-safe; noting it because the hold limit is a security bound. - The deadline timer is armed once, at Record, for
(K+1) x Idlefrom the span start, while the extra slot is measured from the last ping's stamp. If the last ping runs more thanextraSlotMargin(30 s) late, the timer fires before the slot and the extra is dropped. Tick delay is about 2 s per ping, so this needs an unusual delay. Fail-safe direction: nothing is sent late. kaEntry.holdUntilis written byextendHoldLockedand read only by tests. Harmless; it documents the extension's bound.
What I checked
- The full diff of all 5 commits, and the code around every change:
keeper.go(Sweep loop,extraWaiting/extraSlot/extraDue/extendHoldLocked/preExpiryExtraWaitingLocked,fire,fireExtra,endsAtTextTurn,fireSubstitute),substitute.go,manualhold.go(expireAuto),components/offload/ping_claim.go. - The slot arithmetic at both policies the tests use (Idle 280 s and the shipped 240 s): pre_expiry slot 270 s / 268 s, sweep slot 250 s / 210 s, extension capped at the cache expiry. It matches the code and
docs/design.md. - The timer lifecycle: armed at Record, stopped by
clear()on every removal path, re-armed once by the extension, second firing releases. The eager release in Sweep defers topreExpiryExtraWaitingLocked. No path holds an entry pastmin(slot + 15 s, expiry). - Lock ordering: the new reads of the offload registries happen under
k.mu;components/offloadcannot call back intokeepalive, so no reverse order exists. endsAtTextTurnon every shape in its table, plus string content, null content and unknown roles. Every unreadable shape reads as a text turn, the side on which no ping is replaced. OpenAI is excluded at Record; the other eligible providers (Anthropic, Bedrock, BedrockMantle, Vertex) are Claude semantics, so the text-turn rule fits them.- That plain pings are unchanged after a text turn, and that the strategy's cover is what it was: the extra sends no ping and moves no clock.
- Test coverage:
sweeptextturn_test.go,summarytextturn_test.go(including the guard table over substitute kinds and plan lengths), and every existing substitute test switched tokaToolBody. I found no remaining test that expects a substitute to take a planned ping off a text-turn body. Test helpers and themodelinfoconstant the new tests use exist. - Data dependence: the change reads roles and block types of the body the keeper already holds. No new storage, no new dependence.
docs/data-dependence.mdneeds no row change. - The behavior-change rule: the change is named in CLAUDE.md, RELEASING.md and
docs/design.md, and the hold-limit exception records the owner's 2026-10-30 choice ("a1 it is"). I did not read the PR description or comments, per the round-1 rule, so I cannot confirm the change is also named at the top of the PR body itself. - I did not run builds or tests (not approved on this machine).
) Owner decision 2026-10-30: "give it more time, it can run on the 210 sec mark". - The hold extension is removed: the re-armed timer, keepalive_hold_extensions and its tests. Every span keeps today's hold limit. - One extra slot for every substitute: 30 s before the normal hold deadline (210 s after the last ping at the 5-minute defaults). - For the summary's extra request only, the pre-expiry window widens to cover that slot (94 s at the defaults: 90 s left plus two ticks). Planned-ping summaries keep the #715/#717 window. - The summary goes first. The sweep question goes only if the summary declines, in the same slot. Nothing after it. - Kept: a missed slot is never sent late; OpenAI is out of scope. Refs #776 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…cks the breaker (#776) Owner rule 2026-10-30: "as for sweep after summary. dont do that. it can probably have the sweep question pay a cache write like the problem with the ping... so we should probably just do summary at that point". - When a summary is due in the extra slot, only the summary goes, even if it declines. The sweep question takes the slot only when no summary is registered for the thread. Review round 1 on #779: - The extra slot now runs the same route-breaker and dead-credential re-check as a planned ping. On a trip it sends nothing and stops the span. - A short Idle: the slot is at least two ticks after the last ping, and the extra waits until that ping's response is in (pingRunning). - SweepExtraSkipped: the doc names every case it counts. - docs/design.md: endsAtTextTurn is an internal flag, not a metric. - RELEASING.md: the Part B check is numbered like its siblings. Refs #776 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Collaborator
Author
|
Round 1 replies, to both reviewers. Everything is fixed in 4f387a4, which also has the owner's 2 later changes: no hold extension (64965ff) and "only the summary when one is due" (4f387a4). Finding 1, both reviewers (blocking): the extra request skips the route-breaker and dead-credential re-check (
Non-blocking:
|
amiddavid
commented
Oct 30, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.314 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 3 | 4f387a417885 |
approve |
Verdict: approve
Findings
None.
Earlier findings
- Round 1, finding 1 (also reviewer 2, finding 1): the extra request skipped the route-breaker and dead-credential re-check. Fixed. The extra branch in
Sweep(keeper.go:1232-1238) now runsrouteIsTrippedLockedandcredIsDeadLockedunder the lock, before the job is built. On a trip it setse.stopped = trueand sends nothing, exactly as the planned-ping branch does.TestTheExtraSlotSkipsATrippedRouteOrADeadCredentialcovers both marks after the last planned ping and asserts the span stops. I re-read the placement: the check sits inside the due condition, so a trip that lands before the slot is caught at the slot; the release branch then owns the entry. Correct. - Round 1, non-blocking items. All fixed or moot:
- Hold-limit comments, the 43 s headline, the general bound,
holdUntil, the extension granted fromcache_statealone: moot. The owner removed the hold extension (64965ff). Every span is held for exactly (K+1) x Idle again. CLAUDE.md and docs/design.md were updated to match, so the security comments are right as written. SweepExtraSkippeddescription: fixed. The Stats comment now names every case it counts (keeper.go:1766-1770).keepalive.endsAtTextTurnas a metric: fixed. design.md now says "an internal flag on the held entry, not a published metric".- RELEASING.md numbering: fixed. The check is item 10.
- Short-Idle overlap: fixed.
extraSlotfloors the slot at two sweep ticks after the last ping (keeper.go:222-224), andpingRunning(set at dispatch, cleared infire's defer for every non-extra exit) keeps the extra back until that ping's response is in.TestAShortIdleExtraWaitsForTheLastPingand the end-to-endTestAShortIdleExtraIsNotSentWhileTheLastPingIsOutcover it.
- Hold-limit comments, the 43 s headline, the general bound,
The two owner changes in the new commits
- 64965ff, one slot for every substitute, no hold extension. I checked the arithmetic: the slot is
max(Idle - 30 s, 2 ticks)after the last ping (210 s at the shipped defaults),extraDuenever sends paststartedAt + Idle, and the eager release and the deadline timer both fire there, so no span's hold changes.extraSummaryWindowwidens a pre_expiry summary's window to cover the slot (94 s at the defaults: 90 s of remaining life plus two ticks) and never narrows a wider configured one; a planned-ping summary keeps the #715/#717 window (j.extragates the widening), whichTestAPlannedPingSummaryKeepsTheNormalWindowpins at both sides of the 60 s boundary. A HeadTTL1h schedule not granted the tier leaves the phase reading Cold at the slot, so nothing is sent — the safe direction. - 4f387a4, only the summary when one is due.
fireExtrano longer falls back to the sweep after a declined summary; the sweep takes the slot only when no summary is registered at claim time. The rule is the owner's, quoted with a date in the code and docs. The claim still decides,extraReadyLockedstill requires a candidate before the slot is taken, and aPingPlainor vanished candidate countsSweepExtraSkippedand sends nothing. Consistent with design.md. pingRunninglifecycle. Set under the lock at dispatch, cleared infire's first defer for every non-extra job, so limiter refusals,pingBodyfailures and panics inside the substitutes all clear it. It is per entry, so an entry replaced by a newRecordcannot cross-talk. Manual-only entries never take the extra. The extra's own job never sets it.
Non-blocking
- Every commit in this PR carries a
Co-Authored-By:trailer. The repo convention (CLAUDE.md, Conventions) says AI attribution usesAssisted-By:and "neverCo-Authored-By". All 7 commits, including the round-1 ones, have both lines. Process note only; I missed it in round 1. - A manual press (
PingNow) does not setpingRunning. A user pressing the Ping button in the same instant the extra slot fires can put the press and the extra request out together. Both read the same warm prefix, the cost is one duplicate read, and a press movesstartedAt, which postpones any extra not yet due. Very narrow; noting it for completeness.
What I checked
- Last review: round 1, 79d6119, 2026-10-30T10:35:30Z.
- New commits read: 2 (64965ff "the summary uses the 210 s slot, no hold extension", 4f387a4 "only the summary takes a summary's slot; extra re-checks the breaker").
- Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt; the inline file is empty). - New items since my last review: the author's round-1 reply (amiddavid, 2026-10-30T11:25:24Z), which answers both reviewers' finding 1 and every non-blocking item — each checked against the code above; the two new commits — reviewed as a first review, per the section above; reviewer 2's round-1 review — same finding 1 (agree; fixed) and four non-blocking notes, all moot or fixed by the same changes.
- Verified no stale references:
holdExtensions,extendHoldLocked,preExpiryExtraWaitingLocked,holdUntil,extraHoldMarginand thekeepalive_hold_extensionsstat are gone from code, docs and dash, with no remaining reader. - Re-read the full new text of
Sweep's extra branch,extraSlot/extraDue/extraWaiting,extraReadyLocked,fireExtra,fire's defer,extraSummaryWindowandfireSummarySubstitute's window selection, plusPingNowfor the press interaction. - Checked the tests' mechanics: helpers used (
testKeeperWith,markCredDeadLocked,routeTripped) exist; the slot arithmetic in each new test matches the code (Idle 280 and 240, short Idle 20); the blocked-ping test's clock advances line up with the floor and thepingRunninggate. - Did not run builds or tests (not approved). The author reports
go vet,gofmtand-raceon./keepalive/... ./components/offload/... ./proxy/...clean; nothing I read contradicts that.
amiddavid
commented
Oct 30, 2026
amiddavid
left a comment
Collaborator
Author
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.314 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 3 | 4f387a417885 |
approve |
Verdict: approve
Findings
None.
Earlier findings
- Round 1, mine and reviewer 1's, keeper.go:1288 — the extra request skipped the route-breaker and dead-credential re-check. Fixed.
- The extra branch now runs
routeIsTrippedLockedandcredIsDeadLockedunder the lock before it builds the job (keeper.go:1232-1237). On a trip it setse.stopped = trueand sends nothing; the release branch then owns the entry. TestTheExtraSlotSkipsATrippedRouteOrADeadCredentialcovers both cases: route tripped after the last planned ping, and credential marked dead. Both assert no extra request and a stopped span. I checked the fields and helpers the test uses (routeTripped,markCredDeadLocked) exist with those shapes.
- The extra branch now runs
Non-blocking
pingRunningcan be cleared early by an earlier ping.Sweepsets the flag at each dispatch (keeper.go:1285);fire's defer clears it when ANY of the entry's pings returns (keeper.go:1352-1357). With two pings of one entry in flight — possible whenIdleis under the 60 s ping timeout — ping N-1's return clears the flag while ping N is still out. Trace: ping N-1 dispatched at T-Idle returns at R ≤ T-Idle+60; the wrong extra fires on a tick t with max(T+Idle-30, R) < t < T+Idle while ping N is out. That needs Idle between 30 s and 60 s and a slow earlier ping, so the shipped defaults (240 s) cannot reach it. Consequence is mild: the extra starts a few seconds before the last ping's response is in, the exact thing the guard exists to prevent. A counter (increment at dispatch, decrement in the defer, extra waits for zero) would close it. The end-to-end test hangs ping 2 only after ping 1 has returned, so it does not cover overlapping pings.extraSummaryWindowis unbounded for a short Idle. For the extra request it widens tottl - (idle - 30 s) + 4 s, never capped (substitute.go:81-88). With Idle 20 s on a 5-minute cache that is 314 s, more than the ttl, so the phase check reads PreExpiry at any age: apre_expirysummary runs at the extra slot with 296 s of cache left, and the "spend only near expiry" rule no longer binds. This is the owner's "one slot" decision generalized to a config the decision did not discuss. Bounded to one request per span, so cost is capped either way.docs/design.mdnames the slot as "30 s before the normal hold deadline" and does not mention the short-Idle floor (2 ticks) or the wait for the last ping's response. The code comments carry both. A one-line note would keep the doc exact for short-Idle configs.
What I checked
- Last review: round 1, 79d6119, 2026-10-30T10:36:59Z.
- New commits read: 2 — 64965ff "the summary uses the 210 s slot, no hold extension", 4f387a4 "only the summary takes a summary's slot; extra re-checks the breaker".
- Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files in my folder).
- New items since my last review: the author's round-1 reply (one comment, 11:25:24Z) and the two commits above. I checked each claim in the reply against the code, as described below.
- My finding 1: fixed, with the test and the mutations the reply names (see Earlier findings).
- Reviewer 1's finding 1: same fix, verified myself.
- The non-blocking items from both round-1 reviews:
SweepExtraSkipped's doc now names every case it counts (keeper.go:1766-1770);endsAtTextTurnis now "an internal flag, not a published metric" in design.md; RELEASING.md item 10 is numbered; the hold-extension items (comments, 43 s headline, general bound,holdUntil,cache_state-alone grant, timer racing the slot) are moot — 64965ff removed the extension entirely, and I found no leftover references (extendHoldLocked,holdExtended,holdUntil,extraHoldMargin,HoldExtensions,keepalive_hold_extensions) anywhere in the repo. - The new single-slot design:
extraSlot= last ping + max(Idle - 30 s, 2 ticks);extraDuebounds it by the normal hold deadline;extraReadyLockedneeds a summary or sweep candidate; every span is released at (K+1) x Idle exactly (expireAuto is back to its old shape). The eager release andextraDuenow use the same bound. - The owner's "only the summary" rule:
fireExtrano longer falls from a declined summary to the sweep; the sweep takes the slot only through aPingSweepclaim, which requires no summary registered. Tests cover a declining summary (both cache states), no-summary sweep, and the summary-plus-sweep span. extraSummaryWindow: traced at the 5-minute defaults (94 s window, 90 s left at the 210 s slot), the one-hour tier (94 s, 90 s left), aHeadTTL1hschedule not granted the tier (negative widening, keeps the normal window, phase reads Cold, summary refused — fail-safe), and a wider configuredpre_expiry_seconds(never narrows). Planned-ping summaries keep the #715/#717 window;TestAPlannedPingSummaryKeepsTheNormalWindowpins the refusal at 80 s left and the take at 58 s left.pingRunning: set at dispatch, cleared infire's defer for non-extra jobs only;giveBackFailedPing's retry re-stamps and re-dispatches, so no hole there; a cleared flag on a retired entry object writes a dead object, harmless. The residual overlap race is the non-blocking note above.- The new tests' arithmetic:
TestAfterATextTurnAPreExpirySummaryRunsAtTheExtraSlot(Idle 240: pings 241/482, slot 692, deadline 722), the short-Idle end-to-end test (Idle 20: slot at +4 s, deadline +20 s, ping 2 hung across the slot), and the missed-slot test (in-flight at the slot, released at the deadline, nothing sent late). All consistent with the code. - Compile-level sanity of the new test code: imports (
sync,components), helpers (testKeeperWith,markCredDeadLocked,routeTripped), and themaxbuiltin on durations. No build was run on this machine; the author reportsgo vet,gofmtand-raceclean on the box, which I could not verify here. - Docs: CLAUDE.md, RELEASING.md and docs/design.md match the new code, including the two owner decisions quoted with dates.
docs/components/advanced-offload.mdstill describes the slot correctly.
This was referenced Oct 30, 2026
This was referenced Nov 1, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
After a text turn, no keep-alive substitute replaces a strategy ping any more: not the sweep question, not the summarizer's substitute. Every planned ping goes out plain, and the substitute goes out once, as an extra request after the last planned ping. After a tool-result turn nothing changes: a substitute may take ping 1, as on
main. OpenAI is not affected. The owner decided these rules on 2026-10-30.cache_state: pre_expirysummary (themediumpreset) runs there about 90 s before expiry, instead of in the usual last 64 s. See Behavior change.docs/design.md,CLAUDE.md,RELEASING.md). A guard test covers every substitute kind.Fixes #776
What we found
main(8fbc19c). On this short shape, main's ping 2 read the full prefix in 7 of 7 runs. The laptop misses had large prefixes and long text turns. The rule rests on the provider behavior fix(cheapmodel): the prefix question keeps the turn's breakpoint (#776) #777 measured and on the laptop data. The live runs show that the new order costs no cover.What changed
keepalive/keeper.go:endsAtTextTurn(body): true unless the held request's last non-system message is a user turn whose last block is atool_result. It reads roles and block types only. A body it cannot read counts as a text turn, which is the safe side. Record stores the result on the entry.fireSubstitutenever lets the sweep take a planned ping. Both the claim path and the no-registration lookup are gated.extraDue: after a text turn, once the planned pings are spent, the sweep question goes out once, 30 s before the hold deadline. That is the slot after the last ping (T+11.5 min on the 240 s 2-ping plan; T+117.5 min on the 1-hour 1-ping plan).already_askedlatch as before.extraSummaryWindow: for the summary's extra request only, the pre-expiry window widens to cover that slot: ttl - (Idle - 30 s) + 2 ticks, which is 94 s at the defaults (90 s left plus 2 ticks). It never narrows a wider configured window. A summary that takes a planned ping keeps the Keep-alive: the substitute phase treats an OpenAI cache as 5 minutes, not 30 #715/fix(keepalive): read an OpenAI cache as 30 minutes in the substitute's phase check #717 window.pingRunning).endsAtTextis never set there./stats:keepalive_sweep_extra_asked,keepalive_sweep_extra_skipped,keepalive_summary_extra_sent.components/offload/ping_claim.go:KeepAliveCandidateState, a read of the summary candidate's registration only (no content), so the extra slot claims only when there is something to send.components/offload/ping_claim.go:HasSweepPingCandidate, so the extra slot claims only when there is something to ask.keepalive/substitute_test.go,keepalive/openaiphase_test.go, and 2 proxy integration tests now use a body that ends at a tool_result, so they keep checkingmain's behavior there.docs/design.md: a new section, "Keep-alive: the cache strategy comes first". It covers the rule, the one slot, and the summary's wider window there.CLAUDE.md, Hard boundaries: one bullet that points at it.RELEASING.md, Part B: the live check confirms the rule.docs/components/advanced-offload.md: which ping the question takes.kaToolBody), so they keep checking main's behavior there.Behavior change
Decided by the owner, 2026-10-30, in their words: "on those cases where sweep invalidates the cache, it can't contradict the caching strategy and hence if the caching strategy is 2 pings, it needs to come as a 'third ping'. this way if a user comes back within the warm period due to the third ping and we pay a rewrite, that would've happen anyhow with the strategy."
extract_llm_sweepon (thexhighpreset), after a turn that ends at a text turn.extract_llm_sweepout of the pipeline, or a preset other thanxhigh).The summarizer's keep-alive substitute. Decided by the owner, 2026-10-30: "summerizer as well so a)", then "give it more time, it can run on the 210 sec mark".
Who: every keep-alive user with
cache_aware_summarizeron (themedium,highandxhighpresets), after a turn that ends at a text turn, on Anthropic.Old: the summary took a planned ping (for
pre_expiry, the ping that fell inside its window), and that ping did not renew the cache.New: every planned ping is plain. The summary goes out once after the last one, at 210 s (5-minute defaults), for either cache_state.
Sweep and summary in one span: only the summary goes. The owner's rule, 2026-10-30: "as for sweep after summary. dont do that. it can probably have the sweep question pay a cache write like the problem with the ping... so we should probably just do summary at that point". The sweep question takes the slot only when no summary is due. Before this PR, the sweep asked when the summary declined.
New for
cache_state: pre_expiry(medium): in this one request it runs about 90 s before the cache expires, not in the usual last 64 s. Its pre-expiry window widens for this request only.The hold limit: unchanged for every span.
Cost: one extra request per idle span after a text turn (the summary call). The plain ping it used to replace now goes out as well.
Cosmetic, unchanged from main: the question books its cost through the substitute path. That moves the dashboard's "refreshed at" time, so after a text turn the status line may show the cache as renewed at about T+11.5 min, when it was not.
How it was tested
Unit tests, in
keepalive/sweeptextturn_test.go:TestEndsAtTextTurnTestAfterATextTurnBothPingsArePlainAndTheQuestionComesThirdTestAfterATextTurnAOnePingPlanPingsThenAsksTestAfterAToolResultTurnTheQuestionTakesPingOneTestNoExtraQuestionWhenTheCopyIsReleasedTestNoExtraRequestWithoutASweepCandidateTestAfterATextTurnAPlannedPingRunsNoSweepLookupTestNoExtraQuestionOnAStoppedSpanTestGuardNoPlannedPingIsReplacedAfterATextTurn(sweep, pre_expiry summary and any summary; 1-, 2- and 3-ping plans)Round 5, the summarizer at the 210 s slot, in
keepalive/summarytextturn_test.go. Each fails on 79d6119 where the behavior differs:TestAfterATextTurnAPreExpirySummaryRunsAtTheExtraSlotTestTheExtraSlotAndWindowAtTheShippedDefaultsTestNoSpansHoldLimitChangesTestAPlannedPingSummaryKeepsTheNormalWindowTestAfterATextTurnAnAnySummaryUsesTheExtraSlotTestASweepAndAPreExpirySummarySendOneExtraRequestTestADecliningSummaryIsNotFollowedByTheSweep(pre_expiry and any)TestWithNoSummaryTheSweepTakesTheExtraSlotTestTheExtraSlotSkipsATrippedRouteOrADeadCredentialTestAShortIdleExtraWaitsForTheLastPingTestAShortIdleExtraIsNotSentWhileTheLastPingIsOutTestAMissedExtraSlotIsNotSentLateTestOnOpenAIASummaryStillTakesAPlannedPingMutations, each on a copy of the fix:
endsAtTextalways falseTestEndsAtTextTurn...APlannedPingRunsNoSweepLookupextraAskedlatch...QuestionComesThird...QuestionComesThird...OnAStoppedSpan...PreExpirySummaryRunsAtTheExtraSlot...WindowAtTheShippedDefaults...WindowAtTheShippedDefaults...IsNotFollowedByTheSweep...TrippedRouteOrADeadCredential...TrippedRouteOrADeadCredential...TrippedRouteOrADeadCredential...ShortIdleExtraWaitsForTheLastPing...ShortIdleExtraWaitsForTheLastPingpingRunningnever set...IsNotSentWhileTheLastPingIsOutpingRunningnever cleared...NotSentLateBox (head 4f387a4):
go vet ./...andgofmtare clean.-racepassed on./keepalive/... ./components/offload/... ./proxy/.... Non-race passed on./dash/... ./cmd/... ./apply/... ./components/all/....Live, the summarizer: not run. A summary needs a real summary call, and only its timing changed. The unit tests cover the slot and the window on the keeper's own clock.
Live, on the laptop. Each run had its own proxy (pipeline
[extract_llm_sweep], 2 pings) and a forwarder that logged metadata only, to theANTHROPIC_UPSTREAMgateway. Shape: a tool turn, then a text turn (the real turn ends at a TEXT turn), then pings, then one turn. Prefix about 31.3k to 32k. "Q" is the sweep question. Read / write in tokens.Round 3, this rule, the real 240 s plan, turn 3 at T+12.5 min:
Earlier rounds, 200 s plan, turn 3 at T+7.7 min (the old "question on the last ping" builds):
* The Opus turn-3 misses are not caused by the pings. The real Opus turn 2 also missed 3 s after turn 1, with no ping between. Claude Code's Opus turns change the prefix between turns in
-p --resume.Data dependence
No change.
KeepAliveCandidateStatereads only whether a summary candidate is registered (and its config), not content.endsAtTextTurnreads the role and block type of the held request's last messages: metadata, from a body the keeper already holds. Nothing new is stored. Each storage level (off, metadata only, everything) works as before.docs/data-dependence.mdneeds no update.Open questions
-p --resumeturns is a separate finding. It needs its own issue, if it shows on interactive sessions too.🤖 Generated with Claude Code