Skip to content

serve, gpu: keep prompt-cache copies and reusable prefixes within their contracts - #737

Merged
juliankang4 merged 7 commits into
midagedev:mainfrom
juliankang4:fix-prompt-cache-contracts
Oct 23, 2026
Merged

juliankang4 merged 7 commits into
midagedev:mainfrom
juliankang4:fix-prompt-cache-contracts

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

프롬프트 캐시가 복사 중인 메모리를 돌려주거나, 예산을 넘는 상태를 복사하거나, 쓸 만한 앞부분을 지우던 다섯 가지 문제를 고칩니다.

Part of #565. Tracked in #699.

What and why

This fixes five defects in the prompt cache and its staging copies. Each is listed with the commit that introduced it, and each has a regression test that failed before the fix.

  • An asynchronous snapshot could hand its staging extent back while the copy was still running when creating the final event failed (f8f7c3cf86). The extent could then be reused and overwritten under the copy.
  • A state larger than the prompt cache's budget was copied to host memory and only then discarded, on both the seal and the conversation switch paths (6de8b6062f, seal fallback in 9300904d66).
  • A newer entry could evict an older one that restored a useful inner prefix, because only the older entry's end position was compared (6de8b6062f, reached by recurrent saved states through 08a8fd63d3).
  • With a checkpoint budget of two slots, saves at message boundaries could evict the shared system-prompt checkpoint (4429d603a4, serve: keep the Qwen3 shared system prompt at message starts #694).
  • When two entries restored the same prefix length, the cache could pick one whose copy was still pending over one that had landed (f8f7c3cf86 added pending entries to the recency rule from 6de8b6062f).

The fix, by defect:

  • Copy errors (crates/gpu/src/checkpoint/saved.rs): the end event is now created before the copy is queued, and registering the copy and recording its event fail through one place, SaveLane::copy. On failure the lane is synchronized before the staging extent is returned. The number of copies and events on the normal path is unchanged.
  • Budget (crates/serve/src/engine.rs, genloop.rs, promptcache.rs, swap.rs): Engine::snapshot_size reports a state's stored array bytes, so the cache checks the budget before any copy starts. Qwen3.8, GLM, V4.1 and the mock engine implement it; an engine without it keeps the old path. The size is the stored array bytes, not the staging grain, so a state that fits is not refused for rounding. A sealed sparse state is tracked by a weak reference and is not copied again on a conversation switch.
  • Inner prefixes (promptcache.rs, crates/runtime/src/seqstate.rs): an entry is dropped as covered only when the newer state restores every prefix the old one did, and covers uses the same comparison.
  • First checkpoint (seqstate.rs): for a ledger with an interval, the first point is kept to the end and save_points saves it. The two-slot budget is unchanged. With an interval of 0 the order is the existing LRU.
  • Equal prefixes (promptcache.rs): at equal kept length a landed copy is picked first, then the most recent as before.

GPU math, graph and eager selection, kernel launches and numeric gate bands are unchanged. Only which prefixes can be restored and whether a state is saved differ. The size query is one request per save attempt and is not in the per-token decode path.

Release notes: Fixed: The prompt cache no longer returns a staging buffer under a running copy, no longer copies states that exceed its budget, and keeps reusable inner and first prefixes.

Code shape

  • No second copy. The budget and prefix comparison live in PromptCache, array sizes come from each model's existing saved arrays, and copy failure handling sits in SaveLane::copy.
  • Model code holds only architecture facts. Each model adds only its array sizes. No common owner gained a model branch or flag.
  • Dead code is gone. The per-call end-position comparison and the separate budget check in seal were replaced by the shared ones.
  • No silent failure. A failed size query keeps its engine error and is not turned into zero, and a failed copy synchronizes the lane before the extent is returned.
  • Comments state what is true now. The comments describe the current rules.
  • No relaxed gate. No band or tolerance moved. tools/unsafe-ratchet.txt carries a dated PIN for the one new unsafe block, which is in a test that queues a copy on a held stream.
  • cargo fmt passes on what I touched, and git diff --check is clean. I did not run cargo clippy on this change, so the lint count is unchecked.

Duplication found or removed (path:line): none. The duplicate scan flagged five size-query helpers in crates/gpu-gates/src/bind.rs. None is a copy: the snapshot helpers start a copy before the budget can be checked, while the size query only reads array lengths and reuses the existing seat_failure error classification.

What I ran

The runs below used these changes on earlier commits of main. I did not rerun them after the last rebase onto main.

Fail-first. The regression tests were added on top of main's behavior and failed as expected:

left: 8
right: 11
left: 0
right: 1024
EXPECTED_FAILURES=3

Three tests failed as expected: the inner-prefix test kept 8 where 11 is expected, the first-checkpoint test kept 0 where 1024 is expected, and the test for a landed copy over a pending one picked the pending entry.

For the budget defect, with the test and the default size query added over main's behavior:

  left: 2
BASE_BUDGET_RC=101

The oversized state was copied twice where 0 is expected.

Host tests on the fixed code:

test result: FAILED. 349 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.99s
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 349 filtered out; finished in 0.08s
test result: ok. 285 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.18s

The one failure in the first line is api::tests::a_key_never_reaches_what_the_process_prints_or_serves: it needs the bloomery-serve binary, which I had not built yet. After building it, that single test passed (second line), and the bloomery-runtime lib tests passed (third line). The five added cache tests passed in the first run. I did not repeat the 349 serve tests.

Copy errors on the RTX 5090. With the lane synchronization removed from the shared error boundary, a real device-to-host copy queued on a held stream and an injected event error returned the extent too early:

EVENT_MUTANT_RC=101
end event creation returned before the copy landed

This injects the error into the shared boundary. It does not break the CUDA API itself. With the fix, the eight checkpoint::saved tests pass:

test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 379 filtered out; finished in 7.92s

The same run checked that sync and async saves give the same state, that a prefix load and a load plus cut match bit for bit, and the host copy order of checkpoints.

Snapshot size on GB10. A mutant whose size query always returns Ok(None) fails the new link test on the difference between None and Some(0); the fixed code passes all 35 bind::tests:

  left: None
 right: Some(0)
SIZE_MUTANT_RC=101
test result: ok. 35 passed; 0 failed; 0 ignored; 0 measured; 184 filtered out; finished in 0.08s

Command: bash tools/gate.sh --oxide -p bloomery-gpu-gates --features deepseek41 --release --lib -- bind::tests.

just gate-gpu-e2e was not run: these tests ran through tools/gate.sh directly, and no just gate-* recipe covers them.

The full workspace compile on the same hardware finished before the unit tests; that job was cut off before the tests ran, so I count only the compile step from it.

Compile check on the RTX 5090 (cargo check --workspace --all-targets with the GPU feature set; Finished is the last line of the check):

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 39.43s

Real model check. With Qwen3.6-35B-A3B-Q4_K_M on an RTX 5090 (ctx 4096, ubatch 4096), a first request of 3000 positions and a second request sharing a 1024-token prefix reused those 1024 positions. The same request with the cache off reused 0, and generated tokens and probability rows were identical. The server exited 0:

CACHEFIX_Q35 {"ctx": 4096, "ubatch": 4096, "first_positions": 3000, "kept": 1024, "fresh_kept": 0, "tokens": [18, 18, 18, 18], "tokens_equal": true, "probability_rows_equal": true}
CACHEFIX_Q35_SERVER_RC 0

This checks reuse and output equality only. It is not a speed or quality measurement.

This is a fix, so I ran no speed A/B. I ran the checks on one node and did not run two-node (N=2) or N=4 cases.

Hardware

RTX 5090 machine (compile check, held-stream copy test and real model check):

| NVIDIA-SMI 595.99.02              Driver Version: 595.99.02      CUDA Version: 13.2     |
|   0  NVIDIA GeForce RTX 5090        Off |   00000000:01:00.0 Off |                  N/A |

DGX Spark (snapshot size link test):

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |

What I ran into

This does not block the PR. crates/gpu-gates/src/lib.rs builds the bind module only with the deepseek41 feature, so a test of the plain host request path needs a node with the GPU toolchain. The tests above do not depend on it.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve labels Oct 23, 2026
github-actions[bot]
github-actions Bot previously approved these changes Oct 23, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: CLEAN: No demonstrated behavior failure or proven quality defect.

Checked

Duplicates: Budget admission, prefix coverage and copy-error handling use shared owners.
Complexity: SeatEngine::spawn adds a protocol match arm. Slot::reuse adds a sealed-state guard; membership remains owned by PromptCache.
Silent failure: Three conversion, unknown-size and refusal paths followed. Overflow errors propagate; unknown size uses existing admission; refusal emits a skip note.
Tests: Eight new and two modified tests read, not run. Predicted mutation results:

Gates: No numeric band moved. The changed eviction expectation and unsafe ratchet have dated PIN reasons.
Escape catalog: C1–C4 do not match this diff.
Adversarial checks: copy/event errors, exact budgets, sparse prefixes, readiness ties and expired seal references are guarded. No kernel or decode launch count changes.

Notes

No tests were run here. The PR reports runs before its final rebase and lacks tested commit hashes and just gate-* output, so it does not meet the required GPU evidence format.

Card check: needs-gpu. This pull request changes crates/gpu-deepseek41/src/body.rs, crates/gpu-deepseek41/src/body/snap.rs, crates/gpu-gates/src/bin/shared/serve_seats/ds41.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the last review: There were no must-fix or non-blocking items. The interdiff changes only the unsafe-count pin after the rebase.

Verdict: CLEAN: The revised pin matches the source count and carries the required dated reason.

Checked

Duplicates: 0 new items in the interdiff. Dryer reports 0 qualifying pairs; the previously reviewed code patches are unchanged.
Complexity: Crapper flags SeatEngine::spawn (39 → 40, protocol arm) and Slot::reuse (26 → 27, sealed-state guard). Both patches are unchanged since the previous review.
Silent failure: 0 sites added by the interdiff.
Tests: No tests changed since the previous review. Removing SaveLane::copy's error synchronization remains caught by the held-stream test's early-return and lent-byte assertions. GPU tests were not run here.
Gates: tools/unsafe-ratchet.txt:486 pins 2266 → 2267 blocks with a dated reason. Independent recounts match both trees; unsafe functions and implementations remain 281 and 10.
Adversarial checks: A stale or excessive allowance is refuted by the exact recount. The additional block belongs to the named held-stream test and has its safety invariant documented.
Escape catalog: C1–C4 do not match the interdiff.

Notes

The PR reports tests before the final rebase. It lacks tested commit hashes and just gate-* commands with output, so it does not meet the required GPU evidence format.

Card check: needs-gpu. This pull request changes crates/gpu-deepseek41/src/body.rs, crates/gpu-deepseek41/src/body/snap.rs, crates/gpu-gates/src/bin/shared/serve_seats/ds41.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit a15d314 into midagedev:main Oct 23, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant