Skip to content

feat(cache-warming): Keep the prompt cache of idle Conversations warm - #2485

Merged
BYK merged 34 commits into
mainfrom
feat/cache-warming
Nov 9, 2026
Merged

BYK merged 34 commits into
mainfrom
feat/cache-warming

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Many prompt cache writes come from people who reply just after the cache TTL ends, so the next turn writes the full history again. This ports the cache warmer from BYK/loreai (packages/gateway/src/cache-warmer.ts). It is on for every app. JUNIOR_CACHE_WARMING_ENABLED=false is an operational kill switch, like JUNIOR_CONVERSATION_WORK_ENABLED: it defaults to true, stops storing requests, and drops warmups that are already queued.

How it works:

  • When a turn ends (stopReason: "stop") with a large cached prefix (minimum in model.ts), Junior stores the exact provider context (gzip, max 1 MB) in the StateAdapter and sends two delayed, signed queue messages on a new junior_cache_warmups topic: the first warmup, and a horizon message 55 minutes later.
  • Just before the TTL ends, a warmup replays the same system prompt, tools, messages, reasoning level, and cache retention through completeText with maxTokens: 1. The cache read refreshes the TTL.
  • Each next warmup is decided by Lore's model: a histogram of reply gaps (the Conversation's gaps mixed with global gaps as shares) gives the chance of a reply in the next TTL window. That chance must exceed read / (write − read) (≈4.2% for Opus). Earlier warmups are sunk cost, so the threshold is the same for each warmup, not Lore's rising k · read / (write − read). Warming stops when the chance falls below it, and at the 55 minute horizon. Replies after the horizon are not observed, so for a cache that outlives it (OpenAI's 30 minutes) the chance counts only replies before the horizon. That can only make Junior warm less.
  • The global gaps are kept per segment: who started the Turn (user Actor vs system, such as events and automations) × Turn depth (1, 2-3, 4+). Keys: junior:cache_warming:gaps:<segment>.
  • Only a Turn writes the Conversation state. Warmups and the horizon write only keys of their own idle period (snapshot, warmup count, gap claim), so work for an old idle period cannot change a newer one.

Cost guards:

  • Only providers whose cache has a fixed TTL that a read refreshes, with the TTL per provider (CACHE_TTL_MS in warmup.ts): anthropic/ and alibaba/ 5 minutes, openai/ 30 minutes. The warmup timing and the reply chance use that TTL. The TTLs come from models.dev's source files (its api.json does not publish them) and the provider docs, linked in warmup.ts. OpenAI's docs say "A 30-minute read refreshes coverage to at least 30 minutes after that read" for GPT-5.6 and later. Earlier OpenAI models have no cache write price in Pi, so the price check skips them. MiniMax has no TTL on models.dev, so it doesn't warm. The model's cache write must also cost more than a read.
  • No warming for budget thinking on the Anthropic Messages API: Pi adds the budget to the one-token output limit, and a smaller budget would miss the cached messages. Adaptive thinking (Opus 5.5) keeps max_tokens: 1.
  • While warming is on, the recorder sends agent requests with the short cache retention, and warming checks the retention of the request. PI_CACHE_RETENTION then no longer changes agent requests. With the kill switch off, Pi's retention applies again.
  • Every idle period of an eligible Conversation records one gap. The horizon message records "no reply" when nobody replied in 55 minutes. Without this, only replies would be counted and the model would overrate the reply chance.
  • A warmup that reads less than 90% of the expected prefix ends its idle period and sends a Sentry warning (cache_warming.warmup.missed, per model). A provider rejection ends the idle period and reaches the queue boundary as an error.
  • Breaker per provider: when 10 of the last 20 warmups of a provider miss or fail, warming of that provider stops for 24 hours and Junior sends one Sentry error (cache_warming.breaker.opened). OpenAI warming has no live check yet, so a provider whose cache behaves differently than its docs say cannot stop the others.
  • The snapshot is deleted when the next turn starts, when warmups stop, or after 55 minutes.
  • No warmups until reply gaps are recorded.

Verified against the live AI Gateway: a warmup at 4 minutes followed by a request 4 minutes later read the whole prefix from the cache. The control with no warmup wrote the whole prefix again.

End-to-end coverage: tests that run the agent must be integration evals with Roach recordings, and the eval fixture's in-process queue does not deliver this topic. The flow (same prefix, max_tokens: 1, stale-generation no-op, miss stops the period, horizon records no reply) was verified locally with a throwaway component test that is not committed. Unit tests cover the model, the gap segments, the horizon racing a reply, and which requests warm (prices and retention).

nitro.ts: the queue trigger setup was repeated for each topic, so it now uses one small helper for all four routes.

via @BYK.

--

