Skip to content

The prompt cache stays warm through long tool runs (always on; Nous Portal, OpenRouter, Anthropic) - #122094

Closed
teknium1 wants to merge 11 commits into
mainfrom
pi-port/cache-warming
Closed

teknium1 wants to merge 11 commits into
mainfrom
pi-port/cache-warming

Conversation

@teknium1

@teknium1 teknium1 commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

When a tool runs longer than the prompt cache lasts (a build, a test suite, sleep 330), the next request today pays to write the whole conversation into the cache again. Hermes now sends one tiny keep-alive copy of the last request just before the cache expires, so the next request reads the cache instead. It is always on and there is nothing to configure.

Reads the shared cache clock from #156101.

Outcome: a long tool round no longer turns the next Claude request into a full-price cache write, on Nous Portal, OpenRouter and native Anthropic.

Before / after (live: real hermes chat -q, Opus 5.5 on Nous Portal, one sleep 330 tool call, cache_ttl: 5m, no warming config)

main d1b46d718ff (earlier round) this PR, c4e4054e891 (pre-clock) this PR, afcd7793812 (reads the clock, on main 4162ecf11f)
when the keep-alive fires n/a own TTL math: 90% of 5 min from send clock said warm_until 12:44:50 (5m, route_ceiling_5m, declared); keep-alive sent 12:44:22
keep-alive request none 1, 18,643 read, 0 written, $0.0038 1, 12,228 read, 0 written, $0.0025 (task=cache_warm row, carries the clock column)
request after the tool cache hit 62% (11,231 / 18,198), 6,965 re-written cache hit 99% (18,643 / 18,752) cache hit 99% (12,228 / 12,341), 111 written
stop logged n/a new request in flight (refreshes=1, spent=$0.0038) new request in flight (refreshes=1, spent=$0.0025)
session estimated cost (state.db) $0.0753 $0.1029 $0.0684 (first request a cold 12,228-token write)

Same control as before (Haiku 5.5 Reply with just: ok): the warmer refused, expected savings below threshold.

Miss case (stub-driven, not live): a refresh can't be forced to miss on a real provider from outside, so the miss row comes from a local Chat Completions stub, called through the real OpenAI client, that bills every refresh as a 120,000-token cache write.

