Skip to content

fix(keepalive): never send two identical pings in a row - #712

Merged
amiddavid merged 3 commits into
mainfrom
fix/keepalive-ping-varies
Oct 25, 2026
Merged

amiddavid merged 3 commits into
mainfrom
fix/keepalive-ping-varies

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

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_tokens than 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:

Pings since the last real turn Turns Full cache misses
1 146 0
2 67 50 (75%), $71.39 in re-writes

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):

Call Result
The same body twice, 1 s apart the same response id, the same usage, about 2x faster: a gateway cache hit
The same body, 4.5 min later still the old id
metadata.user_id changed still the old id: the gateway's key ignores it
max_tokens, temperature or stop_sequences changed a new id and 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):

Arm Ping 2 Real turn
ping 2 identical to ping 1 (today) cache_read=5190, but ping 1's id miss: cache_write=5190
ping 2 with max_tokens: 2 (this PR) cache_read=4515, a new id hit: cache_read=4515

Why it happens

  1. The real turn asks for thousands of output tokens. Ping 1 asks for 1, so its body differs, and it reaches the provider.
  2. Ping 2 is built from the same recorded body with the same max_tokens: 1, so it is byte-identical to ping 1.
  3. The gateway returns ping 1's stored reply, including its usage. The keeper reads "cache read: full prefix" and believes the cache was refreshed. The provider saw nothing, and its cache expires 5 minutes after ping 1.

What changed

  • keepalive/ping.go: new pingBodyN(body, route, n). The output budget is the base (1, or 16 on Responses) plus n mod 8. pingBody is pingBodyN(..., 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, beside turns, 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 the max_tokens that 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.
  • Not covered: two threads that hold a byte-identical body step through the same values, so their pings can match. That needs both threads to ping in lockstep on the same transcript, and a turn on either thread ends it.
  • Cost: no change in practice. A keep-alive reply is 1 token, and output is billed as generated. At most it allows 8 output tokens. The per-ping price guard still uses the base budget.
  • The 2-ping cap is not changed.

How it was tested

All runs are on the eval box.

Run Tree Result
TestConsecutivePingsAreNeverByteIdentical origin/main + test FAIL: ping 2 is byte-identical to ping 1
TestAManualPingDiffersFromTheAutomaticPingBeforeIt origin/main + test FAIL
TestPingOutputBudgetStaysSmall origin/main + test FAIL
TestANewEntryDoesNotRepeatThePreviousEntrysLastPing (round 1) mutation: step forgotten on a new entry FAIL
TestACycleThatSendsNothingUsesNoStep (round 1) mutation: step taken at due time FAIL
all 3 new tests, plus the existing ping-body and manual-ping tests this branch PASS
mutation: the budget ignores n this branch FAIL, all 3 new tests
go test -race ./keepalive/... this branch PASS
go test -race ./proxy/... this branch, head 89fa98a9dd49 PASS (405 s)
go vet, gofmt -l this branch clean

The new test also checks that model, system, messages, tools, tool_choice and thinking stay byte-identical between pings.

Data dependence

No change. The keeper stores one more counter on an entry it already holds in memory.

Open questions

  1. The keep-alive savings figures need a second look. Every ping 2 on this gateway was booked as a cache read that never happened. So keep-alive savings since feat(keepalive): follow the cache TTL each session was billed at #512 count ping 2 as a refresh, and the misses it did not prevent may be credited wrongly. This PR does not change the accounting.
  2. Other gateways. Any gateway with a response cache does the same. The fix does not depend on this gateway in particular.
  3. The 2-ping cap can now be judged on real data. It was measured while ping 2 did nothing.

Fixes #706

🤖 Generated with Claude Code

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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Findings

  1. 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, and seq is consumed at due time, not at dispatch time. Sweep takes seq := e.sent; e.sent++ for every due ping (keeper.go:1167-1168). fire then 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 after e.sent++ (manual.go:115, then the ErrLimited return at manual.go:120-124). If one dispatched ping has seq s and the next dispatched ping has seq s+8, with no dispatched ping and no new Record between (the body is unchanged), both ask for base + s mod 8 output 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 one Idle apart, keeper.go:187-189); ping seq 8 dispatched with the same e.body → pingBodyN output differs from ping 0 in no byte → gateway cache hit. Reachability needs a policy with MaxPings ≥ 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 on kaEntry.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.mu where fire/PingNow build the body, and pick last + 1 mod pingVary. Then any two dispatched pings in a row differ, whatever happened to the due cycles between.

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, the pingJob copy discipline, and the lock discipline on e.sent.
  • The invariant the PR claims: consecutive dispatched pings differ. It holds when every consumed seq dispatches (the default MaxPings: 2 case, 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_tokens and stream change; the new test asserts model, system, messages, tools, tool_choice, thinking stay byte-identical.
  • The audit rows: record1 (keeper.go:1496) and the manual report (manual.go:186) both record pingOutputBudget(route) + seq%pingVary, which matches the body each path built.
  • Concurrency: e.sent is read and written only under k.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 use pingBodyN; 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 -race on ./keepalive/... and ./proxy/....
  • The PR description. No other review or comment on the PR was read.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Findings

  1. 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.sent starts at 0 in every new entry, and Record builds 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:
      1. 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_tokens 1). The new entry's first ping is seq 0 again, so the exact same bytes.
      2. 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. But record1 books the cached usage as a real cache read, notePingRead resets missed, and refreshedAt moves (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.
    • Proof: Record constructs e := &kaEntry{...} (keeper.go:811) with sent at its zero value. Nothing carries a per-thread seq across entries. Contrast k.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.seqs map beside k.turns (same key, same MaxTurnKeys reset guard), read in Record to seed e.sent. Or fold a per-thread salt into the budget in pingBodyN.

Non-blocking

  • kaEntry.sent is 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.sent is read and incremented under k.mu on 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: MaxTokens in record1 (keeper.go:1496) and manual.go:186 matches the body pingBodyN sent (base + seq%pingVary), on both routes. Correct.
  • Prefix safety: only max_tokens/max_output_tokens and stream change. Both sit outside the hashed prefix, so a ping stays a pure cache read. The /v1/responses base 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 (the asked flag), so the identical-body defect does not apply to them.
  • Repo rules: fail-open behaviour untouched (a pingBodyN failure 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 and Assisted-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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1, at head 89fa98a9dd49.

Both findings: fixed with one change. The keeper keeps the step of the last ping actually dispatched, per thread (Keeper.lastVary, beside turns, with the same MaxTurnKeys bound and reset). The next ping takes that step plus 1, mod 8. The step is chosen at dispatch time, in fire after the limiter and the substitute have had their turn, and in PingNow after the limiter accepts. kaEntry.sent and pingJob.seq are gone.

Reviewer 2, finding 1 (a cycle that sends nothing used up a step): fixed.

  • New test TestACycleThatSendsNothingUsesNoStep: 1 sent ping, 7 cycles refused by the limiter, then 1 sent ping. The 2 sent pings must differ.
  • Mutation: take the step at due time, in Sweep. The test fails with after 7 refused cycles the next sent ping repeats the last sent one.

Reviewer 1, finding 1 (the counter restarted on each new entry): fixed for one thread.

  • New test TestANewEntryDoesNotRepeatThePreviousEntrysLastPing: a ping, the same request recorded again (a new entry, the same body), a ping. The 2 pings must differ.
  • Mutation: forget the step when Record replaces the entry. The test fails with the new entry's first ping is byte-identical to the previous entry's last ping.
  • Two threads with a byte-identical body are NOT covered. Their steps run in parallel, so their pings can match. I tried to start each thread at a step taken from a hash of its key, but with 8 steps that only lowers the chance of a match and does not rule it out (my 2 test keys matched). It also changed ping 1 away from today's max_tokens: 1. So I dropped it. A real match needs both threads to hold the same transcript and ping in lockstep, and a turn on either thread ends it. The limit is written in the nextVaryLocked comment and in the PR body.

Non-blocking:

  • dash/keepalive.go:1123 stale "max_tokens 1": fixed. The comment now says the budget varies from 1 to 8 and one output token is billed.
  • kaEntry.sent doc said "sent", not "attempted": the field is gone. The new lastVary counts dispatched pings only.
  • The new tests covered only one entry: the re-record test above covers that.
  • keeper.go:918, the projected cost uses the base budget: unchanged on purpose. It under-projects by at most 7 output tokens, and the reply is 1 token.
  • pingBody has no production caller now: kept as the step-0 form that the existing tests use.

How it was tested (eval box):

Run Result
all ping-variation tests, plus the existing ping-body and manual-ping tests PASS
M1: step taken at due time FAIL (TestACycleThatSendsNothingUsesNoStep)
M2: step forgotten on a new entry FAIL (TestANewEntryDoesNotRepeatThePreviousEntrysLastPing)
go test -race ./keepalive/... PASS
go test -race ./proxy/... PASS (405 s)
go vet, gofmt -l (keepalive, dash) clean

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Findings

  1. keepalive/keeper.go:1059 — Forget frees a tenant's turns and tier1h keys but not its lastVary keys, so lastVary can grow without bound.
    • What fails: lastVary gains one key per thread that ever dispatches a ping. Its only bounds are the Record prune at keeper.go:836-845, which fires when len(k.turns) > MaxTurnKeys (20000). Forget (keeper.go:1044-1062) deletes the tenant's turns and tier1h entries — and by doing so keeps turns under 20000, so the prune never fires. On a deployment that calls Forget as tenants churn, lastVary keeps 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); Forget breaks that parity. The repo bounds the same class of map on purpose (manualAtMax, manual.go:198-199).
    • Proof: grep of every turns and lastVary mutation site — turns is wiped in Shutdown (keeper.go:543), incremented in Record (830), pruned in Record (836-839), deleted per key in Forget (1059). lastVary is written in New (468), pruned in Record (841-845), and read/written in nextVaryLocked (917-921). No other cleanup. Forget's loop deletes k.turns[key] and k.tier1h[key] (keeper.go:1059-1060) and nothing from lastVary.
    • Fix: add delete(k.lastVary, key) beside the turns delete in Forget's loop. For full parity with the comment, also wipe lastVary in Shutdown (keeper.go:543-544) — harmless there, since the keeper is dead, but the comment says "exactly as turns is".

Non-blocking

  • A dispatch attempt that fails in transport still consumes a step (fire takes the step, then Dispatcher.Do can 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: 1 bytes. The scenario needs two threads holding the same transcript and pinging in lockstep; a turn on either ends it. The limit is documented in nextVaryLocked and 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 — lastVary is keyed per thread like turns, read at dispatch, kept across entries; TestANewEntryDoesNotRepeatThePreviousEntrysLastPing covers 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 fire after the limiter and the substitute (keeper.go:1294-1296) and in PingNow after the limiter accepts (manual.go:125-127); kaEntry.sent and pingJob.seq are gone; the audit rows use j.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. nextVaryLocked runs at dispatch time only; TestACycleThatSendsNothingUsesNoStep sends 1 ping, refuses 7 cycles through Options.Spare, sends 1 ping, and the two differ. I checked the test against the Spare signature (types.go:272-273) and the fire order.
    • 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 sent doc is gone with the field.
  • The new commit in full: nextVaryLocked and its lock discipline (called under k.mu from both fire and PingNow; a sweep ping and a manual press racing get distinct steps), the Record prune keeping the current thread's step (keeper.go:841-845), the pingJob.vary copy, 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 -race clean.
  • Every mutation site of turns, tier1h and lastVary (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.sent remains.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Earlier findings

  • My round-1 finding (the step restarted on each new entry): fixed. Keeper.lastVary keeps the step per thread and outlives the entry (keeper.go:380-384, 916-922). The prev-entry drop path in Record (keeper.go:850-857) does not touch it. TestANewEntryDoesNotRepeatThePreviousEntrysLastPing covers 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. Only max_tokens is a safe field to vary, and 8 values cannot salt an unbounded number of threads. The limit is now written in nextVaryLocked (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 fire after the limiter and the substitute had their turn (keeper.go:1297-1299), and in PingNow after the limiter accepts (manual.go:125-127). TestACycleThatSendsNothingUsesNoStep covers 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.sent and its wrong doc are gone; the re-record test closes the single-entry test gap; pingBody stays 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

  1. 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 lastVary only for the thread whose Record tripped it. Every OTHER thread with a live idle entry loses its step. A thread whose last dispatched step was 0 — the ordinary MaxPings: 2 span, 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's id). No provider call, a phantom cache read booked by record1, 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, nextVaryLocked stores step 0; between t1 and t1+280 s, other threads record turns until len(k.turns) > MaxTurnKeys (20000, types.go:228), and that Record runs k.lastVary = map[string]int{} and re-adds only its own key (keeper.go:841-845); t1+280 s: sweep dispatches ping 2, nextVaryLocked finds 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 lastVary from k.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.

Non-blocking

  • Shutdown clears turns and tier1h but not lastVary (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 (fire takes it before Do). 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 (89fa98a9 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; 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.
  • 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: nextVaryLocked runs under k.mu on both paths; j.key.id() in fire and id in PingNow match the key Record uses for lastVary; pingJob is copied by value before the goroutine, so j.vary set in fire is the copy record1 reads. 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 read j.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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 2, at head e7d0689217b8.

Reviewer 2, finding 1 (Forget leaves lastVary keys behind): fixed.

  • Forget now deletes every lastVary key with the tenant's prefix. That includes threads with no live entry, which the per-entry loop does not reach.
  • Shutdown now clears lastVary too, so the field matches its comment.
  • New test TestForgetDropsTheTenantsPingSteps: 3 steps (2 for the forgotten tenant, one of them on a subagent thread, 1 for another tenant). After Forget, only the other tenant's step stays.
  • Mutation: Forget leaves lastVary alone. The test fails with lastVary holds 3 keys, want 1.

Reviewer 1, finding 1 (the reset drops live threads' steps): fixed.

  • The MaxTurnKeys reset now rebuilds lastVary from the steps of every thread in k.live, plus the recording thread. k.live is bounded, so the map stays bounded.
  • New test TestTheTurnKeyResetKeepsALiveThreadsStep: a thread sends ping 1, then other traffic trips the reset, then the same thread sends ping 2. The 2 pings must differ.
  • Mutation: the reset keeps only the recording thread. The test fails with the idle thread's ping 2 repeats its ping 1.

Non-blocking (both reviewers):

  • A transport-failed dispatch still uses a step. Agreed, and left as is. The step is taken when the body goes to the Dispatcher, which is what round 1 asked for. A repeat needs about 8 failed dispatches in a row on one thread, and a gateway cache entry that old.
  • Two threads with a byte-identical body: thanks for checking. Salting stop_sequences with the thread id would rule it out deterministically. I will raise it as a follow-up, not on this branch. It changes a second field of every ping, and that needs its own live check on the gateway.
  • pingBody has no production caller: kept, as noted.

How it was tested (eval box):

Run Result
both new tests, plus the round-1 tests and TestTierMemoryIsBoundedAndKeepsTheCurrentThread PASS
M3: the reset keeps only the recording thread FAIL (TestTheTurnKeyResetKeepsALiveThreadsStep)
M4: Forget leaves lastVary alone FAIL (TestForgetDropsTheTenantsPingSteps)
go test -race ./keepalive/... PASS
go test -race ./proxy/... PASS (405 s)
go vet, gofmt -l clean

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.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 (Forget leaves lastVary keys behind): fixed. Forget now prefix-scans lastVary and 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. Shutdown clears the map too (keeper.go:545). TestForgetDropsTheTenantsPingSteps seeds 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 prefix Forget already used for live) — 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 lastVary from the steps of every thread in k.live, plus the recording thread (keeper.go:845-854). k.live is bounded by the hold and eviction caps, so the map stays bounded. TestTheTurnKeyResetKeepsALiveThreadsStep sends ping 1, fills turns past MaxTurnKeys to trip the reset, records one more thread, and sends ping 2; the two pings must differ. I traced the timing (280 s Idle, sweeps 281 s apart, MaxPings: 2) and the reset order (the prune runs before the new entry joins live, 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_sequences salt 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. pingBody stays as the step-0 form for the existing tests. All resolved or reasonably deferred.

Non-blocking

  • The field comment still says lastVary is "reset exactly as turns is" (keeper.go:382-383). After this commit the reset is more generous than turns' (every live thread, not just the recording one). Bounded like turns, 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 Record before 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-live change (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 lastVary alone in Forget makes the forget test fail).
    • Commit e7d0689: read the full diff and the code around it. Shutdown wipe, the Record reset rebuild, Forget's prefix scan, and both new tests, line by line.
  • Every mutation site of lastVary at 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: the Record prune (live threads + recording thread), Forget (per tenant), Shutdown (all).
  • The two new tests' mechanics: the filler loop fills k.turns past MaxTurnKeys under k.mu, the trips-the-reset Record runs the prune before the tracking gate, and the fake's ref-to-key mapping makes r.Key == idle filter 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 -race on ./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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Earlier findings

  • My round-2 finding (the MaxTurnKeys reset dropped every live thread's step): fixed. The reset now rebuilds lastVary from the steps of every thread in k.live, plus the recording thread (keeper.go:842-851). The recording thread is kept explicitly because its new entry joins k.live only after the reset block. k.live is hard-bounded (len(k.live) > MaxSessions in evictLocked), so the map stays bounded and no live thread loses its step mid-span. TestTheTurnKeyResetKeepsALiveThreadsStep covers 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 (Forget left lastVary keys behind, unbounded growth): fixed. I checked it myself. Forget now deletes every lastVary key with the tenant's prefix (keeper.go:1072-1077), which reaches threads with no live entry — the per-entry loop cannot. The prefix is tenantID + "\x00", the same one the existing turns and routeFails loops use, and Key.id() is Tenant + "\x00" + thread.Key(...) (types.go:94), so it matches exactly the tenant's own keys. Shutdown clears the map too (keeper.go:545), so the field now matches its doc. TestForgetDropsTheTenantsPingSteps covers 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_sequences salting, 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 nextVaryLocked and the PR body; a deterministic fix (stop_sequences salt) is planned as a follow-up.

What I checked

  • Last review: round 2, 89fa98a, 2026-10-25T18:28:14Z
  • 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:
    • Commit e7d0689 — full diff and the changed code around it: the reset rebuild, the Forget prefix loop, the Shutdown clear, 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 Forget finding checked independently and confirmed fixed (see above).
    • My own round-2 review (18:28:14) — re-read as context.
  • The bounded-live claim in the new comment: evictLocked enforces len(k.live) > MaxSessions, so the rebuilt lastVary is bounded by MaxSessions + 1.
  • The prefix safety of the Forget loop: Key.id() (types.go:94) and the tenantID + "\x00" prefix (keeper.go:1059) share the same encoding the existing turns, routeFails and routeTripped loops 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; Forget deletes both "gone" keys and keeps the other tenant's. Not run live: live tests are not approved.
  • That no other mutation site of turns, tier1h or lastVary remains unpaired: Record's increment/prune, Forget's per-key deletes, Shutdown's wipe — each now treats lastVary consistently.
  • Repo rules: fail-open untouched; no data-dependence change; the commit carries DCO sign-off and Assisted-By:.

@amiddavid
amiddavid merged commit 28b1a49 into main Oct 25, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 25, 2026
amiddavid added a commit that referenced this pull request Oct 25, 2026
- 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]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns (#404 PR C) (#695)

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

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

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

Part of #404.

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

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

Part of #404.

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

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

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

Part of #404.

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

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

Part of #404.

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

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

Part of #404.

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

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

Tests only.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Keep-alive: the second ping reports a cache read, but the cache expires anyway

1 participant