Skip to content

fix(keepalive): read an OpenAI cache as 30 minutes in the substitute's phase check - #717

Merged
amiddavid merged 3 commits into
mainfrom
fix/openai-substitute-ttl
Oct 25, 2026
Merged

amiddavid merged 3 commits into
mainfrom
fix/openai-substitute-ttl

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

On an OpenAI thread, a pre_expiry summary never took the keep-alive ping. The substitute's phase check treated the 30-minute OpenAI cache as a 5-minute one, so at the 28-minute ping it read the cache as Cold. This PR puts the cache-lifetime rule in one function that both the retry guard and the phase check use.

What we found

  • kaEntry.cacheTTL() (from fix(keepalive): retry a ping that failed fast while the cache lives #710) gives 30 minutes for OpenAI.
  • cachePhaseAt (keepalive/substitute.go) chose 5 minutes or 1 hour from a one-hour flag only. That flag is never set on OpenAI.
  • An OpenAI thread pings at 28 minutes (modelinfo.OpenAIDefaultKeepAliveIdle). There, cachePhaseAt returned Cold, so a pre_expiry candidate was refused as a phase mismatch, and an ordinary ping went instead.
  • This failed safe: the ordinary ping still kept the cache. But the summary never got its chance.

What changed

  • New cacheLifetime(provider, ttl1h) in keepalive/keeper.go: 30 minutes on OpenAI, else 1 hour on the one-hour tier, else 5 minutes. This is the one place for the rule.
  • kaEntry.cacheTTL() now calls cacheLifetime(e.provider, e.ttl1h).
  • The default pre-expiry window now covers the keeper's own slack (round 1). Before, an OpenAI ping at 28 minutes had about 120 s of cache left, more than the 60 s default, so the phase read Warm even with the right lifetime. With pre_expiry_seconds unset, the window is now the larger of 60 s and (cache lifetime - idle + 2 sweep ticks). An explicit value is kept as set. On Anthropic at the defaults this stays 60 s (300 - 270 = 30 s). The widened default is capped at 124 s (round 2), so a short schedule, such as a 60 s idle override, still reads its early pings as Warm.
  • cachePhaseAt takes the lifetime instead of a one-hour flag. fireSummarySubstitute passes cacheLifetime(e.provider, e.ttl1h || e.pol.HeadTTL1h). The HeadTTL1h part is unchanged: the substitute already counted the host's one-hour ask, and the retry guard did not, so each caller keeps its own input.

How it was tested

All runs are on the eval box.

Run Tree Result
TestAnOpenAIThreadAtTwentyEightMinutesIsNotCold origin/main + test FAIL: reads cold, want PreExpiry
TestAPreExpirySubstituteTakesAnOpenAIPing (end to end) origin/main + test FAIL: refused as a phase mismatch 1 time(s)
both new tests, plus every existing substitute test and #710's OpenAI retry test this branch PASS
mutation: drop the OpenAI case from cacheLifetime this branch FAIL: both new tests and #710's TestAnOpenAIFastFailureIsRetriedInsideItsThirtyMinuteCache. One rule now drives both.
TestAPreExpirySubstituteTakesAnOpenAIPing, now with the default window (round 1) mutation: default window not widened FAIL
TestAPreExpirySubstituteStillTakesAnAnthropicPingWithTheDefaultWindow (round 1) this branch PASS: Anthropic is unchanged
TestAShortIdleLeavesTheFirstPingWarm (round 2) mutation: no cap FAIL
go test -race ./keepalive/... this branch, head a0a16220488e PASS
go test -race ./proxy/ -run 'KeepAlive|Keepalive|Ping|Keeper|Manual|Substitute' this branch PASS
go vet, gofmt -l this branch clean

The unit test on origin/main uses main's old signature (ttl1h bool). The end-to-end test runs unchanged on both trees.

Data dependence

No change. The rule reads the provider and a tier flag, which the keeper already holds.

Fixes #715

🤖 Generated with Claude Code

…s phase check

cachePhaseAt treated every cache off the one-hour tier as a 5-minute
cache. An OpenAI Responses cache lives 30 minutes and is pinged at 28,
so the check read it as Cold, and a pre_expiry summary never took an
OpenAI ping.

The lifetime rule now lives in one function, cacheLifetime(provider,
ttl1h), which both kaEntry.cacheTTL (the failed-ping retry guard) and
the substitute's phase check call. cachePhaseAt takes the lifetime
instead of a one-hour flag.

Fixes #715

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

Verdict: approve

Findings

None. I could not prove a defect in the change.

Non-blocking

  • keepalive/substitute.go:27-31 — the old comment still says Ctx.CachePhase's CacheTTLMinimum case "never arises here". After this change it does: OpenAI's 30 minutes is a minimum, and cachePhaseAt treats it as an exact life. That is safe here — PreExpiry at 2 minutes left is inside the guarantee, and Cold past 30 minutes only refuses a substitute, so the ordinary ping still goes out. But the comment now misdescribes the function. Fix the comment in a later pass.
  • Default settings still refuse the substitute on OpenAI. The keeper pings at 28 minutes (OpenAIDefaultKeepAliveIdle), so 2 minutes remain. The default pre-expiry window is 1 minute (components.DefaultPreExpiry), so the phase reads Warm, not PreExpiry. A pre_expiry candidate substitutes only when pre_expiry_seconds is about 120 or more, as in the new test (180). The fix is still correct — the window is the tenant's knob — but a reader of the PR may expect default behavior to change, and it does not.

What I checked

  • The full diff: keepalive/keeper.go, keepalive/substitute.go, keepalive/openaiphase_test.go.
  • cacheLifetime keeps cacheTTL byte-for-byte equivalent for every input: OpenAI 30 min, 1 h tier, 5 min default. giveBackFailedPing (the only other cacheTTL caller) is unchanged in behavior.
  • cachePhaseAt has one caller, fireSummarySubstitute. No test or code still passes the old ttl1h bool shape.
  • The old OpenAI behavior: Record forces ttl1h = false for OpenAI (keeper.go:790), so the old cachePhaseAt used 5 minutes. At the 28-minute ping it returned Cold. The PR's claim of the bug is real.
  • The new 30-minute reading cannot mis-spend: PreExpiry fires only inside the guaranteed window, and Cold only falls back to the ordinary ping. Fail open holds.
  • The phase-check input e.ttl1h || e.pol.HeadTTL1h is unchanged from before, so the non-OpenAI paths behave exactly as they did.
  • The end-to-end test, by trace: two Record calls (turn 0 refused, turn 1 held), Idle 28 min, sweep at 28 min 1 s, prevStartedAt 12:00:00, remaining 1 min 59 s, window 3 min, so PreExpiry. Eligibility holds: /v1/responses route, azure/gpt-5.6-luna passes OpenAI30MinuteCache. Prices default to unset, so the cost gate passes. No checkpoint is seeded, so IsRefresh is false. The substitute commits, summarySubstituted is 1, and fs.n() is 0. The registry key matches: thread.Primary is "", the same as the test's empty thread.
  • The unit test: 28 of 30 minutes with a 3-minute window gives PreExpiry. The arithmetic is right.
  • Test isolation: kaCandidateWithCacheState clears the global registry entry via t.Cleanup, the same as the existing substitute tests.
  • Reachability in production: proxy/keepalive.go:440-445 sets OpenAI Idle to 28 minutes, and registerKeepAliveCandidate is not provider-gated, so an OpenAI thread with a pre_expiry candidate does reach this check.
  • The PR states its data dependence (no change). That matches the diff: no storage or metadata change.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 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 e0d957f65676 blocking

Verdict: blocking

Findings

  1. keepalive/substitute.go:94 — with the default pre-expiry window, the fixed phase check still refuses every OpenAI ping
    • What fails: an OpenAI thread, cache_aware_summarizer with cache_state: pre_expiry and no pre_expiry_seconds. The keeper pings at 28 minutes of idle. The cache then has about 2 minutes left. The default window is 60 seconds. The phase reads Warm, not PreExpiry, so the substitute is refused and the ordinary ping goes out. Issue #715's symptom ("a pre_expiry substitute never runs on an OpenAI thread") stays for the default configuration.
    • Proof: OpenAIDefaultKeepAliveIdle is 28 minutes (internal/modelinfo/cachefrac.go:12), and the proxy sets that as the OpenAI idle (proxy/keepalive.go:443). The sweep ticks every 2 seconds (keepalive/types.go:236), so the ping runs at 28–28.03 minutes of idle. cachePhaseAt then computes remaining = 30 min − ~28 min ≈ 118–120 s. preExpiryFor(0) returns DefaultPreExpiry, which is 60 s (components/trigger.go:107; the field default at components/trigger.go:341 is 60). 120 s > 60 s, so the phase is Warm. Production registration carries the operator's PreExpirySeconds verbatim, 0 when unset (components/offload/cache_aware_keepalive.go:171). The new end-to-end test passes only because it sets pre_expiry_seconds to 180. The fail-open path is intact — the ordinary ping still keeps the cache — so this is a lost substitute, not a lost ping.
    • Fix: either state the requirement in the PR and the component docs (on OpenAI, pre_expiry_seconds must be at least ~120 for the substitute to ever take a ping), or widen the effective window on OpenAI (for example, clamp it to the keeper's own 2-minute slack plus a margin). Add a test for the default-window case, whatever the answer is.

Non-blocking

  • keepalive/substitute.go:99 — the comment names cachePhaseLocked. No such function exists in the repo. It also says the check uses "the SAME phase arithmetic Ctx.CachePhase itself uses". On OpenAI the two now differ on purpose: Ctx.CachePhase treats the 30 minutes as a minimum and never returns PreExpiry (components/cachephase.go:119-124). Reword the comment so the next reader does not hunt for a function that is not there.
  • keepalive/substitute.go:38 — cachePhaseAt returns Cold past 30 minutes on OpenAI. A minimum cannot prove expiry (apply/cachelifetime.go:29-33). This is harmless here because the only caller compares against PreExpiry, so Cold and Unknown behave the same. One sentence in the comment would pin that.
  • keepalive/openaiphase_test.go:24 — the second assertion (e.cacheTTL() != cacheLifetime(...)) cannot fail today, because cacheTTL calls cacheLifetime. It is still useful as a pin against a future re-divergence; a short comment saying so would make that intent clear.

What I checked

  • The full diff (one commit) and the code around each change.
  • Both callers of the new cacheLifetime: the retry guard (keepalive/keeper.go:1450) and the phase check. They now share one rule, which is the PR's goal.
  • The OpenAI branch order in cacheLifetime: ttl1h is never set for OpenAI (keepalive/keeper.go:790), and pol.HeadTTL1h is an Anthropic-only ask, so the provider branch winning over the tier is safe.
  • That a provider-wide 30-minute rule cannot hit an older OpenAI model: eligible (keepalive/ping.go:82-90) admits OpenAI only on /v1/responses with GPT-5.6+.
  • The two new tests by hand: helpers exist (testKeeper, kaCandidateWithCacheState, fakeOf, kaHeader), the phase arithmetic lands as asserted (remaining 119 s against a 180 s window), the candidate registry is cleaned up per test, and a nil Record.Store is safe (apply.RecordCacheTouch returns on nil store).
  • That no other test or caller uses the old cachePhaseAt signature, so the change breaks nothing else.
  • The PR body and issue #715. The PR does what the issue proposes; the finding above is the part of the symptom the proposal did not cover.
  • That no other TTL derivation in keepalive/ still reads OpenAI as 5 minutes (holdFor sizes manual holds only; Ctx.CachePhase handles the OpenAI minimum by design).

…lack

With the default 60 s pre-expiry window, an OpenAI ping at 28 minutes
still had about 2 minutes of cache left, so the phase read Warm and a
pre_expiry substitute was still refused.

When pre_expiry_seconds is not set, the substitute's window is now at
least the keeper's own slack (cache lifetime minus idle) plus two sweep
ticks. An operator's value is kept as set. On Anthropic at the defaults
the slack is 30 s, inside the 60 s default, so nothing changes there.

Also rewords the phase-check comment, which named a function that does
not exist, and notes that Cold past an OpenAI minimum is not proof of
expiry.

Fixes #715

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

Copy link
Copy Markdown
Collaborator Author

Replies to round 1, at head ac01f2e07729.

Reviewer 2, finding 1 (the default 60 s window still refuses every OpenAI ping): fixed in code.

  • New substituteWindow(seconds, ttl, idle). If pre_expiry_seconds is set, it is kept as set. If it is not set, the window is the larger of the 60 s default and the keeper's own slack (cache lifetime minus idle) plus 2 sweep ticks.
  • Anthropic at the defaults: 300 s - 270 s = 30 s, inside 60 s, so the window stays 60 s. OpenAI at the defaults: 30 min - 28 min = 120 s, so the window becomes 124 s.
  • TestAPreExpirySubstituteTakesAnOpenAIPing now uses the default window (pre_expiry_seconds 0), not 180.
  • New TestTheSubstituteWindowCoversTheKeepersOwnSlack: the Anthropic default stays 60 s, the OpenAI default covers at least 120 s, and an explicit 30 s stays 30 s.
  • New TestAPreExpirySubstituteStillTakesAnAnthropicPingWithTheDefaultWindow: an Anthropic ping at 281 s with the default window is still substituted.
  • Mutation: do not widen the default. Both OpenAI tests fail (refused as a phase mismatch 1 time(s), and OpenAI default window = 1m0s). The Anthropic tests pass either way, as expected.

Non-blocking, fixed:

  • substitute.go:99, the comment named cachePhaseLocked, which does not exist. Reworded: the check is cachePhaseAt on the entry's own clock. It differs from Ctx.CachePhase on OpenAI on purpose, because that one treats 30 minutes as a minimum and never reports PreExpiry.
  • substitute.go:38, Cold past an OpenAI minimum: one sentence now says it is not proof of expiry, and that the only caller compares against PreExpiry, so Cold and Unknown act the same there.
  • openaiphase_test.go:24, the cacheTTL assertion: a comment now says it cannot fail today and that it pins the two against drifting apart.

How it was tested (eval box):

Run Result
the 4 OpenAI and Anthropic phase tests, plus every existing substitute, refresh and summary test PASS
mutation: default window not widened FAIL, both OpenAI tests
go test -race ./keepalive/... PASS
go test -race ./proxy/ -run 'KeepAlive|Keepalive|Ping|Keeper|Manual|Substitute' 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 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 ac01f2e07729 approve

Verdict: approve

Findings

None in the new commit. I could not prove a defect.

Earlier findings

  • Reviewer 2, finding 1 (the default 60 s window still refuses every OpenAI ping): fixed. substituteWindow widens the unset window to the keeper's slack plus 2 ticks. I checked the numbers myself: tick is 2 s (keepalive/types.go:236), OpenAI slack is 30 min − 28 min = 120 s, so the window is 124 s. At the default ping the cache has 118–120 s left, so the phase reads PreExpiry. An operator's explicit pre_expiry_seconds is returned unchanged. Anthropic at the defaults keeps the 60 s window (slack 34 s). The end-to-end test now uses the default window (pre_expiry_seconds 0), so it proves the fixed case.
  • Reviewer 2, non-blocking (the cachePhaseLocked comment, the Cold-past-minimum note, the tautology comment on the cacheTTL assertion): fixed. All three comments are reworded as promised. I read each new comment; each now matches the code.
  • My round-1 non-blocking note 2 (default settings still refuse the substitute on OpenAI): fixed by the same change.
  • My round-1 non-blocking note 1 (the doc comment above cachePhaseAt still says the CacheTTLMinimum case "never arises here"): not fixed. The sentence at keepalive/substitute.go:27-31 is still there and is still inaccurate — OpenAI's 30-minute minimum now flows through this function. The two new comments (in cachePhaseAt and at the call site) document the same fact correctly, so a reader is no longer misled for long. Still non-blocking.

Non-blocking

  • keepalive/substitute.go:58-64 — the comment justifies the widening with "the keeper pings exactly that far before expiry". That holds only when Idle sits just under the cache life (270/300 s, 28/30 min). A manager strategy may set Idle to 60 s on an Anthropic 5-minute cache (the band is 60–290 s, proxy/keepalive.go:432-436). The slack is then 244 s, so the window is 244 s and every ping reads PreExpiry — the substitute takes every ping, not only those near expiry. The spend stays bounded (per-ping ceiling, refresh break-even, MaxPings), and an operator who wants the old behavior sets pre_expiry_seconds explicitly. Consider capping the widening, or saying in the comment that a schedule much faster than the TTL makes the window cover most of the cache's life.
  • An OpenAI manual override with a shortened Idle has the same shape (proxy/keepaliveoverride.go:209-210 allows any Idle up to 28 min). At 5 min, the window becomes about 25 minutes. The config comment marks that knob "for a controlled test", so the exposure is small.

What I checked

  • Last review: round 1, e0d957f, 2026-10-25T18:38:08Z.
  • New commits read: 1 — ac01f2e0 "fix(keepalive): widen the default pre-expiry window to the keeper's slack".
  • 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 2's round-1 review (blocking, the default-window finding). Checked the fix myself, numbers above. Fixed.
    • The author's reply comment. Each claim in it matches the code and the tests, including the mutation claims — with the widening removed, the OpenAI end-to-end test sees 119 s remaining against a 60 s window, so Warm, so a mismatch.
  • The new commit's full diff and the code around it: substituteWindow has one production caller (fireSummarySubstitute); idle is read under the keeper lock; e.pol.Idle is fixed at record time for a scheduled entry.
  • The arithmetic of all three new tests, by hand:
    • Anthropic default window: max(60 s, 300−270+4 s) = 60 s, unchanged. Correct.
    • OpenAI default window: 124 s, at least the asserted 2 minutes. Correct.
    • An explicit 30 s stays 30 s. Correct.
    • OpenAI end to end: window 124 s, remaining 119 s at the 28 min 1 s sweep, so PreExpiry and the substitute commits. Correct.
    • Anthropic end to end: window 60 s (Idle 280 s gives slack 24 s), remaining 19 s at the 281 s sweep, so PreExpiry. Correct.
  • Edge cases of substituteWindow: a negative slack (Idle above the TTL) returns the 60 s default; the 1 h tier's Idle (about 59 min) gives a 64 s window. Both harmless.
  • That the widening touches nothing else: substituteWindow is used only by the phase check. The turn-path phase check (Ctx.CachePhase) and the component's own trigger window still use preExpiryFor / DefaultPreExpiry.
  • That a reserved checkpoint created earlier is still safe: tryReuse graduates it only on a cold-or-untracked turn's own phase (components/offload/cache_aware_summarizer.go:1068-1084), so the wider creation window cannot splice a reserve into a warm turn.
  • Fail open: a Warm or Cold reading still falls through to the ordinary ping. The new code changes only when the substitute may spend, never whether a ping goes out.
  • The base..HEAD diff is exactly the two commits I reviewed across both rounds (keeper.go, substitute.go, openaiphase_test.go). Nothing else 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 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 ac01f2e07729 blocking

Verdict: blocking

Findings

  1. keepalive/substitute.go:70 — the widened default window has no upper bound, so a short ping schedule turns pre_expiry into "every ping"
    • What fails: a 5-minute thread with a keep-alive override or strategy idle of 60 s (the band allows 60–290 s, proxy/keepaliveoverride.go:55), cache_aware_summarizer with cache_state: pre_expiry and pre_expiry_seconds unset. The first ping fires at 60 s of idle, with 240 s of cache life left. substituteWindow(0, 300 s, 60 s) returns 300 − 60 + 4 = 244 s, so the phase reads PreExpiry and the substitute takes the ping. Before this commit the window was 60 s, the phase read Warm, and the ordinary ping went out. The candidate now spends on every ping from the first, 4 minutes before expiry. The same happens on an OpenAI thread with a shortened idle (the override clamps it only from above, proxy/keepaliveoverride.go:209), and on a thread whose 1-hour HeadTTL1h ask was not granted (window ≈ 55 min).
    • Proof: substituteWindow returns ttl - idle + 2*tick whenever that exceeds 60 s, with no cap (substitute.go:70-72). due fires a ping at idle (keepalive/keeper.go:188-190), so the remaining life at the ping is ttl - idle — always inside the widened window, whatever the schedule. That defeats the contract the state documents: "only a summary reserved for a cache about to expire" (components/offload/cache_aware_summarizer.go:499), and the comment six lines below the new call still promises the window is live "not merely whenever the keeper happens to be sending a ping" (substitute.go:115-117). No matched schedule needs a window wider than about 124 s: the shipped slacks are 30 s (Anthropic 5 min), 60 s (1 h tier), 120 s (OpenAI) — the last is the design margin OpenAIMinimumCacheTTL - OpenAIDefaultKeepAliveIdle. The spend is bounded by MaxUSDPerPing and the refresh break-even, so this is a wrong-schedule spend, not an unbounded one — but it is exactly the divergence the phase check exists to catch.
    • Fix: cap the widened default at a value that still covers every matched schedule, for example 2*DefaultPreExpiry + 2*tick (128 s, above OpenAI's 120 s slack). Add a test: a 60 s idle on a 5-minute thread must leave the first ping refused as Warm.

Non-blocking

  • Reviewer 1, round 1, first item (agree, checked myself): substitute.go:27-31 still says the CacheTTLMinimum case "never arises here". OpenAI's 30 minutes is a minimum and cachePhaseAt now feeds it in directly. The author did not address this one; reviewer 1 asked for a later pass, so this only records that it is still open.
  • substitute.go:115-117 — after this commit, the comment's claim that the window is "not merely whenever the keeper happens to be sending a ping" holds only for an operator-set pre_expiry_seconds. For the default it is now false by construction (see finding 1). Whichever way the finding is resolved, this comment and substituteWindow's doc should tell the same story.

What I checked

  • Last review: round 1, e0d957f, 2026-10-25T18:38:26Z
  • New commits read: 1 (ac01f2e0 fix(keepalive): widen the default pre-expiry window to the keeper's slack)
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review: the commit ac01f2e0 (full diff and surrounding code, below); the author's reply comment at 2026-10-25T18:47:26Z (each claim checked); reviewer 1's round-1 review at 18:38:08Z (older than my last review, read now in full; both non-blocking items checked).
  • My round-1 finding 1 (default 60 s window refuses every OpenAI ping): fixed in code. substituteWindow widens the default to the keeper's slack plus two ticks; the end-to-end test now uses pre_expiry_seconds 0, so it discriminates (the author's mutation run confirms it fails without the widening). I verified the arithmetic: the ping fires at idle (due, keeper.go:188-190), remaining is at most ttl - idle, and the window is ttl - idle + 4 s, so every scheduled ping lands inside it. The fix works for every matched schedule — and only matched ones need it (finding 1 is the over-generalization).
  • My round-1 non-blocking items: all three fixed — the cachePhaseLocked comment is reworded and now states the OpenAI difference from Ctx.CachePhase on purpose; cachePhaseAt notes Cold past an OpenAI minimum is not proof of expiry; the test pin carries the "cannot fail today" comment.
  • That no existing test breaks: every existing pre_expiry registration passes an explicit 60 (substitute_test.go:189,232,324,358,417), which substituteWindow keeps as set, so TestKeepAliveSubstituteRespectsPreExpiryPhaseNotJustKeeperTiming still gets its mismatch. The two new tests with 0 are the only widened ones.
  • The new tests by trace: OpenAI window 124 s against remaining 119 s → PreExpiry, substituted 1, ordinary pings 0. Anthropic window max(60 s, 300−280+4) = 60 s against remaining 19 s → PreExpiry. TestTheSubstituteWindowCoversTheKeepersOwnSlack: Anthropic 270 s idle → 34 s < 60 s → unchanged; OpenAI 124 s ≥ 120 s; explicit 30 s kept.
  • That the manual path cannot reach substituteWindow with a zero idle: PingNow sends its own ordinary ping and never calls the substitutes (keepalive/manual.go:80-134), and the sweep skips manualOnly entries (keeper.go:1117), whose policy carries no Idle.
  • The 1-hour tier at the defaults: slack 3600 − 3540 + 4 = 64 s, so the window moves from 60 s to 64 s — tick-jitter cover only, no behavior change of substance.
  • The author's test table (eval box) is consistent with my traces; I could not run Go here, as before.

Review round 2 of #717: the default window grew to the keeper's whole
slack with no upper bound. A short schedule (a 60 s idle on a 5-minute
cache, or a 1-hour ask that was not granted) then read its first ping
as PreExpiry, and a pre_expiry summary took every ping from the first.

The widened default is now capped at twice the 60 s default plus two
sweep ticks (124 s). That still covers OpenAI's 120 s slack.

Also fixes 2 comments: Ctx.CachePhase's CacheTTLMinimum case does reach
cachePhaseAt (OpenAI), and the phase-check comment now says how the
default window is bounded.

Fixes #715

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

Copy link
Copy Markdown
Collaborator Author

Replies to round 2, at head a0a16220488e.

Reviewer 2, finding 1 (the widened default window has no upper bound): fixed.

  • The widened default is now capped by maxSubstituteWindow = 2 × DefaultPreExpiry + 2 sweep ticks = 124 s (a tick is 2 s, so the cap comes to 124, not 128). It still covers OpenAI's 120 s slack.
  • An operator's own pre_expiry_seconds is still kept as set, without the cap.
  • New test TestAShortIdleLeavesTheFirstPingWarm:
    • a 60 s idle on a 5-minute cache: the window is at most 124 s, and the first ping (240 s of life left) reads Warm;
    • a 1-hour ask that was not granted (270 s idle on a 1-hour lifetime): the window stays within the cap;
    • OpenAI at its defaults: the window still covers its 2-minute slack.
  • Mutation: remove the cap. The test fails with default window for a 60 s idle = 4m4s, want at most 2m4s.

Non-blocking, fixed:

  • substitute.go:27-31: the comment no longer says CacheTTLMinimum "never arises here". It now says OpenAI's 30 minutes is a minimum and reaches this function. Ctx.CachePhase never reports PreExpiry for a minimum, but this function does, because the keeper knows when it pings.
  • substitute.go:115-117: the comment now names a short idle override as one of the divergence cases. It also says the default window is widened only up to maxSubstituteWindow, so a short schedule still reads its early pings as Warm. The substituteWindow doc says the same.

How it was tested (eval box):

Run Result
TestAShortIdleLeavesTheFirstPingWarm, plus every OpenAI, Anthropic, substitute, refresh and summary test PASS
mutation: no cap FAIL (TestAShortIdleLeavesTheFirstPingWarm)
go test -race ./keepalive/... PASS
go test -race ./proxy/ -run 'KeepAlive|Keepalive|Ping|Keeper|Manual|Substitute' 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 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 a0a16220488e approve

Verdict: approve

Findings

None in the new commit. I could not prove a defect.

Earlier findings

  • Reviewer 2, round-2 finding 1 (the widened default window has no upper bound, so a short schedule turns pre_expiry into "every ping"): fixed. This was my round-2 non-blocking note raised as blocking; I agree with their reading and checked the fix myself. maxSubstituteWindow is 2 × 60 s + 2 × 2 s = 124 s (the author's reply is right that reviewer 2's "128 s" was a slip; the code and tests say 124). The cap is applied to the slack before the comparison with the 60 s default.
  • My round-2 non-blocking notes (the 60 s strategy idle, the shortened OpenAI override, the ungranted 1-hour ask): fixed by the same cap. All three cases now get a 124 s window, so their early pings read Warm.
  • My round-1 note and reviewer 2's round-2 note on the doc comment above cachePhaseAt ("CacheTTLMinimum ... never arises here"): fixed. The comment now says the minimum case does reach this function, and why this function still reports PreExpiry for it.
  • Reviewer 2's round-2 note on the call-site comment (the window is live "not merely whenever the keeper happens to be sending a ping"): fixed. The comment now names the short idle override and states the cap, telling the same story as substituteWindow's doc.

Non-blocking

  • keepalive/substitute.go:85 — the cap (124 s) is exactly OpenAI's slack (120 s) plus two ticks, but it is derived from DefaultPreExpiry, not from the OpenAI constants. If OpenAIDefaultKeepAliveIdle is ever shortened, the cap stops covering the slack and the default OpenAI ping reads Warm again. The tests would catch it (TestAPreExpirySubstituteTakesAnOpenAIPing would see a phase mismatch), so this is only a maintenance coupling. Deriving the cap as modelinfo.OpenAIMinimumCacheTTL - modelinfo.OpenAIDefaultKeepAliveIdle + 2*tick would make it track on its own.

What I checked

  • Last review: round 2, ac01f2e, 2026-10-25T18:51:42Z.
  • New commits read: 1 — a0a16220 "fix(keepalive): cap the widened pre-expiry window".
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files).
  • New items since my last review, and what I did about each:
    • Reviewer 2's round-2 review (18:54:51Z, blocking, the unbounded widening). Checked the fix and the arithmetic myself; it is the same defect I had rated non-blocking, and their blocking call was the safer one. Fixed.
    • The author's reply (18:59:54Z). Each claim matches the code; the 124 s correction of reviewer 2's 128 s is right (a tick is 2 s).
  • The new commit's full diff and the code around it. The cap sits inside substituteWindow's slack branch; an operator's explicit pre_expiry_seconds still bypasses it, as before.
  • The cap's arithmetic, by hand, for every schedule that reaches it:
    • OpenAI default: min(120 s + 4 s, 124 s) = 124 s; the ping has 118–120 s left, so PreExpiry. The fix for #715's default case still holds.
    • Anthropic default (270 s idle): slack 34 s, below the 60 s default, so the window stays 60 s.
    • 1 h tier (about 59 min idle): slack 64 s, window 64 s, the ping's 60 s remaining still reads PreExpiry.
    • Short schedule (60 s idle on a 5-minute cache): window 124 s, the first ping's 240 s remaining reads Warm — the pre-round-2 behavior restored, which is what pre_expiry means.
    • Ungranted 1-hour ask (1 h ttl, 270 s idle): window 124 s, about 55 min remaining, Warm. Same as before round 2.
  • The new test TestAShortIdleLeavesTheFirstPingWarm, by trace: all four assertions hold with the numbers above, and it discriminates — the author's mutation output (4m4s, want at most 2m4s) matches the uncapped slack of 244 s.
  • That no other behavior moved: substituteWindow still has one production caller; the turn-path phase check and the component's trigger window are untouched; a Warm or Cold reading still falls through to the ordinary ping, so fail open holds.
  • The base..HEAD diff is exactly the three commits I reviewed across the three rounds (keeper.go, substitute.go, openaiphase_test.go). Nothing else 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 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 a0a16220488e approve

Verdict: approve

Findings

None. I could not prove a defect in the new commit.

Earlier findings

  • My round-2 finding 1 (the widened default window has no upper bound): fixed. substituteWindow now takes min(ttl-idle+2*tick, maxSubstituteWindow), with maxSubstituteWindow = 2*DefaultPreExpiry + 2*tick = 124 s. I checked every configuration by hand:
    • OpenAI at the defaults: slack 120 s + 4 s = 124 s, at the cap exactly; the ping's remaining life is at most 120 s, so it still reads PreExpiry. The cap can never cause a missed OpenAI ping: due fires only at or after idle, so remaining is at most ttl - idle, and delay only makes it smaller.
    • Anthropic 5 min, 60 s idle (my finding's case): window 124 s, remaining 240 s → Warm, refused. Correct.
    • A 1-hour ask not granted, 270 s idle: window 124 s, remaining about 55 min → Warm. Correct.
    • 1-hour granted (59 min idle): window 64 s, unchanged from round 2.
    • Anthropic defaults (270 s idle): window 60 s, unchanged from before this PR.
    • An operator-set pre_expiry_seconds is still returned uncapped, as designed.
  • My round-2 non-blocking items: both fixed. The cachePhaseAt doc no longer claims CacheTTLMinimum "never arises here" — it now says OpenAI's minimum reaches this function and why this function reports PreExpiry where Ctx.CachePhase does not. The phase-check comment names a short idle override as a divergence case and states the cap.
  • Reviewer 1's round-2 non-blocking items (the same unbounded-widening concern, plus an OpenAI override with a shortened idle): fixed by the same cap.
  • Reviewer 1's round-1 note (the CacheTTLMinimum comment): fixed in this commit, as above.
  • My round-1 finding and non-blocking items, and reviewer 1's round-1 items: all fixed in round 2 and unchanged there.

Non-blocking

  • TestAShortIdleLeavesTheFirstPingWarm, first and third assertions compare substituteWindow's result against maxSubstituteWindow, which the function cannot exceed by construction. They are pins, like the cacheTTL assertion; the substantive checks are the Warm reading and the OpenAI lower bound. No change needed.

What I checked

  • Last review: round 2, ac01f2e, 2026-10-25T18:54:51Z
  • New commits read: 1 (a0a16220 fix(keepalive): cap the widened pre-expiry window)
  • Read in full: 3 reviews, 2 comments, 0 inline comments (from the three files)
  • New items since my last review, and what I did about each:
    • The commit a0a16220: full diff and the code around it, below.
    • The author's reply at 2026-10-25T18:59:54Z: each claim checked. The 124 s figure is right — my round-2 fix proposal said 128 s, which was my own arithmetic slip (120 + 2×2 = 124); the author corrected it.
    • Reviewer 1's round-2 review at 18:51:42Z: read in full. Its two non-blocking items match my finding and the OpenAI-override case; both are fixed by the cap.
  • The new test by trace: substituteWindow(0, 300 s, 60 s) = 124 s; cachePhaseAt at 60 s of a 300 s life gives remaining 240 s > 124 s → Warm. Without the cap the window would be 244 s and the phase PreExpiry, so the test discriminates — the author's mutation run confirms it.
  • That the cap introduces no new miss: a schedule whose slack exceeds 124 s (for example a 170 s idle on a 5-minute cache) now never substitutes — but no ping of such a schedule lands near expiry, so refusing is what pre_expiry asks for. An operator who wants substitution there sets pre_expiry_seconds.
  • That the min builtin and the const placement compile in this repo: min is already used on durations and ints (keepalive/types.go:178), Go 1.26.
  • The full base..HEAD diff is exactly the three commits reviewed across the three rounds (keeper.go, substitute.go, openaiphase_test.go). Nothing else changed.
  • Fail open is untouched in all three commits: every refusal path falls through to the ordinary ping, and the substitute only replaces a ping that was going out anyway.

@amiddavid
amiddavid merged commit 344db7f 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 30, 2026
)

Owner decision 2026-10-30: "give it more time, it can run on the 210
sec mark".

- The hold extension is removed: the re-armed timer,
  keepalive_hold_extensions and its tests. Every span keeps today's
  hold limit.
- One extra slot for every substitute: 30 s before the normal hold
  deadline (210 s after the last ping at the 5-minute defaults).
- For the summary's extra request only, the pre-expiry window widens to
  cover that slot (94 s at the defaults: 90 s left plus two ticks).
  Planned-ping summaries keep the #715/#717 window.
- The summary goes first. The sweep question goes only if the summary
  declines, in the same slot. Nothing after it.
- Kept: a missed slot is never sent late; OpenAI is out of scope.

Refs #776

Assisted-By: Claude
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 30, 2026
…776) (#779)

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

The sweep question took ping 1 of an idle span. It reads the turn's
cache entry but does not renew one that ends at a text turn. After a
text turn the entry then expired, and the plain ping 2 wrote the whole
conversation again: 22 of the 80 misses in #776 ($50.18 in 3.9 days on
one laptop), which #777 could not fix.

Ping 1 is now always plain. The question takes the last planned ping of
the span. A one-ping plan (the 1-hour tier's default) sends no question,
so the question is never the only ping.

The summarizer's substitute, the already_asked latch, the cost ceiling
and the batch rules are unchanged.

Owner decision 2026-10-30.

Fixes #776

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
fix(keepalive): after a text turn the sweep question comes third (#776)

Owner decision 2026-10-30: the sweep must not contradict the caching
strategy. Where the question cannot renew the cache, it runs as an extra
request after the strategy's last ping.

- After a turn that ends at a text turn (the last non-system message
  is not a tool_result; roles and block types only), every planned ping
  is plain. The question goes out once at the slot after the last
  planned ping, 30 s before the hold ends. No ping follows it, and it
  sends nothing if the copy is gone or there is no candidate.
- After a tool_result turn the question may take ping 1, as on main:
  it renews the entry (#777).
- This replaces the "plain ping 1, question on the last ping" rule of
  the first commit, which is reverted.

New counters: keepalive_sweep_extra_asked, keepalive_sweep_extra_skipped.

Refs #776

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
docs: keep-alive never shortens the cache strategy (#776)

The owner asked for the rule in the development docs, so a later change
that breaks it is caught.

- docs/design.md: a new section, "Keep-alive: the cache strategy comes
  first". It names the summarizer's substitute as a known gap.
- CLAUDE.md, Hard boundaries: one bullet that points at it.
- RELEASING.md, Part B: the live check confirms that after a text turn
  every planned ping is plain and reads the full prefix.
- A guard test for the sweep on 1-, 2- and 3-ping plans.

Refs #776

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
fix(keepalive): the summarizer follows the cache strategy too (#776)

Owner decisions 2026-10-30: "summerizer as well so a)" and "a1 it is".

- After a text turn the summarizer's keep-alive substitute no longer
  takes a planned ping. Every planned ping is plain, and the summary
  goes out once as the extra request after the last one.
- A cache_state any summary uses the sweep's slot: 30 s before the
  normal hold deadline.
- A cache_state pre_expiry summary (the medium preset) runs only in its
  pre-expiry window. Its slot is the middle of that window: 268 s
  after the last ping at the 5-minute defaults, 32 s before expiry.
- The one exception to the hold limit: only for a span that ended at a
  text turn and still has a pre_expiry summary waiting, the deadline
  timer re-arms once, to 15 s past the slot (43 s longer at the
  defaults), never past the cache expiry. Every other span keeps the
  limit. Counted as keepalive_hold_extensions.
- One request in the extra slot. The summary owns it before the sweep.
  A declining pre_expiry summary is not followed by the sweep.
- A missed extra slot is never sent late.
- OpenAI is out of scope: its cache has no text-turn rule.
- docs/design.md: the known gap is gone. The guard covers every
  substitute kind.

Refs #776

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
test(proxy): the summary-at-a-ping tests use a tool_result turn (#776)

After a text turn the summary now waits for the extra slot after the
last planned ping. These two tests are about a planned ping dispatching
the summary, so their last real turn now ends at a tool_result.

Refs #776

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
fix(keepalive): the summary uses the 210 s slot, no hold extension (#776)

Owner decision 2026-10-30: "give it more time, it can run on the 210
sec mark".

- The hold extension is removed: the re-armed timer,
  keepalive_hold_extensions and its tests. Every span keeps today's
  hold limit.
- One extra slot for every substitute: 30 s before the normal hold
  deadline (210 s after the last ping at the 5-minute defaults).
- For the summary's extra request only, the pre-expiry window widens to
  cover that slot (94 s at the defaults: 90 s left plus two ticks).
  Planned-ping summaries keep the #715/#717 window.
- The summary goes first. The sweep question goes only if the summary
  declines, in the same slot. Nothing after it.
- Kept: a missed slot is never sent late; OpenAI is out of scope.

Refs #776

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
fix(keepalive): only the summary takes a summary's slot; extra re-checks the breaker (#776)

Owner rule 2026-10-30: "as for sweep after summary. dont do that. it can
probably have the sweep question pay a cache write like the problem with
the ping... so we should probably just do summary at that point".

- When a summary is due in the extra slot, only the summary goes, even
  if it declines. The sweep question takes the slot only when no
  summary is registered for the thread.

Review round 1 on #779:
- The extra slot now runs the same route-breaker and dead-credential
  re-check as a planned ping. On a trip it sends nothing and stops the
  span.
- A short Idle: the slot is at least two ticks after the last ping, and
  the extra waits until that ping's response is in (pingRunning).
- SweepExtraSkipped: the doc names every case it counts.
- docs/design.md: endsAtTextTurn is an internal flag, not a metric.
- RELEASING.md: the Part B check is numbered like its siblings.

Refs #776

Assisted-By: Claude
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 substitute phase treats an OpenAI cache as 5 minutes, not 30

1 participant