19 Commits

Author SHA1 Message Date
Teknium
0e8e421640 fix(prompt-cache): a managed local model's unload is counted from when its reply finished
Some checks failed
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Has been cancelled
auto-fix lint issues & formatting / Apply patch (push) Has been cancelled
The managed llama-server's idle-unload wait starts when the model goes idle,
but _managed_unload_end counted it from the request's sent_at, so a long reply
read as cold up to its decode time early and the cold prune could shorten a
still-warm prompt. The estimate now starts at the response's completion (the
fold time).
2026-11-18 03:40:34 -08:00
Teknium
0cf82ca702 fix(cache): review round 2 — managed local unload expiry, malformed route store, CLI dead hook, scan/release handoff
alt-glitch's review of 893b54f9:
- Hermes' own managed llama-server unloads an idle model (and its prompt cache) after 15 min (+ two
  120 s sweeps): its clock now ends there, so /context and the cold offload see it; a user's own local
  server still never expires on the clock. The guarantee is capped at the estimated end.
- A malformed entry in cache/prompt_cache_routes.json (non-numeric timestamp, counters or gap lists) is
  dropped instead of raising into agent build and usage accounting.
- The route key keeps the port (normalized base URL): two local servers on one host learn apart.
- The classic CLI's idle cache hook never ran: `hermes chat --cli` drives a GatewayAgent and the gateway
  owns the warmer and its housekeeping. The hook, its test and its helper are removed (the two CLI
  files are main's again).
- A due-scan's claimed action is handed to a release job that registered for the same chat while the
  scan ran, instead of being dropped.
- Keep-alive log lines carry the chat's session tag (set on the timer thread).
- Tests that could not fail now can: the claim race pauses after the decision, the late-miss branch with
  no successor, and the compaction hand-off through carry_compression_automation (each red when its fix
  is reverted).
- Follow-ups folded in: a finite admission arms no idle keep-alive; delegate cost folding takes the
  session-totals lock; the docs say the gateway offload lands on its 5-minute tick.
2026-11-18 03:40:34 -08:00
Teknium
df702cab6b feat(cache): backtest rulings — upstream-aware misses, 5m->1h tier at the first pause, learning-store guards
Teknium approved every improvement the usage backtest found:

- A keep-alive miss served by another upstream than the reply that cached the prefix (Nous serves one
  Claude model from chatcmpl-* and gen-* upstreams; 70 switches broke a warm cache in the window), or
  one that still read the stable system prefix, is routing, not lifetime. Real misses end warming only
  on the second in a row (three misses of any kind end it too). The upstream key is data
  (prompt_cache_clock.response_upstream: a gateway's upstream field, else the response id family),
  stored on the clock event; a retried miss's rewrite is not charged to the money limit.
- cache_ttl auto: a person's chat starts on 5m and asks for 1h from the first message after an idle gap
  past five minutes, for the rest of the session (kept per session id, carried to the compaction child,
  re-derived from a stored clock that asked for 1h). The upgrade fires only when the clock holds no
  guarantee and the last cache touch is over 300 s old, so markers never change on a warm prefix. No
  idle keep-alives before the upgrade. /context names the pending tier. Explicit pins and machine
  sessions unchanged. Wire snapshot regenerated: fresh cli agents now send 5m markers.
- Route store: a downgrade needs samples from two different sessions, an upstream switch is never a
  sample, and a learned lifetime never undercuts the longest hit ever seen (kept outside the trimmed
  recent gaps).

Tests pinning the single-miss stop and the 1h start are rewritten to the new ruling (assertions only).
2026-11-18 03:40:34 -08:00
Teknium
bf9b193d7c refactor(caching): one owner per helper, no cross-module private imports
- Keep-alive totals go through turn_usage.add_session_usage, the same fold a response uses
  (it now also counts reasoning tokens, as a response does).
- PromptCacheWarmer._with_aux_hooks is auxiliary_hooks.run_with_aux_hooks with a lazy
  normalized= view; _rough_tokens is conversation_compression_manual.estimate_request_tokens.
- prompt_cache_is_cold lives in prompt_cache_clock (its only inputs), ending the
  turn_proactive_prune -> turn_preflight -> turn_proactive_prune circle; the read-dedup reset
  after a committed prune happens once, in _proactive_tool_result_prune, not at three call sites.
- Public names for the helpers other modules import: turn_usage.cache_clock_column /
  agent_session_source, context_compressor_summary.accepts_keyword_argument.
- archive_pruned_originals / archive_compaction_drops lose the never-passed skip= parameter.

Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
2026-11-18 03:40:34 -08:00
Teknium
cef89d150e fix(caching): learn write-on-hit only from an unchanged replay
Equal read and write counts on an ordinary turn just mean it appended about as much as it read;
two such tool rounds disabled warming for every chat on the route. Only a keep-alive re-sends
the prefix unchanged, so only its sizes can show a hit that re-wrote the prefix.
2026-11-18 03:40:34 -08:00
Teknium
3fd2797a53 fix(caching): a 24h-retention request and a local endpoint are never cold-pruned on the clock
After the API-spec refactor, classify_route/_rule_openai_spec stopped reading the request's
prompt_cache_retention, so estimated_until equalled the 30-minute warming deadline on every
OpenAI-spec route. prompt_cache_is_cold() then turned True at 31 minutes, and turn-start prune,
owner offload and route-change offload rewrote history on routes whose cache was still warm:
api.meta.ai and Bedrock Mantle GPT-5.x/4.1 (Hermes asks those for 24h retention), and local
llama.cpp / vLLM / Ollama boxes, which evict on memory pressure, not on a clock. Each needless
rewrite costs a full prefix re-process.

Only the expiry estimate changes (_estimated_end). The 30m stays the guarantee and warming
deadline for every OpenAI-spec route, a 24h request included (warm at 25 min, first miss
disables). A request that asked for 24h is estimated to live read + 24h, and the estimate
survives a read renewal. An is_local_endpoint host has no estimated end (estimated_until None
with a known confidence), so it is never certainly cold on the clock, while route_changed and
compaction still invalidate the window and offload. chatgpt.com Codex gets no retention from
Hermes, so its 30m stands.

Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com>
2026-11-18 03:40:34 -08:00
Teknium
579e25e022 feat(caching): learn how each route really caches, across sessions, from usage already received
agent/prompt_cache_routes.py: a per-profile store (<HERMES_HOME>/cache/prompt_cache_routes.json, atomic,
<= 500 routes, 7-day expiry) keyed by provider, host, model and marker use, fed by the clock from every
folded response (normal replies and keep-alives; no probes). After two consistent samples: never reads
back -> no keep-alives and no markers; re-writes the prefix on every hit -> no keep-alives; early misses
-> keep-alives on the learned lifetime (never past the tier) or none under a minute; an automatic cache
that dies early while the explicit one reads -> markers. /context shows 'Learned: <rule>.'
2026-11-18 03:40:34 -08:00
Teknium
3a4fe9c53c feat(caching): cache rules follow the API spec; first keep-alive miss ends warming for the session; keep warming while a tool runs
Teknium's rulings on PR #156455:
1. A request with cache_control markers is Anthropic spec on any wire or gateway: the 5m/1h it asks
   for is declared and trusted (route ceilings still clamp); 'gateway_1h_untrusted' is gone. Every
   unmarked request is OpenAI spec (30m, renewed by a read), Nous non-Claude models included.
2. The first keep-alive that misses disables warming for the rest of the session on that route (new
   user messages and compactions do not re-arm it; a model/provider switch or a fresh session does).
   The compact/offload fallthrough still runs; /context appends 'Keep-alives: off (one missed).'
3. While a tool call executes, keep-alives continue until it returns, uncounted against the idle
   budget of 3 and bounded only by one rewrite's cost for that tool wait.
2026-11-18 03:40:34 -08:00
Teknium
c5a017707d fix(caching): a clock saved before the two-spec rules restores as the OpenAI spec
Also trims compress() back under its line cap.
2026-11-18 03:40:34 -08:00
Teknium
5c8e2bfedf feat(caching): apply the lifecycle rulings: no post-compaction warming, 5/6 timing, two cache specs, offload at expiry
- A: no priming and no keep-alives after a cache-edge compaction; the next user message starts the
  budget. The budget is keyed on the user message, so tool rounds inside one turn share 3 keep-alives.
- B: a missed keep-alive still stops warming, and now ends the budget so step 2 (compact) or step 3
  (expire + offload) is decided at once.
- C: no $0.05 floor; a keep-alive is sent when its read is cheaper than the rewrite, within one
  rewrite per budget, with known prices and a prefix of at least 1,024 tokens.
- D: keep-alives fire at 5/6 of the TTL (250 s / 25 min / 50 min), >= 10 s margin; compaction decides
  at the same moment.
- E: compaction no longer requires a still-warm cache (the summary is a fresh aux request).
- F: an idle chat past its window is offloaded by its owner (CLI tick, TUI ticker, gateway watcher)
  and on release, not only on return.
- G: two specs: cache_control markers (Anthropic, 5m/1h) or OpenAI-spec automatic caching for every
  other model, declared 30 min renewed by a read; OpenAI-spec routes get the full loop, replayed with
  the smallest accepted output cap (16 for GPT-5/o-series).
- H2: a route switch (/model, fallback) reads as cold, so the first request on the new route offloads.

Removed tests pinning ruled-out behaviour: priming (test_cli_cache_expiry_prime.py, the priming and
prime-billing lifecycle tests, the TUI no-prime test), the $0.05 floor, 90% timing, the still-warm
gate (TUI window-closed test, already_cold), OpenAI pre-5.6 assumed / implicit unknown clock tests.
2026-11-18 03:40:34 -08:00
Teknium
57df5a2bd9 fix(caching): a release ends the warm budget, compaction archives once, and failed compactions buy nothing
Review fixes for the prompt-cache lifecycle (Greptile on 8f99ba52):

- Compact at release: a warm budget ends at whichever comes first, its 3 keep-alives or the owner
  releasing the agent. On a 1h route the gateway evicts an idle agent after an hour, before 3
  keep-alives at ~54 min run out, so step 2 never fired. The gateway idle/LRU evictions and the TUI
  idle/LRU reapers now ask claim_compaction_at_release (same gates, decided at the release, warming
  cancelled) and compact first through the same claim-gated job, then release. No keep-alive after.
- Planning is write-free: _plan_compaction_window no longer archives. compress() archives once after
  admission; a prepared pass archives its own window after taking its slot and the splice skips those
  rows, so no result is written twice and refused passes write nothing.
- The committed summary lists every archived file the generated text omits ("Archived tool output"),
  so the model keeps the path and the retention sweep keeps the file.
- A queued TUI cache-expiry job whose chat closed meanwhile is refused at the busy claim (_closing).
- A no-op, aborted or refused compaction no longer primes or grants a fresh budget (TUI and CLI).
- Keep-alive and priming writes are priced at the tier their request declared (1h = 2x input), as
  loop responses are.
- Docs: keep-alives (and so step 2) are Claude-only; OpenAI routes are never warmed.
- The reset race test proves the reset reached the contested lock with a trace barrier (2 s bound).
2026-11-18 03:40:34 -08:00
Teknium
2828b82fa8 fix(caching): auto keeps the source tier and clamps per send; malformed prompt_caching never breaks startup; 1h writes over a 5m prefix price at 1h 2026-11-18 03:40:34 -08:00
Teknium
d423fa6b1c fix(agent): keep-alives are bound to the prefix they replay; cancel admits no later send; reset epoch fences totals
- A refresh captures the clock's context witness (session, durable generation, rewrite
  count, route) when armed; it is sent, and its reply folded into the clock, only while the
  session still matches. A reply to a compacted prefix is billed but leaves the clock unknown
  and schedules nothing.
- One send admission under the ownership lock, after pricing, with a cancelled flag set when
  the run is cleared: a cancel that returned never sees a later HTTP request.
- reset_session_state advances a monotonic _session_reset_epoch (and zeroes
  session_cache_warm_calls); a refresh from before a reset stays out of the new totals.
2026-11-18 03:40:34 -08:00
Teknium
fe55d8f341 feat(agent): the cache warmer reads the shared prompt-cache clock
The warmer computed its own entry lifetime (the configured tier on native
Anthropic, 5 min on any gateway) and its own send-time anchor. Both now come
from agent/prompt_cache_clock.py: a refresh is due shortly before the clock's
guaranteed-warm deadline, and a window the clock does not call certainly warm
(unknown, assumed gateway 1h, cache moved, already past) arms nothing. Each
refresh is folded back into the clock (record_cache_response gains an
attempt= override so a keep-alive never clobbers the loop's stamped attempt),
its token row carries the clock column, and the next refresh is scheduled from
the deadline the refresh bought. warm_ttl_seconds, the warmer-local
TTL_SECONDS and _last_api_attempt_sent_at are gone: one lifetime source.
2026-11-18 03:40:34 -08:00
yoniebans
ab448ea16b fix(agent): read the prompt-cache clock through the agent's storage handle
The clock reader looked up get_prompt_cache_clock and prompt_cache_generation on agent._session_db; on an agent whose store is a storage interface handle those reads found nothing and the window went silent. Both reads now go to the handle's usage repository when the agent has one, and stay on the agent's own store otherwise (a worker's RuntimeSessionStore). A failed read through the handle raises a PersistenceError, which reports storage_unavailable as the other store errors do.

The persistence cases (restore, compaction before restart, resumed first pure read, failed store read, managed worker generation) run against a real store handle.
2026-11-17 17:51:24 +01:00
Teknium
4162ecf11f fix(cache): worker prunes and micro-compactions invalidate the clock
Some checks failed
Skills Index Freshness Check / check-freshness (push) Has been cancelled
Skills Index Freshness Check / check-catalog-cors (push) Has been cancelled
Docs Search Monitor / probe (push) Has been cancelled
Deploy Site / deploy-vercel (push) Has been cancelled
Deploy Site / deploy-docs (push) Has been cancelled
auto-fix lint issues & formatting / Generate eslint --fix patch (push) Has been cancelled
auto-fix lint issues & formatting / Apply patch (push) Has been cancelled
A worker store has no durable generation reader, and an in-place archive
(prune, micro-compaction) leaves compression_count alone, so a later
response folded pre-rewrite coverage. RuntimeSessionStore.archive_and_compact
counts each committed rewrite locally; the clock adds it to its witness.
2026-11-15 12:04:54 -08:00
Teknium
453d6b9fb2 fix(cache): advisory clock reads, worker generation, saved-route check
- Every clock storage read (restore, prompt_cache_generation) is best-effort:
  sqlite3.Error/OSError/WorkerPersistenceError log at DEBUG and the window
  reports unknown (storage_unavailable); a successful reply is never lost.
- RuntimeSessionStore.prompt_cache_generation reads the owner's durable count
  (session.cache_generation receipt op), so a managed worker's fresh write is
  not reported compacted.
- The agentless /context read compares the saved clock with the row's
  persisted model + model_config provider/base_url, and the breakdown cache
  key includes them: a session.mutate model switch reports unknown.
2026-11-15 12:04:54 -08:00
Teknium
58886fc81e fix(cache): coverage deadlines, guaranteed vs estimated ends, durable generation
The clock modelled every route as "expires = last touch + tier", which is wrong for OpenAI
GPT-5.6+: a read refreshes coverage to at least 30 minutes after it and never restarts a
12h write. It also treated documented minimums as expiries and lost or revived saved state.

- Coverage deadlines per tier with per-route refresh rules: Anthropic family restarts the tier
  on read; OpenAI keeps max(existing, read + 30m) and a 12h deadline stays at write + 12h.
- Windows carry guaranteed_until (earliest deadline, so mixed tiers in one response are only as
  warm as the shorter) and estimated_until (OpenAI: last touch + 24h retention ceiling; pre-5.6
  in_memory 1h). cache_certainly_warm / cache_certainly_cold are the two consumer helpers.
  /context: warm until / may still be warm until / expired / unknown.
- Events bind to the session's durable context generation (rows a compaction or prune archived,
  SessionDB.prompt_cache_generation), kept as saved on restore; a resumed agent restores and
  validates the saved event before folding its first response.
- Route identity is provider + normalize_route_base_url (scheme, host, port, path) + model.
- Agentless session.context_breakdown reads the saved clock (stored_cache_window).
- Codex app-server activity is recorded as an explicit unknown (it sets its own cache options).
- MoA records the resolved aggregator route and the payload the MoA client sent.
- effective_cache_ttl applies the route ceiling on the measured-provider path too.
2026-11-15 12:04:54 -08:00
Teknium
4a89bc6c02 feat(cache): one prompt-cache clock per session; Nous 5m ceiling as data
Every consumer that needs "when does this session's cached prompt expire?" now reads one
answer, agent/prompt_cache_clock.py:cache_window(), instead of re-deriving it from _cache_ttl.

- Per successful attempt the clock records the tier actually on the wire (cache_control ttl,
  prompt_cache_options.ttl, prompt_cache_retention, read from the sent payload), the send time,
  and the tier the response proved: Anthropic cache_creation.ephemeral_5m/1h_input_tokens,
  OpenAI Responses cache_write_tokens_details.ttl_30m/12h_tokens. normalize_usage keeps that
  split as CanonicalUsage.cache_write_by_ttl instead of dropping it.
- Per-route rules are a dict of small handlers: native Anthropic proves via the split;
  OpenRouter Claude is declared (live-probed to honour 1h); routes with a ceiling are clamped;
  other Anthropic-wire gateways assume 5m; OpenAI GPT-5.6+ proves via ttl_30m/12h or declares
  the documented 30m minimum; pre-5.6 assumes ~30m (5m on in_memory); implicit caches are
  unknown. expires = latest read-or-write send time + the written tier. A route switch,
  fallback, session rotation or compaction makes it unknown.
- Route TTL ceiling is data: ProviderProfile.prompt_cache_max_ttl (Nous ships "5m", because
  the Portal's upstream drops 1h after ~7 min and bills 5m), overridden per provider by config
  prompt_caching.route_ttl_ceilings. effective_cache_ttl uses the same helper, so Hermes stops
  asking Nous for 1h. A custom endpoint at the Portal host gets the Nous ceiling.
- Persisted as nullable sessions.prompt_cache_clock (JSON) through the existing token batch;
  restored lazily on resume, falling back to the newest assistant row (assumed).
- Codex app-server: read cacheWriteInputTokens instead of hard-coding cache_write_tokens=0.
- /context shows "Prompt cache: warm until HH:MM (…; 1h, proven)", "expired … ago" or
  "unknown (…)". The surface is absorbed from #142387 (render/duration helpers, the
  SessionContextBreakdownResult.prompt_cache contract and translations), reworked onto the clock.

Co-authored-by: Teknium <127238744+teknium1@users.noreply.github.com>
2026-11-15 12:04:54 -08:00