Skip to content

fix(keepalive): the sweep question takes the last ping, never ping 1 (#776) - #779

Merged
amiddavid merged 7 commits into
mainfrom
fix/sweep-as-ping-2
Oct 30, 2026
Merged

amiddavid merged 7 commits into
mainfrom
fix/sweep-as-ping-2

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

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.

  • Live, Sonnet 5.5, text turn, the real 240 s plan:
    • ping 1 and ping 2 were plain, read 31,451 and wrote 0;
    • the question at slot 3 (T+11.8 min) read 31,451 and wrote 6;
    • a turn at T+12.5 min hit.
  • The hold limit does not change. All substitutes share one extra slot, 210 s after the last ping at the 5-minute defaults. A cache_state: pre_expiry summary (the medium preset) runs there about 90 s before expiry, instead of in the usual last 64 s. See Behavior change.
  • The rule is now in the development docs (docs/design.md, CLAUDE.md, RELEASING.md). A guard test covers every substitute kind.

Fixes #776

What we found

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 a tool_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.
    • After a text turn, fireSubstitute never 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).
      • It is not a ping: no ping clock moves, so nothing follows it.
      • It uses the same claim, cost ceiling and already_asked latch as before.
      • It sends nothing if the copy is gone, the span is stopped, or the thread has no sweep candidate.
      • Why 30 s early: the hold deadline is (K+1) x X, the same instant as the slot, and its timer would race the 2 s sweep tick. The margin keeps the hold limit unchanged.
    • The summarizer's substitute follows the same rule. After a text turn it never takes a planned ping.
    • One extra slot for every substitute: 30 s before the normal hold deadline, so the hold limit never changes.
    • 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.
    • One request in the slot, and only the summary when one is due. If a summary candidate is registered, only the summary goes, even if it declines; the sweep question does not go in that span. The sweep question takes the slot only when no summary is registered. Nothing after it.
    • The same route-breaker and dead-credential re-check as a planned ping (review round 1). The slot waits a full Idle after the last 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. The extra waits until that ping's response is in (pingRunning).
    • A missed slot is never sent late. If a real request is in flight at the slot, the extra request is dropped. It never goes out past the normal hold deadline.
    • OpenAI is out of scope. Its cache has no breakpoints and no text-turn rule, so endsAtText is never set there.
    • New counters in /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.
  • Tests: the summarizer tests in 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 checking main's behavior there.
  • The first commit of this PR ("plain ping 1 always, question on the last ping") is reverted.
  • Docs:
    • 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.
  • Tests: main's sweep tests now run on a body that ends at a tool_result (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."

  • Who: keep-alive users with extract_llm_sweep on (the xhigh preset), after a turn that ends at a text turn.
  • Old: the question took ping 1, and that ping did not renew the cache.
  • New: every planned ping is plain, as the strategy plans. The question goes out once after the last planned ping. The 1-hour tier's 1-ping plan keeps its sweep: a plain ping at 59 min, then the question about 58.5 min later.
  • After a tool-result turn: no change.
  • Cost: one extra request per idle span after a text turn (the question, about $0.01 to $0.02 here: a full-prefix read, about 1.7k fresh input, and the answer). The plain ping it used to replace now goes out as well.
  • Cover: a user back inside the strategy's warm period is covered exactly as without the sweep. A user back later pays the re-write the strategy would have paid anyway.
  • How to turn it off: turn the sweep off (extract_llm_sweep out of the pipeline, or a preset other than xhigh).

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_summarizer on (the medium, high and xhigh presets), 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:

