Skip to content

feat(keepalive): follow the cache TTL each session was billed at - #512

Merged
amiddavid merged 8 commits into
mainfrom
feat/keepalive-ttl-aware
Oct 22, 2026
Merged

amiddavid merged 8 commits into
mainfrom
feat/keepalive-ttl-aware

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #505

Summary

  • Keep-alive now reads the cache lifetime per session from the traffic. It no longer uses one proxy-wide setting.
  • A 1-hour session gets 1 ping at 59 minutes. A 5-minute session behaves exactly as before.
  • Strategies are named by ping count: auto (default), 1-ping, 2-ping. The old name 5-min-ping still works.
  • The data supports the default: one ping at 59 min nets about 3x its cost on recorded human traffic (data comment).

What changed

Cache billed at auto 1-ping 2-ping
5 minutes first ping at 270 s, at most 2 1 ping at 270 s same as auto
1 hour 1 ping at 59 min 1 ping at 59 min 2 pings, 59 min apart
  • Review fixes (commits a4cdb06 and af2a43f).
    • Old binary + new plugin: a 1-hour config key is written only when it differs from the proxy default (so only 2-ping). start-proxy.sh also drops the keys and retries if an old binary rejects them.
    • 1-hour hold is capped: keepalive_max_pings_1h is at most 3, so the hold is at most 236 min.
    • The dashboard credit window and floor follow the row's tier, so a 1-hour rescue is credited.
    • tier1h is written beside turns, and a reset keeps the current thread.
  • One tuning point. The 59-minute value is AnthropicDefaultKeepAliveIdle1h in internal/modelinfo/cachefrac.go. Config keys keepalive_idle_seconds_1h and keepalive_max_pings_1h override it.
  • Aliases. 5-min-ping maps to auto in strategy set, strategy show, strategy sync, install.sh --cache-strategy and strategy list (aliases=). strategy sync rewrites an old marker, so existing installs get the 1-hour schedule on the next start.
  • 1-hour-head and Codex 30-min-ping keep their names.
  • Docs and skills updated.

How it was tested

