Skip to content

fix(keepalive): retry a ping that failed fast while the cache lives - #710

Merged
amiddavid merged 2 commits into
mainfrom
fix/keepalive-failed-ping
Oct 25, 2026
Merged

amiddavid merged 2 commits into
mainfrom
fix/keepalive-failed-ping

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

A keep-alive ping that fails fast in transport (EOF, a reset or refused connection) is now retried at the next sweep tick, while the cache is still alive. A ping that times out is still not retried, so this PR fixes only part of the problem (see Limit). Before, the keeper counted the failed ping as sent and restarted its clock from it. The next ping then came after the cache had expired, and it re-wrote the whole prefix.

What we found

On the live proxy (port 8789), 2 of the 3 missed pings since the proxy started came right after a ping that failed. These 2 failures are the proxy's whole failed count:

Failed ping Error Next ping Re-write
Oct 23, 17:32:58 timeout 17:36:32, missed 780,093 tokens, $3.90
Oct 25, 16:11:49 (main thread) timeout 16:15:26, missed 903,705 tokens, $4.52

The 3rd miss (Oct 25, 12:13:11, $1.88) had no failed ping before it, and it is not part of this fix.

In the older log of the same proxy, fast failures also happen: EOF (Oct 15 and Oct 20), broken pipe (Oct 20) and TCP read timeouts.

Example from the main thread:

  • 16:06:18: the last refresh (a real turn). The cache lives until about 16:11:18.
  • 16:10:49: the keeper sends ping 1. It times out at 16:11:49.
  • 16:15:26: the keeper sends ping 2, 548 s after the last refresh. The cache is gone, so the ping writes 903,705 tokens for $4.52.

Why it happens

Sweep sets e.startedAt = now and e.pings++ before it sends a ping (keepalive/keeper.go). On a transport error, fire counts the failure and returns, and it keeps both changes. So a failed ping:

  1. uses one of the pings, and
  2. moves the next ping a full idle period (270 s) after the failure, not after the last real refresh.

What changed

  • New giveBackFailedPing. On a transport error it restores the clock to the last good refresh and gives the ping back. The next sweep tick (2 s later) then retries.
  • It does this once per run of failures (kaEntry.retried, reset on a good read). A route that keeps failing gets one retry, not one every 2 s.
  • It does this only while the cache is still alive (5 min or 1 h after refreshedAt). After that, a retry can only re-write, which costs more than it saves.
  • The log line cache keep-alive ping failed gains retry=true|false.

Limit: a timed-out ping is still not retried

pingTimeout is 60 s and the default idle is 270 s, so a ping that times out returns about 30 s after the cache expired. This PR does not retry that case, because the retry would only re-write. Both live misses above were timeouts, so this PR would not have prevented either of them. It prevents a miss after a fast failure (EOF, reset, broken pipe). Options for timeouts are in Open questions.

How it was tested

All runs are on the eval box.

Run Tree Result
TestAFastTransportFailureIsRetriedWhileTheCacheLives origin/main + test FAIL: the entry shows 1 pings used, want 0
TestARunOfTransportFailuresIsRetriedOnce origin/main + test FAIL: 1 pings sent inside one lifetime, want 2
TestAFailureAfterTheCacheExpiredIsNotRetried origin/main + test PASS (it guards the new rule; main never retries)
all 3 new tests this branch PASS
mutation: never call giveBackFailedPing this branch FAIL, 2 tests
mutation: drop the once-only guard this branch FAIL: 10 pings sent inside one lifetime, want 2
mutation: lifetime check 1000x too long this branch FAIL: a failure past the cache's lifetime was given back
go test -race ./keepalive/... this branch PASS
go test -race ./proxy/... this branch PASS (406 s)
go vet, gofmt -l this branch clean

I changed one existing test. TestKeepAlivePlanCountsOnlyPingsThatRefreshed expected "2 pings left" after a fast failure, which is the old behaviour. It now expects 3 pings left and the retry due at once. Its second half (a later ping that reads updates RefreshedMS) is unchanged and passes.

Data dependence

