Repository navigation
fix(keepalive): never send two identical pings in a row - #712
Conversation
The IBM LiteLLM gateway answers a byte-identical request from its own response cache: the same response id, the same usage, and no call to the provider. A second keep-alive ping was a copy of the first, so it never refreshed the provider's prompt cache, and the prefix expired 5 minutes after ping 1. Live: after 1 ping the next turn missed 0 of 146 times, after 2 pings 50 of 67 times. Each ping now asks for a different output budget than the one before (max_tokens 1, 2, 3 ... cycling through 8). The field is outside the prefix the provider hashes, so a ping is still a pure cache read. The first ping is unchanged. Manual pings count too. Fixes #706 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
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.310 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 5bc5a2367282 |
blocking |
Verdict: blocking
Findings
- keepalive/ping.go:80 — the budget repeats after 8 due cycles that dispatched no ping, so two dispatched pings in a row can still be byte-identical.
- What fails: the budget is
base + seq mod 8, andseqis consumed at due time, not at dispatch time.Sweeptakesseq := e.sent; e.sent++for every due ping (keeper.go:1167-1168).firethen often dispatches nothing: a substitute takes the ping (keeper.go:1259), the limiter refuses (keeper.go:1234-1238 and 1265-1269), or a manual press fails aftere.sent++(manual.go:115, then theErrLimitedreturn at manual.go:120-124). If one dispatched ping has seqsand the next dispatched ping has seqs+8, with no dispatched ping and no newRecordbetween (the body is unchanged), both ask forbase + s mod 8output tokens and are byte-identical. The gateway then answers the second from its response cache — exactly the #706 defect: no provider call, a phantom "cache read", and a clock refreshed on a lie. - Proof: trace — ping seq 0 dispatched; seqs 1..7 consumed by refused or substituted cycles (each refusal still counts toward
e.pings, keeper.go:1162, and each cycle is oneIdleapart, keeper.go:187-189); ping seq 8 dispatched with the samee.body→pingBodyNoutput differs from ping 0 in no byte → gateway cache hit. Reachability needs a policy withMaxPings≥ 9 (the default is 2, config.go:198, and no upper bound is enforced, config.go:244) or ~8 failed manual presses, ~8 consecutive no-dispatch cycles (a tenant at capacity, or substitutes taking the ping), and a gateway response-cache entry still live after that span. Narrow, but it is the one case the PR title promises cannot happen. The comment onkaEntry.sent("counts the pings this entry has sent", keeper.go:145-146) and the PR body say the same thing; the field counts attempts, not sends. - Fix: count dispatched pings, not due ones. Store on the entry the budget (or seq) of the last ping actually handed to the Dispatcher, updated under
k.muwherefire/PingNowbuild the body, and picklast + 1 mod pingVary. Then any two dispatched pings in a row differ, whatever happened to the due cycles between.
- What fails: the budget is
Non-blocking
- dash/keepalive.go:1124-1127 — the comment says the ping sends
max_tokens: 1. Pings now ask 1..8. The billed figure stays right (a keep-alive reply is one output token, and output is billed as generated), so this is a comment update only. - keeper.go:918 — the projected per-ping cost uses the base budget, so it under-projects by at most 7 output tokens. The PR body states this. Negligible next to the cache-read price.
What I checked
- The full diff (keeper.go, manual.go, ping.go, pingvary_test.go) and the code around each change:
Sweep,fire,noteOutcome,record1,fireSubstitute/fireSummarySubstitute,PingNow,due, thepingJobcopy discipline, and the lock discipline one.sent. - The invariant the PR claims: consecutive dispatched pings differ. It holds when every consumed seq dispatches (the default
MaxPings: 2case, and every test in the PR). It does not hold under skipped cycles — finding 1. - That the hashed prefix is untouched: only
max_tokens/max_output_tokensandstreamchange; the new test assertsmodel,system,messages,tools,tool_choice,thinkingstay byte-identical. - The audit rows:
record1(keeper.go:1496) and the manual report (manual.go:186) both recordpingOutputBudget(route) + seq%pingVary, which matches the body each path built. - Concurrency:
e.sentis read and written only underk.mu(Sweep and PingNow); the job carries a copy. A sweep ping and a manual press racing get distinct seqs. - Callers of the old
pingBody: production paths all usepingBodyN; the wrapper is test-only now, and keeper_test.go:815 still compares against seq 0, which is the first ping in that test. - Config bounds for
MaxPings(config.go:198, 244) to judge reachability of finding 1. - The three new tests, read line by line. I did not run them: live tests are not approved, and Go is not on this machine. The PR body reports them passing on the eval box, plus
-raceon./keepalive/...and./proxy/.... - The PR description. No other review or comment on the PR was read.
amiddavid
left a comment
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.310 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 5bc5a2367282 |
blocking |
Verdict: blocking
Findings
- keepalive/keeper.go:811 — the vary counter is per entry, so two pings can still be byte-identical across an entry boundary.
- What fails:
kaEntry.sentstarts at 0 in every new entry, andRecordbuilds a new entry on every turn. The gateway's response cache keys on the request bytes alone, not on the entry or the thread. Two triggers:- A client re-sends a byte-identical request (a "retry" or "regenerate" after a 2xx turn). The old entry had sent 1 ping (seq 0,
max_tokens1). The new entry's first ping is seq 0 again, so the exact same bytes. - Two threads of one session (agent-team teammates, see keeper.go:250) fork on the same prefix and hold byte-identical bodies. Both entries count 0, 1, 2 ..., so every ping of one thread repeats the other's, whatever the timing.
In both cases the gateway answers the second ping from its response cache. The provider's cache is not refreshed. Butrecord1books the cached usage as a real cache read,notePingReadresetsmissed, andrefreshedAtmoves (keeper.go:1475-1478) — the keeper now believes a prefix is warm that it never touched. The prefix then expires, and the next real turn pays the rewrite. This is the exact symptom of #706, at a lower rate.
- A client re-sends a byte-identical request (a "retry" or "regenerate" after a 2xx turn). The old entry had sent 1 ping (seq 0,
- Proof:
Recordconstructse := &kaEntry{...}(keeper.go:811) withsentat its zero value. Nothing carries a per-thread seq across entries. Contrastk.turns[key]++(keeper.go:829), which does persist per thread across entries. A per-entry counter therefore cannot uphold the PR's claim ("never send two identical pings in a row") outside one idle span. - Fix: keep the seq per thread, not per entry. For example a
k.seqsmap besidek.turns(same key, sameMaxTurnKeysreset guard), read inRecordto seede.sent. Or fold a per-thread salt into the budget inpingBodyN.
- What fails:
Non-blocking
kaEntry.sentis incremented before the send is known to happen (keeper.go:1167-1168, manual.go:115). A spare refusal, a substitute takeover, or a transport error consumes a seq without a ping. Eight consumptions between two sent pings make them identical again (base + n%pingVary). That needs about 8 failed due cycles in a row (roughly 37 minutes), so it is far-fetched. But the field doc says "counts the pings this entry has sent", which it does not quite do.- The new tests cover one entry only. A test that re-records the same body and then sweeps would have caught the finding above.
pingBody(ping.go:52) now has no production caller; only tests use it. Keeping it is fine.- dash/keepalive.go:1123 says the ping sends "max_tokens 1". Pings now ask 1..8 (16..23 on
/v1/responses). The projection stays correct — one output token is billed either way — but the comment is now stale.
What I checked
- Full diff 0a22b9c..HEAD (4 files) and the code around each change: keeper.go (Sweep, fire, record1, noteOutcome, Record, Arrive, clear), manual.go (PingNow), ping.go (pingBodyN), pingvary_test.go.
- Concurrency:
e.sentis read and incremented underk.muon both paths (Sweep, keeper.go:1167; PingNow, manual.go:114-115). A sweep ping and a manual press in flight at the same time get different seqs. Correct. - Audit rows:
MaxTokensin record1 (keeper.go:1496) and manual.go:186 matches the bodypingBodyNsent (base + seq%pingVary), on both routes. Correct. - Prefix safety: only
max_tokens/max_output_tokensandstreamchange. Both sit outside the hashed prefix, so a ping stays a pure cache read. The/v1/responsesbase of 16 keeps the Azure minimum. Correct. - Cost: output is billed as generated, and a keep-alive reply is one token, so a larger cap costs nothing on its own. Correct.
- Existing tests that assert
max_tokens == 1(keeper_test.go:117 and :815, manual_test.go:68, proxy/manualping_test.go:126 and :460) all test the FIRST ping of an entry (seq 0), so they still hold. Reasoned statically; live tests were not approved. - Substitute paths (
fireSubstitute→ summary/sweep) send their own request shapes and are one-shot per thread (theaskedflag), so the identical-body defect does not apply to them. - Repo rules: fail-open behaviour untouched (a
pingBodyNfailure stops only that entry's pings, as before); no data-dependence change (the hold still keeps only the masked body, and no new stored data is read); the commit carries DCO sign-off andAssisted-By:.
Review of #712 found 2 ways for two pings sent in a row to match: - The step was taken when a ping fell due, so a cycle that sent nothing (a substitute took it, the limiter refused it) still used one up. After 8 such cycles the next sent ping repeated the last. - The step counter lived on the entry and started at 0 on each new one, so a re-sent identical turn repeated the ping before it. The keeper now keeps the step of the last ping actually dispatched, per thread, beside its turn count (same bound, same reset), and the next ping takes that step plus 1. A thread's first ping is still max_tokens 1. Fixes #706 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
|
Replies to round 1, at head Both findings: fixed with one change. The keeper keeps the step of the last ping actually dispatched, per thread ( Reviewer 2, finding 1 (a cycle that sends nothing used up a step): fixed.
Reviewer 1, finding 1 (the counter restarted on each new entry): fixed for one thread.
Non-blocking:
How it was tested (eval box):
|
amiddavid
left a comment
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.310 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | 89fa98a9dd49 |
blocking |
Verdict: blocking
Findings
- keepalive/keeper.go:1059 —
Forgetfrees a tenant'sturnsandtier1hkeys but not itslastVarykeys, solastVarycan grow without bound.- What fails:
lastVarygains one key per thread that ever dispatches a ping. Its only bounds are theRecordprune at keeper.go:836-845, which fires whenlen(k.turns) > MaxTurnKeys(20000).Forget(keeper.go:1044-1062) deletes the tenant'sturnsandtier1hentries — and by doing so keepsturnsunder 20000, so the prune never fires. On a deployment that callsForgetas tenants churn,lastVarykeeps every pinged thread's key of every forgotten tenant for the life of the process. The field's comment claims "Bounded and reset exactly as turns is" (keeper.go:382-383);Forgetbreaks that parity. The repo bounds the same class of map on purpose (manualAtMax, manual.go:198-199). - Proof: grep of every
turnsandlastVarymutation site —turnsis wiped inShutdown(keeper.go:543), incremented inRecord(830), pruned inRecord(836-839), deleted per key inForget(1059).lastVaryis written inNew(468), pruned inRecord(841-845), and read/written innextVaryLocked(917-921). No other cleanup.Forget's loop deletesk.turns[key]andk.tier1h[key](keeper.go:1059-1060) and nothing fromlastVary. - Fix: add
delete(k.lastVary, key)beside theturnsdelete inForget's loop. For full parity with the comment, also wipelastVaryinShutdown(keeper.go:543-544) — harmless there, since the keeper is dead, but the comment says "exactly as turns is".
- What fails:
Non-blocking
- A dispatch attempt that fails in transport still consumes a step (
firetakes the step, thenDispatcher.Docan fail, keeper.go:1294-1300). Eight such failures between two delivered pings repeat the bytes. This needs ~8 consecutive failed dispatches on one thread (~37 min) and a gateway cache entry alive that long, and the step is only taken when the body is built and handed to the Dispatcher — what the round-1 fix asked for. Acceptable residual. - The two-thread case (byte-identical bodies, lockstep pings): I checked the author's rejection and accept it. A hash-of-key start is only probabilistic (a colliding pair matches on every ping, 1 in 8 pairs collides), and it moves a thread's first ping off the measured
max_tokens: 1bytes. The scenario needs two threads holding the same transcript and pinging in lockstep; a turn on either ends it. The limit is documented innextVaryLockedand in the PR body. If it ever must be ruled out, salting a field the gateway keys on but the provider ignores (stop_sequences, per the PR's own measurement) with the thread id would do it deterministically. pingBody(step 0) still has no production caller. The author keeps it as the form the existing tests use. Fine.
What I checked
- Last review: round 1, 5bc5a23, 2026-10-25T18:03:10Z
- New commits read: 1 (89fa98a "fix(keepalive): choose the ping's budget per thread, at dispatch")
- Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
- New items since my last review, and what I did about each:
- Reviewer 1's round-1 review (18:04:02Z): finding 1, per-entry counter restart across entries. Fixed —
lastVaryis keyed per thread liketurns, read at dispatch, kept across entries;TestANewEntryDoesNotRepeatThePreviousEntrysLastPingcovers the re-sent-turn trigger. The two-thread trigger was rejected by the author; I checked the reason and accept it (Non-blocking above). - The author's reply comment (18:23:06Z): claims both findings fixed with one change, lists mutations and eval-box runs. Verified in code: the step is taken in
fireafter the limiter and the substitute (keeper.go:1294-1296) and inPingNowafter the limiter accepts (manual.go:125-127);kaEntry.sentandpingJob.seqare gone; the audit rows usej.vary(keeper.go:1524, manual.go:189), which matches the body each path built. - My round-1 finding 1 (a no-dispatch cycle used up a step): fixed.
nextVaryLockedruns at dispatch time only;TestACycleThatSendsNothingUsesNoStepsends 1 ping, refuses 7 cycles throughOptions.Spare, sends 1 ping, and the two differ. I checked the test against theSparesignature (types.go:272-273) and thefireorder. - My round-1 non-blocking items: the stale dash comment is fixed (dash/keepalive.go:1124-1127); the cost projection at keeper.go:918 is unchanged on purpose, and the reason (at most 7 output tokens against a 1-token reply) is right; the misleading
sentdoc is gone with the field.
- Reviewer 1's round-1 review (18:04:02Z): finding 1, per-entry counter restart across entries. Fixed —
- The new commit in full:
nextVaryLockedand its lock discipline (called underk.mufrom bothfireandPingNow; a sweep ping and a manual press racing get distinct steps), theRecordprune keeping the current thread's step (keeper.go:841-845), thepingJob.varycopy, and both new tests line by line. I did not run them: live tests are not approved, and Go is not on this machine. The author's reply reports them passing on the eval box, plus mutations failing and-raceclean. - Every mutation site of
turns,tier1handlastVary(grep listed in finding 1) — this is where the new finding came from. - The PR body: updated to describe the per-thread step and to state the two-thread limit. No stale claim about
kaEntry.sentremains.
amiddavid
left a comment
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.310 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | 89fa98a9dd49 |
blocking |
Verdict: blocking
Earlier findings
- My round-1 finding (the step restarted on each new entry): fixed.
Keeper.lastVarykeeps the step per thread and outlives the entry (keeper.go:380-384, 916-922). The prev-entry drop path inRecord(keeper.go:850-857) does not touch it.TestANewEntryDoesNotRepeatThePreviousEntrysLastPingcovers the re-record case, and the author's mutation check confirms it fails when the step is forgotten. I traced both by hand; they hold. - The two-threads sub-case of my finding: rejected by the author, and I accept the reason. With 8 steps, a per-thread hashed start cannot rule out a match — the author's own two test keys collided — and it would move ping 1 off
max_tokens: 1. Onlymax_tokensis a safe field to vary, and 8 values cannot salt an unbounded number of threads. The limit is now written innextVaryLocked(keeper.go:911-913) and in the PR body. Accepted. - Reviewer 2's finding (a cycle that sent nothing used up a step): fixed. I checked it myself. The step is now taken at dispatch time only — in
fireafter the limiter and the substitute had their turn (keeper.go:1297-1299), and inPingNowafter the limiter accepts (manual.go:125-127).TestACycleThatSendsNothingUsesNoStepcovers 7 refused cycles between two sent pings, and fails under the due-time mutation. Agree with reviewer 2, round 1, finding 1; the fix is right. - Non-blocking items from round 1: the stale dash comment is fixed (dash/keepalive.go:1123-1126);
kaEntry.sentand its wrong doc are gone; the re-record test closes the single-entry test gap;pingBodystays as the step-0 form for existing tests; the base-budget cost projection at keeper.go:918 is kept on purpose (at most 7 output tokens on a 1-token reply). All resolved or reasonably declined.
Findings
- keepalive/keeper.go:841-845 — the MaxTurnKeys reset drops the step of every live thread, so one entry's second ping can repeat its first.
- What fails: the reset keeps
lastVaryonly for the thread whoseRecordtripped it. Every OTHER thread with a live idle entry loses its step. A thread whose last dispatched step was 0 — the ordinaryMaxPings: 2span, which has sent exactly ping 1 — then takes step 0 again for ping 2. Same entry, same body, same step: ping 2 is byte-identical to ping 1. The gateway answers it from its response cache (the PR's own measurement: the same body 4.5 min later still returns ping 1'sid). No provider call, a phantom cache read booked byrecord1, the prefix expires, and the next real turn pays the rewrite — the exact #706 defect, inside one entry. - Proof: trace — thread T records, goes idle; t1: sweep dispatches ping 1,
nextVaryLockedstores step 0; between t1 and t1+280 s, other threads record turns untillen(k.turns) > MaxTurnKeys(20000, types.go:228), and thatRecordrunsk.lastVary = map[string]int{}and re-adds only its own key (keeper.go:841-845); t1+280 s: sweep dispatches ping 2,nextVaryLockedfinds no entry for T and returns 0 (keeper.go:916-919) →pingBodyN(raw, route, 0)= ping 1's exact bytes. Rate: a reset fires once per 20000 new distinct thread keys, so the chance one lands inside a given 280 s ping gap is about 280/20000 ≈ 1.4% at one new thread per second, and rises with traffic. On the small deployment in the PR's live data this is a tail; on a busy multi-tenant gateway it silently breaks a small share of two-ping spans. - Fix: in the reset, keep the step of every thread that still has a live entry, plus the recording thread — rebuild
lastVaryfromk.live(its size is already bounded by the hold and eviction caps), so the map stays bounded and no live thread's step is forgotten mid-span.
- What fails: the reset keeps
Non-blocking
Shutdownclearsturnsandtier1hbut notlastVary(keeper.go:541-543). Harmless — steps keep advancing — but the map doc says "reset exactly as turns is", which is now true only of the MaxTurnKeys path.- A dispatch attempt that fails in transport still consumes a step (
firetakes it beforeDo). Eight transport-failed attempts in a row (~37 min) plus a gateway cache entry that old would repeat a body. Far-fetched; noting it only because the round-1 wording promised "dispatched pings only". - The two-threads residual is accepted (see above) and documented. No action.
What I checked
- Last review: round 1, 5bc5a23, 2026-10-25T18:04:02Z
- New commits read: 1 (
89fa98a9fix(keepalive): choose the ping's budget per thread, at dispatch) - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files; the inline file is empty)
- New items since my last review:
- Commit
89fa98a9— read the full diff and the changed code around it (keeper.go, manual.go, ping.go, dash/keepalive.go, pingvary_test.go). - Author reply at 18:23:06 — each claim checked against the code: both fixes verified, the mutation results traced by hand, the two-threads rejection reason checked and accepted.
- Reviewer 2's round-1 review (posted 18:03:10, read now for the first time) — its finding checked independently and confirmed fixed.
- The updated PR body — read in full; the "Not covered" limit matches the code comment.
- Commit
- The new tests, line by line, traced by hand against the new code: both fail under their stated mutations, both pass on this branch's logic. Existing first-ping assertions (keeper_test.go:117, manual_test.go:68, proxy/manualping_test.go:126, :460, keeper_test.go:815) still hold, because a thread's first dispatch is still step 0. Not run live: live tests are not approved.
- Lock and key discipline of the new code:
nextVaryLockedruns underk.muon both paths;j.key.id()infireandidinPingNowmatch the keyRecorduses forlastVary;pingJobis copied by value before the goroutine, soj.varyset infireis the copyrecord1reads. A sweep ping and a manual press racing get distinct steps. - The audit rows still match the body sent:
record1(keeper.go:1524) and manual.go:189 readj.vary, set at dispatch time on the same job copy. - Repo rules: fail-open untouched; no data-dependence change (one more in-memory counter, stated in the PR body); the commit carries DCO sign-off and
Assisted-By:.
…Forget Review round 2 of #712: - The MaxTurnKeys reset kept the ping step of the recording thread only. A live thread idle between its pings lost its step, so its ping 2 repeated ping 1. The reset now keeps the step of every thread with a live entry, plus the recording thread. - Forget dropped a tenant's turns and tier keys but not its ping steps, so lastVary could grow for the life of the process. Forget now drops every step of the tenant, and Shutdown clears the map. Fixes #706 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
|
Replies to round 2, at head Reviewer 2, finding 1 (
Reviewer 1, finding 1 (the reset drops live threads' steps): fixed.
Non-blocking (both reviewers):
How it was tested (eval box):
|
amiddavid
left a comment
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.310 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 3 of 3 | e7d0689217b8 |
approve |
Verdict: approve
Findings
None.
Earlier findings
- My round-2 finding (
ForgetleaveslastVarykeys behind): fixed.Forgetnow prefix-scanslastVaryand deletes every key of the tenant (keeper.go:1074-1077), which also reaches threads with no live entry — the case my one-line fix in the entry loop would have missed.Shutdownclears the map too (keeper.go:545).TestForgetDropsTheTenantsPingStepsseeds 3 steps (2 for the forgotten tenant, one on a subagent thread, 1 for another tenant) and checks only the other tenant's stays. I traced the test against the key format (tenant\x00..., same prefixForgetalready used forlive) — it holds. - Reviewer 1's round-2 finding (the MaxTurnKeys reset dropped every live thread's step): fixed. I checked it myself. The reset now rebuilds
lastVaryfrom the steps of every thread ink.live, plus the recording thread (keeper.go:845-854).k.liveis bounded by the hold and eviction caps, so the map stays bounded.TestTheTurnKeyResetKeepsALiveThreadsStepsends ping 1, fillsturnspastMaxTurnKeysto trip the reset, records one more thread, and sends ping 2; the two pings must differ. I traced the timing (280 sIdle, sweeps 281 s apart,MaxPings: 2) and the reset order (the prune runs before the new entry joinslive, which is why the recording thread is added explicitly) — both hold. Agree with reviewer 1, round 2, finding 1; the fix is right. - Non-blocking items: the transport-failure residual is left as is, and the reason is right (the step is taken when the body goes to the Dispatcher, which is what round 1 asked for). The two-thread
stop_sequencessalt moves to a follow-up, and the reason is right — it changes a second field of every ping and needs its own live gateway check.pingBodystays as the step-0 form for the existing tests. All resolved or reasonably deferred.
Non-blocking
- The field comment still says
lastVaryis "reset exactly as turns is" (keeper.go:382-383). After this commit the reset is more generous thanturns' (every live thread, not just the recording one). Bounded liketurns, but no longer reset identically. Comment drift only. - Residual, same accepted class as the two-thread and transport cases: the reset drops the step of a thread with no live entry. That thread needs a new
Recordbefore it can ping again, and a new request changes the body — unless the client re-sends a byte-identical request after the entry retired (~15 min later), in which case its ping 1 (step 0) can repeat an older ping 1. Needs a byte-identical retry plus a gateway cache entry that old.
What I checked
- Last review: round 2, 89fa98a, 2026-10-25T18:27:50Z
- New commits read: 1 (e7d0689 "fix(keepalive): keep live threads' ping steps on reset, drop them on Forget")
- Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files; the inline file is empty)
- New items since my last review, and what I did about each:
- Reviewer 1's round-2 review (18:28:14Z): its finding — the reset keeping only the recording thread's step let a live thread's ping 2 repeat its ping 1 — is a real defect I missed in round 2. Checked and confirmed fixed by the rebuild-from-
livechange (see above). - The author's reply comment (18:41:55Z): each claim checked against the code — both fixes verified, the two mutation results traced by hand (keeping only the recording thread makes the reset test fail; leaving
lastVaryalone inForgetmakes the forget test fail). - Commit e7d0689: read the full diff and the code around it.
Shutdownwipe, theRecordreset rebuild,Forget's prefix scan, and both new tests, line by line.
- Reviewer 1's round-2 review (18:28:14Z): its finding — the reset keeping only the recording thread's step let a live thread's ping 2 repeat its ping 1 — is a real defect I missed in round 2. Checked and confirmed fixed by the rebuild-from-
- Every mutation site of
lastVaryat the new head (grep: 380-384, 468, 545, 845-854, 926-930, 1074-1077) — write, prune, dispatch, and forget paths each accounted for. The map is bounded on all three axes now: theRecordprune (live threads + recording thread),Forget(per tenant),Shutdown(all). - The two new tests' mechanics: the filler loop fills
k.turnspastMaxTurnKeysunderk.mu, the trips-the-resetRecordruns the prune before the tracking gate, and the fake's ref-to-key mapping makesr.Key == idlefilter correctly. Not run live: live tests are not approved, and Go is not on this machine. The author's reply reports both tests plus mutations and-raceon./keepalive/...and./proxy/...passing on the eval box. - The cumulative diff from base 0a22b9c to head e7d0689 was read across the three rounds; nothing outside the files reviewed here changed.
amiddavid
left a comment
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.310 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 3 of 3 | e7d0689217b8 |
approve |
Verdict: approve
Earlier findings
- My round-2 finding (the MaxTurnKeys reset dropped every live thread's step): fixed. The reset now rebuilds
lastVaryfrom the steps of every thread ink.live, plus the recording thread (keeper.go:842-851). The recording thread is kept explicitly because its new entry joinsk.liveonly after the reset block.k.liveis hard-bounded (len(k.live) > MaxSessionsinevictLocked), so the map stays bounded and no live thread loses its step mid-span.TestTheTurnKeyResetKeepsALiveThreadsStepcovers the exact trace from my finding — ping 1, a reset tripped by other traffic, ping 2 — and I traced both the test and its stated mutation by hand: they hold. - Reviewer 2, round 2, finding 1 (
ForgetleftlastVarykeys behind, unbounded growth): fixed. I checked it myself.Forgetnow deletes everylastVarykey with the tenant's prefix (keeper.go:1072-1077), which reaches threads with no live entry — the per-entry loop cannot. The prefix istenantID + "\x00", the same one the existingturnsandrouteFailsloops use, andKey.id()isTenant + "\x00" + thread.Key(...)(types.go:94), so it matches exactly the tenant's own keys.Shutdownclears the map too (keeper.go:545), so the field now matches its doc.TestForgetDropsTheTenantsPingStepscovers two keys of the forgotten tenant (one on a subagent thread) beside one of another tenant; the mutation claim holds. - Round-1 items: all resolved in round 2 and unchanged here. The author's non-blocking replies are all reasonable: a transport-failed dispatch still consumes a step (needs ~8 in a row plus a gateway cache entry that old — accepted residual), and the two-threads case goes to a follow-up with
stop_sequencessalting, off this branch because it changes a second field of every ping and needs its own live gateway check. Agreed.
Findings
None. The mechanism now holds its claim everywhere I can reach: two dispatched pings in a row on one thread differ, whatever the due cycles, the entry boundaries, the turn-key reset, or Forget do between them. The remaining gaps are the documented and accepted residuals below.
Non-blocking
- The reset still drops the steps of threads NOT in
k.live. A thread between entries (a real request in flight) that re-sends a byte-identical body, with a reset landing in that window and its previous last step at 0, could repeat a ping. This needs two narrow events at once — the identical re-send of my round-1 finding AND a reset in the in-flight window — so it is a second-order residual. No action needed on this branch. - A transport-failed dispatch consumes a step. About 8 in a row on one thread (~37 min) plus a gateway response-cache entry that old would repeat a body. Accepted by both reviewers and the author.
- Two threads with byte-identical bodies step through the same values. Documented in
nextVaryLockedand the PR body; a deterministic fix (stop_sequencessalt) is planned as a follow-up.
What I checked
- Last review: round 2, 89fa98a, 2026-10-25T18:28:14Z
- New commits read: 1 (
e7d0689fix(keepalive): keep live threads' ping steps on reset, drop them on Forget) - Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files; the inline file is empty)
- New items since my last review:
- Commit
e7d0689— full diff and the changed code around it: the reset rebuild, theForgetprefix loop, theShutdownclear, both new tests. - Author reply at 18:41:55 — every claim checked against the code: both fixes verified, both mutation results traced by hand, the eval-box run table is consistent with the code.
- Reviewer 2's round-2 review (18:27:50) — read in full for the first time; its
Forgetfinding checked independently and confirmed fixed (see above). - My own round-2 review (18:28:14) — re-read as context.
- Commit
- The bounded-
liveclaim in the new comment:evictLockedenforceslen(k.live) > MaxSessions, so the rebuiltlastVaryis bounded byMaxSessions + 1. - The prefix safety of the
Forgetloop:Key.id()(types.go:94) and thetenantID + "\x00"prefix (keeper.go:1059) share the same encoding the existingturns,routeFailsandrouteTrippedloops rely on. - Both new tests, line by line, traced by hand: the filler loop trips
len(k.turns) > MaxTurnKeys; "trips-the-reset" is recorded once, so it is turn 0 and never tracked, and only the idle thread pings;Forgetdeletes both "gone" keys and keeps the other tenant's. Not run live: live tests are not approved. - That no other mutation site of
turns,tier1horlastVaryremains unpaired: Record's increment/prune, Forget's per-key deletes, Shutdown's wipe — each now treatslastVaryconsistently. - Repo rules: fail-open untouched; no data-dependence change; the commit carries DCO sign-off and
Assisted-By:.
- 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]>
… 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]>
Summary
The second keep-alive ping never kept the cache. The IBM LiteLLM gateway answers a byte-identical request from its own response cache, so ping 2 (a copy of ping 1) never reached the provider. This PR makes each ping ask for a different
max_tokensthan the one before. The prefix the provider hashes does not change.What we found
On the live proxy (port 8789), since Oct 18, for the first real turn after a ping:
By minutes since the last real turn, there are 0 misses up to minute 8, and 70 to 100% from minute 9. Minute 9.5 is ping 1 (at 4.5 min) plus the 5-minute cache life. Ping 2 also ran faster than ping 1: 5.4 s against 12.9 s on average.
On the gateway, with direct test calls (not through context-guru; owner-approved; about 5k-token prefixes; under $0.25 in total):
id, the same usage, about 2x faster: a gateway cache hitidmetadata.user_idchangedid: the gateway's key ignores itmax_tokens,temperatureorstop_sequenceschangedidand a real provider read (cache_read= the whole prefix)Timed test (write the cache, ping 1 at +270 s, ping 2 at +540 s, a real turn at +600 s, which is 330 s after ping 1):
cache_read=5190, but ping 1'sidcache_write=5190max_tokens: 2(this PR)cache_read=4515, a newidcache_read=4515Why it happens
max_tokens: 1, so it is byte-identical to ping 1.What changed
keepalive/ping.go: newpingBodyN(body, route, n). The output budget is the base (1, or 16 on Responses) plusn mod 8.pingBodyispingBodyN(..., 0), so ping 1 sends the same bytes as before.keepalive/keeper.go: the keeper keeps, per thread, the step of the last ping it actually dispatched (lastVary, besideturns, with the same bound and reset). The next ping takes that step plus 1. The step is chosen at dispatch time, so a cycle that sends nothing (a substitute took it, the limiter refused it) uses no step, and a new entry on the same thread continues the count. The audit row records themax_tokensthat was really sent.keepalive/manual.go: a manual press takes the thread's next step too, so it never repeats the automatic ping before it.How it was tested
All runs are on the eval box.
TestConsecutivePingsAreNeverByteIdenticalorigin/main+ testping 2 is byte-identical to ping 1TestAManualPingDiffersFromTheAutomaticPingBeforeItorigin/main+ testTestPingOutputBudgetStaysSmallorigin/main+ testTestANewEntryDoesNotRepeatThePreviousEntrysLastPing(round 1)TestACycleThatSendsNothingUsesNoStep(round 1)ngo test -race ./keepalive/...go test -race ./proxy/...89fa98a9dd49go vet,gofmt -lThe new test also checks that
model,system,messages,tools,tool_choiceandthinkingstay byte-identical between pings.Data dependence
No change. The keeper stores one more counter on an entry it already holds in memory.
Open questions
Fixes #706
🤖 Generated with Claude Code