Test 8fbc19c 88330e1
TestEndsAtTextTurn fails fails
TestAfterATextTurnBothPingsArePlainAndTheQuestionComesThird fails fails
TestAfterATextTurnAOnePingPlanPingsThenAsks fails fails
TestAfterAToolResultTurnTheQuestionTakesPingOne passes (main's behavior) fails
TestNoExtraQuestionWhenTheCopyIsReleased fails fails
TestNoExtraRequestWithoutASweepCandidate passes (main's behavior) passes
TestAfterATextTurnAPlannedPingRunsNoSweepLookup new in round 3 new in round 3
TestNoExtraQuestionOnAStoppedSpan new in round 3 new in round 3
TestGuardNoPlannedPingIsReplacedAfterATextTurn (sweep, pre_expiry summary and any summary; 1-, 2- and 3-ping plans) fails fails

Round 5, the summarizer at the 210 s slot, in keepalive/summarytextturn_test.go. Each fails on 79d6119 where the behavior differs:

Test What it checks 79d6119
TestAfterATextTurnAPreExpirySummaryRunsAtTheExtraSlot at Idle 240 s: plain pings, then the summary at 210 s, nothing after fails
TestTheExtraSlotAndWindowAtTheShippedDefaults slot 210 s; planned window 64 s (unchanged); extra window 94 s; the phase is pre_expiry with it and warm without it fails
TestNoSpansHoldLimitChanges every shape is released at (K+1) x X fails (it extended)
TestAPlannedPingSummaryKeepsTheNormalWindow a planned-ping summary keeps the #715/#717 window passes (unchanged)
TestAfterATextTurnAnAnySummaryUsesTheExtraSlot an any summary at the same slot passes
TestASweepAndAPreExpirySummarySendOneExtraRequest one request: the summary —
TestADecliningSummaryIsNotFollowedByTheSweep (pre_expiry and any) a summary is due and declines: no sweep question that span new, round 6
TestWithNoSummaryTheSweepTakesTheExtraSlot no summary: the sweep question goes new, round 6
TestTheExtraSlotSkipsATrippedRouteOrADeadCredential review round 1: nothing on a tripped route or dead credential; the span stops new, round 6
TestAShortIdleExtraWaitsForTheLastPing the slot floor and the in-flight wait new, round 6
TestAShortIdleExtraIsNotSentWhileTheLastPingIsOut end to end: a tick past the slot with ping 2 hanging sends nothing new, round 6
TestAMissedExtraSlotIsNotSentLate a missed slot is dropped, the span is released on time fails (pre_expiry)
TestOnOpenAIASummaryStillTakesAPlannedPing OpenAI unchanged passes

Mutations, each on a copy of the fix:

Mutation Killed by
endsAtText always false 3 tests
Do not skip the trailing system reminder 20 tests
Read the first block, not the last TestEndsAtTextTurn
The claim path not gated 5 tests, the guard included
The no-registration lookup not gated ...APlannedPingRunsNoSweepLookup
No extra slot 2 tests
No extraAsked latch ...QuestionComesThird
No 30 s margin 2 tests
Fire the extra slot at any time ...QuestionComesThird
No candidate check 6 tests
The extra job sends a plain ping 2 tests
A stopped span still asks ...OnAStoppedSpan
The extra request also counts as a ping survived: equivalent (the pings are already spent, so nothing changes)
Round 4-5: the summary not gated on the claim path 5 tests, the guard included
Round 4-5: the rule applied on OpenAI too 2 tests
Round 5: no window widening for the extra summary ...PreExpirySummaryRunsAtTheExtraSlot
Round 5: the widening on every ping 2 tests (the planned window is unchanged)
Round 5: the widening without the 2 ticks ...WindowAtTheShippedDefaults
Round 5: the widening narrows a wider window ...WindowAtTheShippedDefaults
Round 6: the sweep asks after a declined summary ...IsNotFollowedByTheSweep
Round 6: the sweep never takes the slot 3 tests
Round 6: no route-breaker check at the slot ...TrippedRouteOrADeadCredential
Round 6: no dead-credential check at the slot ...TrippedRouteOrADeadCredential
Round 6: a trip does not stop the span ...TrippedRouteOrADeadCredential
Round 6: no short-Idle floor ...ShortIdleExtraWaitsForTheLastPing
Round 6: no wait for the last ping ...ShortIdleExtraWaitsForTheLastPing
Round 6: pingRunning never set ...IsNotSentWhileTheLastPingIsOut
Round 6: pingRunning never cleared 8 tests
Round 5: a missed slot sent late ...NotSentLate
Round 5: the slot at the deadline, not 30 s before 7 tests
Round 5: the extra slot ignores the summary 2 tests

Box (head 4f387a4): go vet ./... and gofmt are clean. -race passed 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 the ANTHROPIC_UPSTREAM gateway. 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:

Run Build Ping 1 Ping 2 Slot 3 Turn 3 Spend
L-fix this PR (7e0abd2) plain 31,451 / 0 plain 31,451 / 0 Q 31,451 / 6 (T+11.8 min) 31,451 / 77 hit $0.11
L-main 8fbc19c Q 31,350 / 6 plain 31,350 / 0 none 31,350 / 72 hit $0.11

Earlier rounds, 200 s plan, turn 3 at T+7.7 min (the old "question on the last ping" builds):

Run Build Model Ping 1 Ping 2 Turn 3 Spend
s-main x5 8fbc19c Sonnet 5.5 Q ~31.4k / 6 plain ~31.4k / 0 hit $0.57
s-fix x5 88330e1 Sonnet 5.5 plain ~31.4k / 0 Q ~31.4k / 6 hit $0.58
s-var plain then Q at the last ping Sonnet 5.5 plain / 0 plain / 0, then Q / 6 hit $0.11
o-main, o-fix, o-var all 3 Opus 5.5 full read full read miss on all 3* $1.93

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

  • Total live spend for this PR: $3.42.
  • The captured data and test databases were deleted after each round.

Data dependence

No change. KeepAliveCandidateState reads only whether a summary candidate is registered (and its config), not content. endsAtTextTurn reads 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.md needs no update.

Open questions

  • The Opus prefix changing between -p --resume turns is a separate finding. It needs its own issue, if it shows on interactive sessions too.

🤖 Generated with Claude Code

…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]>
amiddavid and others added 4 commits October 30, 2026 09:32
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 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.314 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 79d6119c4609 blocking

Verdict: blocking

Findings

  1. 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 — the offload package cannot see the keeper's breaker. An entry whose own ping tripped the route is stopped (e.stopped), so extraWaiting() 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 — set e.stopped = true and continue instead 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. extendHoldLocked re-arms to slot + 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 — SweepExtraSkipped counts more than its description. fireExtra also counts it when a summary declined and no sweep candidate existed, and when the claim came back PingPlain (thread busy). The Stats comment says "the claim gave the sweep no question". Naming or doc mismatch only.
  • docs/design.md:278 — keepalive.endsAtTextTurn reads like a published metric. No such metric exists; it is the internal function endsAtTextTurn (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) is startedAt + 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: extraAsked is 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, Arrive and Shutdown all still release the extended entry.
  • Checked lock ordering and deadlocks: extraReadyLocked and preExpiryExtraWaitingLocked run under k.mu and touch only leaf mutexes in offload; endsAtTextLocked, fireExtra and both substitute calls take k.mu on the ping goroutine only; ClaimPing is never called under k.mu.
  • Checked endsAtTextTurn against 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, and eligible admits no other breakpoint-less provider).
  • Checked that planned pings stay plain after a text turn for every substitute kind (fireSubstitute gates 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; fireSweepSubstitute keeps its panic recovery.
  • Checked data dependence: endsAtTextTurn reads 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 startedAt without 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 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.314 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 79d6119c4609 blocking

Verdict: blocking

Findings

  1. 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 / credIsDeadLocked right 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 queues pingJob{extra: true, ...} with no such check. The extra slot sits idle a full Idle period 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 = true and continue, 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 of fireExtra, 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_state alone (extendHoldLocked). A pre_expiry candidate that KeepAliveSubstitute would 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 Idle from the span start, while the extra slot is measured from the last ping's stamp. If the last ping runs more than extraSlotMargin (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.holdUntil is written by extendHoldLocked and 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 to preExpiryExtraWaitingLocked. No path holds an entry past min(slot + 15 s, expiry).
  • Lock ordering: the new reads of the offload registries happen under k.mu; components/offload cannot call back into keepalive, so no reverse order exists.
  • endsAtTextTurn on 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 to kaToolBody. I found no remaining test that expects a substitute to take a planned ping off a text-turn body. Test helpers and the modelinfo constant 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.md needs 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).