earlier head d46c2c21371 this PR
refreshes sent while every one misses 2 of 2 fired, still scheduled 1, then inactive
estimated cost of those refreshes $1.50 (each costed at write price, run kept going) $0.75, then stopped
log prompt cache warmed (#2): cache_read=0 write=120000 prompt cache warming stopped: cache refresh missed (read=0, write=120000, cost=$0.7500) (refreshes=1, spent=$0.7500)

Control: on the earlier head, the same prompt with sleep 5 sent no keep-alive. Live spend on the clock round: $0.070 (one sleep 330 Opus run $0.068 plus the Haiku control $0.0015).

Why the gateway clamp: on Nous Portal a ttl: "1h" entry was measured gone after 7 minutes, the same as a 5-minute entry. So off native Anthropic the keep-alive runs on the 5-minute schedule whatever cache_ttl asks for. Native Anthropic keeps its configured tier.

What was removed, and why

  • Idle mode is deleted (code, constants, docs, tests). It kept warming after the turn ended, betting (at p = 0.15) that you reply within the TTL. That is speculative spend. Every turn exit now cancels the warmer.
  • prompt_caching.cache_warming is gone. Warming during a running turn has no real tradeoff: the next request is certain, a keep-alive costs about 1/12 of the write it prevents, and the economics gate already refuses small prompts, unpriced routes and subscription-included routes. Warming follows prompt caching itself: a request with no cache_control markers (caching off, non-Claude) is never warmed.

Spend guards (fix round)

  • A refresh that misses stops the run. After each refresh its own usage is read: cache_read == 0 or cache_write > 0 means the entry was already gone or re-written, so warming stops for that turn and says why. Missing usage or an unknown cost also stops it.
  • The cap counts what was billed. The refreshes of one run may never cost more in total than the single cache write they prevent. The total is the sum of each sent refresh's estimated billed cost (estimate_usage_cost on its usage), not (n+1) × an assumed read cost. Each refresh is priced as a cache read of the cached prefix plus the uncached tail at the full input rate, and is reserved at no less than what the last one was billed.
  • Every stop reason is logged at INFO, once per change of reason, with the refresh count and spend. Routine stops of a run that sent nothing (next request, turn end) stay at DEBUG.
  • Usage goes to the session that sent the refresh. The run snapshots its session and billing route when it arms. A refresh still in flight when compression rotates the session writes its state.db row to the old session, and still counts in the agent's running totals (compression keeps them; only a session reset zeroes them).
  • Cache lifetime has one source: the shared cache clock. The warmer asks prompt_cache_clock.cache_window for the session's guaranteed-warm deadline and refreshes shortly before it. A window the clock does not call certainly warm (unknown, a gateway asked for an untrusted 1h, the cache moved, already past) arms nothing. Each refresh is folded back into the clock (its row carries prompt_cache_clock), so /context shows the window it bought and the next refresh is due from that deadline. The warmer's own TTL math (warm_ttl_seconds, its TTL_SECONDS, the send-time anchor) is deleted. Route ceilings now decide the gateway clamp (Nous ships 5m), so lifting a ceiling needs no warmer change.

Changes

  • agent/prompt_cache_warmer.py::PromptCacheWarmer: a timer at 90% of the lifetime that replays the exact request (deep-copied) with max_tokens=1, no stream, max_retries=0 and a 60 s timeout. It uses the agent's Anthropic client or its Chat Completions client, sends X-OpenRouter-Cache: false, and times its first refresh from the attempt's own send time.
  • Economics: miss − warm ≥ $0.05 from usage_pricing.get_pricing_entry, the billed-cost cap and miss stop above, and a one-hour age limit. Budget-based thinking is skipped.
  • Wiring: arm after each response (turn_response_check), cancel before each real request (turn_api_request.build_request_payload), cancel on every turn exit (conversation_loop.run_conversation's finally), on release_clients and on close(). Cache-parity forks opt out (_skip_prompt_cache_warming).
  • Accounting: tokens and dollars go into the session totals and state.db, never into the compressor, usage anchors or session_api_calls.
  • Docs: user guide (configuration.md, no key) and developer guide.

Validation

Check Result
tests/agent/test_prompt_cache_warmer.py 20 passed. Clock round, both red on the pre-clock code: test_warming_follows_the_shared_clock_and_never_warms_without_a_guarantee, test_a_refresh_moves_the_clock_and_the_next_one_is_due_from_its_new_deadline. Earlier rounds: New and each red on the commit before its fix: test_a_refresh_that_misses_the_cache_stops_warming_and_says_why and test_the_spend_cap_counts_what_refreshes_were_billed_not_an_assumed_read (both use a local HTTP stub through the real OpenAI client), test_every_stop_reason_is_logged_once_at_info, test_an_uncached_tail_is_priced_at_the_input_rate, test_a_refresh_in_flight_when_the_session_rotates_is_booked_where_it_was_sent[_compress/_new_session]
tests/agent/ + tests/hermes_state/ (1,431 files) 16,267 passed, 86 skipped; 1 collection error unrelated (test_vault_key_storage.py: keyring not installed in the local env)
scripts/check --only health, ruff ok
Live run + stub miss case above hit row live, miss row stub-driven

Not covered: native Anthropic (api.anthropic.com; this install has no Anthropic API key), an OpenRouter leg (the key is expired; an earlier OpenRouter run on this PR showed 68% → 100%), and a live miss (it can't be forced from outside, so the stub covers it).

Infographic

cache kept warm


Rebuilt onto current main by cherry-picking the original 4 commits; streaming warming made unconditional per the maintainer's call. A fix round then added the miss stop, the billed-cost cap and the stop logging. Awaiting review — not merged.

@teknium1 teknium1 added the ci-reviewed applied to manually approve dangerous changes label Sep 25, 2026
@alt-glitch alt-glitch added type/feature New feature or request P3 Low — cosmetic, nice to have comp/agent Core agent runtime: loop, agent_init, prompt builder, context-compression, responses endpoint provider/anthropic Anthropic native Messages API area/config Config system, migrations, profiles sweeper:risk-caching Sweeper risk: may break/degrade prompt caching or cache-key stability (invariant) sweeper:risk-compatibility Sweeper risk: may break existing users, config, migrations, defaults, or upgrades labels Sep 25, 2026
@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

૮ >ﻌ< ა ci review

ran on 613cfd7 — fix(agent): keep-alives fire the auxiliary call events, neve

ℹ️ Info

CI caches · View report · View job

27 / 27 cache hits (0 misses)
4397.41 MiB restored
0 B not restored.

per-job cache results

hits

JobStepLogsRestoredΔ vs main
Repository guards / Repository guardsRun ./.github/actions/setup-pm / Restore verified PM tools without savingview step156.33 MiB+0 B
Repository guards / Repository guardsRun ./.github/actions/setup-pm / Restore uv dependency downloads and buildsview step42.63 MiB+0 B
Repository guards / Repository guardsRun ./.github/actions/setup-pm / Restore node dependency downloadsview step181.19 MiB+0 B
Python lints / Python lintsRun ./.github/actions/setup-pm / Restore verified PM tools without savingview step83.21 MiB+0 B
Docs Site / docs-site-checksSet up the locked site toolchain / Restore verified PM tools without savingview step156.33 MiB+0 B
Docs Site / docs-site-checksSet up the locked site toolchain / Restore node dependency downloadsview step92.97 MiBunknown
Python tests / Run tests (1/3)Set up locked Python and test dependencies / Restore verified PM tools without savingview step154.64 MiB+0 B
Python tests / Run tests (1/3)Set up locked Python and test dependencies / Restore uv dependency downloads and buildsview step42.63 MiB+0 B
Python tests / Run tests (1/3)Restore per-file duration cacheview step0.10 MiBunknown
Python tests / Run tests (2/3)Set up locked Python and test dependencies / Restore verified PM tools without savingview step154.64 MiB+0 B
Python tests / Run tests (2/3)Set up locked Python and test dependencies / Restore uv dependency downloads and buildsview step42.63 MiB+0 B
Python tests / Run tests (2/3)Run testsview step0.10 MiB+37 B
Python tests / Run tests (3/3)Set up locked Python and test dependencies / Restore verified PM tools without savingview step154.64 MiB+0 B
Python tests / Run tests (3/3)Set up locked Python and test dependencies / Restore uv dependency downloads and buildsview step42.63 MiB+0 B
Python tests / Run tests (3/3)Run testsview step0.10 MiB-44 B
OS-specific tests / macOS-only tests (2/2)Set up locked Python and test dependencies / Restore verified PM tools without savingview step107.21 MiB+0 B
OS-specific tests / macOS-only tests (2/2)Set up locked Python and test dependencies / Restore uv dependency downloads and buildsview step165.98 MiB+0 B
OS-specific tests / Windows-only testsSet up locked Python and test dependencies / Restore verified PM tools without savingview step236.12 MiB+0 B
OS-specific tests / Windows-only testsSet up locked Python and test dependencies / Restore uv dependency downloads and buildsview step101.52 MiB+0 B
OS-specific tests / Windows-only tests (arm64, 2/2)Set up native ARM64 build dependencies / Cache ARM64 OpenSSL development filesview step26.23 MiB+0 B
OS-specific tests / Windows-only tests (arm64, 2/2)Set up locked Python and test dependencies / Restore verified PM tools without savingview step222.51 MiB+0 B
OS-specific tests / Windows-only tests (arm64, 2/2)Set up locked Python and test dependencies / Restore uv dependency downloads and buildsview step855.57 MiB+0 B
OS-specific tests / Windows-only tests (arm64, 1/2)Set up native ARM64 build dependencies / Cache ARM64 OpenSSL development filesview step26.23 MiB+0 B
OS-specific tests / Windows-only tests (arm64, 1/2)Set up locked Python and test dependencies / Restore verified PM tools without savingview step222.51 MiB+0 B
OS-specific tests / Windows-only tests (arm64, 1/2)Set up locked Python and test dependencies / Restore uv dependency downloads and buildsview step855.57 MiB+0 B
OS-specific tests / macOS-only tests (1/2)Set up locked Python and test dependencies / Restore verified PM tools without savingview step107.21 MiB+0 B
OS-specific tests / macOS-only tests (1/2)Set up locked Python and test dependencies / Restore uv dependency downloads and buildsview step165.98 MiB+0 B

misses

none

Compressed archive bytes. Not-restored bytes use the main-size reference; missing sizes remain unknown.


debug info

CI timings

CI timings · View report · View job

Wall time 10m26s vs 9m13s (+13.2%). 4 job(s) slower, 8 faster, 1 unchanged.

  • OS-specific tests / Windows-only tests (arm64, 1/2): -113.0s
  • Python lints / Python lints: +51.0s
  • OS-specific tests / Windows-only tests (arm64, 2/2): -19.0s
  • OS-specific tests / Windows-only tests: -18.0s
  • OS-specific tests / macOS-only tests (2/2): -16.0s

@kiramakes

Copy link
Copy Markdown

Summary

Solid feature port — Anthropic prompt-cache warming with sensible economics gating.

Positives

  • prompt_cache_warmer.py is well-structured: clear phase separation (streaming vs idle), economics evaluation with MINIMUM_EXPECTED_SAVINGS_USD = $0.05 floor, and hard age limits (60 min streaming, 30 min idle).
  • is_replayable() correctly excludes budget-based thinking (budget_tokens) from replay — replaying with max_tokens=1 would change the budget key and be rejected by Anthropic.
  • has_cache_markers() walks the full request tree (system, tools, messages) — comprehensive.
  • Opt-in via config (cache_warming: "off"|"streaming"|"idle"), default off — safe default.
  • on_turn_settled() properly transitions streaming->stop and idle->continue with 30 min cap.
  • Status property exposes state, phase, next_warm_at, warm_count, decision — good for debugging/monitoring.

Suggestions

  • agent/prompt_cache_warmer.py:66 — IDLE_CONTINUATION_PROBABILITY = 0.15 is from pi's measured constant. Worth noting this is a rough heuristic; per-session estimation was tried and not better, but a future improvement could track actual continuation rates per session.
  • agent/prompt_cache_warmer.py:72 — WARM_REQUEST_TIMEOUT_S = 60.0 is a single HTTP round-trip timeout. If the Anthropic client has its own timeout configured, the warmer's timer could fire before the request completes. Consider whether this should coordinate with the client's timeout.
  • The _pricing() method is referenced but I didn't see its full implementation in the diff — confirm it handles unpriced models gracefully (the evaluate_economics function returns 0 cost for None rates, which is correct).

Questions

  • The start() method deep-copies api_kwargs via _replay_kwargs() — is the copy depth sufficient? Message dicts are mutated in place between requests (cache-marker redecoration, tool-result eviction), so the replay must be a true snapshot. Worth verifying _replay_kwargs does a deep copy, not shallow.

@Enough1122

Copy link
Copy Markdown
Contributor

AI code review — automated follow-up for reference; not a maintainer.

Scope of the anthropic_messages gate is wider than documented

The gate at agent/prompt_cache_warmer.py:192 tests only the wire name, and the stop reason
string it emits (:193), the module docstring (:15) and the user guide
(website/docs/user-guide/configuration.md:1395) all describe the warmed set as native Anthropic
(api.anthropic.com). But api_mode == "anthropic_messages" is not a native-Anthropic signal —
it is the Anthropic-wire transport name, and hermes assigns it to at least three more routes.

agent/agent_runtime_helpers.py:1720 grants caching to any Anthropic-wire Claude with the comment
# third-party Anthropic-compatible gateway:

if is_anthropic_wire and is_claude:
    return True, True  # third-party Anthropic-compatible gateway

and :1730 does the same for MiniMax on its Anthropic-compatible endpoint. So for those routes
_use_prompt_caching is True and native-block cache_control markers are in the request, which is
exactly what the remaining gates want. The same holds for Bedrock: hermes_cli/runtime_provider_backends.py:228
sets api_mode="anthropic_messages" for is_anthropic_bedrock_model(...) and not has_bearer_token, and
Bedrock Claude is "claude" in model_lower, so :1720 returns (True, True) there too.

All three therefore pass every check in start() (anthropic_messages at :192, _use_prompt_caching at
:194, cache markers at :202, budget-thinking at :204) and get a max_tokens=1 replay fired from a
daemon timer against their own endpoint. The economics gate does not catch this — it only reads
usage_pricing.get_pricing_entry, which prices Bedrock (:224-228) and third-party Claude routes
independently of the endpoint actually being warmed.

Why this matters

The replay is billed on whatever the resolved route bills. The author states the core premise in the
PR body — Anthropic refreshes a cache entry's TTL on read and does not key it on max_tokens — and
correctly flags that this install had no Anthropic-direct credential to confirm it vendor-side. That
evidence is specific to Anthropic's own endpoint. For a third-party Anthropic-compatible gateway or a
Bedrock InvokeModel route, the prefix may be a full-price write with no TTL refresh at all, and the
$0.05 floor in evaluate_economics (:154) is computed from Anthropic's Opus rates, so a
120k-token prefix on an unrouted gateway still clears it and spends.

This is opt-in (cache_warming defaults to "off"), so nothing regresses for existing installs. The
cost is that the documented scope does not match the implemented scope, and the one place the
evidence is weakest is the place with the most routes.

Suggested fix

Either narrow the gate to what the evidence covers, reusing the same is_native_anthropic identity
that agent/agent_runtime_helpers.py:1673 already computes:

from agent.agent_runtime_helpers import base_url_hostname
if getattr(agent, "api_mode", None) != "anthropic_messages" or (
        base_url_hostname(agent.base_url) != "api.anthropic.com" and agent.provider != "anthropic"):
    return self._stop("only native Anthropic requests are warmed")

or, if the wider set is intended, keep it and say so — the docstring at :15, the stop reason at
:193, and the sentence in configuration.md:1395 should name the third-party-gateway and Bedrock
cases, and _pricing() (:434) should refuse to price a route whose cache semantics are unverified
rather than assuming Anthropic's.

Not a blocker: the feature is off by default and the narrower gate is a one-line change. Raising it
because the behaviour is real and the documentation is the thing that is wrong.

Minor: the module docstring's cache_control scope is likewise imprecise

:15 says warmed requests "actually carry cache_control markers". has_cache_markers
(:107) walks system/tools/messages and accepts the envelope layout too
(msg["cache_control"], the non-native form emitted at agent/prompt_caching.py:56). That is the
right check for the routes it covers — no marker, no entry to keep warm — so this is wording only, and
is subsumed by the same edit.


Verification notes. Read at head 3021afd. Line numbers are post-image. I did not execute the
suite: codeload and the contents API were rate-limited (HTTP 429) for part of this review, so the
finding above is static and traced through the real post-image call chain
(start() → anthropic_prompt_cache_policy → resolve_billing_route → get_pricing_entry), not
reproduced at runtime. The existing reviewer comment asks whether _replay_kwargs deep-copies
correctly — it does, via copy.deepcopy per key at :459-464 — and that is the one question here I
can answer from the source without running it.

@tozes

tozes commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

@teknium1 I'd like to help move this forward rather than start a competing implementation. We have a native-Anthropic provider result that may help close the vendor-validation gap described above.

In an isolated synthetic-prefix test on Opus 5.5 with medium effort and a one-hour cache TTL:

  • Seeded a 7,147-token prefix, then replayed it at 50 minutes with max_tokens: 0: 7,147 cache-read tokens, zero cache writes and zero output tokens.
  • A normal request at 65 minutes still read all 7,147 tokens from cache, with no cache write.
  • A separate, untouched control expired: its normal request at 65 minutes read zero cached tokens and wrote its 7,151-token prefix again.

This validates zero-output retention beyond the original hour on the tested native Anthropic route. It does not validate this PR's implementation, other providers, repeated overnight refreshes, or subscription-quota savings. No real conversation was replayed.

Our follow-up use case is opt-in, bounded idle warming for selected/pinned conversations across overnight breaks, with refresh usage accounted separately and a time/budget limit measured from real activity. I see this PR currently caps idle warming at 30 minutes and excludes subscription-included routes; those would need separate agreement and evidence, not a silent relaxation.

Would you prefer help updating and landing this PR first, with a linked issue/follow-up for longer idle retention, or a separate proposal before implementation? Happy to share the minimal synthetic repro and sanitized usage results.

@alt-glitch alt-glitch added area/billing Account usage, credit usage, billing (cross-cutting) comp/cli CLI entry point, hermes_cli/, setup wizard labels Nov 6, 2026
@teknium1
teknium1 force-pushed the pi-port/cache-warming branch from 3021afd to 55ec460 Compare November 9, 2026 17:41
@teknium1 teknium1 changed the title feat(agent): opt-in Anthropic prompt-cache warming keeps the prefix alive through long tool runs (port of pi#9668) feat(agent): opt-in prompt-cache warming keeps the cache alive through long tool runs, on Nous Portal and OpenRouter too (port of pi#9668) Nov 9, 2026
@teknium1

teknium1 commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Independent review of 55ec4605b3c (cache warming on chat_completions). Findings first; each was checked against the PR head.

P1: a streaming-mode timer outlives turns that end by early return. agent/turn_finalizer.py::finalize_turn is the only place that settles the warmer, but agent/conversation_loop.py::_run_conversation_turn returns _ri/_v.result directly. Those paths skip _finalize_from_state. Examples: turn_tool_validation.py partial exits (lines 138/201), turn_response_intake.py:221, the repetition stop at turn_final_response.py:322, and turn_truncation.py::end_turn (its own comment says "never reaches finalize_turn"). In each case check_api_response has already armed a run, session_api_calls doesn't move again, and the interrupt flag stays False. So is_current() keeps returning True, and the run replays every 270s at p=1.0 for up to 60 minutes after the turn ended (the gate passes at about 10k tokens on Opus). Fix: call settle_prompt_cache_warming in run_conversation's finally next to end_voice_turn_route.

P2: in idle mode, duplicate warmers survive on forks and evicted agents. agent/background_review.py::release_cache_parity_fork / _release_fork_clients and run_agent.py::AIAgent.release_clients (gateway eviction) never cancel the warmer; only close() does. Each review fork is a fresh AIAgent with the parent's prefix (cache parity), so its idle run warms the same entry as the parent's for up to 30 minutes. The parent's next real request cancels only the parent's own warmer. The Timer also keeps the released fork alive. Fix: cancel in release_clients, and set _cache_warming_mode="off" in build_cache_parity_fork.

P2: OpenRouter's response cache makes the 2nd and later refreshes no-ops. The replay goes through the shared agent.client, whose default headers come from client_lifecycle._ROUTE_DEFAULT_HEADERS → build_or_headers(). That adds X-OpenRouter-Cache: true, and openrouter.response_cache defaults to True. _Run.api_kwargs is frozen at start(), so each refresh is byte-identical and lands within the 300s response-cache TTL (interval 270s). OpenRouter then serves it from its own cache and never touches Anthropic, so the prompt cache still expires. _record meanwhile books the cached response's usage as spend. Fix: send extra_headers={"X-OpenRouter-Cache": "false"} on the replay, as turn_api_request.build_request_payload already does for empty-response retries.

P2: is_replayable misses budget thinking on the chat wire. agent/prompt_cache_warmer.py::is_replayable only inspects a top-level thinking key, which chat_completions never sends. The reasoning knob lives in extra_body.reasoning: NousProfile.build_api_kwargs_extras always sends {"enabled": true, "effort": …}, and OpenRouter sends it for non-adaptive Claude (≤4.5). For effort-based reasoning the gateway derives budget_tokens from max_tokens, so max_tokens=1 changes or rejects the budget, which is exactly the case this guard exists for. Please verify on Portal and OpenRouter. Fix: skip when extra_body.reasoning is enabled and the model is not adaptive-only.

P2: the warmer passes source="cache_warm" to queue_token_counts. The signature is compatible: **kwargs → update_token_counts, and the keys pass _worker_usage's allowed set. But source is meant to be the session's real surface (#111999):

  • _insert_session_row would mint a row as cache_warm, and only the placeholder unknown ever gets corrected.
  • hermes_state_runtime._worker_usage stamps created_source=created_surface("cache_warm") on an unset row, such as a compression child on a Desktop worker.

Fix: use turn_usage._agent_session_source(agent) and mirror the main path's billing_mode / task.

P3: race between the timer thread and the loop. In PromptCacheWarmer._refresh, the _stop(...) calls after _send fails or _evaluate says stop call _clear_run. That clears whatever self._run is at that moment. If the loop armed a new run while the warm call was in flight (up to 60s), the timer thread cancels the new run. _record's session_* += updates also race with record_response_usage on the loop thread. Fix: a warmer-level lock, and stop only if self._run is run.

P3: the replay doesn't use the client the real request used. The real chat request uses make_client → _create_request_openai_client. The replay instead calls agent.client.chat.completions.create directly, which:

The MoA guard is also keyed on _moa_prepared_request. If provider=="moa" without that key, the replay reaches MoAClient.create and runs a full fan-out. Fix: refuse when agent.provider == "moa", and capture or compare the route identity.

P3: max_completion_tokens is popped and replaced by max_tokens. On a route whose max_tokens_param is max_completion_tokens, the replay gets a 400 and warming switches off silently. Fix: write 1 into whichever key the original request carried.

P3: non-Claude routes are warmed too. Markers on Qwen (Portal, DashScope, OpenCode) and Kimi (OpenRouter, Portal) pass has_cache_markers, so those routes are warmed whenever the economics allow it. The docs say "Claude requests". Either add an is_claude gate or update the docs.

Verdict: request changes. Fix the P1 (settle on every turn exit) plus the OpenRouter response-cache and fork/eviction P2s before merge. Accounting and thread-safety are minor.

teknium1 added a commit that referenced this pull request Nov 9, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
@teknium1

teknium1 commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Review findings addressed in 8f0e981bde1 (one push):

  • P1, warmer outlives early turn exits: fixed. run_conversation now settles the warmer in its finally, next to end_voice_turn_route, so every exit path stops streaming warming. The settle in finalize_turn is removed; it was a duplicate.
  • P2, forks and evicted agents: fixed. AIAgent.release_clients cancels the warmer, and build_cache_parity_fork sets the fork's mode to off because the parent already keeps that prefix warm.
  • P2, OpenRouter response cache: fixed. The replay sends X-OpenRouter-Cache: false. The new invariant test asserts it.
  • P2, budget reasoning on the chat wire: fixed. is_replayable skips the replay when extra_body.reasoning is on for a Claude model without adaptive thinking (anthropic_adapter._supports_adaptive_thinking). Opus 5.5 and other adaptive models still warm.
  • P2, accounting source: fixed. Rows keep _agent_session_source(agent) and the same billing_mode rule as turn_usage, and are tagged task="cache_warm".
  • P3, timer/loop race: fixed. _stop_if_current means the timer thread never cancels a newer run the loop armed during the warm call.
  • P3, MoA by provider; Claude only on Chat Completions: both fixed. The docs already say "Claude requests".
  • P3, max_completion_tokens: fixed. The replay caps whichever token key the request carried.
  • P3, request-local client / GIL transform: not changed. The replay is a max_tokens: 1 call on a daemon timer thread, and is_current already pins session_api_calls and model. A credential rotation or fallback lands a new response, which bumps session_api_calls and stops the run.

Tests: warmer, agent-init, finalizer, background-review and release_clients suites, 216 passed. scripts/check --only health passes. A live re-run on this head is in progress, and its result will go in the PR body.

@greptile-apps

greptile-apps Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; all four numbered findings are addressed, and no new actionable issue was established.

Summary

This PR keeps Claude prompt caches warm during long tool runs. It schedules one-token replays from the shared cache clock and stops warming when the turn ends.

  • Claude prompt caches stay warm during long-running turns.
  • Refresh spending stops at the cache-write limit and usage stays with its session.

Review checks were based on source inspection; tests were not run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Provider response] --> B[Update shared cache clock]
  B --> C{Warm window and savings confirmed?}
  C -->|No| D[Do not arm]
  C -->|Yes| E[Schedule refresh]
  E --> F{Run still current and before deadline?}
  F -->|No| G[Stop warming]
  F -->|Yes| H[Emit auxiliary start event]
  H --> I[Send one-token replay]
  I --> J[Emit auxiliary end event]
  J --> K[Record usage and cost]
  K --> L{Cache hit at known cost?}
  L -->|No| G
  L -->|Yes| B
  M[Next request or turn exit] --> G
Loading

Reviews (7) · Last reviewed commit: "fix(agent): keep-alives fire the auxilia..." · Reviewed by Greptile

Comment thread agent/prompt_cache_warmer.py Resolved
Comment thread agent/prompt_cache_warmer.py Resolved
Comment thread hermes_cli/config_defaults.py Resolved
teknium1 added a commit that referenced this pull request Nov 9, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
Comment thread agent/turn_response_check.py Resolved
teknium1 added a commit that referenced this pull request Nov 9, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 9, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
@teknium1
teknium1 force-pushed the pi-port/cache-warming branch from b3b8ffc to 8eab506 Compare November 9, 2026 19:03
teknium1 added a commit that referenced this pull request Nov 15, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 15, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 16, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 17, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 18, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 18, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 18, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
teknium1 added a commit that referenced this pull request Nov 18, 2026
…, and bypasses the OpenRouter response cache

Review findings on the widened warmer (#122094):

- Settle the warmer in run_conversation's finally (every turn exit), not only in
  finalize_turn: early returns (tool-validation exits, repetition stop, truncation)
  left a streaming run replaying every 270 s for up to an hour.
- Cancel it in release_clients (gateway eviction, review forks) and force it off on
  cache-parity forks, which share the parent's prefix.
- Send X-OpenRouter-Cache: false on the replay: a byte-identical request inside
  OpenRouter's 300 s response-cache TTL is answered from that cache and never
  refreshes the prompt cache upstream.
- Skip a Chat Completions replay when reasoning is on for a Claude model without
  adaptive thinking (the gateway turns it into a budget a one-token replay changes),
  and warm only Claude on that wire; refuse MoA by provider too.
- Cap the token key the request actually carried; the timer thread never stops a
  newer run the loop armed; accounting rows keep the session's real source and
  billing mode and are tagged task=cache_warm.
teknium1 added a commit that referenced this pull request Nov 18, 2026
…ownership checks are atomic

Greptile review on #122094:

- The first refresh was scheduled delay_s after the RESPONSE finished, so a response
  that took over 30 s on a 5-minute entry sent its keep-alive after expiry (a paid
  write, not a warm). It now counts from the request's send time (api_start_time), each
  later refresh from its own send time, and an entry already past its lifetime arms
  nothing.
- _validate / _stop_if_current / start check and replace _run under one RLock, so an
  old timer callback can never cancel a run the loop armed meanwhile.
- New invariant test reads cache_warming from a real config.yaml in HERMES_HOME and
  pins the send-time anchor.
teknium1 added a commit that referenced this pull request Nov 18, 2026
…t, warm x3, expire

agent/prompt_cache_lifecycle.py owns the per-chat decision at each pre-expiry point,
replacing agent/prompt_cache_warmer.py's scheduler and agent/cache_expiry_compaction.py's
decision (both deleted). A real request opens a budget of 3 keep-alives; chats a person
types into keep warming while idle, machine sessions (subagents, side agents, forks,
machine-paced sources) only while a tool runs. A spent budget on a proven/declared
window >= 30m with context >= half the compaction threshold and growth since the last
compaction is claimed once by the surface owner (CLI idle tick, TUI ticker, gateway
watcher); CLI and TUI then prime the compacted chat for one fresh budget. Any miss ends
warming; an unknown clock arms nothing. Every #122094 guard (witness, single admission
under lock, reset epoch, aux hooks, unknown-price refusal, spend cap, $0.05 floor) and
every #156253 owner guard (claim_gate, profile scope, bounded jobs, detached chats) is
kept. The one-hour age cap is replaced by the budget.
@teknium1

Copy link
Copy Markdown
Collaborator Author

Superseded by #156455 (merged as 0e8e421). This PR's warming (keep-alives while a long tool runs, on Anthropic Messages and Chat Completions for Nous Portal, OpenRouter and Anthropic) is now the tool-wait half of the merged lifecycle, in agent/prompt_cache_lifecycle/warmer.py::PromptCacheWarmer. Keep-alives fire at 5/6 of the TTL until the tool returns, with no count cap, and one tool wait's keep-alives together never cost more than the single rewrite they prevent.

The review fixes made here carried over:

  • settle on every turn exit, and cancel on release_clients and on forks;
  • X-OpenRouter-Cache: false on the replay;
  • the budget-reasoning skip;
  • the session source and billing of keep-alives;
  • the _admit lock and the context witness;
  • the reset epoch;
  • the max_completion_tokens cap.

#156455 adds idle warming, the 2-miss stop, compaction or offload at the cache edge, and per-route learning on top.

Credit: @mitsuhiko for the original design in earendil-works/pi#9668, which this PR ported. Closing as superseded.

@teknium1 teknium1 closed this Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing Account usage, credit usage, billing (cross-cutting) area/config Config system, migrations, profiles ci-reviewed applied to manually approve dangerous changes comp/agent Core agent runtime: loop, agent_init, prompt builder, context-compression, responses endpoint comp/cli CLI entry point, hermes_cli/, setup wizard P3 Low — cosmetic, nice to have provider/anthropic Anthropic native Messages API sweeper:risk-caching Sweeper risk: may break/degrade prompt caching or cache-key stability (invariant) sweeper:risk-compatibility Sweeper risk: may break existing users, config, migrations, defaults, or upgrades type/feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants