Repository navigation
fix(keepalive): no ping while the session has a request in flight; failed pings stop and trip the route - #527
Conversation
56e7df4 to
a7a4c22
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
Review: REQUEST CHANGES at da2f351. (Posted as a comment: GitHub does not let the author account request changes.)
Verified:
gofmtandgo vetare clean.go test ./proxypasses in full (nice 10). Both commits are by Osher-Elhadad and signed off, with no AI attribution, and the PR text has no figures.- Mutations:
- Each of these makes a new test fail: the in-flight skip in
sweep, the failed-ping branch infire,claudeModelforced true, and the tenant dropped fromkaRouteKey. - With the
arriveincrement removed, TestNoPingWhileARequestOfTheSessionIsInFlight hangs until the 10 mingo testtimeout instead of failing. Give it a deadline.
- Each of these makes a new test fail: the in-flight skip in
- In-flight pairing.
arrive(proxy.go, inside the pipeline closure, which recovers) runs only with a non-empty session.servealways follows, and itsdefercallsrecord, which callsdepartedfirst with the same tenant and session. Errors, client cancel and streaming aborts all endserveand run the defer, and the same holds on the OpenAI path and for tenants with keep-alive off. Only a panic inservebefore the defer is registered (its first ~60 lines) would leak a count, and the cost is that session is never pinged. - Eviction case. A ping that reads 0 and writes the prefix still takes the
CacheWrite > CacheReadbranch first: it is countedwrote, the session stops, and the route breaker is not touched. That is right. A stop lasts until the session's next real request, which re-arms a fresh entry. - Breaker key. It includes the tenant (da2f351), so one tenant cannot switch off another. A revoked key (4xx) only stops that session, as before.
Blocking:
- A transient 5xx now stops the session and counts toward the 1 h trip. The new branch fires on
status/100 != 2, which includes the 5xx statuses that pass the 4xx check above. That reverses the existing rule, whose comment two lines up still says "A 5xx is transient and the next ping may work". Under a provider overload burst (529s), three sessions' pings fail in a row and keep-alive goes off for that tenant, upstream and model for an hour, which turns a short provider blip into an hour of cache misses. Count only a 2xx that read nothing (status/100 == 2 && CacheRead == 0) as failed and toward the breaker. Leave 5xx and 429 as before: the next ping may work. Add a test that three 529 pings do not trip the route. - The name test also drops real Claude deployments on Bedrock and Vertex.
claudeModelgates every case of the first switch arm: Anthropic, Bedrock, BedrockMantle and Vertex. A Bedrock application inference profile (arn:aws:bedrock:…:application-inference-profile/<id>) or a custom gateway alias has no Claude word, so it silently loses keep-alive. The problem you are solving is a non-Claude model on the Anthropic route behind LiteLLM. Apply the name test only tobschemas.Anthropic, where the route breaker already catches a mislabelled alias. On Bedrock and Vertex the provider is the Claude evidence. Also check whether any client sends a tier name such as Bob'spremiumon the Anthropic route.
Non-blocking:
3. Pair the in-flight count where it is raised: defer h.keeper.departed(...) right after arrive in the caller, instead of inside record. Then no panic path can leak a count, and record keeps one job.
4. routeTripped and routeFails are never pruned, and tenant purge (forget) does not clear them or inflight. They are bounded by tenants × routes × models, so this is small, but delete expired trips when they are read, and clear a tenant's keys in forget.
5. routeIsTripped takes k.mu on every real request's record. That is cheap, but it could move inside the critical section record already enters.
6. The docs line "3 in a row switch the keep-alive off for that upstream and model" should say per account, to match the code.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at c85907f. (Posted as a comment: GitHub does not let the author account approve.)
Both blockers from the review at da2f351 are fixed:
- Transient errors. A 429 or any 5xx (including 529) is counted
skipped: the audit row is kept, nothing stops, the breaker is untouched and the next slot retries. Making the branch non-transient, or dropping 429 from it, fails TestOverloadedPingsDoNotTripTheRoute and TestPingFailureNeedsNoUsageOrAnError. - Name check. It now runs only for the Anthropic route forwarded to a host other than
anthropic.com/*.anthropic.com. Bedrock, BedrockMantle and Vertex qualify by type, and so does native Anthropic under any model name. Applying the check to every provider, or name-checking native hosts, fails TestKeepAliveNameCheckIsForRelaysOnly. A look-alike host (evil-anthropic.com.example) counts as a relay. WithCONTEXT_GURU_KEEPALIVE_MODELSignored, TestKeepAliveModelAliasesFromTheEnvironment fails.
Other changes, verified:
- A non-retryable 4xx stops the session and counts toward a breaker keyed by tenant + upstream + model. With the tenant removed from the key, TestPingThatRefreshesNothingFailsAndTripsTheRoute fails. A 2xx with no usage counts as a failure: removing that branch fails two tests.
- A real miss is counted
missedand pinging continues. Making it stop immediately fails TestARealMissIsNotAFailedPing, and a second Anthropic miss stops the session through the wrote guard. - The in-flight skip: removing the
arriveincrement now fails at once ("the slow request never arrived") instead of hanging. Everyarrive(proxy.go, beforeserve) reachesserve's deferredrecordwith no return in between, anddepartedruns first inrecord. - Expired trips are pruned on the next failure, and
forgetclears the tenant's breaker state. gofmtandgo vetare clean, andgo test ./proxypasses in full (nice 10). All 5 commits are by Osher-Elhadad and signed off, with no AI attribution. The PR text and docs have no numbers.
Non-blocking test gaps (each mutation below still passes every test):
- A 4xx counting toward the breaker: with
routeFailedremoved from the 4xx branch, nothing fails. TestPingFailureNeedsNoUsageOrAnError checksfailedbut notroute_trips. forgetclearingrouteTripped.- The OpenAI double miss: with
|| u.CacheRead == 0removed from the guard, nothing fails, because an Anthropic miss writes and hitsCacheWrite > CacheReadanyway. Also, the stop is then logged as "CREATED a cache entry", which reads oddly for OpenAI. - A host like
evilanthropic.com(suffix with no dot) is not in the table. The code is right; the test does not pin it.
Note: three 401s from one user's revoked key switch the keep-alive off for that account's route + model for an hour, including for teammates on the same account. That is documented ("for that account only") and acceptable; just flag it in the docs if accounts are shared by several people.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 087e102. It covers 4808d44, c9b5902, 74d615a and 087e102. (Posted as a comment: GitHub does not let the author account approve.)
Verified:
- Credential-dead behaviour. A 401 or 403 on a caller-pays hold marks that credential dead for 1 h. The sweep stops every entry pinging with it,
recordrefuses new holds with it, and a teammate on the same account pings on. A server-held key (up.setKey) has no credential id, so its 401 still goes to the route breaker. Each of these mutations makes a test fail:- removing the sweep check;
- removing the
recordrefusal; - removing
markCredDead; - collapsing
credKeyto the tenant alone, which is the teammate-collision case (fails TestAuthRefusalStopsOnlyThatCredential and TestCredentialIDsDoNotCollideOnAMask).
- Secret handling.
credKeyis an HMAC-SHA256 under a random 32-byte key per process, over the masked header values. No plaintext copy is made, the key is never stored, and the id is never logged or exported: the newslogline has nocredfield, and it appears in no metric or debug route. - Map bounds.
credDeadis pruned of expired marks on every new mark, andforget(tenant)clears the tenant's marks by prefix. gofmtandgo vetare clean, andgo test ./proxypasses in full (nice 10). All 4 commits are by Osher-Elhadad and signed off, with no AI attribution. The PR body has no figures.
Non-blocking:
- A 403 is not always a dead key. Anthropic answers 403
permission_errorwhen a key may not use one model or feature, and gateways use 403 for per-key budget or policy refusals. As written, one such ping stops keep-alive for that key on every model and route for an hour. Real requests are unaffected; only holds stop. Consider marking only on 401, or keying a 403 on credential + model. - Bedrock SigV4. The
Authorizationvalue carries a per-request date and signature, so every hold gets its own credential id, and a dead mark only ever matches its own entry. That is harmless: it degrades to the old per-session stop, and replaying a stored SigV4 header fails anyway. Worth one line in the comment so no one relies on cross-session matching there. forgetclearingcredDeadis untested. Removing that loop still passes every test. A one-line assertion in the existing forget test would pin it.credDeadhas no count cap. It is bounded in practice by holds (512) times ping cycles per hour, which is fine; aponytail:note would record the ceiling.
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at ac5515d. (Posted as a comment: GitHub does not let the author account approve.)
- fb4bb94:
departedis now deferred to the end ofrecord, so a request leaves the in-flight count only after its hold is stored. - ac5515d: a 403 marks only (credential, model), and a 401 marks the credential on every model. With the 403 special case removed, TestA403BlocksTheKeyOnThatModelOnly fails. It also pins that
forgetclears the marks. - The SigV4 comment and the note on the missing count cap are in.
gofmtandgo vetare clean, and the-racekeep-alive, credential and signal subset passes. Both commits are signed off with no AI attribution.
Approved.
5a46885 to
9f9980f
Compare
ac5515d to
9e0295f
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 9e0295f. This is a rebase only: git range-diff against the approved ac5515d shows all 11 patches identical (=). go test ./proxy passes in full on this head, along with the thread, dash signal and plugin signal tests and the Codex tests. CI is green, and the commits are signed off. Approved. Merge after #524.
SummaryOne concern about fix (a), "no ping while the session has a request in flight". It pauses pings for every thread of the session while any request of the session is in flight. That can bring back the gap that per-thread keep-alive (#426) closed. Fix (b), the failed-ping rules, has no problem from my side. What we found
I reasoned this from the code. I did not run a test that shows a missed ping. Why the stated reason is mostly goneThe motivation is a long Proposal
Posted by an AI assistant (Claude), for the release integrator. |
amiddavid
left a comment
There was a problem hiding this comment.
Verdict
Not ready to merge as is. One defect (finding 1). The failed-ping rules are correct.
Findings
- A long call on one thread stops the main thread's ping until its cache is already gone.
proxy/keepalive.go:1123skips every due entry of a session whilek.inflight[kaKey(tenant, session)] > 0. The count is per session, not per thread. This confirms the concern in #527 (comment).- Failing case (test I wrote, it fails on the PR code): main thread entry due at 60 s idle (cache life 300 s). A request on another thread (the "SUMMARIZE" call of the PR's own test) stays in flight. I sweep at t=61 s and t=299 s. Result: 0 pings before the main cache expires. The test wants 1.
- After the slow call ends (t=301 s) the sweep then sends the ping. The cache is already gone, so the ping is a miss and writes the prefix again. That costs money and saves nothing. Nothing caps the wait, because
due()has no upper bound (keepalive.go:359). - Real default: ping at 270 s, cache life 300 s. One subagent or compact request that is in flight for more than 30 s at that moment is enough. Long Opus calls do this. Before the PR the ping went out on time.
- Proposed fix: (a) count in flight per thread (
kaThreadKey) instead of per session. A compact on another thread is already handled by #520, which retires the main thread on the compact signal. (b) Also cap the wait. If the entry would expire within one sweep tick, ping anyway. Then a leaked count cannot make the main cache expire.
- No other defect found in the in-flight count.
arriveis called atproxy.go:1249. Between it andservethere is no return.servealways runsrecordin a defer (proxy.go:1590), andrecordrunsdeparted(keepalive.go:740). A leak is not reachable on a normal path.
What I verified
- New test
TestReviewMainPingFiresWhileSubagentCallInFlight(not pushed): fails on the PR code, "0 pings (t=299s)", 1 ping at t=301 s. - Mutation: removing the in-flight check makes
TestNoPingWhileARequestOfTheSessionIsInFlightfail ("1 pings while ... in flight"). The PR's test is real. go test -race ./proxy/(whole package, box 1): pass, 411 s.- A ping transport error (timeout, issue #532) does not trip the breaker and does not stop the session. In
fire,err != nilonly doesfailed++and returns (keepalive.go:1262).routeFailed,markStoppedandmarkCredDeadare not called. The next slot retries. Note: the ping still counts towardMaxPings, becausesweepincrementse.pingsbefore the send. Two timeouts use up a 2-ping budget. - 429 and 5xx: counted
skipped, no stop, no breaker. 401/403 block the credential, not the route. Other 4xx and empty-usage 2xx trip the route after 3. A real miss resets nothing and does not trip. - The credential id is an HMAC under a per-process key. It is not logged or exported.
- Stack: this PR touches
keepalive.go,clientsignal.goand tests. Rebase on #524 and then main should be clean. #521 changeskeeper.record(campaign hook), so watch the defer order there.
Questions
- Is a cap on the wait in scope for this PR, or a follow-up? I think it belongs here, because the PR adds the wait.
Reviewed by an AI reviewer (Claude)
|
@amiddavid thanks. The fix is in 6bf5248. 1. Per-thread count. Done. The in-flight count now uses the same thread key that 2. Tests (both pass with
3. Does any case still need a session-wide pause? No. The motivating case was a long compaction call on another thread while the main entry was due. After #519 the compaction call stays on the main thread, and its arrival clears and pauses that thread itself. The per-thread pause still covers overlapping requests of one thread. Checks: |
9f9980f to
ba8cd68
Compare
OsherElhadad
left a comment
There was a problem hiding this comment.
Re-review: APPROVE at 6bf5248 (addresses the per-thread in-flight comment). (Posted as a comment: GitHub does not let the author account approve.)
arrive,record's deferreddepartedand the sweep check now all usekaThreadKey(tenant, session, threadID).servepasses the samesessionandthreadIDtoarriveand torecord, so the counts pair up.departeddeletes at count 1 or below and never goes negative.- Mutations. With all three switched back to the session-wide key, TestASlowSubagentRequestDoesNotDelayTheMainThreadsPing fails. With the pause removed entirely, TestAnOpenRequestOnTheSameThreadPausesItsPing fails.
gofmtandgo vetare clean, and the-racekeep-alive, ping, signal and compact subset of./proxypasses. CI is green, and the commit is signed off with no AI attribution.
This approval covers 6bf5248.
…iled pings stop and trip the route A due ping waits while any real request of the same session is in flight (a long /compact call). A ping that reads nothing from the cache (200 with no usage, or a relayed 5xx) counts as failed, stops that session, and three in a row switch the keep-alive off for that upstream and model for an hour. On the Anthropic-shaped route only Claude models are held. Signed-off-by: Osher-Elhadad <[email protected]>
…switch off another Signed-off-by: Osher-Elhadad <[email protected]>
…del aliases from the environment Failure is a non-2xx or a 200 with no usage at all. A ping that read nothing but billed input or wrote the prefix (it landed after expiry) is counted missed: pinging goes on and the route does not trip; a second miss in a row is a prefix mismatch and stops the session, as a partial read always did. CONTEXT_GURU_KEEPALIVE_MODELS adds model names for aliases that do not name a Claude model. Signed-off-by: Osher-Elhadad <[email protected]>
…s for the Anthropic route only Only a 2xx with no usage fails a ping and counts toward the route breaker; an overload burst (529) does neither. Bedrock and Vertex are not name-checked, so inference-profile ARNs keep their keep-alive. Expired trips are pruned and an account's breaker state goes with forget. The in-flight test fails instead of hanging when the count is broken. Signed-off-by: Osher-Elhadad <[email protected]>
…heck applies to relays only A 429 or any 5xx (a 529 overload) is transient: counted skipped, booked, and the next slot retries; nothing stops and the route breaker is untouched. A non-retryable 4xx and a 2xx with no usage are the failures. Native Anthropic, Bedrock and Vertex upstreams are eligible by type; only the Anthropic route forwarded to another host (LiteLLM, a gateway) needs a Claude model name or a CONTEXT_GURU_KEEPALIVE_MODELS alias. Signed-off-by: Osher-Elhadad <[email protected]>
…ip, the OpenAI double miss, a look-alike host Signed-off-by: Osher-Elhadad <[email protected]>
…so another test's price table cannot skip its hold Signed-off-by: Osher-Elhadad <[email protected]>
…t the account's route An auth refusal marks the credential (a hash of the masked auth slots) for an hour: every session pinging with it stops and new holds with it are refused, while a teammate's sessions on the same account, route and model ping on. The route breaker keeps no-usage 200s and other non-retryable 4xx. A server-held key has no credential id and still counts toward the route. Signed-off-by: Osher-Elhadad <[email protected]>
…ue under a per-process key Adds a test with two keys that share every character a display mask keeps. Signed-off-by: Osher-Elhadad <[email protected]>
…old is stored departed is deferred to the end of record, so a ping can never see the session idle between the response and the hold. The in-flight test waits for record (it runs after the client has its response) and uses an in-memory dashboard; it passed 40 runs in a row and the full suite 3 of 3. Signed-off-by: Osher-Elhadad <[email protected]>
…ry model A 403 is often a per-model permission or a gateway policy or budget refusal, so it marks the (credential, model) pair; a 401 still marks the credential. Tests cover a 403 on one model leaving the key pinging on another, a 401 blocking both, and forget clearing the marks. Signed-off-by: Osher-Elhadad <[email protected]>
The in-flight count was per session, so while any subagent request was open no thread of the session was pinged, and a slow gateway request could let the main thread's cache expire. It is now per thread (the key arrive and record use), and the record-after-store ordering holds per thread. No case needs a session-wide pause: the compaction call stays on the main thread. Signed-off-by: Osher-Elhadad <[email protected]>
6bf5248 to
693192b
Compare
Stacked on #524. Two keep-alive fixes found while testing the lifecycle signals with real sessions.
(a) No ping while a request of the same thread is in flight
The keeper counts each thread's real requests between
arriveandrecord, keyed like the held entries. A due ping waits only while its own thread has a request open, for example two overlapping requests of one thread. Other threads are never held back: a subagent's slow request does not delay the main thread's ping, so a session-wide pause cannot let the main cache expire. A request leaves the count only after its hold is stored. If a count ever leaked, that thread would stop pinging, which costs nothing. No case needs a session-wide pause, because the compaction call stays on the main thread (#519).(b) A ping that gets no usable answer is a failure; transient errors and real misses are not
skippedand booked. Nothing stops, the route breaker is untouched, and the next ping slot retries.route_tripsin/stats). A successful ping or a miss resets the count.missed, pinging goes on and the route is not tripped. A second miss in a row means the prefix does not match, and the session stops.Eligibility. Native Anthropic (
*.anthropic.com), Bedrock and Vertex upstreams are eligible by type, whatever the deployment is called (ARNs, inference profiles, aliases). The Anthropic route forwarded to any other host (LiteLLM, a corporate gateway) may serve another family there, such as an OpenAI or Azure model with no explicit cache control. On those relays only, the model name must containclaude,opus,sonnetorhaiku, or matchCONTEXT_GURU_KEEPALIVE_MODELS. The failed-ping breaker is the backstop for a Claude-named alias of another family.Tests
TestASlowSubagentRequestDoesNotDelayTheMainThreadsPing(end to end, slow upstream: the main ping fires on time while a subagent request is open; fails with a session-wide count) andTestAnOpenRequestOnTheSameThreadPausesItsPing(fails without the pause).TestPingThatRefreshesNothingFailsAndTripsTheRoute: empty-usage pings are counted failed, the session stops, the route trips, a tripped route holds nothing, another route is unaffected, and the trip expires.TestARealMissIsNotAFailedPing(miss, read, miss, miss: pinging continues after one miss and stops after two; nothing failed, no trip),TestPingFailureNeedsNoUsageOrAnError(no usage and a 401 fail; a 5xx, a 429, an OpenAI miss and an Anthropic miss do not),TestOverloadedPingsDoNotTripTheRoute(529/429: every session retried at its next slot, nothing failed, no trip),TestKeepAliveNameCheckIsForRelaysOnly(native Anthropic alias, Bedrock/Vertex ARNs pass; relay names checked; a look-alike host is a relay),TestKeepAliveModelAliasesFromTheEnvironment,TestAuthRefusalStopsOnlyThatCredential(a revoked key's other sessions stop and new holds are refused; the teammate pings on; a rotated key is held; no route trip),TestCredentialIDsDoNotCollideOnAMask,TestA403BlocksTheKeyOnThatModelOnly(403: the key keeps pinging on another model; 401: blocked on both; forget clears the marks),TestBreakerCountsA4xxForgetClearsItAndAnOpenAIDoubleMissStops.TestPingThatWritesInsteadOfReadingStopsTheSessionnow uses a partial read; a zero read is a miss first.go test ./proxypasses.TestKeeperSurvivesASideRequestsArrivalnow finishes its side request before the sweep.Live check (real Claude Code 2.1.296, Anthropic route -> LiteLLM -> Azure gpt-5-mini, experimental proxy)
gpt-5-minias the model name, nothing is held and no pings are sent./compactstill releases the old prefix, and no ping was sent during it. That compaction was shorter than the idle interval, so the in-flight case is covered by the slow-upstream test.