amiddavid and others added 2 commits October 30, 2026 12:44
)

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]>
@amiddavid

Copy link
Copy Markdown
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). go vet ./... and gofmt are clean. -race passed on ./keepalive/... ./components/offload/... ./proxy/....

Finding 1, both reviewers (blocking): the extra request skips the route-breaker and dead-credential re-check (keeper.go:1288). Fixed.

  • The extra branch in Sweep now runs routeIsTrippedLocked and credIsDeadLocked under the lock, the same as a planned ping. On a trip it sets e.stopped = true and sends nothing.
  • Test: TestTheExtraSlotSkipsATrippedRouteOrADeadCredential, with 2 cases: the route trips after the last planned ping, and the credential is marked dead. In both, no extra request goes out and the span stops.
  • Mutations, each killed by that test: no route check; no credential check; a trip that does not stop the span.

Non-blocking:

  • The hold-limit comments (keeper.go:103-104, 296-298), the 43 s headline, the general bound, holdUntil, a timer racing the slot, the extension granted from cache_state alone. Moot. The owner removed the hold extension (64965ff): every span is held for exactly (K+1) x Idle again, so the security comments are right as written. All substitutes now share one slot, 30 s before the normal deadline.
  • SweepExtraSkipped counts more than its description. The doc now names every case it counts: the thread is busy, the summary declined (the sweep does not ask after it), or the question declined or failed. Each of those also counts under its own substitute reason.
  • docs/design.md:278, keepalive.endsAtTextTurn. Now "an internal flag on the held entry, not a published metric".
  • RELEASING.md:153, the bullet has no number. Now item 10 of the list.
  • A short Idle can overlap the extra with the last ping. Yes, keepalive_idle_seconds accepts any positive value.
    • extraSlot is now at least 2 ticks after the last ping.
    • The extra waits until the last ping's response is in: a new pingRunning flag, set at dispatch and cleared when fire returns.
    • Tests: TestAShortIdleExtraWaitsForTheLastPing, and an end-to-end TestAShortIdleExtraIsNotSentWhileTheLastPingIsOut. In the second, ping 2 hangs while a tick passes the slot, and nothing goes out until it returns.
    • Mutations, all killed: no floor; no wait; the flag never set; the flag never cleared.
  • The extra dropped if the last ping runs more than 30 s late (reviewer 2). Agreed: this is the safe direction, and nothing is sent late. No change.

@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.314 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 3 4f387a417885 approve

Verdict: approve

Findings

None.

Earlier findings

  1. 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 runs routeIsTrippedLocked and credIsDeadLocked under the lock, before the job is built. On a trip it sets e.stopped = true and sends nothing, exactly as the planned-ping branch does. TestTheExtraSlotSkipsATrippedRouteOrADeadCredential covers 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.
  2. Round 1, non-blocking items. All fixed or moot:
    • Hold-limit comments, the 43 s headline, the general bound, holdUntil, the extension granted from cache_state alone: 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.
    • SweepExtraSkipped description: fixed. The Stats comment now names every case it counts (keeper.go:1766-1770).
    • keepalive.endsAtTextTurn as 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. extraSlot floors the slot at two sweep ticks after the last ping (keeper.go:222-224), and pingRunning (set at dispatch, cleared in fire's defer for every non-extra exit) keeps the extra back until that ping's response is in. TestAShortIdleExtraWaitsForTheLastPing and the end-to-end TestAShortIdleExtraIsNotSentWhileTheLastPingIsOut cover it.

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), extraDue never sends past startedAt + Idle, and the eager release and the deadline timer both fire there, so no span's hold changes. extraSummaryWindow widens 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.extra gates the widening), which TestAPlannedPingSummaryKeepsTheNormalWindow pins 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. fireExtra no 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, extraReadyLocked still requires a candidate before the slot is taken, and a PingPlain or vanished candidate counts SweepExtraSkipped and sends nothing. Consistent with design.md.
  • pingRunning lifecycle. Set under the lock at dispatch, cleared in fire's first defer for every non-extra job, so limiter refusals, pingBody failures and panics inside the substitutes all clear it. It is per entry, so an entry replaced by a new Record cannot 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 uses Assisted-By: and "never Co-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 set pingRunning. 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 moves startedAt, 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, extraHoldMargin and the keepalive_hold_extensions stat 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, extraSummaryWindow and fireSummarySubstitute's window selection, plus PingNow for 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 the pingRunning gate.
  • Did not run builds or tests (not approved). The author reports go vet, gofmt and -race on ./keepalive/... ./components/offload/... ./proxy/... clean; nothing I read contradicts that.

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

Verdict: approve

Findings

None.

Earlier findings

  1. 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 routeIsTrippedLocked and credIsDeadLocked under the lock before it builds the job (keeper.go:1232-1237). On a trip it sets e.stopped = true and sends nothing; the release branch then owns the entry.
    • TestTheExtraSlotSkipsATrippedRouteOrADeadCredential covers 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.

Non-blocking

  • pingRunning can be cleared early by an earlier ping. Sweep sets 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 when Idle is 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.
  • extraSummaryWindow is unbounded for a short Idle. For the extra request it widens to ttl - (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: a pre_expiry summary 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.md names 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); endsAtTextTurn is 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); extraDue bounds it by the normal hold deadline; extraReadyLocked needs 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 and extraDue now use the same bound.
  • The owner's "only the summary" rule: fireExtra no longer falls from a declined summary to the sweep; the sweep takes the slot only through a PingSweep claim, 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), a HeadTTL1h schedule not granted the tier (negative widening, keeps the normal window, phase reads Cold, summary refused — fail-safe), and a wider configured pre_expiry_seconds (never narrows). Planned-ping summaries keep the #715/#717 window; TestAPlannedPingSummaryKeepsTheNormalWindow pins the refusal at 80 s left and the take at 58 s left.
  • pingRunning: set at dispatch, cleared in fire'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 the max builtin on durations. No build was run on this machine; the author reports go vet, gofmt and -race clean 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.md still describes the slot correctly.

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.

fix(keepalive): ping 2 re-writes the whole prefix after a ping 1 that wrote 6 tokens

1 participant