diff --git a/.agents/skills/manage-ci/SKILL.md b/.agents/skills/manage-ci/SKILL.md
index 953bf520..4334474c 100644
--- a/.agents/skills/manage-ci/SKILL.md
+++ b/.agents/skills/manage-ci/SKILL.md
@@ -58,7 +58,12 @@ contract; no downstream product's workflow topology applies here.
runs Graph Contracts in parallel with sixteen package jobs.
Each CPU job supplies a shared platform CLI to its backend jobs. Routine CI
uses two device jobs and checks the three remaining CUDA archives on hosted
- compiler-image runners.
+ compiler-image runners. A dedicated KV path filter selects short cache checks
+ in the Metal and ARM64 CUDA 13 device jobs. Full CI qualifies all four KV
+ fixtures in those same device jobs using their exact packaged runtimes.
+ KV qualification gates known answers, identity/isolation and observed reuse;
+ token/score traces and optional upstream observations are diagnostics. It does
+ not require a separately built upstream server or numerical equivalence.
Tagged releases add device smoke on those exact archives, including x64 CUDA 13.
Windows ARM64 CPU is package-only in full CI and releases. Windows x64 CPU
retains archive verification. Full CI additionally requires
@@ -295,3 +300,5 @@ target matrix and `ci/README.md`. Validate syntax, matrix consistency, relevant
Rust tests and the actual Just commands. Report unexecuted hardware checks and
unverified external runner/repository configuration explicitly. Never describe
workflow syntax validation as a successful build or hardware qualification.
+
+KV cache qualification in this branch runs after exact-package device smoke in the Metal and ARM64 CUDA 13 package jobs: short on selected PR packages, full on full CI. Harness and action inputs select those packages through the shared package filter.
diff --git a/.github/actions/ci-cache-correctness/action.yml b/.github/actions/ci-cache-correctness/action.yml
new file mode 100644
index 00000000..d2ba3ed2
--- /dev/null
+++ b/.github/actions/ci-cache-correctness/action.yml
@@ -0,0 +1,33 @@
+name: KV cache correctness
+description: Qualify the exact native runtime in a Skippy package on its matching GPU.
+inputs:
+ runtime-id:
+ description: Packaged runtime from ci/targets.json.
+ required: true
+ profile:
+ description: Short dense fixture or full four-fixture qualification.
+ required: true
+runs:
+ using: composite
+ steps:
+ - uses: ./.github/actions/setup-hf
+ - name: Test KV reuse against the shipped runtime
+ shell: bash
+ env:
+ RUNTIME_ID: ${{ inputs.runtime-id }}
+ KV_PROFILE: ${{ inputs.profile }}
+ run: |
+ just cache-correctness-package "$RUNTIME_ID" "$KV_PROFILE" "dist/products/$RUNTIME_ID" "target/cache-qualification-$RUNTIME_ID"
+ - name: Retain reports and native logs
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: ${{ env.SKIPPY_ARTIFACT_SCOPE }}-cache-correctness-${{ inputs.runtime-id }}
+ path: |
+ target/cache-qualification-${{ inputs.runtime-id }}/*.json
+ target/cache-qualification-${{ inputs.runtime-id }}/*/*.json
+ target/cache-qualification-${{ inputs.runtime-id }}/*/*.log
+ target/cache-qualification-${{ inputs.runtime-id }}/*/template-identity/*.log
+ if-no-files-found: ignore
+ overwrite: true
+ retention-days: 14
diff --git a/.github/actions/ci-package/action.yml b/.github/actions/ci-package/action.yml
index 810aa17c..8f07a4e8 100644
--- a/.github/actions/ci-package/action.yml
+++ b/.github/actions/ci-package/action.yml
@@ -16,6 +16,9 @@ inputs:
smoke:
description: Select inference smoke, artifact smoke, or none for a package-only runtime.
default: inference
+ kv-profile:
+ description: Run short or full KV qualification against the packaged runtime.
+ default: ''
windows-cuda:
description: Pinned CUDA toolkit version to provision on the hosted Windows builder.
default: ''
@@ -175,6 +178,7 @@ runs:
if: inputs.smoke == 'inference'
with:
runtime_id: ${{ inputs.runtime-id }}
+ kv-profile: ${{ inputs.kv-profile }}
- name: Upload package
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
diff --git a/.github/actions/ci-smoke/action.yml b/.github/actions/ci-smoke/action.yml
index 80352f5a..42c92529 100644
--- a/.github/actions/ci-smoke/action.yml
+++ b/.github/actions/ci-smoke/action.yml
@@ -7,6 +7,9 @@ inputs:
download-package:
description: Restore the archived package for a separate release device smoke.
default: 'false'
+ kv-profile:
+ description: Run short or full KV qualification after device smoke.
+ default: ''
evidence-suffix:
description: Driver vendor suffix for independent Vulkan device evidence.
default: ''
@@ -58,6 +61,11 @@ runs:
export TMPDIR="$RUNNER_TEMP"
fi
just ci-smoke "$RUNTIME_ID" "dist/products/$RUNTIME_ID"
+ - uses: ./.github/actions/ci-cache-correctness
+ if: inputs.kv-profile != ''
+ with:
+ runtime-id: ${{ inputs.runtime_id }}
+ profile: ${{ inputs.kv-profile }}
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: inputs.download-package == 'true'
with:
diff --git a/.github/actions/setup-hf/action.yml b/.github/actions/setup-hf/action.yml
new file mode 100644
index 00000000..136c69ce
--- /dev/null
+++ b/.github/actions/setup-hf/action.yml
@@ -0,0 +1,19 @@
+name: Prepare Hugging Face CLI
+description: Supply the hf command when it is missing from the runner.
+runs:
+ using: composite
+ steps:
+ - name: Set up hf
+ shell: bash
+ run: |
+ if command -v hf >/dev/null; then
+ exit 0
+ fi
+ venv="$RUNNER_TEMP/skippy-hf"
+ python3 -m venv "$venv"
+ bin="$venv/bin"
+ if [[ "$RUNNER_OS" == Windows ]]; then
+ bin="$venv/Scripts"
+ fi
+ "$bin/python" -m pip install --disable-pip-version-check 'huggingface-hub==1.33.0'
+ echo "$bin" >> "$GITHUB_PATH"
diff --git a/.github/path-filters.yml b/.github/path-filters.yml
index 3396d6f6..f2abd1e0 100644
--- a/.github/path-filters.yml
+++ b/.github/path-filters.yml
@@ -58,6 +58,8 @@ code:
packages:
- 'crates/**'
+ - 'tools/xtask/**'
+ - '.github/actions/ci-cache-correctness/**'
- 'skippy_api/src/**'
- 'skippy_api/include/**'
- 'skippy_api/CMakeLists.txt'
diff --git a/.github/scripts/ci-gate.test.cjs b/.github/scripts/ci-gate.test.cjs
index 03b52301..730f4060 100644
--- a/.github/scripts/ci-gate.test.cjs
+++ b/.github/scripts/ci-gate.test.cjs
@@ -555,3 +555,14 @@ test('full CI requires both Windows GPU results and PR checks skip them', () =>
pr.smoke_windows_cuda.result = 'success';
assert.throws(() => gate(pr), /smoke_windows_cuda must be skipped/);
});
+
+test('native package smoke retains exact-archive KV qualification in both device jobs', () => {
+ for (const key of ['package_darwin_aarch64_metal', 'package_linux_aarch64_cuda13']) {
+ const body = workflow.split(`\n ${key}:\n`)[1].split(/\n \w+:\n/)[0];
+ assert.match(body, /kv-profile:.*needs.plan.outputs.profile == 'full'.*'full'.*'short'/);
+ }
+ const packageAction = readFileSync(join(__dirname, '../actions/ci-package/action.yml'), 'utf8');
+ assert.match(packageAction, /kv-profile: \$\{\{ inputs.kv-profile \}\}/);
+ const smoke = readFileSync(join(__dirname, '../actions/ci-smoke/action.yml'), 'utf8');
+ assert.ok(smoke.indexOf('just ci-smoke') < smoke.indexOf('uses: ./.github/actions/ci-cache-correctness'));
+});
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d4305cc2..a8614340 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -605,6 +605,7 @@ jobs:
with:
runtime-id: darwin-aarch64-metal
host-id: darwin-aarch64
+ kv-profile: ${{ needs.plan.outputs.profile == 'full' && 'full' || 'short' }}
build-cli: ${{ needs.plan.outputs.profile == 'pr' }}
candidate-artifact: ${{ inputs.candidate_artifact }}
candidate-sha: ${{ inputs.candidate_sha }}
@@ -862,6 +863,7 @@ jobs:
with:
runtime-id: linux-aarch64-cuda13
host-id: linux-aarch64
+ kv-profile: ${{ needs.plan.outputs.profile == 'full' && 'full' || 'short' }}
build-cli: ${{ needs.plan.outputs.profile == 'pr' }}
candidate-artifact: ${{ inputs.candidate_artifact }}
candidate-sha: ${{ inputs.candidate_sha }}
diff --git a/Cargo.lock b/Cargo.lock
index 04e87f63..b88417fb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5304,6 +5304,7 @@ dependencies = [
"skippy-cache",
"skippy-config",
"skippy-coordinator",
+ "skippy-events",
"skippy-ffi",
"skippy-hf-hub",
"skippy-inference-api",
@@ -5788,6 +5789,7 @@ dependencies = [
"futures-util",
"libc",
"opentelemetry-proto",
+ "reqwest 0.13.5",
"serde",
"serde_json",
"sha2 0.11.1",
@@ -8025,6 +8027,20 @@ version = "0.8.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
+[[package]]
+name = "xtask"
+version = "0.80.0"
+dependencies = [
+ "hex",
+ "serde",
+ "serde_json",
+ "sha2 0.11.1",
+ "skippy-model-artifact",
+ "skippy-subprocess",
+ "tar",
+ "tempfile",
+]
+
[[package]]
name = "xxhash-rust"
version = "0.8.21"
diff --git a/Cargo.toml b/Cargo.toml
index dd3b79e9..ced7c591 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = ["crates/*", "tools/process-supervision"]
+members = ["crates/*", "tools/process-supervision", "tools/xtask"]
default-members = ["crates/skippy-cli"]
resolver = "2"
@@ -24,6 +24,11 @@ tokio-tungstenite = "0.29"
cognitive_complexity = "warn"
too_many_lines = "warn"
+# Hardware cache qualification uses the cold-prefill budget when staging a
+# disk restore. Keep the pack digest on the same optimized path as release.
+[profile.dev.package.blake3]
+opt-level = 3
+
[profile.dev.package.sha2]
opt-level = 3
diff --git a/Justfile b/Justfile
index 57d10417..6e3fcc88 100644
--- a/Justfile
+++ b/Justfile
@@ -135,6 +135,36 @@ test: skippy-api-test
@cargo test --workspace --no-default-features
@cargo test --manifest-path skippy-api-rs/Cargo.toml --workspace
+cache-correctness-metal:
+ @SKIPPY_CACHE_QUAL_BACKEND=metal LLAMA_STAGE_BACKEND=metal just with-lld cargo test --locked -p skippy-serving --lib frontend::tests::cache_qualification::cross_tier -- --ignored --exact --nocapture
+
+[unix]
+cache-correctness-cuda:
+ @SKIPPY_CACHE_QUAL_BACKEND="${SKIPPY_CACHE_QUAL_BACKEND:-cuda}" LLAMA_STAGE_BACKEND=cuda just with-lld cargo test --locked -p skippy-serving --lib frontend::tests::cache_qualification::cross_tier -- --ignored --exact --nocapture
+
+cache-correctness-matrix backend output *options:
+ @cargo run --locked -p xtask -- "{{ backend }}" "{{ output }}" {{ options }}
+
+cache-correctness-package variant profile product output:
+ @cargo run --locked -p xtask -- package {{ quote(variant) }} {{ quote(profile) }} {{ quote(product) }} {{ quote(output) }}
+
+[unix]
+cache-correctness-verify backend report:
+ @SKIPPY_CACHE_QUAL_BACKEND={{ quote(backend) }} SKIPPY_CACHE_QUAL_VERIFY_REPORT={{ quote(report) }} just with-lld cargo test --locked -p skippy-serving --features dynamic-native-runtime --lib frontend::tests::cache_qualification::verify_report -- --ignored --exact --nocapture
+
+[unix]
+cache-correctness-verify-matrix backend source report_dir:
+ @cargo run --locked -p xtask -- verify {{ quote(backend) }} {{ quote(source) }} {{ quote(report_dir) }}
+
+[unix]
+cache-correctness-native-dir:
+ @scripts/build-llama.sh --print-build-dir
+
+[unix]
+cache-correctness-reference source build pin *options:
+ @cmake -S "{{ source }}" -B "{{ build }}" -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DLLAMA_BUILD_COMMIT="{{ pin }}" -DLLAMA_BUILD_COMMON=ON -DLLAMA_BUILD_SERVER=ON -DLLAMA_BUILD_TOOLS=ON -DLLAMA_BUILD_APP=OFF -DLLAMA_BUILD_TESTS=OFF -DLLAMA_BUILD_EXAMPLES=OFF -DLLAMA_OPENSSL=OFF -DLLAMA_BUILD_UI=OFF -DLLAMA_USE_PREBUILT_UI=OFF {{ options }}
+ @cmake --build "{{ build }}" --target llama-server
+
llama-prepare:
@scripts/prepare-llama.sh pinned
@@ -292,6 +322,10 @@ ci-model-fetch:
ci-artifact-smoke runtime product_dir:
@"{{ automation_python }}" scripts/ci-product.py artifact-smoke "$@"
+[positional-arguments]
+ci-extract-runtime runtime product_dir output:
+ @"{{ automation_python }}" scripts/ci-product.py extract-runtime "$@"
+
ci: lint test llama-check
[positional-arguments]
diff --git a/README.md b/README.md
index bd76476e..1583a7db 100644
--- a/README.md
+++ b/README.md
@@ -53,6 +53,7 @@ shared HTTP surface in
- [Retained compatibility identifiers](docs/COMPATIBILITY.md)
- [Configuration reference](docs/CONFIGURATION.md)
- [Serving settings](docs/SERVING_SETTINGS.md)
+- [Disk KV cache operations](docs/PROMPT_CACHE.md#inspect-and-maintain-the-disk-cache)
- [Continuous integration](ci/README.md)
- [Private releases](RELEASE.md)
- [Split serving](docs/SKIPPY_SPLITS.md)
diff --git a/ci/INFERENCE_QUALIFICATION.md b/ci/INFERENCE_QUALIFICATION.md
index daf15df4..0b52f2e8 100644
--- a/ci/INFERENCE_QUALIFICATION.md
+++ b/ci/INFERENCE_QUALIFICATION.md
@@ -110,7 +110,8 @@ matching official tokenizer revision and layer count. Most fixtures use Q4_K_M;
Flash-Next uses the four-shard IQ4_XS base model, not similarly named MTP sidecars.
Admission reserves at least 16 GiB beyond weight bytes and checks available
unified memory. This floor is not proof every context fits; real allocation
-failures remain failures. Model caches are explicit, hash-verified inputs.
+failures remain failures. Native jobs use `hf download` with the NAS-backed
+Hugging Face cache, verify each shard, and serve from the snapshot paths.
Nightly and release run CPU chain parity and state-handoff checks against native
monolithic execution (sharing file-backed weights avoids duplicate GPU copies
diff --git a/ci/README.md b/ci/README.md
index 14f2f3a5..07f3c9b6 100644
--- a/ci/README.md
+++ b/ci/README.md
@@ -112,6 +112,16 @@ documentation and image builds use their ordinary workflows, not Depot wrappers.
The existing inference PR comment is target-event-only; fork qualification links
and artifacts are available in **Approved fork CI** and the aggregate status.
+The `kv` filter also selects the Metal and Linux ARM64 CUDA 13 package jobs.
+Each selected short run checks one dense fixture for known JSON answers,
+L1 reuse, and L3 restoration in a fresh process. Numerical traces are diagnostic; the gate
+requires correct answers, identity/isolation and actual reuse. Full profiles run all four
+fixtures in those same jobs after device smoke, against the exact packaged
+runtime. PRs read base-revision filters, falling back conservatively to code
+selection before the KV filter lands. Main uses its last verified covered
+commit and forces KV qualification when prior coverage cannot be verified.
+See the [KV correctness gate](../docs/CACHE_CORRECTNESS_GATE.md).
+
Inference implementation changes require native qualification on every PR head.
This includes serving, scheduling, runtime/FFI, native patches and qualification
execution code; adding report or test files to the same PR does not remove that
@@ -271,7 +281,7 @@ compares verified measurements directly with its saved baselines, and uploads
aggregate Parquet results, the baseline manifest, and the generated card in
one revision-checked commit to
[the public qualification dataset](https://huggingface.co/datasets/meshllm/skippy-inference-qualification).
-The initial tolerance and promotion threshold are 5% per performance metric.
+The tolerance and promotion threshold are 1% per performance metric.
A changed benchmark recipe seeds its own reference. Passing measurements are
recorded while the saved reference remains in force until a new source exceeds
the improvement threshold. Regressions and incomplete evidence fail nightly
@@ -687,8 +697,8 @@ Sparks. Protected dispatch code verifies trust before sending a pinned source
SHA. Jobs use the standard JY account and its existing host permissions without publisher credentials,
fresh workspaces, read-only admitted models, exclusive machine reservations and
bounded leases. Clean up job processes and workspaces after every outcome;
-quarantine an allocation whose cleanup fails. Fork and other untrusted PRs still
-require isolated ephemeral execution. The `unconfined` capability is not itself
+quarantine an allocation whose cleanup fails. Fork PRs enter native execution only through the protected approved-fork
+controller after maintainer workflow approval; other untrusted work stays isolated. The `unconfined` capability is not itself
an admission failure; no separate job-account migration is required. Actions
only orchestrates these jobs, so the 6 GiB runner-container limit does not bound
model execution. Split jobs reserve both Sparks atomically. This policy does not
@@ -715,6 +725,18 @@ artifact smoke is recorded separately from inference evidence.
## Artifact flow
+```mermaid
+flowchart LR
+ path["Independent path selection and build plan"] --> automation["Offline automation"]
+ automation --> quality["Source checks when selected"]
+ quality --> metal["Metal package and device smoke"]
+ quality --> arm["ARM64 CUDA 13 package and device smoke"]
+ metal --> metalKv["KV in the same job
Selected short: one fixture; full: four"]
+ arm --> armKv["KV in the same job
Selected short: one fixture; full: four"]
+ metalKv --> gate["CI result gate"]
+ armKv --> gate
+```
+
`just ci-plan` validates the target matrix with `jq`. The package and
smoke commands use Python 3.9 or later. Release inventory uses Python
3.11 or later for TOML parsing. With uv installed, Justfile recipes run Python
@@ -1073,3 +1095,5 @@ publication gates on scheduled llama upgrades. An already-current release must
finish at hosted resolution without entering those stages.
No hosted/hardware capacity or secret configuration is implied by these files.
+
+KV qualification remains attached to both native package jobs (Metal and ARM64 CUDA 13): short checks on selected PR packages and the full four-fixture checks on full CI. Both use the exact packaged runtime after device smoke and retain independent KV evidence. The shared packages filter includes the KV harness and action inputs. CUDA archives use the shared product handoff; no separate duplicate ARM64 package/device job is required.
diff --git a/crates/llama-spec-bench/Cargo.toml b/crates/llama-spec-bench/Cargo.toml
index ebf9b6b1..5b132f13 100644
--- a/crates/llama-spec-bench/Cargo.toml
+++ b/crates/llama-spec-bench/Cargo.toml
@@ -6,6 +6,9 @@ license.workspace = true
publish = false
version.workspace = true
+[features]
+dynamic-native-runtime = ["skippy-runtime/dynamic-native-runtime", "skippy-runtime/test-support"]
+
[dependencies]
anyhow.workspace = true
clap.workspace = true
diff --git a/crates/llama-spec-bench/README.md b/crates/llama-spec-bench/README.md
index 34bc93e7..1f4a7388 100644
--- a/crates/llama-spec-bench/README.md
+++ b/crates/llama-spec-bench/README.md
@@ -101,3 +101,60 @@ generation may legitimately diverge from the baseline at a near-tie token.
The default corpus path is
`evals/corpora/kv_mixed_prompts.jsonl`.
+
+## Packaged native runtimes
+
+Build with `--features dynamic-native-runtime` to use a separately packaged
+runtime. Set `SKIPPY_NATIVE_RUNTIME_BUNDLE_DIR` to the matching runtime bundle
+directory before invoking the benchmark. The default build retains static
+linking.
+
+For draft readout comparisons, run `--dflash` once with
+`SKIPPY_DFLASH_GPU_READOUT` unset and once with it set to `1`. JSON reports
+include `draft_backend_readout`, `draft_backend_token_rows` and
+`draft_host_fallback_rows`, so a requested backend path cannot silently be
+reported as measured offload. Keep the same corpus, token counts and draft
+window, warm up each arm, and interleave repeated runs before comparing rates.
+
+Compare feature transfers separately with `SKIPPY_DFLASH_GPU_READOUT=0` and
+`SKIPPY_DFLASH_DEVICE_FEATURES=0` versus `1`. The
+`draft_device_feature_rows` field must be positive in the device arm. These
+component rates measure forward timings. The `*_decode_wall_ms` and
+`*_wall_tokens_per_second` fields measure the complete post-prefill loop,
+including rollback and bookkeeping. Use a serving workload to establish
+request latency and concurrent throughput gains.
+
+DFlash target contexts default to `window + 1` recurrent rollback snapshots,
+matching the serving plan's draft-plus-anchor depth. The JSON report records
+`target_recurrent_rollback_tokens`. Use `--recurrent-rollback-tokens 0` only
+when deliberately measuring checkpoint fallback; undersized snapshots can
+make rollback replay dominate decode time.
+
+`--verify-reference` diagnoses target batching independently of a drafter.
+It replays the serial continuation as forced inputs, compares single-token
+sampling against `window + 1` row verification, and records the first
+divergence with the top five raw log probabilities in each path. A trace
+stops at its first mismatch because sampled verification intentionally does
+not sample a rejected suffix. It fails on a difference unless
+`--allow-mismatch` explicitly requests a diagnostic report. No throughput
+claim should use that diagnostic mode.
+
+`--verify-reference --dflash-lanes 2 --shared-verify` traces shared target
+forwards on two equal-length reference continuations without a draft model.
+Add `--dflash` to attach the draft's feature-capture graph while still never
+proposing or rolling back draft tokens. The report records `draft_attached`,
+`lane_count` and actual `shared_forwards`, so capture and multi-sequence graph
+effects can be distinguished from draft proposal or repair effects.
+
+For two concurrent DFlash lanes, provide two prompts and `--dflash-lanes 2`.
+The control verifies each lane independently; `--shared-verify` combines
+equal-length windows using native ABI `0.1.82`. Both arms include proposing,
+verification, repair, and bookkeeping in `decode_wall_ms`, and report total
+output throughput across the lanes. The report records shared versus single
+forwards and the output tokens of each lane for exact comparison. This is a
+runtime diagnostic, not a measurement of the serving scheduler.
+
+Add `--shared-draft` to combine compatible lanes' draft noise blocks too.
+`shared_draft_lane_proposals` counts lanes that actually shared draft forwards,
+so a capacity or head fallback remains visible. Hold `--shared-verify` fixed
+when comparing independent and shared drafting to isolate its contribution.
diff --git a/crates/llama-spec-bench/src/concurrent_dflash.rs b/crates/llama-spec-bench/src/concurrent_dflash.rs
new file mode 100644
index 00000000..b6cfaf5a
--- /dev/null
+++ b/crates/llama-spec-bench/src/concurrent_dflash.rs
@@ -0,0 +1,268 @@
+//! Matched concurrent decode loops with independent or shared verification.
+use std::{collections::BTreeMap, time::Instant};
+
+use anyhow::{Context, Result, bail};
+use serde::Serialize;
+use skippy_runtime::dflash::proposal_batch::DFlashBatchRequest;
+use skippy_runtime::{StageModel, StageSession, verification_batch::VerifyBatchRequest};
+
+use crate::{Args, Baseline, PromptCase, elapsed_ms, first_mismatch, tokens_per_second};
+
+struct Lane {
+ session: StageSession,
+ current: i32,
+ tokens: Vec,
+ accepted: usize,
+ finished: bool,
+}
+
+#[derive(Serialize)]
+struct Report {
+ mode: &'static str,
+ shared_verify: bool,
+ shared_draft: bool,
+ shared_draft_lane_proposals: u64,
+ lane_count: usize,
+ ctx_size: u32,
+ window: usize,
+ decode_wall_ms: f64,
+ output_tokens: usize,
+ output_tokens_per_second: f64,
+ shared_forwards: usize,
+ single_forwards: usize,
+ device_feature_rows: u64,
+ lanes: Vec,
+}
+
+#[derive(Serialize)]
+struct LaneReport {
+ id: String,
+ correct: bool,
+ mismatch_index: Option,
+ accepted_draft_tokens: usize,
+ output_tokens: Vec,
+ baseline_output_tokens: Vec,
+ verify_windows_in_place: u64,
+ verify_windows_checkpointed: u64,
+ shared_draft_proposals: u64,
+}
+
+pub(super) fn run(
+ args: &Args,
+ target: &StageModel,
+ prompts: &[PromptCase],
+ baselines: &[Baseline],
+) -> Result<()> {
+ let mut lanes = Vec::new();
+ for baseline in baselines {
+ let mut session = target.create_session()?;
+ let prefix = &baseline.target_tokens[..baseline.target_tokens.len() - 1];
+ session.prefill_chunked(prefix)?;
+ lanes.push(Lane {
+ session,
+ current: *baseline.target_tokens.last().expect("nonempty prompt"),
+ tokens: Vec::new(),
+ accepted: 0,
+ finished: false,
+ });
+ }
+ let mut shared_forwards = 0;
+ let mut single_forwards = 0;
+ let started = Instant::now();
+ while lanes.iter().any(|lane| !lane.finished) {
+ let inputs = propose(args, &mut lanes)?;
+ let (predictions, shared, single) = verify(&mut lanes, &inputs, args.shared_verify)?;
+ shared_forwards += shared;
+ single_forwards += single;
+ for ((lane, input), predicted) in lanes.iter_mut().zip(&inputs).zip(&predictions) {
+ if !lane.finished {
+ commit(target, args.max_new_tokens, lane, input, predicted)?;
+ }
+ }
+ }
+ let decode_wall_ms = elapsed_ms(started);
+ let mut reports = Vec::new();
+ for ((lane, prompt), baseline) in lanes.into_iter().zip(prompts).zip(baselines) {
+ let mismatch_index = first_mismatch(&baseline.generation.tokens, &lane.tokens);
+ let rollback = lane.session.verify_rollback_counts()?;
+ reports.push(LaneReport {
+ id: prompt.id.clone(),
+ correct: mismatch_index.is_none(),
+ mismatch_index,
+ accepted_draft_tokens: lane.accepted,
+ output_tokens: lane.tokens,
+ baseline_output_tokens: baseline.generation.tokens.clone(),
+ verify_windows_in_place: rollback.in_place,
+ verify_windows_checkpointed: rollback.checkpointed,
+ shared_draft_proposals: lane
+ .session
+ .dflash_draft_stats()
+ .map_or(0, |stats| stats.shared_proposals),
+ });
+ }
+ let output_tokens = reports
+ .iter()
+ .map(|report| report.output_tokens.len())
+ .sum();
+ let report = Report {
+ mode: "concurrent DFlash diagnostic; complete post-prefill loop",
+ shared_verify: args.shared_verify,
+ shared_draft: args.shared_draft,
+ shared_draft_lane_proposals: reports.iter().map(|lane| lane.shared_draft_proposals).sum(),
+ lane_count: args.dflash_lanes,
+ ctx_size: args.ctx_size,
+ window: args.speculative_window,
+ decode_wall_ms,
+ output_tokens,
+ output_tokens_per_second: tokens_per_second(output_tokens, decode_wall_ms),
+ shared_forwards,
+ single_forwards,
+ device_feature_rows: target.dflash_device_feature_rows(),
+ lanes: reports,
+ };
+ eprintln!(
+ "concurrent decode: {:.2} tok/s shared={} single={}",
+ report.output_tokens_per_second, shared_forwards, single_forwards
+ );
+ let json = serde_json::to_string_pretty(&report)?;
+ if let Some(path) = &args.json_out {
+ std::fs::write(path, format!("{json}\n"))?;
+ } else {
+ println!("{json}");
+ }
+ if !args.allow_mismatch && report.lanes.iter().any(|lane| !lane.correct) {
+ bail!("concurrent verification diverged from serial target output");
+ }
+ Ok(())
+}
+
+fn propose(args: &Args, lanes: &mut [Lane]) -> Result>> {
+ if args.shared_draft {
+ let mut requests: Vec<_> = lanes
+ .iter_mut()
+ .filter(|lane| !lane.finished)
+ .map(|lane| DFlashBatchRequest {
+ session: &mut lane.session,
+ anchor: lane.current,
+ max_tokens: args
+ .speculative_window
+ .min((args.max_new_tokens - lane.tokens.len()).saturating_sub(1)),
+ })
+ .collect();
+ let outputs = StageSession::dflash_propose_batch(&mut requests)?;
+ let mut outputs = outputs.into_iter();
+ return lanes
+ .iter()
+ .map(|lane| {
+ if lane.finished {
+ return Ok(Vec::new());
+ }
+ let proposal = outputs
+ .next()
+ .flatten()
+ .context("concurrent target has no DFlash draft")?;
+ let mut input = vec![lane.current];
+ input.extend(proposal.tokens);
+ Ok(input)
+ })
+ .collect();
+ }
+ lanes
+ .iter_mut()
+ .map(|lane| {
+ if lane.finished {
+ return Ok(Vec::new());
+ }
+ let remaining = args.max_new_tokens - lane.tokens.len();
+ let proposal = lane
+ .session
+ .dflash_propose(
+ lane.current,
+ args.speculative_window.min(remaining.saturating_sub(1)),
+ )?
+ .context("concurrent target has no DFlash draft")?;
+ let mut input = vec![lane.current];
+ input.extend(proposal.tokens);
+ Ok(input)
+ })
+ .collect()
+}
+
+fn verify(
+ lanes: &mut [Lane],
+ inputs: &[Vec],
+ shared: bool,
+) -> Result<(Vec>, usize, usize)> {
+ let mut groups = BTreeMap::>::new();
+ for (index, input) in inputs
+ .iter()
+ .enumerate()
+ .filter(|(_, input)| !input.is_empty())
+ {
+ groups.entry(input.len()).or_default().push(index);
+ }
+ let mut predictions = vec![Vec::new(); lanes.len()];
+ let mut shared_forwards = 0;
+ let mut single_forwards = 0;
+ for (width, indexes) in groups {
+ if shared && indexes.len() > 1 {
+ let mut requests: Vec<_> = lanes
+ .iter_mut()
+ .zip(inputs)
+ .filter(|(_, input)| input.len() == width)
+ .map(|(lane, input)| VerifyBatchRequest {
+ session: &mut lane.session,
+ token_ids: input,
+ sampling: None,
+ })
+ .collect();
+ let outputs = StageSession::verify_batch_sampled(&mut requests)?;
+ for (index, output) in indexes.into_iter().zip(outputs) {
+ predictions[index] = output;
+ }
+ shared_forwards += 1;
+ } else {
+ for index in indexes {
+ predictions[index] = lanes[index]
+ .session
+ .verify_tokens_sampled(&inputs[index], None)?;
+ single_forwards += 1;
+ }
+ }
+ }
+ Ok((predictions, shared_forwards, single_forwards))
+}
+
+fn commit(
+ target: &StageModel,
+ limit: usize,
+ lane: &mut Lane,
+ inputs: &[i32],
+ predicted: &[i32],
+) -> Result<()> {
+ let accepted = inputs[1..]
+ .iter()
+ .zip(predicted)
+ .take_while(|(draft, target)| draft == target)
+ .count();
+ let base = lane.session.token_count() - inputs.len() as u64;
+ let mut committed = 0;
+ for &token in predicted.iter().take(accepted + 1) {
+ lane.tokens.push(token);
+ lane.current = token;
+ committed += 1;
+ if target.token_is_eog(token)? || lane.tokens.len() == limit {
+ lane.finished = true;
+ break;
+ }
+ }
+ anyhow::ensure!(committed > 0, "verification produced no committed token");
+ lane.accepted += accepted.min(committed);
+ if committed == inputs.len() {
+ lane.session
+ .retire_verify_checkpoint(base, inputs.len() as u64)?;
+ } else {
+ lane.session.trim_session(base + committed as u64)?;
+ }
+ Ok(())
+}
diff --git a/crates/llama-spec-bench/src/dflash.rs b/crates/llama-spec-bench/src/dflash.rs
index f94c4ed9..a6340340 100644
--- a/crates/llama-spec-bench/src/dflash.rs
+++ b/crates/llama-spec-bench/src/dflash.rs
@@ -16,7 +16,7 @@ pub(crate) fn generate_dflash(
let mut session = target.create_session()?;
let target_prefill_started = Instant::now();
if run.prompt_tokens.len() > 1 {
- session.prefill_chunk(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?;
+ session.prefill_chunked(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?;
}
let target_prefill_ms = elapsed_ms(target_prefill_started);
@@ -83,7 +83,12 @@ pub(crate) fn generate_dflash(
}
}
+ let decode_wall_ms = elapsed_ms(started);
+ let rollback = session.verify_rollback_counts()?;
Ok(SpecGeneration {
+ verify_windows_in_place: rollback.in_place,
+ verify_windows_checkpointed: rollback.checkpointed,
+ decode_wall_ms,
tokens: generated,
stats,
target_prefill_ms,
diff --git a/crates/llama-spec-bench/src/main.rs b/crates/llama-spec-bench/src/main.rs
index fe20fbb6..d09a6b05 100644
--- a/crates/llama-spec-bench/src/main.rs
+++ b/crates/llama-spec-bench/src/main.rs
@@ -13,7 +13,9 @@ use skippy_runtime::{
StageSession,
};
+mod concurrent_dflash;
mod dflash;
+mod verify_reference;
const DEFAULT_CORPUS: &str = "skippy/evals/corpora/kv_mixed_prompts.jsonl";
@@ -49,6 +51,21 @@ struct Args {
/// Treat the draft as a DFlash/DFlash2 block drafter attached to the target.
#[arg(long)]
dflash: bool,
+ /// Target rollback snapshots; DFlash defaults to window + anchor.
+ #[arg(long)]
+ recurrent_rollback_tokens: Option,
+ /// Diagnose batched verification on the serial baseline's exact inputs.
+ #[arg(long)]
+ verify_reference: bool,
+ /// Concurrent DFlash lanes; provide exactly one prompt per lane.
+ #[arg(long, default_value_t = 1)]
+ dflash_lanes: usize,
+ /// Combine equal-length concurrent verify windows in one target forward.
+ #[arg(long)]
+ shared_verify: bool,
+ /// Combine concurrent noise blocks in one draft forward.
+ #[arg(long)]
+ shared_draft: bool,
}
#[derive(Debug, Clone)]
@@ -60,6 +77,11 @@ struct PromptCase {
#[derive(Debug, Serialize)]
struct Report {
+ target_recurrent_rollback_tokens: u32,
+ draft_backend_readout: bool,
+ draft_backend_token_rows: u64,
+ draft_host_fallback_rows: u64,
+ draft_device_feature_rows: u64,
target_model_path: String,
draft_model_path: String,
ctx_size: u32,
@@ -73,6 +95,13 @@ struct Report {
#[derive(Debug, Default, Serialize)]
struct Summary {
+ verify_windows_in_place: u64,
+ verify_windows_checkpointed: u64,
+ baseline_decode_wall_ms: f64,
+ speculative_decode_wall_ms: f64,
+ baseline_wall_tokens_per_second: f64,
+ speculative_wall_tokens_per_second: f64,
+ speculative_wall_speedup_vs_baseline: f64,
correct_prompts: usize,
mismatched_prompts: usize,
prompt_tokens_total: usize,
@@ -96,6 +125,10 @@ struct Summary {
#[derive(Debug, Serialize)]
struct PromptReport {
+ verify_windows_in_place: u64,
+ verify_windows_checkpointed: u64,
+ baseline_decode_wall_ms: f64,
+ speculative_decode_wall_ms: f64,
id: String,
category: Option,
prompt_tokens: usize,
@@ -118,10 +151,13 @@ struct PromptReport {
speculative_ttft_ms: f64,
baseline_text_preview: String,
speculative_text_preview: String,
+ baseline_output_tokens: Vec,
+ speculative_output_tokens: Vec,
}
#[derive(Debug)]
struct Generation {
+ decode_wall_ms: f64,
tokens: Vec,
prefill_ms: f64,
decode_ms: f64,
@@ -130,6 +166,9 @@ struct Generation {
#[derive(Debug)]
struct SpecGeneration {
+ verify_windows_in_place: u64,
+ verify_windows_checkpointed: u64,
+ decode_wall_ms: f64,
tokens: Vec,
stats: SpecStats,
target_prefill_ms: f64,
@@ -149,6 +188,8 @@ struct SpecStats {
fn main() -> Result<()> {
let args = Args::parse();
+ #[cfg(feature = "dynamic-native-runtime")]
+ skippy_runtime::test_support::require_native_runtime();
if args.max_new_tokens == 0 {
bail!("--max-new-tokens must be greater than zero");
}
@@ -172,6 +213,21 @@ fn main() -> Result<()> {
if prompts.is_empty() {
bail!("prompt set is empty");
}
+ if args.dflash_lanes == 0
+ || (args.dflash_lanes > 1
+ && ((!args.dflash && !args.verify_reference) || prompts.len() != args.dflash_lanes))
+ {
+ bail!("multiple lanes require --dflash or --verify-reference, and one prompt per lane");
+ }
+ if args.shared_verify && args.dflash_lanes < 2 {
+ bail!("--shared-verify requires multiple DFlash lanes");
+ }
+ if args.shared_draft && args.dflash_lanes < 2 {
+ bail!("--shared-draft requires multiple DFlash lanes");
+ }
+ if args.shared_draft && args.verify_reference {
+ bail!("--verify-reference does not run a draft model");
+ }
eprintln!(
"loading target={} draft={} prompts={} ctx={} max_new_tokens={} window={}",
@@ -185,11 +241,12 @@ fn main() -> Result<()> {
let mut target_config =
full_model_config(&args.target_model_path, args.ctx_size, args.n_gpu_layers)?;
- // This context later verifies drafts, even though its first run is serial.
- // DFlash includes the current-token anchor; reserve that bound for both
- // benchmark modes rather than relying on a native default.
- target_config.recurrent_rollback_tokens =
- u32::try_from(args.speculative_window.saturating_add(1)).unwrap_or(u32::MAX);
+ target_config.lane_count =
+ u32::try_from(args.dflash_lanes).context("lane count exceeds u32")?;
+ // Both DFlash and native MTP verify drafts after the serial baseline.
+ target_config.recurrent_rollback_tokens = args.recurrent_rollback_tokens.unwrap_or_else(|| {
+ u32::try_from(args.speculative_window.saturating_add(1)).unwrap_or(u32::MAX)
+ });
let mut target = StageModel::open(&args.target_model_path, &target_config)
.with_context(|| format!("open target model {}", args.target_model_path.display()))?;
// Baselines run before any draft exists: an attached DFlash draft makes
@@ -199,7 +256,18 @@ fn main() -> Result<()> {
eprintln!("baseline {}/{} {}", index + 1, prompts.len(), prompt.id);
baselines.push(run_baseline(&args, &target, prompt)?);
}
+ if args.verify_reference {
+ // Capture can change target graph fusion. Exercise that graph when
+ // requested, while still never proposing or rolling back draft tokens.
+ if args.dflash {
+ load_draft(&args, &mut target, &target_config)?;
+ }
+ return verify_reference::run(&args, &target, &baselines);
+ }
let draft = load_draft(&args, &mut target, &target_config)?;
+ if args.dflash_lanes > 1 {
+ return concurrent_dflash::run(&args, &target, &prompts, &baselines);
+ }
let mut reports = Vec::with_capacity(prompts.len());
for (index, (prompt, baseline)) in prompts.iter().zip(baselines).enumerate() {
@@ -214,7 +282,13 @@ fn main() -> Result<()> {
}
let summary = summarize(&reports);
+ let (draft_backend_token_rows, draft_host_fallback_rows) = target.dflash_backend_readout_rows();
let report = Report {
+ target_recurrent_rollback_tokens: target_config.recurrent_rollback_tokens,
+ draft_backend_readout: target.dflash_backend_readout_enabled(),
+ draft_backend_token_rows,
+ draft_host_fallback_rows,
+ draft_device_feature_rows: target.dflash_device_feature_rows(),
target_model_path: args.target_model_path.display().to_string(),
draft_model_path: args.draft_model_path.display().to_string(),
ctx_size: args.ctx_size,
@@ -412,6 +486,10 @@ fn run_prompt_pair(
};
Ok(PromptReport {
+ verify_windows_in_place: speculative.verify_windows_in_place,
+ verify_windows_checkpointed: speculative.verify_windows_checkpointed,
+ baseline_decode_wall_ms: baseline.decode_wall_ms,
+ speculative_decode_wall_ms: speculative.decode_wall_ms,
id: prompt.id.clone(),
category: prompt.category.clone(),
prompt_tokens: target_tokens.len(),
@@ -434,6 +512,8 @@ fn run_prompt_pair(
speculative_ttft_ms: speculative.ttft_ms,
baseline_text_preview: preview_text(target, &baseline.tokens)?,
speculative_text_preview: preview_text(target, &speculative.tokens)?,
+ baseline_output_tokens: baseline.tokens,
+ speculative_output_tokens: speculative.tokens,
})
}
@@ -445,7 +525,7 @@ fn generate_baseline(
let mut session = model.create_session()?;
let prefill_started = Instant::now();
if prompt_tokens.len() > 1 {
- session.prefill_chunk(&prompt_tokens[..prompt_tokens.len() - 1])?;
+ session.prefill_chunked(&prompt_tokens[..prompt_tokens.len() - 1])?;
}
let prefill_ms = elapsed_ms(prefill_started);
let mut current = *prompt_tokens.last().expect("checked non-empty prompt");
@@ -466,6 +546,7 @@ fn generate_baseline(
}
}
Ok(Generation {
+ decode_wall_ms: elapsed_ms(started),
tokens: generated,
prefill_ms,
decode_ms,
@@ -488,7 +569,7 @@ fn generate_speculative(
let mut draft_session = draft.create_session()?;
let target_prefill_started = Instant::now();
if run.prompt_tokens.len() > 1 {
- target_session.prefill_chunk(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?;
+ target_session.prefill_chunked(&run.prompt_tokens[..run.prompt_tokens.len() - 1])?;
}
let target_prefill_ms = elapsed_ms(target_prefill_started);
let draft_prefill_started = Instant::now();
@@ -559,6 +640,9 @@ fn generate_speculative(
}
Ok(SpecGeneration {
+ verify_windows_in_place: 0,
+ verify_windows_checkpointed: 0,
+ decode_wall_ms: elapsed_ms(started),
tokens: generated,
stats,
target_prefill_ms,
@@ -572,7 +656,7 @@ fn generate_speculative(
fn reset_draft_to_context(session: &mut StageSession, context_tokens: &[i32]) -> Result<()> {
session.reset()?;
if context_tokens.len() > 1 {
- session.prefill_chunk(&context_tokens[..context_tokens.len() - 1])?;
+ session.prefill_chunked(&context_tokens[..context_tokens.len() - 1])?;
}
Ok(())
}
@@ -595,6 +679,10 @@ fn preview_text(model: &StageModel, tokens: &[i32]) -> Result {
fn summarize(prompts: &[PromptReport]) -> Summary {
let mut summary = Summary::default();
for prompt in prompts {
+ summary.verify_windows_in_place += prompt.verify_windows_in_place;
+ summary.verify_windows_checkpointed += prompt.verify_windows_checkpointed;
+ summary.baseline_decode_wall_ms += prompt.baseline_decode_wall_ms;
+ summary.speculative_decode_wall_ms += prompt.speculative_decode_wall_ms;
summary.correct_prompts += usize::from(prompt.correct);
summary.mismatched_prompts += usize::from(!prompt.correct);
summary.prompt_tokens_total += prompt.prompt_tokens;
@@ -608,6 +696,18 @@ fn summarize(prompts: &[PromptReport]) -> Summary {
summary.speculative_target_decode_ms += prompt.speculative_target_decode_ms;
summary.speculative_draft_decode_ms += prompt.speculative_draft_decode_ms;
}
+ summary.baseline_wall_tokens_per_second = tokens_per_second(
+ summary.baseline_generated_total,
+ summary.baseline_decode_wall_ms,
+ );
+ summary.speculative_wall_tokens_per_second = tokens_per_second(
+ summary.speculative_generated_total,
+ summary.speculative_decode_wall_ms,
+ );
+ summary.speculative_wall_speedup_vs_baseline = speedup(
+ summary.baseline_decode_wall_ms,
+ summary.speculative_decode_wall_ms,
+ );
summary.accept_rate = if summary.draft_tokens == 0 {
0.0
} else {
@@ -637,8 +737,6 @@ fn summarize(prompts: &[PromptReport]) -> Summary {
fn print_human_summary(report: &Report) {
let summary = &report.summary;
- let current_spec_total_ms =
- summary.speculative_target_decode_ms + summary.speculative_draft_decode_ms;
eprintln!("speculative pair benchmark:");
eprintln!(
" prompts total={} correct={} mismatched={}",
@@ -668,18 +766,18 @@ fn print_human_summary(report: &Report) {
eprintln!(
"{:<28} {:>12.2} {:>12.2} {:>10.2}x {:>10}",
"target baseline",
- summary.baseline_decode_ms,
- summary.baseline_tokens_per_second,
+ summary.baseline_decode_wall_ms,
+ summary.baseline_wall_tokens_per_second,
1.0,
- "actual"
+ "wall"
);
eprintln!(
"{:<28} {:>12.2} {:>12.2} {:>10.2}x {:>10}",
"target/draft speculative",
- current_spec_total_ms,
- summary.speculative_total_tokens_per_second,
- summary.speculative_speedup_vs_baseline,
- "actual"
+ summary.speculative_decode_wall_ms,
+ summary.speculative_wall_tokens_per_second,
+ summary.speculative_wall_speedup_vs_baseline,
+ "wall"
);
eprintln!();
eprintln!(
diff --git a/crates/llama-spec-bench/src/verify_reference.rs b/crates/llama-spec-bench/src/verify_reference.rs
new file mode 100644
index 00000000..a353fb3a
--- /dev/null
+++ b/crates/llama-spec-bench/src/verify_reference.rs
@@ -0,0 +1,253 @@
+//! Teacher-forced target verification isolates batch numerics from rollback.
+use anyhow::{Context, Result, bail, ensure};
+use serde::Serialize;
+use skippy_runtime::{SamplingConfig, StageModel, StageSession, TokenLogprobs};
+
+use crate::{Args, Baseline};
+
+#[derive(Serialize)]
+struct Report {
+ mode: &'static str,
+ window: usize,
+ lane_count: usize,
+ shared_verify: bool,
+ shared_forwards: usize,
+ draft_attached: bool,
+ prompts: Vec,
+}
+
+#[derive(Serialize)]
+struct Prompt {
+ baseline_tokens: Vec,
+ serial_tokens: Vec,
+ batch_tokens: Vec,
+ differences: Vec,
+}
+
+#[derive(Serialize)]
+struct Difference {
+ index: usize,
+ serial: Row,
+ batch: Row,
+}
+
+#[derive(Serialize)]
+struct Row {
+ token: i32,
+ logprob: f32,
+ top: Vec<(i32, f32)>,
+}
+
+impl From<&TokenLogprobs> for Row {
+ fn from(row: &TokenLogprobs) -> Self {
+ Self {
+ token: row.token,
+ logprob: row.logprob,
+ top: row.top.clone(),
+ }
+ }
+}
+
+pub(super) fn run(args: &Args, target: &StageModel, baselines: &[Baseline]) -> Result<()> {
+ let width = args
+ .speculative_window
+ .checked_add(1)
+ .context("verify window overflow")?;
+ let mut prompts = Vec::new();
+ let (mut shared_trace, shared_forwards) = if args.shared_verify {
+ let (rows, forwards) = trace_shared(target, baselines, width)?;
+ (Some(rows), forwards)
+ } else {
+ (None, 0)
+ };
+ for (index, baseline) in baselines.iter().enumerate() {
+ let mut inputs = vec![*baseline.target_tokens.last().expect("nonempty prompt")];
+ inputs.extend_from_slice(&baseline.generation.tokens);
+ inputs.truncate(baseline.generation.tokens.len());
+ let serial = trace(target, baseline, &inputs, 1)?;
+ let batch = if let Some(traces) = &mut shared_trace {
+ std::mem::take(&mut traces[index])
+ } else {
+ trace(target, baseline, &inputs, width)?
+ };
+ let differences: Vec<_> = serial
+ .iter()
+ .zip(&batch)
+ .enumerate()
+ .filter(|(_, (serial, batch))| serial.token != batch.token)
+ .map(|(index, (serial, batch))| Difference {
+ index,
+ serial: serial.into(),
+ batch: batch.into(),
+ })
+ .collect();
+ eprintln!("teacher-forced differences={}", differences.len());
+ prompts.push(Prompt {
+ baseline_tokens: baseline.generation.tokens.clone(),
+ serial_tokens: serial.iter().map(|row| row.token).collect(),
+ batch_tokens: batch.iter().map(|row| row.token).collect(),
+ differences,
+ });
+ }
+ let report = Report {
+ mode: "teacher-forced target verification; no draft proposals or rollback",
+ window: width,
+ lane_count: args.dflash_lanes,
+ shared_verify: args.shared_verify,
+ shared_forwards,
+ draft_attached: args.dflash,
+ prompts,
+ };
+ let json = serde_json::to_string_pretty(&report)?;
+ if let Some(path) = &args.json_out {
+ std::fs::write(path, format!("{json}\n"))?;
+ } else {
+ println!("{json}");
+ }
+ if !args.allow_mismatch
+ && report.prompts.iter().any(|prompt| {
+ !prompt.differences.is_empty() || prompt.serial_tokens != prompt.baseline_tokens
+ })
+ {
+ bail!("teacher-forced verification diverged from the serial baseline");
+ }
+ Ok(())
+}
+
+/// Forces identical continuations through a shared target without attaching
+/// any draft, so cross-sequence kernel numerics can be inspected directly.
+fn trace_shared(
+ target: &StageModel,
+ baselines: &[Baseline],
+ width: usize,
+) -> Result<(Vec>, usize)> {
+ use skippy_runtime::{StageSession, verification_batch::VerifyBatchRequest};
+ let length = baselines
+ .first()
+ .context("no reference lanes")?
+ .generation
+ .tokens
+ .len();
+ ensure!(
+ baselines
+ .iter()
+ .all(|baseline| baseline.generation.tokens.len() == length),
+ "shared reference tracing requires equal continuation lengths"
+ );
+ let mut sessions = Vec::new();
+ let mut inputs = Vec::new();
+ for baseline in baselines {
+ let mut session = target.create_session()?;
+ session.prefill_chunked(&baseline.target_tokens[..baseline.target_tokens.len() - 1])?;
+ sessions.push(session);
+ let mut tokens = vec![
+ *baseline
+ .target_tokens
+ .last()
+ .context("empty reference prompt")?,
+ ];
+ tokens.extend_from_slice(&baseline.generation.tokens);
+ tokens.truncate(length);
+ inputs.push(tokens);
+ }
+ let sampling = SamplingConfig {
+ enabled: true,
+ temperature: 0.0,
+ top_logprobs: Some(5),
+ ..SamplingConfig::default()
+ };
+ let mut rows = vec![Vec::new(); baselines.len()];
+ let mut forwards = 0;
+ for offset in (0..length).step_by(width) {
+ let end = (offset + width).min(length);
+ let bases: Vec<_> = sessions.iter().map(StageSession::token_count).collect();
+ let mut requests: Vec<_> = sessions
+ .iter_mut()
+ .zip(&inputs)
+ .map(|(session, inputs)| VerifyBatchRequest {
+ session,
+ token_ids: &inputs[offset..end],
+ sampling: Some(&sampling),
+ })
+ .collect();
+ StageSession::verify_batch_sampled(&mut requests)?;
+ forwards += 1;
+ for (index, request) in requests.into_iter().enumerate() {
+ let chunk_rows = request.session.take_token_logprobs()?;
+ ensure!(
+ !chunk_rows.is_empty() && chunk_rows.len() <= end - offset,
+ "missing shared trace logprobs"
+ );
+ rows[index].extend(chunk_rows);
+ request
+ .session
+ .retire_verify_checkpoint(bases[index], (end - offset) as u64)?;
+ }
+ if rows.iter().zip(baselines).any(|(rows, baseline)| {
+ rows.iter()
+ .zip(&baseline.generation.tokens)
+ .any(|(row, &token)| row.token != token)
+ }) {
+ break;
+ }
+ }
+ Ok((rows, forwards))
+}
+
+fn trace(
+ target: &StageModel,
+ baseline: &Baseline,
+ inputs: &[i32],
+ width: usize,
+) -> Result> {
+ let mut session = target.create_session()?;
+ ensure!(
+ width <= session.batch_size()?,
+ "verify window exceeds native batch size"
+ );
+ session.prefill_chunked(&baseline.target_tokens[..baseline.target_tokens.len() - 1])?;
+ let sampling = SamplingConfig {
+ enabled: true,
+ temperature: 0.0,
+ top_logprobs: Some(5),
+ ..SamplingConfig::default()
+ };
+ let mut rows = Vec::new();
+ for chunk in inputs.chunks(width) {
+ trace_chunk(&mut session, chunk, &sampling, width == 1)?;
+ let chunk_rows = session.take_token_logprobs()?;
+ ensure!(
+ !chunk_rows.is_empty() && chunk_rows.len() <= chunk.len(),
+ "missing trace logprobs"
+ );
+ rows.extend(chunk_rows);
+ // Stateful sampling stops at the first rejected proposal. These are
+ // deliberately forced inputs, but stop the trace rather than sample
+ // or fabricate probabilities for the unreported suffix.
+ if rows
+ .iter()
+ .zip(&baseline.generation.tokens)
+ .any(|(row, &token)| row.token != token)
+ {
+ break;
+ }
+ }
+ Ok(rows)
+}
+
+fn trace_chunk(
+ session: &mut StageSession,
+ chunk: &[i32],
+ sampling: &SamplingConfig,
+ serial: bool,
+) -> Result<()> {
+ if serial {
+ session.decode_step_sampled(chunk[0], Some(sampling))?;
+ } else {
+ let start = session.token_count();
+ session.verify_tokens_sampled(chunk, Some(sampling))?;
+ // Every forced input is committed, irrespective of the prediction.
+ session.retire_verify_checkpoint(start, chunk.len() as u64)?;
+ }
+ Ok(())
+}
diff --git a/crates/skippy-api/Cargo.toml b/crates/skippy-api/Cargo.toml
index a63f518b..55809939 100644
--- a/crates/skippy-api/Cargo.toml
+++ b/crates/skippy-api/Cargo.toml
@@ -22,6 +22,7 @@ reqwest = { version = "0.13", features = ["json"] }
tokio = { version = "1", features = ["macros", "net", "rt", "sync", "time"] }
skippy-config = { path = "../skippy-config", version = "0.80.0" }
skippy-cache = { path = "../skippy-cache", version = "0.80.0" }
+skippy-events = { path = "../skippy-events", version = "0.80.0" }
skippy-serving = { path = "../skippy-serving", version = "0.80.0" }
skippy-native-runtime = { path = "../skippy-native-runtime", version = "0.80.0" }
skippy-runtime-install = { path = "../skippy-runtime-install", version = "0.80.0" }
diff --git a/crates/skippy-api/src/execution/split/plan.rs b/crates/skippy-api/src/execution/split/plan.rs
index fa504c23..8b127cc6 100644
--- a/crates/skippy-api/src/execution/split/plan.rs
+++ b/crates/skippy-api/src/execution/split/plan.rs
@@ -133,6 +133,7 @@ impl SplitOptions {
ctx_size: options.ctx_size,
lane_count: options.generation_concurrency as u32,
selected_device: options.selected_device.clone(),
+ max_request_tier: None,
package_ref: identity.package_ref.clone(),
manifest_sha256: identity.manifest_sha256.clone(),
model_path: Some(identity.source_model_path.to_string_lossy().into_owned()),
diff --git a/crates/skippy-api/src/family_policy.rs b/crates/skippy-api/src/family_policy.rs
index 423c7d88..0bba7b00 100644
--- a/crates/skippy-api/src/family_policy.rs
+++ b/crates/skippy-api/src/family_policy.rs
@@ -53,6 +53,7 @@ impl FamilyPolicy {
max_entries: bounded_entries,
max_bytes,
l2_max_bytes: 0,
+ l1_checkpoint_max_bytes: None,
codec: skippy_protocol::StageKvCacheCodec::Native,
min_tokens,
shared_prefix_stride_tokens: 128,
diff --git a/crates/skippy-api/src/native-recipe.json b/crates/skippy-api/src/native-recipe.json
index 2a8af891..9d180dc6 100644
--- a/crates/skippy-api/src/native-recipe.json
+++ b/crates/skippy-api/src/native-recipe.json
@@ -1,4 +1,4 @@
{
"llama_upstream_sha": "918fe468dbaae80bcdaf975c1b368023f2578ead",
- "patch_queue_sha256": "eca168e13f2535d5c7f0efd20a837e96ac9741a61aa6b77f4a6380ffd9807986"
+ "patch_queue_sha256": "059242225b40fa06c3d7bc3d43d58cf4c9ef44b2a33dcee10f7f79010669d389"
}
\ No newline at end of file
diff --git a/crates/skippy-api/src/serving.rs b/crates/skippy-api/src/serving.rs
index 776ff1d3..68375f92 100644
--- a/crates/skippy-api/src/serving.rs
+++ b/crates/skippy-api/src/serving.rs
@@ -31,6 +31,8 @@ pub struct InferenceOptions {
pub pipeline_decode_groups: Option,
pub adaptive_generation_min_concurrency: Option,
pub generation_queue_capacity: usize,
+ /// Percent of the KV token budget only `local`-tier requests may reserve.
+ pub local_kv_reserve_percent: u8,
pub generation_admission_timeout_secs: u64,
pub prefill_chunk_size: usize,
pub prefill_chunk_policy: String,
@@ -88,6 +90,7 @@ impl InferenceOptions {
generation_queue_capacity: skippy_serving::frontend::default_generation_queue_capacity(
generation_concurrency,
),
+ local_kv_reserve_percent: 0,
generation_admission_timeout_secs: DEFAULT_GENERATION_ADMISSION_TIMEOUT_SECS,
prefill_chunk_size: BUILTIN_PREFILL_CHUNK_SIZE,
prefill_chunk_policy: skippy_config::local_serving::PREFILL_CHUNK_POLICY.to_string(),
@@ -148,6 +151,7 @@ impl InferenceOptions {
pipeline_decode_groups: self.pipeline_decode_groups,
adaptive_generation_min_concurrency: self.adaptive_generation_min_concurrency,
generation_queue_capacity: self.generation_queue_capacity,
+ local_kv_reserve_percent: self.local_kv_reserve_percent,
generation_admission_timeout_secs: self.generation_admission_timeout_secs,
prefill_chunk_size: self.prefill_chunk_size,
prefill_chunk_policy: self.prefill_chunk_policy,
diff --git a/crates/skippy-api/src/serving/local.rs b/crates/skippy-api/src/serving/local.rs
index 970dcfa5..575d2216 100644
--- a/crates/skippy-api/src/serving/local.rs
+++ b/crates/skippy-api/src/serving/local.rs
@@ -22,7 +22,14 @@ impl LocalDiskCacheOptions {
) {
Ok(manager) => manager,
Err(error) => {
- tracing::warn!(%error, "disk prompt cache unavailable; using cold prefill");
+ let message = "Skippy L3 disk cache unavailable. Serving continues without L3.";
+ tracing::warn!(%error, "{message}");
+ let _ = skippy_events::diagnostics::emit(
+ skippy_events::diagnostics::ServingDiagnostic::Warning {
+ message: message.to_owned(),
+ context: Some(format!("{error:#}")),
+ },
+ );
None
}
}
diff --git a/crates/skippy-api/src/split_execution/direct.rs b/crates/skippy-api/src/split_execution/direct.rs
index b8ac78f5..747c0124 100644
--- a/crates/skippy-api/src/split_execution/direct.rs
+++ b/crates/skippy-api/src/split_execution/direct.rs
@@ -264,6 +264,7 @@ fn realize_configs(
upstream: index.checked_sub(1).map(peer),
downstream: (index + 1 < topology.stages.len()).then(|| peer(index + 1)),
admission: admission.clone(),
+ max_request_tier: None,
};
configs.push(stage_load::admitted_stage_config(&load, None, names)?);
}
diff --git a/crates/skippy-api/src/stage.rs b/crates/skippy-api/src/stage.rs
index 2792186a..769cda4f 100644
--- a/crates/skippy-api/src/stage.rs
+++ b/crates/skippy-api/src/stage.rs
@@ -224,6 +224,7 @@ pub fn single_stage_config(
bind_addr: "127.0.0.1:0".to_string(),
upstream: None,
downstream: None,
+ max_request_tier: None,
};
config.kv_cache = options
.kv_cache
diff --git a/crates/skippy-api/src/stage_load.rs b/crates/skippy-api/src/stage_load.rs
index 8f42ecf1..cf3394a0 100644
--- a/crates/skippy-api/src/stage_load.rs
+++ b/crates/skippy-api/src/stage_load.rs
@@ -76,6 +76,9 @@ pub struct AdmittedStageOptions {
pub upstream: Option,
pub downstream: Option,
pub admission: skippy_protocol::StageAdmissionDescriptor,
+ /// Highest request tier this stage serves; see
+ /// [`StageConfig::max_request_tier`]. `None` serves the stamped tier.
+ pub max_request_tier: Option,
}
impl AdmittedStageOptions {
@@ -199,6 +202,7 @@ pub fn admitted_stage_config(
bind_addr: load.bind_addr.clone(),
upstream: load.upstream.clone(),
downstream: load.downstream.clone(),
+ max_request_tier: load.max_request_tier.clone(),
};
let family_policy = crate::family_policy::family_policy_for_stage_config(&config);
config.kv_cache = package.map_or_else(
diff --git a/crates/skippy-cache/README.md b/crates/skippy-cache/README.md
index 3b85fdc6..bff991f8 100644
--- a/crates/skippy-cache/README.md
+++ b/crates/skippy-cache/README.md
@@ -24,6 +24,12 @@ used to discover shared resident prefixes. Attention admission uses physical
native occupancy rather than summing overlapping logical prefix lengths.
Recurrent checkpoint RAM is bounded separately and works with disk disabled.
+Serving puts the request tier and private partition in the cache namespace
+(see `skippy-inference-api`'s request tiers), so a prefix one tier or partition
+computed never matches another's. Recurrent entries are evicted by the
+retention their owner gives them (`evict_recurrent_by_retention`), least
+recently used first among equals; serving uses the storing request's tier.
+
This adopts SGLang's separation of radix-owned attention blocks and recurrent
checkpoints through llama.cpp's native memory interfaces. It does not embed
SGLang's Torch runtime. See [the prompt-cache design](../../docs/PROMPT_CACHE.md)
diff --git a/crates/skippy-cache/src/identity.rs b/crates/skippy-cache/src/identity.rs
index 74a3b5b6..a5d8aa46 100644
--- a/crates/skippy-cache/src/identity.rs
+++ b/crates/skippy-cache/src/identity.rs
@@ -677,6 +677,7 @@ mod identity_completeness_tests {
bind_addr: "127.0.0.1:0".to_string(),
upstream: None,
downstream: None,
+ max_request_tier: None,
}
}
@@ -1047,6 +1048,7 @@ mod identity_stability_tests {
bind_addr: "127.0.0.1:0".to_string(),
upstream: None,
downstream: None,
+ max_request_tier: None,
}
}
@@ -1076,6 +1078,7 @@ mod identity_stability_tests {
max_entries: 64,
max_bytes: 0,
l2_max_bytes: 0,
+ l1_checkpoint_max_bytes: None,
codec: StageKvCacheCodec::CacheGen,
min_tokens: 64,
shared_prefix_stride_tokens: 128,
diff --git a/crates/skippy-cache/src/l2/mod.rs b/crates/skippy-cache/src/l2/mod.rs
index 0a73565c..4bbf2380 100644
--- a/crates/skippy-cache/src/l2/mod.rs
+++ b/crates/skippy-cache/src/l2/mod.rs
@@ -3,7 +3,7 @@
//! The radix cache (L1) holds resident payloads; the L3 tier holds the same
//! state durably on disk as content-addressed packed segments. This module
//! adds the missing middle tier: a bounded host-RAM cache of *immutable
-//! packed segments*, keyed and identified exactly like the L3 entries they
+//! checkpoint bytes*, keyed and identified exactly like the L3 entries they
//! mirror.
//!
//! Contract (mirrors `crate::tier::L3Tier`):
@@ -20,7 +20,7 @@
//! entry's L3 manifest segment list onto those handles. A longer prefix
//! that extends a shorter one references the same segment handles, so
//! turn growth shares prefix bytes instead of duplicating them — L2 RAM
-//! tracks *distinct segment* bytes, not per-prefix assembled bytes.
+//! tracks *distinct segment* bytes.
//! - **Integrity**: the whole concatenated L3 wire digest (the manifest key)
//! is verified exactly once, at admission, against the payload being
//! admitted. After admission the segment bytes are immutable, so every
@@ -35,12 +35,13 @@
//! first admission pays for it.
//! - **Zero-copy reads**: `get` clones handles, not bytes; the returned
//! `CacheBytes` is a block-backed view over the shared segment storages,
-//! contiguous in the single-segment case.
+//! contiguous in the single-segment case. Native import can consume the
+//! shared segments directly.
//!
//! `skippy-server` wires this tier as a bounded mirror of repeated or
//! high-value L3 fills. An L2 hit rewarms L1.
use std::{
- collections::HashMap,
+ collections::{HashMap, HashSet},
ops::Range,
sync::{
Arc, Mutex,
@@ -52,7 +53,8 @@ use std::{
use crate::PayloadCodec;
use crate::payload::{CacheBytes, ExactStatePayload, ExactStatePayloadKind};
use crate::{
- HandoffManifest, HandoffSegmentRef, MANIFEST_VERSION, SegmentCodecIdentity, segment_digest,
+ CHECKPOINT_MANIFEST_VERSION, HandoffManifest, HandoffSegmentRef, MANIFEST_VERSION,
+ SegmentCodecIdentity, segment_digest,
};
const DIRECT_SEGMENT_BYTES: usize = 1024 * 1024;
@@ -91,8 +93,7 @@ pub struct L2Stats {
pub entries: u64,
/// Sum of entries' distinct segment charges — the live budget usage.
pub bytes: u64,
- /// Sum of entry payload lengths including cross-entry sharing; larger
- /// than `bytes` exactly when entries share prefix segments.
+ /// Sum of entry payload lengths, including cross-entry sharing.
pub logical_bytes: u64,
/// Distinct immutable segment handles currently held.
pub segments: u64,
@@ -229,13 +230,13 @@ impl ExactStatePayloadMirror {
/// Segment digests in wire order, deduplicated.
fn segment_digests(&self) -> Vec<&str> {
- let mut seen = Vec::new();
- for (digest, _) in &self.layout().segments {
- if !seen.contains(&digest.as_str()) {
- seen.push(digest.as_str());
- }
- }
- seen
+ let mut seen = HashSet::new();
+ self.layout()
+ .segments
+ .iter()
+ .map(|(digest, _)| digest.as_str())
+ .filter(|digest| seen.insert(*digest))
+ .collect()
}
}
@@ -260,13 +261,16 @@ impl L2Hit {
/// `Cow` on `as_cow`.
pub fn to_payload(&self) -> crate::payload::ExactStatePayload {
let layout = self.payload.layout();
- let wire = self.wire_view(0..layout.total_bytes);
match self.payload.kind() {
crate::payload::ExactStatePayloadKind::FullState => {
- crate::payload::ExactStatePayload::FullState { bytes: wire }
+ crate::payload::ExactStatePayload::FullState {
+ bytes: self.wire_view(0..layout.total_bytes),
+ }
}
crate::payload::ExactStatePayloadKind::RecurrentOnly => {
- crate::payload::ExactStatePayload::RecurrentOnly { recurrent: wire }
+ crate::payload::ExactStatePayload::RecurrentOnly {
+ recurrent: self.wire_view(0..layout.total_bytes),
+ }
}
crate::payload::ExactStatePayloadKind::KvRecurrent => {
// Split the wire at kv_bytes exactly like L3 load does: kv
@@ -280,6 +284,23 @@ impl L2Hit {
}
}
+ /// Borrows the verified KV portion in wire order. The last segment may
+ /// also contain recurrent bytes, which are outside this view.
+ pub fn kv_chunks(&self) -> Option> {
+ let layout = self.payload.layout();
+ if layout.payload_kind != ExactStatePayloadKind::KvRecurrent {
+ return None;
+ }
+ let kv_len = layout.kv_bytes.min(layout.total_bytes);
+ let end = layout
+ .segments
+ .partition_point(|(_, range)| range.start < kv_len);
+ Some(layout.segments[..end].iter().map(move |(digest, range)| {
+ let len = (range.end.min(kv_len) - range.start) as usize;
+ &self.segments[digest].bytes[..len]
+ }))
+ }
+
/// Block-backed `CacheBytes` over `range` of the assembled wire, in
/// wire order. Blocks outside `range` are skipped; edge blocks are
/// narrowed to the overlap. Byte-identical views share the same
@@ -625,6 +646,42 @@ impl L2Tier {
self.budget_bytes
}
+ /// Mirror the exact layout of a checkpoint without hashing its bytes as
+ /// a second, monolithic object. The shared admission path verifies every
+ /// segment before installing it in the immutable pool.
+ pub fn admit_manifest_payload(
+ &self,
+ cache_key: String,
+ manifest: &HandoffManifest,
+ payload: &ExactStatePayload,
+ ) -> Result, L2InsertRefusal> {
+ let mirror = ExactStatePayloadMirror::from_manifest(manifest)?;
+ let digest = manifest.payload_digest.clone();
+ if manifest.version != CHECKPOINT_MANIFEST_VERSION {
+ let (wire, _, _) = payload_wire(payload)?;
+ return self.admit(
+ cache_key,
+ manifest.token_count,
+ digest,
+ &wire,
+ mirror,
+ L2Origin::FromL3,
+ );
+ }
+ manifest
+ .verify_checkpoint()
+ .map_err(|error| L2InsertRefusal::MalformedManifest(error.to_string()))?;
+ let (wire, _, _) = payload_wire(payload)?;
+ self.admit_segments(
+ cache_key,
+ manifest.token_count,
+ digest,
+ &wire,
+ mirror,
+ L2Origin::FromL3,
+ )
+ }
+
/// Admit an exact-state payload restored from the authoritative L3 tier.
///
/// The payload is cut into stable one-MiB content chunks. This preserves
@@ -726,6 +783,18 @@ impl L2Tier {
actual,
});
}
+ self.admit_segments(cache_key, token_count, payload_digest, wire, mirror, origin)
+ }
+
+ fn admit_segments(
+ &self,
+ cache_key: String,
+ token_count: u64,
+ payload_digest: String,
+ wire: &[u8],
+ mirror: ExactStatePayloadMirror,
+ origin: L2Origin,
+ ) -> Result, L2InsertRefusal> {
let payload_bytes = mirror.byte_len();
if payload_bytes == 0 {
// Mirrors L3: an empty payload cannot represent state.
@@ -752,8 +821,9 @@ impl L2Tier {
let mut new_segments: Vec<(String, SegmentHandle)> = Vec::new();
let mut new_bytes = 0u64;
let mut shared_bytes = 0u64;
- for &(digest, slice) in segments.iter() {
- if new_segments.iter().any(|(d, _)| d == digest) {
+ let mut seen = HashSet::with_capacity(segments.len());
+ for (digest, slice) in segments {
+ if !seen.insert(digest) {
// Within-admission duplicate digest: the validation pass
// already proved both slices have identical content, so
// keep the first copy.
@@ -786,22 +856,18 @@ impl L2Tier {
.to_string(),
});
}
- new_bytes = new_bytes.saturating_add(slice.len() as u64);
- new_segments.push((
- digest.to_string(),
- SegmentHandle {
- bytes: Arc::new(slice.to_vec()),
- },
- ));
+ let handle = SegmentHandle {
+ bytes: Arc::new(slice.to_vec()),
+ };
+ new_bytes = new_bytes.saturating_add(handle.bytes.len() as u64);
+ new_segments.push((digest.to_string(), handle));
}
None => {
- new_bytes = new_bytes.saturating_add(slice.len() as u64);
- new_segments.push((
- digest.to_string(),
- SegmentHandle {
- bytes: Arc::new(slice.to_vec()),
- },
- ));
+ let handle = SegmentHandle {
+ bytes: Arc::new(slice.to_vec()),
+ };
+ new_bytes = new_bytes.saturating_add(handle.bytes.len() as u64);
+ new_segments.push((digest.to_string(), handle));
}
}
}
@@ -1182,23 +1248,26 @@ impl L2Tier {
/// corruption cleanup, and rollback alike. Deterministic: identical
/// map states produce identical ownership.
fn recompute_all_charges(inner: &mut L2Inner) {
- let mut ownership: HashMap = HashMap::new();
- for digest in inner.segments.keys() {
- let Some(bytes) = inner.segments.get(digest).map(|h| h.bytes.len() as u64) else {
- continue;
- };
- let owner = inner
- .map
- .iter()
- .filter(|(_, entry)| entry.payload.segment_digests().contains(&digest.as_str()))
- .map(|(key, _)| key.clone())
- .min();
- if let Some(owner) = owner {
- *ownership.entry(owner).or_insert(0) += bytes;
+ let mut owners = HashMap::<&str, &str>::with_capacity(inner.segments.len());
+ for (key, entry) in &inner.map {
+ for (digest, _) in &entry.payload.layout().segments {
+ let owner = owners.entry(digest).or_insert(key);
+ *owner = (*owner).min(key);
+ }
+ }
+ let mut charges = HashMap::::with_capacity(inner.map.len());
+ for (digest, owner) in owners {
+ if let Some(segment) = inner.segments.get(digest) {
+ let bytes = segment.bytes.len() as u64;
+ if let Some(charge) = charges.get_mut(owner) {
+ *charge += bytes;
+ } else {
+ charges.insert(owner.to_owned(), bytes);
+ }
}
}
for (key, entry) in inner.map.iter_mut() {
- entry.charge_bytes = ownership.get(key).copied().unwrap_or(0);
+ entry.charge_bytes = charges.get(key).copied().unwrap_or(0);
}
}
@@ -1404,6 +1473,50 @@ mod tests {
l2_cache_key("model-a", "state-a", namespace, tokens)
}
+ #[test]
+ fn kv_chunks_borrow_shared_segments_and_exclude_recurrent_bytes() {
+ let tier = L2Tier::new(16);
+ let admit = |key: &str, wire: &[u8], kv_bytes: u64| {
+ let mut start = 0;
+ let segments = wire
+ .chunks(4)
+ .map(|chunk| {
+ let end = start + chunk.len() as u64;
+ let segment = (segment_digest(chunk), start..end);
+ start = end;
+ segment
+ })
+ .collect();
+ let layout = L2Layout {
+ payload_kind: ExactStatePayloadKind::KvRecurrent,
+ total_bytes: wire.len() as u64,
+ kv_bytes,
+ recurrent_bytes: wire.len() as u64 - kv_bytes,
+ kv_desc_json: None,
+ segments,
+ };
+ tier.admit(
+ key.into(),
+ 2,
+ segment_digest(wire),
+ wire,
+ ExactStatePayloadMirror::KvRecurrent { layout },
+ L2Origin::Direct,
+ )
+ .unwrap();
+ };
+ admit("first", b"abcdefRR", 6);
+ admit("grown", b"abcdefghiirr", 10);
+ assert_eq!(tier.stats().bytes, 16);
+ let first = tier.get("first").unwrap();
+ let grown = tier.get("grown").unwrap();
+ let first_chunks: Vec<_> = first.kv_chunks().unwrap().collect();
+ let grown_chunks: Vec<_> = grown.kv_chunks().unwrap().collect();
+ assert_eq!(first_chunks, [b"abcd".as_slice(), b"ef"]);
+ assert_eq!(grown_chunks, [b"abcd".as_slice(), b"efgh", b"ii"]);
+ assert_eq!(first_chunks[0].as_ptr(), grown_chunks[0].as_ptr());
+ }
+
#[test]
fn admit_get_round_trip_serves_wire_bytes() {
let tier = L2Tier::new(1 << 20);
@@ -1940,6 +2053,7 @@ mod tests {
payload_kind: "kv-recurrent".to_string(),
total_bytes: wire_bytes.len() as u64,
payload_digest: digest.clone(),
+ prefix_key: None,
segments: vec![
HandoffSegmentRef {
index: 0,
@@ -2000,6 +2114,7 @@ mod tests {
payload_kind: "blob".to_string(),
total_bytes: 10,
payload_digest: "blake3:aa".to_string(),
+ prefix_key: None,
segments: Vec::new(),
kv_bytes: 10,
kv_decoded_bytes: 10,
@@ -2725,6 +2840,7 @@ mod tests {
payload_kind: "full-state".to_string(),
total_bytes: 32,
payload_digest: digest.clone(),
+ prefix_key: None,
segments: vec![HandoffSegmentRef {
index,
offset,
diff --git a/crates/skippy-cache/src/l3.rs b/crates/skippy-cache/src/l3.rs
index bb9c2caa..c42dca83 100644
--- a/crates/skippy-cache/src/l3.rs
+++ b/crates/skippy-cache/src/l3.rs
@@ -61,6 +61,9 @@ const EVICTION_LOW_WATER_PERCENT: u64 = 85;
/// version whose segment lacks it is rejected rather than reinterpreted.
pub const MANIFEST_VERSION: u32 = 4;
+/// Serving checkpoints address ordered page metadata instead of concatenated bytes.
+pub const CHECKPOINT_MANIFEST_VERSION: u32 = 5;
+
/// The pre-codec-identity manifest format. These entries predate codec
/// identity, are always raw by construction, and are decoded as raw through
/// the explicit legacy path in [`decode_manifest`]. New manifests are never
@@ -313,8 +316,12 @@ pub struct HandoffManifest {
#[serde(default)]
pub codec: Option,
pub total_bytes: u64,
- /// BLAKE3 of the assembled payload; also the manifest's key.
+ /// Manifest key. Older handoff manifests use the digest of the assembled bytes.
+ /// Serving checkpoints use the digest of the manifest with this field cleared.
pub payload_digest: String,
+ /// The serving prefix coordinate includes the cache namespace and token IDs.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub prefix_key: Option,
pub segments: Vec,
pub kv_bytes: u64,
/// Decoded native KV length. Equal to `kv_bytes` for native pages; for a
@@ -335,6 +342,32 @@ pub struct HandoffManifest {
}
impl HandoffManifest {
+ pub(crate) fn checkpoint_digest(&self) -> Result {
+ let mut manifest = self.clone();
+ manifest.payload_digest.clear();
+ let mut hasher = blake3::Hasher::new_derive_key("Skippy L3 checkpoint manifest v5");
+ hasher.update(&serde_json::to_vec(&manifest)?);
+ Ok(hasher.finalize().to_hex().to_string())
+ }
+
+ pub(crate) fn verify_checkpoint(&self) -> Result<()> {
+ if self.version == CHECKPOINT_MANIFEST_VERSION {
+ if !self
+ .prefix_key
+ .as_deref()
+ .is_some_and(|key| key.strip_prefix("blake3:").is_some_and(packed::is_digest))
+ {
+ bail!("checkpoint manifest has no valid prefix key");
+ }
+ if self.checkpoint_digest()? != self.payload_digest {
+ bail!("checkpoint manifest does not match its digest");
+ }
+ } else if self.prefix_key.is_some() {
+ bail!("handoff manifest carries a serving checkpoint prefix key");
+ }
+ Ok(())
+ }
+
pub fn new(state_identity: String, payload_kind: String) -> Self {
Self::new_for_model(state_identity.clone(), state_identity, payload_kind)
}
@@ -352,6 +385,7 @@ impl HandoffManifest {
codec: Some(PayloadCodec::raw()),
total_bytes: 0,
payload_digest: String::new(),
+ prefix_key: None,
segments: Vec::new(),
kv_bytes: 0,
kv_decoded_bytes: 0,
@@ -525,6 +559,11 @@ impl StoreLimits {
minimum_free_bytes,
}
}
+
+ pub fn low_water_bytes(self) -> Option {
+ (self.budget_bytes > 0)
+ .then(|| self.budget_bytes.saturating_mul(EVICTION_LOW_WATER_PERCENT) / 100)
+ }
}
/// Why a write was not admitted. Every refusal is a miss with a stable reason,
@@ -632,7 +671,7 @@ impl Drop for ManifestPin<'_> {
}
/// What the store currently holds, for the status contract.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoreUsage {
pub budget_bytes: u64,
pub used_bytes: u64,
@@ -646,7 +685,7 @@ pub struct StoreUsage {
}
/// Repairs performed before a node starts serving a cache root.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoreReconciliation {
pub removed_temporary_files: u64,
pub quarantined_manifests: u64,
@@ -702,8 +741,25 @@ pub fn segment_digest(bytes: &[u8]) -> String {
blake3::hash(bytes).to_hex().to_string()
}
+/// Another process has the exclusive lock for this cache directory.
+#[derive(Debug)]
+pub struct CacheRootInUse(PathBuf);
+
+impl std::fmt::Display for CacheRootInUse {
+ fn fmt(&self, output: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ output,
+ "cache root {} is already owned by another manager",
+ self.0.display()
+ )
+ }
+}
+
+impl std::error::Error for CacheRootInUse {}
+
fn acquire_root_lock(root: &Path) -> Result {
let path = root.join(ROOT_LOCK_FILE);
+ fsinfo::refuse_symlink(&path)?;
let file = fs::OpenOptions::new()
.create(true)
.truncate(false)
@@ -711,18 +767,14 @@ fn acquire_root_lock(root: &Path) -> Result {
.write(true)
.open(&path)
.with_context(|| format!("failed to open cache root lock {}", path.display()))?;
- fsinfo::restrict_to_owner(&path, 0o600)?;
-
if let Err(error) = fs2::FileExt::try_lock_exclusive(&file) {
if fsinfo::is_lock_contended(&error) {
- bail!(
- "cache root {} is already owned by another manager",
- root.display()
- );
+ return Err(CacheRootInUse(root.to_path_buf()).into());
}
return Err(error).with_context(|| format!("failed to lock cache root {}", root.display()));
}
+ fsinfo::restrict_to_owner(&path, 0o600)?;
Ok(file)
}
@@ -750,6 +802,14 @@ impl HandoffSegmentStore {
root: impl Into,
limits: StoreLimits,
) -> Result {
+ Ok(Self::open_unreconciled(root, |_| Ok(Some(limits)))?
+ .expect("a fixed limit always opens the cache or returns an error"))
+ }
+
+ pub(crate) fn open_unreconciled(
+ root: impl Into,
+ select_limits: impl FnOnce(&Path) -> Result