View Session [Sentry]

…onversations

Port the cache warmer from BYK/loreai. When a turn ends on an Anthropic
model with a large cached prefix, Junior stores the request and sends a
delayed queue message. Before the 5 minute TTL ends, the message replays
the request with a one-token output limit, so the prefix stays cached.
A reply-gap survival model with Lore's rising ROI threshold decides each
next warmup. A breaker stops warmups for a model after cache misses.

The feature is behind the cache-warming experimental flag.

Co-Authored-By: Burak Yigit Kaya <[email protected]>
@vercel

vercel Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Nov 9, 2026 12:21pm UTC

Request Review

Remove the experimental flag, so cache warming runs for every app.

- Warm only anthropic/ models. OpenAI and xAI models also use the
  Anthropic Messages API on the gateway, but cache in other ways.
- Skip models with budget thinking, because the budget adds output
  tokens to each one-token warmup.
- Record each idle period once, also when no reply comes. A delayed
  horizon message records no reply after 55 minutes. Before, only
  replies were recorded, so the model overrated the reply chance.
- Open the breaker at 3 misses in the last 20 warmups of a model. A
  success no longer resets it. The old reset deleted a normal key, so
  it did not clear the Redis list.
- Delete the request snapshot when warmups stop, and keep it at most
  55 minutes and 1 MB.
- Skip state reads for mid-turn model calls after the first one.

Co-Authored-By: BYK <[email protected]>
Co-Authored-By: Burak Yigit Kaya <[email protected]>
@sentry-junior sentry-junior Bot changed the title feat(cache-warming): Add experimental prompt cache warming for idle Conversations feat(cache-warming): Keep the prompt cache of idle Conversations warm Oct 31, 2026
Warming stays on by default. Setting the switch to false stops Junior
from storing requests and drops warmups that are already queued, so an
operator can turn warming off without a revert or long cache retention.

Co-Authored-By: BYK <[email protected]>
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

9 screenshot changes — 9 changed · 0 added · 0 removed

Review screenshots in Frameshift

Conversation Attachment · Desktop
Conversation Attachment · Desktop
Changed
Conversation Captured Memories Popover · Desktop
Conversation Captured Memories Popover · Desktop
Changed
Conversation Captured Memories Popover · Mobile
Conversation Captured Memories Popover · Mobile
Changed
Conversation Details Watched Linked Work · Desktop
Conversation Details Watched Linked Work · Desktop
Changed
Conversation Long Transcript Touch · Mobile
Conversation Long Transcript Touch · Mobile
Changed
Conversation Stop Active · Mobile
Conversation Stop Active · Mobile
Changed
Show 3 more changed screenshots
Conversations Sections Collapsed · Desktop
Conversations Sections Collapsed · Desktop
Changed
Memories · Mobile
Memories · Mobile
Changed
Settings Mcp · Desktop
Settings Mcp · Desktop
Changed