No change. The keeper stores no new data. The new field is a flag on an entry it already holds in memory.

Open questions

  1. Timeouts. To save the cache after a timed-out ping, the keeper would have to send the ping earlier, or use a shorter timeout. For example: a 20 s ping timeout, or a ping at idle minus the timeout. That is a policy change for the owner.

Refs #703
Refs #707 (fast failures only; a timed-out ping is still not retried)

🤖 Generated with Claude Code

A ping that failed in transport refreshed nothing, but the keeper had
already moved its clock to the ping's start and used one of its pings.
So the next ping came a full idle period after the FAILED one, past the
cache's lifetime, and re-wrote the prefix.

Now a transport failure that comes back while the cache entry is still
alive gives the ping back: the clock returns to its last good refresh,
the ping count drops by one, and the next sweep tick retries. Once per
run of failures. A failure that returns after the cache expired is not
retried, because a retry can then only re-write.

Refs #703

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 d541f9d377aa approve

Verdict: approve

Findings

None.

Non-blocking

  • keepalive/keeper.go:1229 and keepalive/keeper.go:1260 — a ping the limiter refuses ("no spare
    concurrency") is skipped, but Sweep already moved startedAt and spent one ping. The next ping
    then comes a full Idle later, past the cache lifetime, and re-writes the prefix. This is the same
    #703 symptom on a path this fix does not cover. It is pre-existing, so it needs its own issue
    rather than a change on this branch.
  • keepalive/keeper_test.go:239 — the comment on TestPingErrorFailsOpen says a failure "must
    still count against K". After this change a fast failure is given back and does not count, once
    per run. The test still passes. Only the words are now wrong.
  • keepalive/keeper.go:1430 — the TTL values (5 min, 1 h) are written a second time; they already
    exist in cachePhaseAt (keepalive/substitute.go:33). One shared helper would stop the two
    copies from drifting.
  • keepalive/keeper.go:1433 — after a first-miss ping re-writes the prefix, refreshedAt stays on
    the last read by design. A later fast transport failure then gets no retry, because the TTL check
    sees the entry as dead. The schedule is still anchored on the write, so the cost is small. I note
    it so the choice is visible.

What I checked

  • Read the full diff: keepalive/keeper.go, keepalive/failedping_test.go,
    proxy/keepaliveplan_test.go. Read CLAUDE.md and the keep-alive rows of docs/design.md.
  • Traced the give-back against the entry lifecycle. Arrive deletes the entry, Record replaces
    it, retirement and eviction clear it. A give-back that lands on a removed entry mutates an
    orphan, so it cannot corrupt live state. The e.pings != j.ping guard stops a double decrement.
  • Traced the schedule. Sweep stamps startedAt and pings under the lock before the ping, which
    also stops a second ping while one is in flight. The give-back runs under the same lock after the
    call returns, so no retry can overlap the ping it restores.
  • Checked the retry bound. e.retried allows one give-back per run of failures and is reset only by
    a read (notePingRead) or a new entry from Record. A route that keeps failing gets one retry,
    as TestARunOfTransportFailuresIsRetriedOnce asserts. Total successful pings stay bounded by
    MaxPings plus one per failure that a later read pays back, and the hard (K+1) x Idle timer is
    untouched, so no entry outlives its deadline.
  • Checked the TTL guard. It reads e.ttl1h, the tier the provider billed, and e.refreshedAt,
    which Record and record1 set only on a real refresh. A slow failure past the TTL gets no
    give-back, which TestAFailureAfterTheCacheExpiredIsNotRetried asserts. The guard uses k.now(),
    the same clock the production ticker passes to Sweep (keeper.go:512).
  • Verified the test arithmetic by hand: Idle 280 s, TTL 300 s, pingTimeout 60 s. All three new
    tests and the updated plan test produce the asserted counts and times under those values.
  • Checked the other tests that model ping failures (TestPingErrorFailsOpen,
    TestATransportErrorIsNotAFailure, TestAnyOther4xxStops). None sweeps twice after a transport
    failure, so none contradicts the retry.
  • Checked the substitute paths. A substitute that declines or errors falls through to the ordinary
    ping in the same fire call, so the fix covers those failures too.
  • Checked the repo rules. Library change only, no proxy import from keepalive. Data dependence
    unchanged: the give-back reads keeper metadata (refreshedAt, ttl1h, pings) already held in
    memory, so docs/data-dependence.md needs no row. Commit carries DCO and Assisted-By:.
  • Live tests were not approved, so I read the code only.

@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 d541f9d377aa blocking

Verdict: blocking

Findings

  1. keepalive/keeper.go:1429 — the retry guard knows only Anthropic cache lifetimes, so an OpenAI thread never gets the retry
    • What fails: an OpenAI /v1/responses thread (GPT-5.6+) has a 30-minute cache minimum and pings at a 28-minute Idle. Its ping fails fast in transport at refreshedAt + 28 min. giveBackFailedPing then tests now < refreshedAt + 5 min, because ttl1h is always false for OpenAI. The test fails, so no retry is given. The next ping comes a full Idle later, at +56 min, past the 30-minute guarantee, and re-writes the prefix. This is the exact #703 pattern, and it stays unfixed for every OpenAI thread.
    • Proof: keeper.go:789 forces ttl1h false for OpenAI (ResolveTier(...) && provider != bschemas.OpenAI). keeper.go:1429-1432 picks the ttl from ttl1h alone: 5 minutes or 1 hour. proxy/keepalive.go:440-444 sets an OpenAI entry's Idle to OpenAIIdle, whose default is modelinfo.OpenAIDefaultKeepAliveIdle = OpenAIMinimumCacheTTL - 2 min (28 min, internal/modelinfo/cachefrac.go:11-12). eligible() (keepalive/ping.go:82-90) admits these threads, so the keeper does ping them. No test covers an OpenAI entry in failedping_test.go.
    • Fix: derive the ttl from the entry itself. For e.provider == bschemas.OpenAI, use modelinfo.OpenAIMinimumCacheTTL. Add one test with an OpenAI entry whose ping fails fast.

Non-blocking

  • keeper.go:1295-1359 — a 429 or 5xx answer gets no give-back. It also refreshes nothing and comes back fast while the cache lives, so the next ping comes a full Idle later and can re-write the prefix. Refusing an immediate retry is right for 429 (a rate limit), but a 5xx could take the same retry. The debug line at keeper.go:1357 ("retrying at the next slot") now overstates what happens: the next slot is a full Idle away.
  • keeper_test.go:239-241 — the comment is now stale. It says a transport failure "must still count against K". After this PR, a fast failure is given back and does not count against K. The bound now comes from the retried flag. Update the comment, not the test.
  • keeper.go:1404-1409 — retried is reset only by notePingRead. A summary or sweep substitute that reads the cache (substitute.go:209), or a manual ping (manual.go:165), updates refreshedAt but does not reset retried. A transport failure later in the same idle span then gets no retry. Conservative direction; minor.
  • keeper.go:1260-1264 — a refused spare slot keeps the stamp. The ping is never sent, but startedAt and e.pings stay spent, so the next ping comes a full Idle later. Same shape as #703. Pre-existing; out of scope here.
  • keeper.go:1753 — Plan.NextPing can now be in the past. After a give-back the retry is due immediately, so the plan reports prevStartedAt + Idle, a past time. The proxy test embraces this ("the retry due at ..."). A host that renders it as a future instant should treat a past value as "due now".

What I checked

  • The full diff (3 files) and the code around each change: Sweep's stamp, fire's error path, noteOutcome, record1, both substitutes, PingNow, Plans, the route breaker and the dead-credential marks.
  • The timing math of the three new tests and the changed proxy test. All consistent: the inline Go runner makes each failure and its give-back synchronous inside Sweep, and the shared clock makes the timeout case cross the 300 s boundary before the give-back runs.
  • Existing tests that transport-fail a ping (TestPingErrorFailsOpen, TestATransportErrorIsNotAFailure): both still pass. Each sweeps once, and the give-back changes no field they assert.
  • The retry bound: retried is set once per run of failures and reset only by a cache read. Attempts per idle span stay at most K+1. The hard deadline timer and the credential hold are untouched, so the security bound holds.
  • Concurrency: giveBackFailedPing takes k.mu; the e.pings != j.ping guard blocks a give-back onto a newer ping; a give-back onto an entry already dropped from k.live mutates a dead object and cannot reach the map. No new race.
  • Fail-open: the error path still only counts and logs. No new stop, panic or drop path.
  • Money: a retry can only fire earlier than the old schedule, never later. If the entry is dead, the retry writes once and stops, the same write the old schedule would have paid later. No path spends more than before.
  • Data dependence: no change. The fix reads timestamps, counters and flags only. docs/data-dependence.md needs no new row.

The retry guard chose the cache's life from the billed tier alone, 5
minutes or 1 hour. An OpenAI Responses thread never sets that tier, but
its cache lives 30 minutes and it pings at 28. So every OpenAI fast
failure looked past the cache's life and was never retried. The guard
now asks the entry (kaEntry.cacheTTL).

Also fixes 2 stale texts the review found: the comment on
TestPingErrorFailsOpen and the debug line for a 429 or 5xx answer.

Refs #703
Refs #707

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

Copy link
Copy Markdown
Collaborator Author

Replies to round 1, at head 40f651d8d75c.

Reviewer 1, finding 1 (OpenAI ttl in the retry guard): fixed.

  • New kaEntry.cacheTTL(): 30 min for an OpenAI thread (modelinfo.OpenAIMinimumCacheTTL), else 1 h or 5 min by the billed tier. giveBackFailedPing uses it.
  • New test TestAnOpenAIFastFailureIsRetriedInsideItsThirtyMinuteCache: an OpenAI Responses entry, Idle 28 min, a fast failure, then a retry 2 s later.
  • Mutation: remove the OpenAI case. The test fails with 1 pings sent, want 2. With the fix it passes.

Non-blocking, fixed:

  • keeper_test.go:239: the comment on TestPingErrorFailsOpen now says that a fast failure is given back once, and that the retried flag (not K) bounds the retries.
  • keeper.go:1357: the debug line for a 429 or 5xx now says "the next ping comes a full idle period later", not "retrying at the next slot".
  • Reviewer 2, the duplicated TTL values: the new cacheTTL() is the one place in keeper.go. cachePhaseAt in substitute.go still has its own copy. I did not change that function, because its callers are outside this fix.

Non-blocking, out of scope here (each a separate change):

  • A 5xx gets no give-back. A 5xx is a reply from the gateway. It can mean an upstream that is overloaded, and an immediate retry adds load. Treating it like a transport error is a policy choice, so it waits for the owner.
  • retried is reset only by an ordinary read. A substitute or manual read leaves it set, so a later failure in the same idle span gets no retry. That is the conservative direction (fewer pings), and the cost is at most one missed retry.
  • A refused spare slot keeps the stamp (both reviewers). It is the same shape as cache_aware_summarizer never summarizes on xhigh: 0 of 2,547 runs, ~1,030 decline with no gate #703 on a different path, and it is older than this PR. It needs its own issue and fix, not a change on this branch.
  • Plan.NextPing can be in the past after a give-back. That is correct: the retry is due now. A host that shows it should read a past time as "due now". No host renders it as a countdown today.
  • Reviewer 2, refreshedAt stays on the last read after a first-miss write. That is by design (a write refreshes nothing that was there before). A later fast failure then gets no retry, and the cost is small, as you note.

How it was tested (eval box):

Run Result
TestAnOpenAIFastFailureIsRetriedInsideItsThirtyMinuteCache PASS
the same test, with the OpenAI case removed FAIL
go test -race ./keepalive/... PASS
go test -race ./proxy/ -run 'KeepAlive|Keepalive|Ping|Keeper|Manual' PASS
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 2 of 2 40f651d8d75c approve

Verdict: approve

Findings

None.

Earlier findings

  • Reviewer 1, finding 1 (the retry guard knew only Anthropic lifetimes, so an OpenAI thread never
    got the retry): fixed. kaEntry.cacheTTL() returns modelinfo.OpenAIMinimumCacheTTL
    (30 min, internal/modelinfo/cachefrac.go:11) for an OpenAI entry, else 1 h or 5 min by the
    billed tier. giveBackFailedPing now asks the entry. I verified the pieces myself:
    • Every OpenAI entry in the keeper is GPT-5.6+ on /v1/responses: eligible
      (keepalive/ping.go:82) gates it at Record, and GPT56OrLater accepts the test's
      azure/gpt-5.6-luna. So the 30-minute minimum applies to exactly the entries that reach the
      guard.
    • ttl1h is always false for OpenAI (keeper.go:789), so the OpenAI case cannot be shadowed by
      the tier cases.
    • Test arithmetic: Idle 28 min (OpenAIDefaultKeepAliveIdle), the failure at 28 min 1 s, the
      guard's window 30 min, so the give-back fires and the retry lands 2 s later. I also checked the
      mutation claim by hand: without the OpenAI case the guard sees the entry as dead at 28 min, no
      give-back, the second sweep is not due until 56 min, and the test's want 2 fails.
  • Reviewer 2, non-blocking (the limiter-refused ping keeps the stamp): deferred by the author,
    reason accepted.
    It is pre-existing and out of this branch's scope. Issue #707 ("after a failed
    ping, the next ping is too late") is still open and can carry it.
  • Reviewer 2, non-blocking (stale comment on TestPingErrorFailsOpen): fixed. The comment now
    names the retried flag as the bound.
  • Reviewer 2, non-blocking (TTL values written twice): partly fixed, reason accepted.
    cacheTTL() is now the one place in keeper.go. cachePhaseAt in substitute.go keeps its own
    copy; the author left it because its callers are outside this fix. The two copies answer
    different questions (entry method vs. free function), so I accept leaving it.
  • Reviewer 2, non-blocking (refreshedAt stays on the last read after a miss-write): accepted as
    by design.
    The cost is one idle span at most.
  • Reviewer 1, non-blocking items (429/5xx no give-back, retried reset only by an ordinary read,
    refused spare slot, Plan.NextPing in the past): all deferred or accepted by the author with
    reasons I checked and agree with.
    The debug line for a 429 or 5xx is fixed and now tells the
    truth: without a give-back, the next ping is a full Idle away.

The new commit

  • 40f651d8 — I reviewed it as a first review. cacheTTL() reads e.provider and e.ttl1h, both
    set once at Record and read under k.mu in giveBackFailedPing. No new state, no new race. The
    new test builds its OpenAI entry through the real Record gate, so it exercises eligible,
    pingBody on /v1/responses, and the give-back together. The two text fixes (test comment,
    debug line) match the code. No defect found.

What I checked

  • Last review: round 1, d541f9d377aa82b80428b760f27e861c1fe564d0, 2026-10-25T17:43:50Z.
  • New commits read: 1 — 40f651d8 "fix(keepalive): give an OpenAI fast failure its 30-minute retry
    window".
  • 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 (17:44:38Z): read it all, checked its finding 1 and its five
      non-blocking notes against the code.
    • The author's reply comment (18:02:29Z): read it all, checked every claimed fix and every
      deferral reason against the code.
    • Commit 40f651d8: read the whole diff and the code around each change.
  • Verified the OpenAI constants (OpenAIMinimumCacheTTL 30 min, OpenAIDefaultKeepAliveIdle
    28 min), GPT56OrLater on azure/gpt-5.6-luna, eligible's OpenAI gate, relayServesClaude
    (true for non-Anthropic), and pingBody's /v1/responses branch.
  • Checked the author's eval-box test table against the code: the pass and the mutation fail are
    both what the code predicts. Live tests were not approved for me, so I read the code only.
  • Repo rules: library change only, no proxy import, data dependence unchanged (the TTL comes from
    e.provider and e.ttl1h, metadata already in memory), DCO and Assisted-By: present.

@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 40f651d8d75c approve

Verdict: approve

Findings

None.

Round-1 findings

  • Mine, finding 1 (the retry guard knew only Anthropic lifetimes): fixed. kaEntry.cacheTTL() (keeper.go:1413-1422) returns modelinfo.OpenAIMinimumCacheTTL for an OpenAI thread, else 1 h or 5 min by the billed tier. giveBackFailedPing now reads it (keeper.go:1444). The new test proves the retry: without the give-back the entry is not due again until +56 min, so the second sweep would send nothing. I traced the test's gates myself: the fixture passes eligible() (route /v1/responses, GPT56OrLater("azure/gpt-5.6-luna") is true), the prefix clears MinPrefixTokens, and the failure at 28 min + 1 s is inside the 30-minute window.
  • Mine, non-blocking (stale comment on TestPingErrorFailsOpen): fixed. The comment now names the retried flag as the bound.
  • Mine, non-blocking (misleading "retrying at the next slot" debug line): fixed. It now says the next ping comes a full idle period later.
  • Mine, non-blocking, deferred by the author — I accept each reason. A 5xx gets no give-back (a policy choice for the owner; an immediate retry can add load to an overloaded upstream). retried is reset only by an ordinary read (conservative; at most one missed retry). The refused spare slot keeps the stamp (pre-existing, needs its own issue). Plan.NextPing in the past means "due now" (no host renders it as a countdown).
  • Reviewer 2, non-blocking (TTL values duplicated): partly addressed, reason accepted. keeper.go now has one place, cacheTTL(). cachePhaseAt (substitute.go:32-38) keeps its own copy, and the author did not change it because its callers are outside this fix. I checked: unifying it would change the substitute's phase behavior for OpenAI, which is genuinely a separate change. See the non-blocking note below.
  • Reviewer 2, non-blocking (refreshedAt stays on the last read after a first-miss write): rejected by the author, reason accepted. A write refreshes nothing that was there before; I verified in round 1 that record1 gates refreshedAt on CacheRead > 0 for exactly that reason.

Non-blocking

  • keepalive/substitute.go:36-38 — cachePhaseAt still models every non-1h thread as a 5-minute cache, so it now disagrees with cacheTTL() on OpenAI. Effect: 28 minutes into a 30-minute life the phase reads Cold, so a pre_expiry substitute candidate never fires on an OpenAI thread and the ordinary ping goes instead. Fail-open and conservative, and the behavior is unchanged by this PR. File a follow-up issue so the two functions cannot drift further apart.

What I checked

  • Last review: round 1, d541f9d377aa82b80428b760f27e861c1fe564d0, 2026-10-25T17:44:38Z.
  • New commits read: 1 — 40f651d8 fix(keepalive): give an OpenAI fast failure its 30-minute retry window. Read the full diff and the code around each change.
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review: reviewer 2's round-1 review (posted before mine, so unread in round 1 by rule; read now) — its two unique points are answered above; the author's reply comment at 18:02:29 — every item in it is addressed above; the new commit — reviewed as a first review.
  • The new commit's correctness: cacheTTL() case order and semantics; only giveBackFailedPing reads it, so no other path changes behavior. Non-OpenAI entries get the same 5 min / 1 h as before.
  • The new test's arithmetic: Idle 28 min, failure at 28 min + 1 s, retry at 28 min + 3 s, both inside the 30-minute window. The eligibility gates for the OpenAI fixture (eligible, GPT56OrLater, relayServesClaude, prefix floor, turn count) all pass by trace.
  • Repo rules: the change is library-only, keepalive imports no host package (internal/modelinfo is internal, which a library package may import). DCO sign-off and Assisted-By: present on the commit. Data dependence unchanged: cacheTTL() reads the entry's provider and billed tier, both already in memory; docs/data-dependence.md needs no row.
  • Live tests were not approved, so I read the code only. The author's eval-box results (test PASS, mutation FAIL, -race clean) are consistent with my trace but not rerun by me.

@amiddavid
amiddavid merged commit 76fe119 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.

1 participant