On eval box 1, -race, CGO_ENABLED=1, at 5878748 (main merged at c4fed6f, v0.5.4):

  • go build ./... and go vet ./...: clean.
  • go test ./config ./apply ./internal/modelinfo ./cmd/... ./keepalive/...: 8 packages ok.
  • go test ./proxy/...: ok (435 s). go test ./dash/...: ok (555 s). go test ./context-guru-plugin: ok (354 s).
  • No port_changed_since_plan failure in the final runs (Plugin install tests flake on the shared eval box (port_changed_since_plan) #513 is the known flake).
  • Two things that looked like failures were my own stale upload, not the code: tar never deletes, so files main removed (11 skill dirs, dash/ui assets, internal/cheapmodel) stayed on the box and failed the skill and asset checks. I removed those named files by full path and re-ran. The box tree now matches git ls-files exactly.
  • New tests since main moved the keeper into package keepalive: 16 in keepalive/ttl_test.go, 4 in proxy/keepalive_ttl_test.go, 4 in dash/keepalive_ttl_test.go, 1 in config, 3 in context-guru-plugin.

Mutations (each test fails when the logic breaks)

Mutation Test that fails
ResolveTier ignores the all-breakpoints check TestMixedAskOnAReadOnlyTurnGoesBackToFiveMinutes
Record never swaps to the 1h schedule 5 tests, among them TestOneHourBilledSessionPingsOnceNear59Minutes
ForOneHour has no cap TestCredentialHoldPerTier
ForOneHour sets KeepAlive (a none thread gets a schedule) TestNoneStaysNoneOnAOneHourThread
Manual-only hold stays 300 s on a 1h thread TestManualHoldFollowsTheThreadsTier, TestManualPingOnAOneHourThreadWorksPastFiveMinutes
Override does not bound the 1h count TestOverrideOnAOneHourThreadUsesTheOneHourTimingAndBoundsTheCount
Campaign does not bound the 1h count TestCampaignBoundsAOneHourThreadsPingCountDownward
Remove the 1h credit floor in dash/event.go TestKeepAliveCreditFloorFollowsTheRequestsTier
Remove the 1h window in kaSaved TestKaSavedCreditsAOneHourRescue
Reset drops the current thread's tier TestTierMemoryIsBoundedAndKeepsTheCurrentThread
Remove the start-proxy.sh recovery, the log offset, or the marker's version the three plugin tests from the earlier rounds

Main's keep-alive features, made tier-aware

Main moved the keeper into package keepalive and added several features while this PR was open. Each one that computes time or cost from the TTL is listed here.

Feature Change
Manual-only hold for the Ping button (#666) Changed. The hold was a fixed 300 s. On a 1h thread the cache is still warm then, and by the time a press matters (near the hour) the hold was gone, so the button could never work. It is now 59 min (ManualHoldMax1h) on a 1h thread and 300 s otherwise. A press still never extends it. It is still opt-in per request.
Manual ping endpoint and its deadline (#655) No code change, test added. PingNow follows the entry's own hold. A press on a 1h thread at 30 min works, and a press restarts the automatic clock from the press.
Next-request costs and the rewrite credit No change needed. dash.NextRequestUSD already prices a 1h rewrite at 2.0x input. Test added.
held_until (counts only pings that refreshed the cache) No change needed. heldUntil(ttl) takes the thread's TTL. Tests added for a 1h plan, a late ping, and two chained pings.
manual_pings credit No change needed. The credit is the endpoint's rewrite figure, which is tier-priced. Covered by an end-to-end test on a 1h thread (rewrite at 2.0x, warm for an hour).
Predictive campaigns and the predictor Changed. A campaign is scored on 5-minute economics, so its k counts 5-minute windows. On a 1h thread it now bounds the 1h ping count downward only. It never raises it and never sets the 1h timing.
Per-tenant builder, shadow mode, route breaker, lifecycle signals No change needed. They do not use the TTL.
none / manual-only Guarded. A policy that is off never gets a schedule from the 1h swap. Test and mutation added.

Decided by the owner

Credential hold. About 2 hours for a 1-hour thread is accepted. The schedule stays as it is. The proxy holds the caller's key and the last request (conversation content) in memory until the hard deadline, (K+1) x idle:

Thread Default Maximum
5-minute about 14 min 58 min (override band)
1-hour, auto / 1-ping 118 min 236 min at K=3
1-hour, 2-ping 177 min 236 min at K=3
  • keepalive_max_pings_1h is capped at 3 (validation and a clamp).
  • The consent copy, the arm dialog and max_hold_minutes_1h in the ctl API state these numbers.
  • A session override applies its ping count to a 1-hour thread, downward only. The 1-hour timing stays the account's, because the override's 60-290 s band cannot express an hour. Tested, and confirmed by mutation (TestOverrideOnAOneHourThreadUsesTheOneHourTimingAndBoundsTheCount).

Open questions

  1. 60-second margin. A ping at 59 min leaves about 60 s. If the cache clock starts earlier than assumed, or ping latency is high, a ping can land on an expired cache and pay a 2.0x rewrite. The data comment keeps 59 min (comment). Check Investigate Prompt Cache TTL Differences: Claude Code and Codex Subscriptions vs API #489 data before moving it.
  2. Subscription limits. The data counts cache reads and writes at billing ratios. I could not verify the limit counts them the same way.
  3. Name 1-hour-head. It is not a ping count, so I kept it.
  4. Old binary. With an old proxy, a 2-ping install starts only after the retry, and a 1-hour cache is pinged on the 5-minute schedule until /context-guru:update.

Technical notes

  • keepalive.ResolveTier decides the tier at record time. Policy.ForOneHour swaps Idle and MaxPings and clamps K to 3. kaEntry.hold() is the one source of the hold and of the retention timer. Keeper.holdFor gives a manual-only hold its tier-specific length.
  • keeper.tier1h is read before the gates and written beside turns, so refused requests do not grow it.
  • Dash: keepaliveCreditFloorMs and kaSaved use the returning row's cache_ttl (what the request asked) as the tier signal. No schema change. A gateway that downgrades a 1h ask still gets credit only for real hits.
  • settings.py omits _1h keys equal to the proxy default, and strategy sync --legacy-binary keeps them out (marker line 1h-keys-omitted).
  • apply.AllBreakpointsAskExtendedTTL counts breakpoints with ttl: "1h" against all breakpoints.
  • Not in this PR: dash and stats views still show the 5-minute idle_seconds. The settings form does not expose the two new keys.

Read the cache lifetime per thread from the traffic. A thread is a 1h
thread when every breakpoint asks ttl 1h and the response billed the
1h tier for the whole write. Anything else keeps the 5m schedule.

Name strategies by ping count: auto (default), 1-ping, 2-ping. The old
name 5-min-ping stays as an alias of auto. Default per TTL: 5m cache
keeps today's schedule (270 s, 2 pings); 1h cache gets 1 ping at 59 min.
The 59 min value is one constant in internal/modelinfo.

Refs #505

Assisted-By: Claude <[email protected]>
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.

Changes needed. The design is right and the tests pass. Three problems must be fixed before merge: an upgrade break, an unbounded credential hold, and a dashboard that will call the feature a loss.

What I verified (works)

  • Tier rule (every breakpoint asks 1h and the whole write billed 1h) is correct. Partial bill, downgrade (#330), and mixed ask fall back to 5m. A pure-read turn inherits. Threads are keyed separately (kaThreadKey).
  • none still stops all pings: pol.on() runs before forOneHour() (proxy/keepalive.go:818-828).
  • Old names resolve in settings.py, install.sh, insights.py. Codex 30-min-ping is untouched.
  • Ping cost already uses CostWithCacheWrite1h. No double count found.
  • Fail open holds: resolveTier is pure and returns false (5m) on any doubt.
  • Timing: the ping clock starts at request START, as before. Slack is about 58 s. I could not check this live (no live test on PRs). I would keep 59 min and check #489 data before moving it.

Findings

1. Plugin update breaks the proxy for users on an old binary (blocking)

  • What: auto, 1-ping and 2-ping write keepalive_idle_seconds_1h and keepalive_max_pings_1h into the generated YAML (context-guru-plugin/scripts/settings.py:3272). The plugin and the binary ship separately.
  • Why it fails: config.LoadBytes is strict (config/config.go:295, KnownFields(true)). An old binary rejects the new keys and exits.
  • Evidence: I loaded that YAML with the origin/main loader. Result: field keepalive_idle_seconds_1h not found in type config.CacheConfig (and the _max_pings_1h key).
  • Impact: start-proxy.sh recovers only from unknown preset (section 3b). Every default install that updates the plugin first has a dead proxy. Claude Code stays routed to it.
  • Fix (pick one): omit the _1h keys when they equal the defaults (the proxy default applies anyway; only 2-ping needs a key); or teach 3b to re-render without them on not found in type; or gate on the binary version.

2. Credential hold grows from 14 min to 118-177 min with no cap (blocking)

  • What: a 1h thread holds the caller's key and conversation for (K+1) x 59 min: 118 min for auto, 177 min for 2-ping.
  • Contradicts the code's own limits:
    • Consent text in the Settings form says "up to about 14 minutes" (dash/ui/app.js:7284). It is now wrong for 1h threads.
    • maxOverrideHold = 1h and the comment "the real ceiling on the hold is 58 minutes" (proxy/keepaliveoverride.go:61-73). The arm dialog shows the user max_hold_minutes: 60.
    • OpenAI is explicitly capped to one hour (overrideForOpenAI). The 1h Anthropic tier already has a cap of 3 pings (maxOverridePings1h, keepalivestrategy.go:173).
  • Concrete failure: a user arms a session override with hold 14 min. The dialog says 14 min. The 1h thread ignores the override pair (forOneHour swaps in Idle1h/MaxPings1h) and holds 118 min.
  • Also: keepalive_max_pings_1h has only a < 0 check (config/config.go:246). A value of 100 holds a credential for about 4 days.
  • Fix: cap keepalive_max_pings_1h (3 matches the existing 1h band). Update the consent copy and the arm dialog to state the 1h hold. Decide on the override rule and test it: either the override also bounds a 1h thread, or the dialog says it does not.

3. The dashboard will report the 1h ping as a loss, and insights will tell users to turn it off (blocking for the owner's goal)

  • What: kaSaved only credits a rescued request within providerCacheTTLMs (5 min) after a ping row (dash/keepalive.go:171). For a 1h thread the ping is at 59 min. A user who returns at 80 min was rescued, but the credit is zeroed (64 min < 80 min).
  • Result: ping cost counts, credit does not. insights.py:1148 then emits keepalive-underwater and suggests cache strategy: none.
  • Also stale: dash/event.go:930-949 says the 1h floor is missing and "Inert today". This PR makes it live. The comment is now false.
  • Write path: credit uses the 1.25x miss rate; a 1h entry misses at 2.0x. That under-credits (safe direction). The 5-min floor also credits a return in the 59-60 min window that would have survived; that is small.
  • Evidence: by reading the code. I did not run a dash test. The PR says dash is not in scope; I think it must be, or this needs a tracked issue and a note in the docs before release.

4. The "every breakpoint asks 1h" half of the rule is not tested

  • I deleted !apply.AllBreakpointsAskExtendedTTL(body) from resolveTier. All 7 new tests still pass. The mixed-ask case passes only because its bill is partial (600 < 1200).
  • The check matters on a pure-read turn (no bill): a 1h thread followed by a mixed-ask read-only turn must go back to 5m. No test covers it.
  • Reverting the billing check (return true) does fail .../1h_asked,_gateway_downgraded. That half is covered.
  • Missing tests: main thread (1h) and a: subagent thread (5m) in the same session; none with a 1h thread; session override with a 1h thread; the 118 min hard timer.

5. tier1h is not bounded as stated, and the reset loses the current key

  • proxy/keepalive.go:885 resets tier1h right after line 823 set it for this key. Next pure-read turn on that thread falls back to 5m.
  • tier1h is written before the paths that return without turns++ (thinking enabled, ineligible model). The size check lives only on the turns path, so the map can grow past maxKeepAliveTurnKeys.
  • Fix: keep key when resetting, or make tier1h part of the same bounded structure as turns.

Open questions in the PR

  • 58 vs 59 min: keep 59 (see above).
  • Manager strategies and overrides on 1h threads: see finding 2. Not a bug for none.
  • 1-hour-head: keep the name.

Tests I ran (eval box 1, -race, CGO_ENABLED=1)

  • go test ./proxy -run 'OneHour|FiveMinute|PureRead|TwoTiers|AllBreakpoints': 7 tests pass. (The suggested Keepalive pattern matched no new test.)
  • go test ./config ./apply ./internal/modelinfo ./proxy ./dash ./cmd/...: all 7 packages ok.
  • go test ./context-guru-plugin: ok (one full run, no port flakes).
  • Mutations: removing the all-breakpoints check, 0 failures (finding 4). Billing check to return true, 1 failure (expected).
  • Skew check: old origin/main loader rejects the new YAML keys (finding 1).

"keepalive_max_pings": 2,
"keepalive_max_usd_per_ping": 0.50,
"keepalive_min_prefix_tokens": 80000,
"keepalive_idle_seconds_1h": 3540,

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.

Finding 1: an old proxy binary rejects this key (strict YAML, config/config.go:295). Every default install that updates the plugin before the binary gets a proxy that will not start. Omit the _1h keys when they equal the default.

Comment thread config/config.go
c.KeepAliveMaxPings < 0 || c.HeadTTLMinTokens < 0 ||
c.KeepAliveMaxUSDPerPing < 0 || c.KeepAliveMinPrefixTokens < 0 {
c.KeepAliveMaxUSDPerPing < 0 || c.KeepAliveMinPrefixTokens < 0 ||
c.KeepAliveIdleSeconds1h < 0 || c.KeepAliveMaxPings1h < 0 {

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.

Finding 2: keepalive_max_pings_1h has no upper bound. 100 holds the caller's credential for about 4 days. The existing 1h band caps at 3 (maxOverridePings1h).

Comment thread proxy/keepalive.go Outdated
e.turn = k.turns[key] - 1
if len(k.turns) > maxKeepAliveTurnKeys {
k.turns = map[string]int{key: k.turns[key]}
k.tier1h = map[string]bool{}

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.

Finding 5: this wipes the tier that line 823 just set for the current key. The next pure-read turn on this thread falls back to 5m.

- Plugin/binary skew: write a 1-hour config key only when it differs
  from the proxy default, and have start-proxy.sh drop the keys and
  retry when an older binary rejects them.
- Credential hold: cap keepalive_max_pings_1h at 3 (236 min), clamp it
  in forOneHour, state the per-tier hold in the consent copy, the arm
  dialog and the ctl API. An override does not change a 1h schedule.
- Dashboard: the credit floor and kaSaved window follow the row's
  cache_ttl, so a 1h rescue is credited and insights stays honest.
- tier1h: write it beside turns, keep the current thread on reset,
  and never grow it on refused requests.
- Tests for each, confirmed by mutation.

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

Copy link
Copy Markdown
Collaborator Author

All findings fixed in a4cdb06. Full proxy, dash, config, apply and plugin suites pass on box 1.

  1. Upgrade break. Two layers. settings.py writes a _1h key only when it differs from the proxy default, so auto and 1-ping load on any binary. start-proxy.sh also recognises field keepalive_..._1h not found, re-renders with strategy sync --legacy-binary and retries. Test: TestAnOldProxyThatRejectsTheOneHourKeysStillStarts (a stub binary with the old strict loader). I chose both because omission avoids the failed start in the common case, and the retry covers 2-ping and future keys.
  2. Credential hold. keepalive_max_pings_1h is capped at 3 (config validation, and a clamp in forOneHour), so the hold is at most 236 min. Consent copy, arm dialog and max_hold_minutes_1h in the ctl API now state the per-tier hold. An override does not change a 1-hour thread's schedule (tested). The numbers are in the PR body under Open questions for the owner.
  3. Dashboard. The write-side credit floor and the kaSaved window follow the row's cache_ttl. The stale comment in dash/event.go is rewritten. Tests: TestKeepAliveCreditFloorFollowsTheRequestsTier, TestKaSavedCreditsAOneHourRescue, and TestInsightsDoesNotCallAOneHourRescueALoss.
  4. Test gaps. Added: mixed ask on a read-only turn, main 1h + subagent 5m, none on a 1h thread, override on a 1h thread, the hold per tier. Each was confirmed by mutation; the list is in the PR body.
  5. tier1h. Written beside turns, so refused requests do not grow it. A reset keeps the current thread. Test: TestTierMemoryIsBoundedAndKeepsTheCurrentThread.

The override bounds a 1-hour thread's ping count downward; the 1-hour
timing stays the account's. The arm dialog and ctl API state the hold.
Owner accepted a hold of about 2 hours for a 1-hour thread.

Assisted-By: Claude <[email protected]>
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.

Looks good, with one doc fix and two small follow-ups. All five round-1 findings are fixed. I re-ran the tests and two of the author's mutations myself.

Round-1 findings

  1. Upgrade break: fixed. settings.py now omits a _1h key that equals the default, so auto and 1-ping load on any binary. start-proxy.sh retries once with --legacy-binary for 2-ping. Test: TestAnOldProxyThatRejectsTheOneHourKeysStillStarts passes.
  2. Credential hold: fixed. keepalive_max_pings_1h is capped at 3 in config validation and by a clamp in forOneHour. Hold is 118 min default, 236 min at most. Consent copy, arm dialog and max_hold_minutes_1h state it. I removed the clamp: TestCredentialHoldPerTier fails.
  3. Dashboard credit: fixed. The write-side floor (dash/event.go:899) and kaSaved (dash/keepalive.go:172-177) follow the row's cache_ttl. The stale "Inert today" comment is gone.
  4. Test gaps: fixed. I removed the all-breakpoints check: TestMixedAskOnAReadOnlyTurnGoesBackToFiveMinutes fails now (it passed in round 1).
  5. tier1h bound: fixed. It is written beside turns, and the reset keeps the current thread.

Your checks

  • (a) Override on a 1h thread: safe, and shown. none still wins, because pol.on() runs first. The override still enables the session and sets the prefix floor. The arm dialog and the armed-list hint say a 1h cache keeps the account schedule. One gap: the worst-case spend the server quotes at arm time uses the override's K. A 1h thread can run up to K=3 from the account. The cost guard per ping still applies. Not blocking.
  • (b) Gateway downgrade cannot over-credit. cache_ttl is what the request asked for (dash/event.go:220). If a gateway bills 5m for a 1h ask, the floor rises to 60 min, so the credit falls. Credit also needs CacheRead > 0 on the returning request, so an expired entry earns nothing. The only over-credit case: a return that asks 5m after a 1h thread, in the 59-60 min window. That is tiny.
  • (c) --legacy-binary retry: no loop, cannot hide the real error. It is one if, one retry, then the preset path and the named diagnostics still run. Two issues, both minor:
    • $LOG is append-only (>>). A stale field keepalive_..._1h not found line from an earlier start still matches after the user updates the proxy. A later unrelated start failure then rewrites the config and prints the wrong note. The log still holds the real error.
    • The legacy marker is sticky. strategy sync keeps omitting the keys while the marker is in the file (settings.py:3585). After a proxy update, 2-ping stays at 1 ping on a 1h cache until someone runs strategy set. The comment says a later update renders afresh; only strategy set does. Fix: have sync drop the marker when the binary is newer, or read only the last launch's log lines.
  • (d) PR body: not fixed. "Credential hold per tier (owner decision)" is still listed under Open questions and asks "Is 118 min the right default?". Move it to a Decided line: "Owner decision: a hold of about 2 hours on a 1h thread is acceptable." Question 2 (override turning pings off) is also still open; say so or close it.

Tests (eval box 1, -race, CGO_ENABLED=1)

  • ./config ./apply ./internal/modelinfo ./proxy ./dash ./cmd/...: 7 packages ok.
  • ./context-guru-plugin: ok.
  • Mutations: all-breakpoints check removed, 1 failure (TestMixedAskOnAReadOnlyTurnGoesBackToFiveMinutes). MaxPings clamp removed, 1 failure (TestCredentialHoldPerTier). Both expected.

@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.

Looks good at af2a43f. The override change is correct and tested. This updates my last review.

  • Override on a 1h thread: fixed and safe. overrideFor now sets MaxPings1h = min(account K1h, override K) (proxy/keepaliveoverride.go:187-196). It can only lower the count. The 59-min timing stays. none is unchanged (pol.on() runs first). The arm dialog and the armed-list hint now show (min(K,3)+1) x 59 min. That matches the code.
  • Spend quote gap I raised: closed. The worst-case quote uses the override K. The 1h thread can no longer exceed it.
  • PR body (d): fixed. The hold is now under "Decided by the owner".
  • Mutation: I replaced the min with a no-op. TestOverrideOnAOneHourThreadUsesTheOneHourTimingAndBoundsTheCount fails, as it should.
  • Still open from last review (minor, not blocking): stale $LOG text can fire the --legacy-binary retry later, and the legacy marker stays in the file until strategy set.

Tests (eval box 1, -race): ./proxy, ./dash, ./config all ok.

… version

- start-proxy.sh reads only the log written by the current launch, so a
  rejection from an earlier run cannot trigger the recovery.
- The legacy marker records the proxy version. After an update the
  1-hour keys are written again.

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

Copy link
Copy Markdown
Collaborator Author

Thanks. Already covered by af2a43f: point (d), and the arm-time K gap. A session override's ping count now bounds a 1-hour thread downward, and the arm dialog and ctl API state the hold.

The two minor items under (c) are fixed in 6de7ccf:

  1. Stale log line. start-proxy.sh records the log size before each launch and greps only the bytes written after it. Test: TestAStaleLogLineDoesNotTriggerTheOneHourRecovery. It fails if the offset is removed.
  2. Sticky legacy marker. The marker now records the proxy version it was written for. strategy sync keeps the 1-hour keys out only while the installed version (the proxy-version file) is the same. After an update the keys come back. Test: TestTheLegacyMarkerEndsWhenTheProxyIsUpdated. It fails if the marker ignores the version.

./context-guru-plugin passes with -race on box 1.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Moved to the next release by the release owner. v0.5.3 is out without it. It needs a rebase on main before review.

Main moved the keeper core into package keepalive and added the manual
ping (#655), the manual-only hold (#666), predictive campaigns and the
per-tenant builder. This merge keeps those and re-applies the TTL-aware
schedule in the new package:

- keepalive: ResolveTier, Policy.ForOneHour, per-thread tier1h,
  entry.hold(), MaxHold1h.
- Manual-only hold lives 59 min on a 1h thread (ManualHoldMax1h), 300 s
  otherwise. A press still never extends it.
- Campaigns and overrides bound a 1h thread's ping count downward.
- Tests for each interaction, confirmed by mutation.

Assisted-By: Claude <[email protected]>
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.

Changes needed. The merge kept every #512 guarantee. One consent text is now false: the manual-only hold says 5 minutes, but a 1h thread holds the key for 59 minutes.

Guarantees after the move to keepalive/

All kept. Each has a test in keepalive/ttl_test.go or proxy/keepalive_ttl_test.go.

  • Tier from the billed write: ResolveTier (keepalive/keeper.go). OpenAI is excluded.
  • All-breakpoints rule, 59-min 1-ping default, 5m path, none stays off (ForOneHour never sets KeepAlive, gated by pol.On()).
  • Cap of 3 and hold per tier (hold(), MaxHold1h).
  • tier1h written beside turns, reset keeps the current thread, cleared in Forget and Shutdown.
  • Campaign (proxy/predictive.go) and override bound the 1h count with min, never raise it, never set the timing.
  • Manual ping on a 1h thread works past 5 min. PingNow follows the entry's own hold.

Finding (blocking): consent text for the manual-only hold is stale

  • What: ManualHoldMax1h makes a manual-only hold last 59 min on a 1h thread (keepalive/manualhold.go). Three texts still say 5 minutes:
    • context-guru-plugin/scripts/install.sh:1246 (ping_note): "up to 5 minutes ... drops the copy 5 minutes after your last request".
    • docs/dashboard.md:153-156: "at most 300 seconds ... even for a one-hour cache". The code now does the opposite.
    • context-guru-plugin/scripts/settings.py:59: "at most 300 s".
  • Why it matters: the install writes the x-context-guru-ping: 1 header by default. On a Claude subscription every main-thread request is 1h. A user with strategy none is told 5 minutes. The proxy holds their key and conversation for 59 minutes, 12 times longer. This is the consent act, and it is given on a false number. The auto-keep-alive consent copy was updated; this one was missed.
  • Fix: say "up to 5 minutes, or 59 minutes when your cache lasts 1 hour" in all three places. The PR body says the consent copy is updated for the hold, so this should match.
  • Safety of the change itself: acceptable. It stays opt-in per request, no ping is ever sent for it, a press never extends it, and the per-tenant caps (16 threads, 32 MiB) still apply. The owner has accepted about 2 hours for the auto hold; 59 min is shorter.

Tests and mutations (eval box 1, -race, new dir scratch-review-512-merge)

  • go test -race ./keepalive/... ./proxy -run 'OneHour|FiveMinute|PureRead|TwoTiers|AllBreakpoints|Manual|Campaign|Hold|None|Override|Armed|TierMemory|MainThread|Mixed': 120 tests pass, 2 packages ok (./keepalive, ./proxy).
  • Mutation 1, remove the all-breakpoints check in ResolveTier: TestMixedAskOnAReadOnlyTurnGoesBackToFiveMinutes fails.
  • Mutation 2, disable ManualHoldMax1h in holdFor: TestManualHoldFollowsTheThreadsTier/1-hour_thread and TestManualPingOnAOneHourThreadWorksPastFiveMinutes fail.
  • Not run at this head: ./dash, ./config, ./context-guru-plugin. The merge did not change their logic.

The manual-only hold lasts 300 s on a 5-minute cache and up to 59 min
on a 1-hour cache. Five texts still said 5 minutes. Fix the install
consent note, the install skill, the dashboard doc, the data-dependence
doc and the settings.py comment, plus two Go comments. The install
test now pins the per-tier wording.

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

Copy link
Copy Markdown
Collaborator Author

Fixed in 1037c71. Each text now states the manual-only hold per tier: 300 s after the last request on a 5-minute cache, up to 59 minutes on a 1-hour cache, and a press never extends it.

  1. context-guru-plugin/scripts/install.sh ping_note
  2. context-guru-plugin/skills/install/SKILL.md, the line that tells the model to relay ping_note
  3. docs/dashboard.md, which said "even for a one-hour cache"
  4. context-guru-plugin/scripts/settings.py, the comment on the header
  5. docs/data-dependence.md, the keep-alive row (found by grep, it said 300 seconds)
  6. Two Go comments: keepalive/types.go and keepalive/keeper.go

TestInstallSaysWhatThePingHeaderMeans now pins the per-tier wording. It fails if the note drops the 1-hour hold.
./context-guru-plugin and ./keepalive/... pass with -race on box 1.

@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 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 1037c71c3ead approve

Verdict: approve

Findings

None. The PR correctly implements one-hour cache tier support for the keep-alive mechanism.

Non-blocking

  • OpenAI exclusion at keeper.go:763 — The tier decision excludes OpenAI with && provider != bschemas.OpenAI. OpenAI supports prompt caching, but this exclusion is deliberate. Consider adding a comment explaining why OpenAI is excluded (different TTL semantics, incomplete support, or other reason).

  • Stale tier memory edge case — After a mixed-ask read-only turn (test at ttl_test.go:136), the tier1h map entry stays true from the previous turn but the entry's policy is not swapped to ForOneHour. This is correct: the policy on the entry determines the schedule, and the stale tier memory is overwritten on the next write. The subtlety is worth a comment at keeper.go:800-806 explaining that a read-only turn with a changed ask leaves tier1h stale but harmless.

What I checked

  • Read CLAUDE.md and docs/design.md for repo rules
  • Read the full diff (keeper.go, ttl_test.go, types.go, manualhold.go, substitute.go, apply.go, proxy integration)
  • Verified ResolveTier logic: checks all breakpoints ask 1h, and all writes were billed 1h (or inherits prev for read-only turns)
  • Verified tier1h map: bounded at MaxTurnKeys, reset keeps current thread, written only when appropriate
  • Verified Policy.ForOneHour: swaps Idle/MaxPings to 1h values, deliberately does not touch KeepAlive (so parked policies stay off)
  • Verified manual hold: extended to ManualHoldMax1h (59 min) for 1h threads via holdFor
  • Verified test coverage: 1h schedule, 5m schedule preservation, read-only inheritance, mixed ask, subagent threads, manual-only holds, credential hold durations, tier memory bounds, manual ping, override/campaign interactions
  • Verified AllBreakpointsAskExtendedTTL: walks all cache_control objects, returns true only if all ask 1h
  • Checked fail-open: no new panic paths, existing recovers preserved
  • Checked data loss: tier memory is bounded and reset, no customer data stored
  • Checked security: tier decision based on trusted inputs, no new credential handling

@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 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 1037c71c3ead approve

Verdict: approve

Findings

None. The implementation is correct and complete.

Non-blocking

None.

What I checked

  • Core tier detection logic (keeper.go:202-210, ResolveTier): Requires both request (all breakpoints ask 1h) AND billing (CacheWrite1h >= CacheWrite). Read-only turns inherit the previous tier. Fails open to 5m on any doubt. OpenAI is excluded (they do not support 1h tier). Correct.

  • Policy swap (keeper.go:765, types.go:176-191): ForOneHour() only swaps schedule when pol.On() is true. Never sets KeepAlive, so parked policies stay parked. Explicit 1h schedules (Idle >= 300s) are left alone. MaxPings is capped at 3. Correct and tested (ttl_test.go:169-186).

  • tier1h map lifecycle (keeper.go:760-815): Bounded at MaxTurnKeys. Written only when usageOK && (CacheWrite > 0 || ttl1h). Reset keeps current thread. Read before lock release is safe (no race). Correct.

  • Manual hold duration (keeper.go:842, manualhold.go:26-50): Uses k.holdFor(ttl1h) which returns ManualHoldMax1h (59 min) for 1h threads, ManualHoldMax (300s) for 5m threads. Correct and tested (ttl_test.go:264-291).

  • Fail-open paths: ResolveTier returns false on any doubt (no usage, mixed ask, no write and no prev). The 5m schedule is used. Policy.ForOneHour() is only called when ttl1h is true. Manual-only holds with keep-alive off stay off. All fail-open paths preserve existing behavior. Correct.

  • Test coverage (keepalive/ttl_test.go, proxy/keepalive_ttl_test.go): 15 new tests cover 1h schedule, mixed asks, read-only turns, tier inheritance, manual holds, overrides, campaigns, and tier memory bounds. Comprehensive.

  • Data dependence: No new stored customer data. The tier1h map holds one bool per thread key, bounded and reset like turns. Correct.

  • Security: No credential handling changes. The 1h hold extends ManualHoldMax to 59 min for 1h threads, which is still bounded and documented. Correct.

  • Reversibility: No lossy changes. The tier detection is pure (request + billing). Correct.

  • All changed lines verified: keeper.go (tier detection, policy swap, tier1h map, manual hold), types.go (Policy.ForOneHour, MaxHold1h), manualhold.go (holdFor, ManualHoldMax1h), usage.go (CacheWrite1h field), apply.go (AllBreakpointsAskExtendedTTL), substitute.go (cachePhaseAt signature), keepalivectl.go (max_hold_minutes_1h), keepaliveoverride.go (MaxPings1h bound), predictive.go (MaxPings1h bound), modelinfo/cachefrac.go (constants), and all tests. All correct.

@amiddavid
amiddavid merged commit a1b24ad into main Oct 22, 2026
10 of 12 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 22, 2026
OsherElhadad pushed a commit that referenced this pull request Oct 25, 2026
…0.2.5)

Both plugins changed in this release, so installed plugins must update.

- Claude Code plugin: 0.6.0 was set in #694. No change here.
- Codex plugin: 0.2.4 to 0.2.5. The vendored cg.py and costly.py
  and one skill changed in #512, #681, #683, #691, #694 and #698.

Assisted-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Osher Elhadad <[email protected]>
amiddavid pushed a commit that referenced this pull request Oct 26, 2026
…0.2.5) (#701)

chore(plugin): bump the plugins for v0.6.0 (Claude Code 0.6.0, Codex 0.2.5)

Both plugins changed in this release, so installed plugins must update.

- Claude Code plugin: 0.6.0 was set in #694. No change here.
- Codex plugin: 0.2.4 to 0.2.5. The vendored cg.py and costly.py
  and one skill changed in #512, #681, #683, #691, #694 and #698.

Assisted-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Osher Elhadad <[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 pings a 1-hour cache every 4.5 minutes on Claude subscriptions

1 participant