The agent sends its Conversation ID as x-session-affinity (#2590), but
warmups went through completeText with no session ID. Pass the same
session ID, so a warmup reaches the same gateway session as the request
that it refreshes.

Co-Authored-By: BYK <[email protected]>
…reshold

Keep separate global gap histograms by who started the Turn (a person or
an event/automation) and by Turn depth (1, 2-3, 4+). Use the same
read/(write - read) threshold for each warmup, because earlier warmups
are already paid.

In 30 days of production data, this cut the cost of the next request by
40-41% vs never warming, against 32% for one histogram with the rising
threshold, out of sample.

Co-Authored-By: BYK <[email protected]>
@BYK
BYK marked this pull request as ready for review November 8, 2026 18:07
@github-actions github-actions Bot added the risk: high PR risk score: high label Nov 8, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Warmups and the horizon run while the next Turn can start. They wrote the
whole Conversation state with a read-then-write and deleted the one shared
snapshot key, so an old idle period could overwrite or empty a newer one.
The horizon could also add a no-reply gap after the reply recorded one.

Give each idle period its own snapshot and warmup-count keys, keep the
Conversation's gaps in a list, and let only a Turn write the Conversation
state. The reply and the horizon claim the gap with setIfNotExists, so each
idle period records one gap.
The blend mixed raw bin counts, so the long global gap list hid the
conversation's own gaps until the weight reached 1. It now mixes the
two histograms as shares.

Also cover the horizon that races a reply: only the real gap is
recorded.
…isses

Warm any model whose cache write costs more than a read, not only
anthropic/ models. Budget thinking stays excluded on the Anthropic
Messages API.

The recorder sets the short cache retention on agent requests and the
warmups, so warming reads the retention that Junior sends instead of
Pi's PI_CACHE_RETENTION.

A miss ends its idle period and sends a Sentry warning. The per-model
breaker is replaced by one for all models: when 10 of the last 20
warmups miss or fail, warming stops for 24 hours and Junior sends a
Sentry error.

Co-Authored-By: BYK <[email protected]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Each warmup runs one margin before the previous cache expires, so a plan
of warmups costs more reads than one per TTL.
Level 1 compresses faster than levels 3 and 4 at about 10% more bytes,
and compute matters more than size for snapshots.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 8a231c9. Configure here.

Comment thread packages/junior/src/chat/agent/index.ts Resolved
… first

Record the model call even when delivering the reply fails, so the idle
period still ends and the new prefix is snapshotted. Send the horizon
before the first warmup, so a failed warmup send does not lose the
no-reply gap. Clamp the warmup retention at zero delay.

@BYK BYK left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

"returnsPerWarmup" counts replies that would already hit the existing cache. I reproduced this with a 5-minute TTL, a decision at 4:15, 20 reply samples at 4:30, and 80 no-reply samples. The planner approves warming at 15.8% against an 8.7% break-even threshold, even though the refresh avoids zero writes.

Can we pass "cacheExpiresAtMs - idle.sinceMs" into the planner and use "max(0, S(currentExpiry) - S(planExpiry)) / S(idleMs)" for the return probability? That keeps the existing warmup-cost weighting and credits only the extra coverage. The fixture above should return "warm: false".

…ires

Returns before the current cache expires read it without a warmup, so a
plan's returns now start at the current expiry, not at the decision
time.
- Do not count retryable provider errors as misses, so an overload does
  not open the breaker for 24 hours.
- Keep each Conversation's gaps per segment, like the global gaps.
- Require 20 gaps before a decision, so one gap cannot set the return
  chance of a whole segment.
- Delete the snapshot when the reply's first request starts, so a warmup
  that comes due during that request sends nothing.

Co-Authored-By: BYK <[email protected]>
Retryable failures such as overloads and rate limits must not count
toward the provider breaker. Name that rule and test it with the errors
that Pi reports for Anthropic.

Co-Authored-By: BYK <[email protected]>
@BYK
BYK merged commit b81665c into main Nov 9, 2026
45 checks passed
@BYK
BYK deleted the feat/cache-warming branch November 9, 2026 13:07
BYK added a commit that referenced this pull request Nov 9, 2026
Stacked on #2485.

Sometimes a tool runs longer than the 5 minute cache TTL. Then the next
model request writes the whole history to the cache again. The running
agent now sends the same 1-token warmup before the cache expires.

- `cache-warming/request.ts`: the code that idle and tool-wait warming
share moves here from `warmup.ts`: eligibility (`supportsWarming`,
`SHORT_TTL_PROVIDERS`), timing (`warmupTiming`), the warmup request
(`sendWarmup`: core-model call, 90% read check, Sentry warning on a
miss, outcome count), and the global breaker (one `breaker:open` key
read per warmup).
- `cache-warming/tool-wait.ts`: when a model request ends with `toolUse`
on an eligible model with a large prefix, an in-process timer runs until
the warmup is due. The decision uses the same cost model as idle warming
(`decideWarmup`). It warms only while P(next request in the next TTL) ≥
read / (write − read), with the model's prices. The gaps are recorded
tool waits (`junior:cache_warming:gaps:tool_wait`). Only waits of 2
minutes or more are recorded, because shorter waits cannot change a
decision. Until waits are recorded, no tool-wait warmups are sent.
- Warmups stop when the next request starts, the run ends
(`cacheWarming.stop()` in the agent run `finally`), a warmup misses, or
the breaker is open. A warmup that is still in flight when warmups stop
does not schedule another one.
- Logs get `app.cache_warming.trigger` (`idle` or `tool_wait`).

**Live Gateway check:** an earlier version of this branch ran end to end
on Opus 5.5. The tool-wait timer sent a warmup before the TTL ended, and
the request after a 7 minute "tool" read the whole prefix from the cache
instead of writing it again. The cost-based decision and the shared
request code came later, and they have no live check yet.

**Tests**
- `tests/unit/chat/cache-warming-tool-wait.test.ts`: warms while
recorded waits make a return likely and stops when they don't, sends no
warmups without recorded waits or for a small prefix, stops when the run
ends (also during a warmup), and records only waits of 2 minutes or
more. A test that runs the agent with a slow tool would break the
test-architecture rule.
- Typecheck, lint, and the cache-warming tests pass.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3AC08SCGTC39P%3A1793334186.156159 -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/slack%3AC08SCGTC39P%3A1793334186.156159)
[[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC08SCGTC39P%3A1793334186.156159/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
BYK added a commit that referenced this pull request Nov 9, 2026
Stacked on #2923 (stack: #2485 → #2923 → #2944). Idle warming sends no
warmups for a `gapSegment` until that segment has recorded gaps, so each
install starts from zero after deploy. This fills the empty segment
lists once from stored Conversation history, so warming can start right
away.

## What it reads

`backfill.ts` replays the stored model calls of Conversations that had
activity in the last 30 days (`GLOBAL_GAPS_TTL_MS`) and applies the live
recording rules:

- **Times:** the `timestamp` of each stored `assistant_message`. Pi sets
it when the model request starts, so it is the same clock that the
recorder's `startedAtMs` uses. A gap runs from the request that ended a
Turn (`stopReason: "stop"`) to the next recorded request. Error and
aborted requests are skipped, the same as `record()` skips them.
- **No reply:** a gap of 55 minutes or more, or an idle period with no
later call that is older than the horizon, records `NO_REPLY_GAP_MS`. An
idle period that is still in its horizon records nothing.
- **Segment:** `gapSegment(userActor, endedTurns)`. `userActor` comes
from the Actor of the Turn's instruction `user_message` (it has a
`userId`). Task Conversations always count as not a person, the same as
`agent/index.ts`. The Turn count resets after
`CONVERSATION_STATE_TTL_MS` with no call, the same as the expiring
Conversation state. Earlier Turns of the Conversation count, including
Turns before the window.
- **Eligibility:** live recording records gaps only for idle periods
that it could warm. The stored `usage` has the cached prefix size
(`cacheRead + cacheWrite`), so periods below `MIN_WARMUP_PREFIX_TOKENS`
are skipped. The model, cache retention, and snapshot size are not
checked. That is an assumption: reply timing does not depend on them.
- **Forks:** a fork copies its source rows with their old times, so rows
from before the Conversation was created are skipped.

Each segment list that is empty when the run starts gets its newest
gaps, at most half of `GLOBAL_GAPS_MAX`. State lists have no atomic
replace, so live recording can append while the backfill writes. The
free half keeps those appends from trimming live gaps. A segment list
that already has gaps is not changed. Per-Conversation gap lists are not
filled.

## Scan budget

The heartbeat gives no deadline, so a run scans for at most 60 seconds
(monotonic clock). It reads Conversations newest `last_activity_at`
first, 10 per query, and checks the budget before each query after the
first. Small queries stay far under the SQL statement timeout. If the
timeout still cancels one, the scan skips that batch and goes on. A run
in which every query was canceled does not complete, and a heartbeat
tries again after the claim expires. When the budget is used, it stops,
writes the gaps that it has with the same rules, and marks the install
as done. Some recent gaps are better than none, and a run that could
never finish would otherwise try again each hour. The completion log has
the number of Conversations scanned and whether the run stopped on the
budget, and how many batches were canceled.

## Trigger: the heartbeat

`runHeartbeat` calls `backfillCacheWarmingGaps` last, after plugin
heartbeats, in its own try/catch. I picked it over a lazy call in the
warmup decision because:

- It runs within about a minute of deploy, before the first warmup
decision. A lazy call would run inside a warmup message that has seconds
before its cache expires. A long first scan there would make that warmup
late or make it miss.
- It needs no change in `runCacheWarmup`. `warmup.ts` only exports
`GLOBAL_GAPS_MAX`, `GLOBAL_GAPS_TTL_MS`, `CONVERSATION_STATE_TTL_MS`,
and `segmentGapsKey`.
- It already runs in background work (`waitUntil`) on every install.

A `setIfNotExists` claim with a 1 hour TTL lets only one run start. A
completed run sets the key to `done` with no TTL, so later heartbeats
make one state call and return. A run that fails or is stopped before it
completes leaves the claim to expire, and a heartbeat an hour later
tries again. With `JUNIOR_CACHE_WARMING_ENABLED=false` nothing runs and
nothing is claimed.

## Tests

`tests/integration/cache-warming-backfill.test.ts` runs person Turns
through the real Conversation path (`createAgent`, with only the model
stream faked so the test can set the cached prefix size), adds a Task
child, and runs the real `runHeartbeat`.

- The first case checks the reply gap, the no-reply gaps, the prefix
filter, the Task segment, that a non-empty segment is not changed, and
that a second heartbeat does nothing.
- The second case uses a zero budget. The newer Conversations fill the
first batch and are written. The older Task in the second batch is not
scanned, and a later heartbeat does not scan it.

`pnpm lint` and `tsc --noEmit` pass. The backfill, cache-warming unit,
and heartbeat tests pass.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A95e8c282792eaed301a34c0abeedcaae -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A95e8c282792eaed301a34c0abeedcaae)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A95e8c282792eaed301a34c0abeedcaae/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — 5bac788d Deployed Nov 9, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant