diff --git a/docs/e2e-data/943b-analysis.txt b/benchmarks/e2e-data/943b-analysis.txt similarity index 100% rename from docs/e2e-data/943b-analysis.txt rename to benchmarks/e2e-data/943b-analysis.txt diff --git a/docs/e2e-data/943b-env.tsv b/benchmarks/e2e-data/943b-env.tsv similarity index 100% rename from docs/e2e-data/943b-env.tsv rename to benchmarks/e2e-data/943b-env.tsv diff --git a/docs/e2e-data/943b-trace.csv b/benchmarks/e2e-data/943b-trace.csv similarity index 100% rename from docs/e2e-data/943b-trace.csv rename to benchmarks/e2e-data/943b-trace.csv diff --git a/docs/e2e-data/943d-codex-ttt-analysis.txt b/benchmarks/e2e-data/943d-codex-ttt-analysis.txt similarity index 100% rename from docs/e2e-data/943d-codex-ttt-analysis.txt rename to benchmarks/e2e-data/943d-codex-ttt-analysis.txt diff --git a/docs/e2e-data/943d-codex-ttt-trace.csv b/benchmarks/e2e-data/943d-codex-ttt-trace.csv similarity index 100% rename from docs/e2e-data/943d-codex-ttt-trace.csv rename to benchmarks/e2e-data/943d-codex-ttt-trace.csv diff --git a/docs/e2e-data/945-analysis.txt b/benchmarks/e2e-data/945-analysis.txt similarity index 100% rename from docs/e2e-data/945-analysis.txt rename to benchmarks/e2e-data/945-analysis.txt diff --git a/docs/e2e-data/945-env.tsv b/benchmarks/e2e-data/945-env.tsv similarity index 100% rename from docs/e2e-data/945-env.tsv rename to benchmarks/e2e-data/945-env.tsv diff --git a/docs/e2e-data/945-trace.csv b/benchmarks/e2e-data/945-trace.csv similarity index 100% rename from docs/e2e-data/945-trace.csv rename to benchmarks/e2e-data/945-trace.csv diff --git a/docs/e2e-data/945c-partial-trace.csv b/benchmarks/e2e-data/945c-partial-trace.csv similarity index 100% rename from docs/e2e-data/945c-partial-trace.csv rename to benchmarks/e2e-data/945c-partial-trace.csv diff --git a/docs/e2e-data/945d-codex-crm-analysis.txt b/benchmarks/e2e-data/945d-codex-crm-analysis.txt similarity index 100% rename from docs/e2e-data/945d-codex-crm-analysis.txt rename to benchmarks/e2e-data/945d-codex-crm-analysis.txt diff --git a/docs/e2e-data/945d-codex-crm-trace.csv b/benchmarks/e2e-data/945d-codex-crm-trace.csv similarity index 100% rename from docs/e2e-data/945d-codex-crm-trace.csv rename to benchmarks/e2e-data/945d-codex-crm-trace.csv diff --git a/docs/e2e-data/945d-env.tsv b/benchmarks/e2e-data/945d-env.tsv similarity index 100% rename from docs/e2e-data/945d-env.tsv rename to benchmarks/e2e-data/945d-env.tsv diff --git a/docs/e2e-data/codex-compare/browser.json b/benchmarks/e2e-data/codex-compare/browser.json similarity index 100% rename from docs/e2e-data/codex-compare/browser.json rename to benchmarks/e2e-data/codex-compare/browser.json diff --git a/docs/e2e-data/codex-compare/check_ttt_v2.mjs b/benchmarks/e2e-data/codex-compare/check_ttt_v2.mjs similarity index 100% rename from docs/e2e-data/codex-compare/check_ttt_v2.mjs rename to benchmarks/e2e-data/codex-compare/check_ttt_v2.mjs diff --git a/docs/e2e-data/codex-compare/compare.csv b/benchmarks/e2e-data/codex-compare/compare.csv similarity index 100% rename from docs/e2e-data/codex-compare/compare.csv rename to benchmarks/e2e-data/codex-compare/compare.csv diff --git a/docs/e2e-data/codex-compare/compare.md b/benchmarks/e2e-data/codex-compare/compare.md similarity index 100% rename from docs/e2e-data/codex-compare/compare.md rename to benchmarks/e2e-data/codex-compare/compare.md diff --git a/docs/e2e-data/codex-compare/index.md b/benchmarks/e2e-data/codex-compare/index.md similarity index 100% rename from docs/e2e-data/codex-compare/index.md rename to benchmarks/e2e-data/codex-compare/index.md diff --git a/docs/e2e-data/codex-compare/rounds.csv b/benchmarks/e2e-data/codex-compare/rounds.csv similarity index 100% rename from docs/e2e-data/codex-compare/rounds.csv rename to benchmarks/e2e-data/codex-compare/rounds.csv diff --git a/docs/e2e-data/kar-off-ab/codex/browser-ttt.txt b/benchmarks/e2e-data/kar-off-ab/codex/browser-ttt.txt similarity index 98% rename from docs/e2e-data/kar-off-ab/codex/browser-ttt.txt rename to benchmarks/e2e-data/kar-off-ab/codex/browser-ttt.txt index f71bbf5f..07a618aa 100644 --- a/docs/e2e-data/kar-off-ab/codex/browser-ttt.txt +++ b/benchmarks/e2e-data/kar-off-ab/codex/browser-ttt.txt @@ -1,5 +1,5 @@ # ttt browser checks (Chromium 1148 via playwright 1.49.1, software GL, laptop; each page one run at a time, 2026-11-05) -# first column: check_ttt.mjs (thirds probe, scripts/e2e/codex/tasks/ttt/hidden), second: check_ttt_v2.mjs (gap-clustering probe, docs/e2e-data/codex-compare) +# first column: check_ttt.mjs (thirds probe, scripts/e2e/codex/tasks/ttt/hidden), second: check_ttt_v2.mjs (gap-clustering probe) LELK-r1 check_ttt.mjs rc=0 6 pass, 0 fail, SUMMARY 6/6 LELK-r1 check_ttt_v2.mjs rc=1 3 pass, 3 fail, SUMMARY 3/6 LELK-r2 check_ttt.mjs rc=0 6 pass, 0 fail, SUMMARY 6/6 diff --git a/docs/e2e-data/kar-off-ab/codex/compare.csv b/benchmarks/e2e-data/kar-off-ab/codex/compare.csv similarity index 100% rename from docs/e2e-data/kar-off-ab/codex/compare.csv rename to benchmarks/e2e-data/kar-off-ab/codex/compare.csv diff --git a/docs/e2e-data/kar-off-ab/codex/compare.md b/benchmarks/e2e-data/kar-off-ab/codex/compare.md similarity index 100% rename from docs/e2e-data/kar-off-ab/codex/compare.md rename to benchmarks/e2e-data/kar-off-ab/codex/compare.md diff --git a/docs/e2e-data/kar-off-ab/quality-a-kar-vs-gguf.txt b/benchmarks/e2e-data/kar-off-ab/quality-a-kar-vs-gguf.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/quality-a-kar-vs-gguf.txt rename to benchmarks/e2e-data/kar-off-ab/quality-a-kar-vs-gguf.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p1/mem-ready.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/mem-ready.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p1/mem-ready.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/mem-ready.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p1/nvme-read.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/nvme-read.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p1/nvme-read.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/nvme-read.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p1/order.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/order.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p1/order.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/order.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p1/ready_s.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/ready_s.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p1/ready_s.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/ready_s.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p1/replay.jsonl b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/replay.jsonl similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p1/replay.jsonl rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p1/replay.jsonl diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p2/mem-ready.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/mem-ready.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p2/mem-ready.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/mem-ready.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p2/nvme-read.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/nvme-read.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p2/nvme-read.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/nvme-read.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p2/order.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/order.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p2/order.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/order.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p2/ready_s.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/ready_s.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p2/ready_s.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/ready_s.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p2/replay.jsonl b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/replay.jsonl similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p2/replay.jsonl rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p2/replay.jsonl diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p3/mem-ready.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/mem-ready.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p3/mem-ready.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/mem-ready.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p3/nvme-read.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/nvme-read.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p3/nvme-read.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/nvme-read.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p3/order.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/order.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p3/order.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/order.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p3/ready_s.txt b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/ready_s.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p3/ready_s.txt rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/ready_s.txt diff --git a/docs/e2e-data/kar-off-ab/speed/gguf-p3/replay.jsonl b/benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/replay.jsonl similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/gguf-p3/replay.jsonl rename to benchmarks/e2e-data/kar-off-ab/speed/gguf-p3/replay.jsonl diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p1/mem-ready.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p1/mem-ready.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p1/mem-ready.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p1/mem-ready.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p1/nvme-read.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p1/nvme-read.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p1/nvme-read.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p1/nvme-read.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p1/order.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p1/order.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p1/order.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p1/order.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p1/ready_s.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p1/ready_s.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p1/ready_s.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p1/ready_s.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p1/replay.jsonl b/benchmarks/e2e-data/kar-off-ab/speed/kar-p1/replay.jsonl similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p1/replay.jsonl rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p1/replay.jsonl diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p2/mem-ready.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p2/mem-ready.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p2/mem-ready.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p2/mem-ready.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p2/nvme-read.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p2/nvme-read.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p2/nvme-read.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p2/nvme-read.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p2/order.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p2/order.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p2/order.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p2/order.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p2/ready_s.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p2/ready_s.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p2/ready_s.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p2/ready_s.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p2/replay.jsonl b/benchmarks/e2e-data/kar-off-ab/speed/kar-p2/replay.jsonl similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p2/replay.jsonl rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p2/replay.jsonl diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p3/mem-ready.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p3/mem-ready.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p3/mem-ready.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p3/mem-ready.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p3/nvme-read.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p3/nvme-read.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p3/nvme-read.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p3/nvme-read.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p3/order.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p3/order.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p3/order.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p3/order.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p3/ready_s.txt b/benchmarks/e2e-data/kar-off-ab/speed/kar-p3/ready_s.txt similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p3/ready_s.txt rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p3/ready_s.txt diff --git a/docs/e2e-data/kar-off-ab/speed/kar-p3/replay.jsonl b/benchmarks/e2e-data/kar-off-ab/speed/kar-p3/replay.jsonl similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/kar-p3/replay.jsonl rename to benchmarks/e2e-data/kar-off-ab/speed/kar-p3/replay.jsonl diff --git a/docs/e2e-data/kar-off-ab/speed/speed.json b/benchmarks/e2e-data/kar-off-ab/speed/speed.json similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/speed.json rename to benchmarks/e2e-data/kar-off-ab/speed/speed.json diff --git a/docs/e2e-data/kar-off-ab/speed/speed.md b/benchmarks/e2e-data/kar-off-ab/speed/speed.md similarity index 100% rename from docs/e2e-data/kar-off-ab/speed/speed.md rename to benchmarks/e2e-data/kar-off-ab/speed/speed.md diff --git a/benchmarks/laptop/prompts.txt b/benchmarks/laptop/prompts.txt index 8432dab9..1acf562a 100644 --- a/benchmarks/laptop/prompts.txt +++ b/benchmarks/laptop/prompts.txt @@ -1,4 +1,4 @@ -# Laptop profile paired prompts (docs/laptop-profile.md): one user turn per line, thinking off, 128 new tokens. +# Laptop profile paired prompts: one user turn per line, thinking off, 128 new tokens. Write a Python function that converts an ISO-8601 duration string such as P3DT4H12M5S into a total number of seconds. Reject years and months with a clear ValueError, validate the whole input with one regular expression, and add three short doctest examples. After the code, explain in two sentences which edge cases you considered and why. Explain to a junior engineer how a write-ahead log makes a database safe against crashes. Cover what is written before the data pages change, how recovery replays or discards log records after a power loss, why the order of fsync calls matters, and one common performance trade-off. Use a short numbered list followed by a one-paragraph summary. You are reviewing a pull request that changes a Rust HTTP server to stream responses as server-sent events. List the five most important things to check for correctness, including client cancellation, backpressure, errors that happen after the first byte was sent, and the terminal event. For each item, describe one concrete test you would write. diff --git a/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md b/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md index 1764f1e4..d6c448a5 100644 --- a/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md +++ b/benchmarks/quality/gpt-oss-20b-teacher-forced/README.md @@ -44,9 +44,9 @@ build) much larger than 0.005 mean KL is suspect. `cargo run --release -p leleka-gptoss-igpu --example dump_logprobs_gpu -- ids.txt gpu.jsonl 20` prefills the ids on the integrated GPU (every position's hidden state), projects each on the CPU and writes the -same format. Against `llama-reference.jsonl` (two kernel variants, see the table in `docs/igpu-prefill.md`): 97.1% / mean KL 0.0100 and 95.3% / 0.0121; first variant: best token agrees 97.1% (372/383), mean KL 0.0100, NLL 1.2976 vs +same format. Against `llama-reference.jsonl` (two kernel variants, see the table in `spec node igpu-prefill.md`): 97.1% / mean KL 0.0100 and 95.3% / 0.0121; first variant: best token agrees 97.1% (372/383), mean KL 0.0100, NLL 1.2976 vs 1.2828. Against the CPU decoder's own dump: 97.4% (373/383), mean KL 0.0067, NLL 1.2976 vs 1.2979. Details and -caveats in `docs/igpu-prefill.md`. +caveats in `spec node igpu-prefill.md`. ## Longer reference set (`set2/`, 2026-10-15) diff --git a/benchmarks/results/igpu-prefill-ab-2026-10-15.txt b/benchmarks/results/igpu-prefill-ab-2026-10-15.txt index 0114dcfe..4e47dcb4 100644 --- a/benchmarks/results/igpu-prefill-ab-2026-10-15.txt +++ b/benchmarks/results/igpu-prefill-ab-2026-10-15.txt @@ -1,7 +1,7 @@ # paired prefill A/B (warm) model: gpt-oss-20b-MXFP4.gguf (12109565632 bytes, sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB) cpu: 14 threads, kernels avx-vnni; gpu: Intel(R) Graphics (Vulkan), batch 512; context capacity = prompt + 1 -date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see docs/igpu-prefill.md) +date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see spec node igpu-prefill.md) ## 512 prompt tokens, 5 pairs pair first cpu s gpu s speed-up next tokens @@ -28,7 +28,7 @@ paired speed-up cpu/gpu: mean 3.40x, 95% CI [2.77, 4.04], median 3.26x (5 pairs) # paired prefill A/B (warm) model: gpt-oss-20b-MXFP4.gguf (12109565632 bytes, sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB) cpu: 14 threads, kernels avx-vnni; gpu: Intel(R) Graphics (Vulkan), batch 512; context capacity = prompt + 1 -date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see docs/igpu-prefill.md) +date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see spec node igpu-prefill.md) ## 2048 prompt tokens, 3 pairs pair first cpu s gpu s speed-up next tokens diff --git a/benchmarks/results/kar-quality-2026-10-16.txt b/benchmarks/results/kar-quality-2026-10-16.txt index 86b3f7bc..fd20c676 100644 --- a/benchmarks/results/kar-quality-2026-10-16.txt +++ b/benchmarks/results/kar-quality-2026-10-16.txt @@ -1,7 +1,7 @@ # real KAR codec roundtrip, teacher-forced against llama.cpp (benchmarks/quality/gpt-oss-20b-teacher-forced/set2/table-igpu, 770 positions) model: gpt-oss-20b-MXFP4.gguf (sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB); dump_logprobs 14 threads, top 20; avx-vnni codec: crates/kar-codec (moved unchanged from control-plane/src/kar_codec.rs), group 32, codebook fitted per tensor to 65,536 evenly sampled values; reconstruction stored as Q8_0 -baseline (8-bit attention/output, MXFP4 experts): 93.4% agreement, mean KL 0.016 (docs/cpu-runtime.md) +baseline (8-bit attention/output, MXFP4 experts): 93.4% agreement, mean KL 0.016 (spec node cpu-runtime.md) date: 2026-10-16; the first table was built in the shared checkout and reproduced exactly (4 levels, all tensors) from a clean worktree build ## attention + output weights, LELEKA_EXPERIMENTAL_KAR_LEVELS=3..6 diff --git a/benchmarks/results/npu-prefill-ab-2026-10-15.txt b/benchmarks/results/npu-prefill-ab-2026-10-15.txt index 25a2c575..14618ec4 100644 --- a/benchmarks/results/npu-prefill-ab-2026-10-15.txt +++ b/benchmarks/results/npu-prefill-ab-2026-10-15.txt @@ -1,7 +1,7 @@ # paired prefill A/B (warm) model: gpt-oss-20b-MXFP4.gguf (12109565632 bytes, sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB) cpu: 14 threads, kernels avx-vnni; npu service device: Intel(R) AI Boost, batch 2048; context capacity = prompt + 1 -date: 2026-10-15 12:22 (hardware/driver/power state are not controlled; see docs/npu-service.md) +date: 2026-10-15 12:22 (hardware/driver/power state are not controlled; see spec node npu-service.md) ## 1024 prompt tokens, 3 pairs pair first cpu s npu s speed-up next tokens diff --git a/benchmarks/tools/Capture-MachineState.ps1 b/benchmarks/tools/Capture-MachineState.ps1 index 0028a797..4bf6dd3c 100644 --- a/benchmarks/tools/Capture-MachineState.ps1 +++ b/benchmarks/tools/Capture-MachineState.ps1 @@ -4,7 +4,7 @@ .DESCRIPTION Read-only. Uses the same locale-independent forms as the command catalogue in - docs/reference-hardware/win-core-ultra-7-265u-npu.md (C04, C07, C08, C09, C11, C13, C14, C15, C17, C18): + spec node reference-hardware/win-core-ultra-7-265u-npu.md (C04, C07, C08, C09, C11, C13, C14, C15, C17, C18): CIM classes, setting GUIDs and ISO-8601 UTC times, no parsing of translated labels. Every benchmark run calls this before and after and stores both objects with its results. diff --git a/docs/adaptive-spec.md b/docs/adaptive-spec.md deleted file mode 100644 index 95aad688..00000000 --- a/docs/adaptive-spec.md +++ /dev/null @@ -1,146 +0,0 @@ -# Adaptive speculative window (`claude/adaptive-spec`) - -Status: implemented, measured on the 5090, **default on** (`LELEKA_SPEC_ADAPTIVE=off` or `LELEKA_SPEC=N` selects the fixed Original window). - -## Why - -The Original verifies a fixed window: MTP chain of `spec - 1` = 3 drafts cut at `--spec-min-p 0.5`, plus an optional suffix -(prompt lookup) window up to `spec + 2` = 6 rows chosen by `DraftPolicy` (a yes/no on the suffix, with the MTP window as the -alternative). Whether a wider window pays depends on two things that differ between workloads and between moments of one run: - -* how often the next draft is right (code edit, a file re-emitted from the context, tool-call JSON: high; prose: low), and -* what one more verified row costs (expert tier hit rate, CPU pool and PCIe load: with a converged tier the extra rows are nearly - free; with a cold tier each row touches more distinct experts and the window gets slower). - -At about 50 ms a round, one more accepted token per round is worth 30-40 %, so the choice of the width is worth more than most -kernel work, and a fixed value is wrong for part of every session. - -## Policy (crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive.rs) - -Per round the policy sees everything the drafters offer: the MTP chain (tokens and their own probabilities) and the suffix -continuation (up to `max_t - 1` tokens, the match length, whether its first token equals the MTP's first draft). It evaluates every -prefix of each as a candidate window and takes the one with the best - - rate(t) = E[tokens committed by the round](t) / (T(t) + chain ms) - E(t) = 1 + sum_{j= kVerifyMaxT` -static_assert, head and MoE group tables), so 8 rows is the ceiling without kernel changes and a re-seal of the PTX -(sm_120 + sm_86); 12 or 16 rows are not available from this branch. With `--spec 6` equivalent (`LELEKA_SPEC=6`, adaptive) the -verifier records windows 1..8 (one more capture + instantiate than 1..6, about +20 ms per request), the MTP is loaded at 8. - -## Results (RTX 5090, driver 595.99, CUDA 13.2, KAR PLE, int8 KV, conversation/prefix caches as noted; 1 model load per job) - -Method. All arms of a job run in ONE process (`LELEKA_SPEC_ARMS`): same tier, caches and clocks, the verifier built for the widest arm -(8 rows) for all of them, so the arms differ only in the window policy. Arm order rotates per repetition; 3 repetitions each. -`fixedN@P` is the Original's `--spec N` with `spec_min_p = P` (0.5 = the Original's serve setting, 0 = what the live Codex runs shipped). -Decode tok/s is tokens / verify-loop time (`decode.serve`) for the corpus jobs and `weighted_decode_tok_s` (total tokens / total decode -time) for the replays. Jobs: 9a1, 9a2 (chat + code corpus, 192 new tokens, 10 prompts x 3 repetitions per arm), 9b1-9b3 (real Codex session -replays, `scripts/spec/`, teacher forced to the recorded text, so every arm does identical work). - -| workload / tier | fixed3@0.5 | fixed4@0.5 | fixed6@0.5 | fixed4@0 (shipped) | adaptive | adaptive vs fixed4@0.5 (per repetition) | -| --- | --- | --- | --- | --- | --- | --- | -| corpus, static tier 2048 slots (hit ~11 %), job 9a1 | 60.25 | 63.05 | 63.15 | - | **65.06** | +2.5 / +3.1 / +3.9 % | -| corpus, auto tier + adaptation (hit 91-97 %), job 9a2 | 148.34 | 153.18 | 151.12 | - | **155.99** | +5.0 / +0.3 / +0.1 % | -| tic-tac-toe session, requests 0-15 (9-30k ctx), auto tier, job 9b1 | 135.72 | 138.40 | 134.79 | 134.52 | **141.04** | +1.8 / +1.8 / +2.1 % | -| CRM session, requests 0-15 (10-30k ctx), auto tier, prefix cache, job 9b2 | 139.71 | 144.48 | 145.25 | 141.57 | **150.71** | +4.4 / +4.2 / +4.4 % | -| CRM session, requests 56-67 (80-90k ctx), auto tier, job 9b3 | 121.62 | 125.59 | 124.89 | 122.64 | **130.10** | +3.8 / +3.3 / +3.6 % | - -Against the shipped live configuration (fixed4@0): +4.9 % (tic-tac-toe), +6.5 % (CRM), +6.1 % (CRM long context). Adaptive is above every fixed arm in every repetition of every -replay; ranges over the three repetitions are under 1 % of the mean. -The gain is small because the cost of a verified row is not small: measured round ms by width (replay 9b1, auto tier): T1 13.0, T2 15.1, T3 18.3, -T4 22.3, T5 26.2, T6 31.2, T7 34.8, T8 38.9 (about 3.6 ms per row, 28 % of the one-row window; with the static 2048-slot tier 10.5 ms per row, 45 %). -A row pays only when the cumulative acceptance of the rows before it times its own exceeds roughly 0.6, so the policy mostly moves the width -between 2 and 4 in uncertain text and to 7-8 in re-emitted code. Width histograms (share of rounds) in 9b2: adaptive T2 26 %, T3 17 %, T4 11 %, -T5 8 %, T6 11 %, T7 8 %, T8 15 % against fixed4@0.5 T4 79 %. Tokens per round: 3.69 (adaptive) / 3.17 (fixed4@0.5) / 3.91 (fixed6) with mean round 24.4 / 21.9 / 26.9 ms. - -Policy trace (tic-tac-toe request 4, adaptive, `width:accepted/source`, `LELEKA_SPEC_TRACE=1`): `3:1 2:1 2:0 3:1 2:1 4:0 5:4 5:4 2:1 3:2 2:1 3:1 -3:2 3:1 2:1 2:0 4:3 4:2 3:2 5:4 3:2 6:5 5:4 8:7(suffix) 8:7(suffix) 8:7(suffix) 8:7(suffix) 8:1(suffix) 8:5 8:7 8:7 8:2 8:5(suffix) 5:4 5:4 8:7 8:7 8:7 -7:6(suffix) 7:1(suffix) 7:5 3:2 7:6 7:6 5:4`: narrow in uncertain code, 8 rows inside a re-emitted block, back to 3 when the match ends. - -Draft floor: the policy's computed floor is at its ceiling (0.9 when the request carries 0, otherwise the request's value) in every trace inspected: with 3-4 ms -per row a draft below 0.9 never clears the marginal bar, so "a lower floor when rows are cheap" never triggered on this hardware; the verify-time prefix -choice (calibrated acceptance, not the raw draft probability) does the work that a floor would do. Job 9b5 (adaptive@0.5 / @0.7 / @0) measures the -ceiling; it was not run when this was written. - -Exactness. Verification is unchanged and the controller tests (fake target, perfect/poor/failing drafters, suffix on and off) check that the adaptive -window emits exactly the greedy text. On the device (static tier, seed off, adaptation off, 10 prompts, 192 tokens, 3 passes each, compared with the -first fixed4 pass of the same prompt): adaptive identical in 16/30 requests, fixed3 13/30, fixed6 13/30, and fixed4 against its own repeats 15/20; the -differences are the known batch-rounding envelope (a different window width rounds a near tie differently; the first difference is at token 5-170), -not a policy effect: the adaptive arm is no further from fixed4 than fixed3 or fixed6 are. With the auto tier (placement changes with timing): -21/30, 17/30, 19/30 and 11/20. Sampled requests are untouched (acceptance is equality with the sampled target token). - -Not feasible / not done: windows beyond 8 rows (`kVerifyMaxT = 8` is compiled into the window kernels); the 100k/180k jobs 9a3/9a4 are void (the -raw-text prompt makes the model stop after two tokens; the replay 9b3 at 80-90k context replaces them); 9b4 (static-tier replay) was skipped by the -queue; the chain-step graphs are captured lazily per request, the policy's deeper chains pay a capture the first time a depth is used in a request. - -## Results on the live CRM session (job 9b7) and the profile default - -Replay of the first 24 requests of the live Codex CRM session 9e3 (34,443 tokens in every arm, auto expert tier, 3-4 repeats, weighted decode tok/s): -fixed window 4 @ 0.5 (the reference configuration) 148.71 (147.98 / 149.25 / 149.06 / 148.55), adaptive @ 0 **156.26** (+5.1 %; 156.00 / 156.12 / 156.65), -adaptive @ 0.7 154.43 (+3.8 %). On the tic-tac-toe replay (job 9b5) the same arms gave +1.6 % (@0) and +0.9 % (@0.7), and adaptive @ 0.5 was 0.7 % below the -fixed window. `spec_min_p` is the ceiling of the adaptive policy's floor (0 = 0.9), so the `rtx5090-32g` profile now sets `spec_min_p: 0` (the adaptive -window is the default of the serve stack). The speculative controller only chooses window shapes and drafts; the verified tokens are the verifier's, and -window shapes are inside the Original's own envelope in `docs/quality-gate.md` (R3, `--spec 2`). - -## Final formal paired A/B (job 9f0, 2026-10-26) and quality gate (job 9q1) - -Workload: the live CRM Codex session capture 9e3 (first 24 requests, 34,443 recorded tokens per pass), RTX 5090, binary `rt-final`, expert slots auto, adapt-every 2. -Ten rounds, each a process of arm A and a process of arm B with 3 passes each, interleaved (30 passes per arm). - -| Arm | Configuration | passes | weighted decode tok/s (mean) | sd | 95% CI | -|---|---|---|---|---|---| -| A | fixed window 4 at min_p 0.5, no chain kernels | 30 | 148.93 | 0.24 | +-0.08 | -| B | adaptive window (ceiling 0 = 0.9 floor) + `LELEKA_CHAIN=all` | 30 | 166.81 | 0.39 | +-0.14 | - -Gain of B over A: **+12.0 %** decode (end-to-end replay of an agent session, not a kernel microbenchmark); the intervals are far apart. TTFT and reprefill were not the -variable of this A/B. - -Quality gate on the same binary (9q1, `q_analyze.py`, Original-envelope rule of `docs/quality-gate.md`): P1-final (plain) and P6-final-chain (chain kernels) against the -Original: d_top1 p99 0.216 / 0.223 (tolerance 0.238), flip rate 2.29 % / 2.29 % (tolerance 4.81 %), flip margin max 0.405. The strict rule still reports `top1 max` outside for -both (1.759, one row of prompt p1), as it does for every earlier port arm including the pre-merge static one (P1-static 1.152, P1-merged 1.759): the same row, unchanged by -this work. Chain kernels give the same rows and the same 14 flips as the plain arm. Run-to-run noise of the port itself (job 9n0) is of the same size, so this reads as -"no change against the previous merged state", not as a new pass of the strict envelope. diff --git a/docs/api-contract.md b/docs/api-contract.md deleted file mode 100644 index 96e7098a..00000000 --- a/docs/api-contract.md +++ /dev/null @@ -1,995 +0,0 @@ -# Native API contract status - -## Idle SSE transport - -Native Responses (text, tools and buffered structured/reasoning output), Chat -Completions and Messages streams emit `: keep-alive` SSE comments after 15 seconds -without a stream event. These transport comments contain no model output, usage, -sequence number or completion signal. SSE clients must ignore comment-only frames. -The internal adapters and offline replay verifier do so. A finished stream ends -normally; keep-alive does not extend generation deadlines or retain disconnected -requests. Normal backpressure still applies; this is not a guarantee against -proxy timeouts shorter than 15 seconds or intermediaries that buffer SSE. - -## Chat Completions (text/function subset) - -`POST /v1/chat/completions` uses the native Responses generation path. The wire -shape follows [Chat Completions create](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create): -JSON `chat.completion` and live SSE `chat.completion.chunk` with one indexed choice, -assistant content/function calls, `stop` / `length` / `tool_calls` finish reasons, -and a final `data: [DONE]`. SSE text deltas arrive before engine completion. -Function calls are published only after native tool validation, with a complete -argument string in one delta per call. This deliberately does not stream -unvalidated argument fragments. - -Supported inputs: - -- `model`, `messages` with system/developer/user/assistant text and tool results; - text strings or arrays of `{"type":"text","text":"..."}` parts; -- assistant `tool_calls` (`id`, `type: function`, `function.name/arguments`) and - tool `tool_call_id`/text; complete returned assistant messages can be reused; -- function tools, `auto`/`none`/`required` or a forced function name, - `parallel_tool_calls`, temperature and top_p, and the sampling controls listed under - "Sampling controls" below (`frequency_penalty`, `presence_penalty`, `seed`, `top_k`, `min_p`, - `repetition_penalty`, `penalty_last_n`); -- `max_completion_tokens` or the older `max_tokens` alias (not both), `n: 1`; -- `response_format` text, json_object, or json_schema containing name/schema/strict - under `json_schema`; the same native schema subset and final validation apply. - This is validation of generated output, not constrained token sampling; -- `stream` and `stream_options.include_usage`: when requested, normal chunks carry - `usage: null`, followed by a final empty-choices usage chunk before `[DONE]`. - -This first subset always uses `reasoning_effort: none` (also the default here) -and `store: false`; no hidden reasoning is requested or returned. Other efforts, -storage, multiple choices, multimodal input/output, custom/namespace tools, -custom stop sequences, log probabilities, -schema descriptions, non-null refusal text and unknown fields are rejected before -worker generation. It does not implement the full upstream API or stored Chat -retrieval. Omitted optional values use existing Responses defaults, including its -output-token limit. A Chat ID is not a Responses history ID. - -Usage renames native input/output/total counters to prompt/completion/total tokens, -including cached/reasoning detail counters. Incomplete output uses `length` and -does not publish a truncated tool call. An error emits the native error object -(and `[DONE]` for SSE) without a successful finish reason or final usage. Text -already streamed before final schema validation can precede that error. - -Auth, 16 MiB request bodies, admission/drain/queue limits and worker cancellation -are shared with Responses. The adapter bounds each native SSE event or JSON body -at 64 MiB; exceeding it fails explicitly. A disconnected Chat stream drops the -native stream consumer, triggering existing STOP/drain isolation; a failed request -is never replayed automatically. Request text and completions are not persisted. - -The CPU HTTP gate compares actual engine `GEN` token IDs and fixture outputs -against equivalent Responses with tolerance zero, including tools/continuation, -Unicode, JSON/SSE/usage, errors and live disconnect→STOP→fresh request. This is -protocol qualification only; real-model/harness rollout remains a separate gate. - -## Anthropic Messages (text/client-tool subset) - -`POST /v1/messages` uses the same native Responses worker, with -`anthropic-version: 2023-06-01`. It follows the [Messages request/response](https://platform.claude.com/docs/en/api/messages/create) -and [named streaming events](https://platform.claude.com/docs/en/build-with-claude/streaming) -shapes for text and client tools. This serves the configured local model, not a -Claude model or an Anthropic cloud service. - -Inputs are `model`, required positive `max_tokens`, optional `system` text/blocks, -user/assistant `messages`, `tools` with name/description/input_schema, `tool_choice` -(`auto`, `any`, `tool` with name, `none`) and `disable_parallel_tool_use`, `stream`, -temperature (0..1), top_p and top_k (plus the extension controls under "Sampling controls"). Text parts join with newlines; consecutive turns of -the same role combine. This initial subset requires first and last user messages; -assistant prefill is rejected. Assistant `tool_use` carries an object `input` and -ID; user `tool_result` returns the same `tool_use_id` and text or text blocks. -Omitted result `content` means empty text; explicit null and non-text blocks remain -invalid. [Client-tool errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) -with `is_error: true` are supported. Because the native template has text tool -outputs, the adapter serializes `{"content":"","is_error":true}` -as that call's tool output, preserving the flag and text (including escaped -control characters). Normal/`is_error: false` results retain their existing text -unchanged. Counting and serving share this conversion. This supports transport -of failures; recovery behavior still requires model qualification. -Tool names, arguments, results and choice policies reuse native validation. - -Thinking is disabled (omitted or `{"type":"disabled"}`); requests are stateless. -Thinking/redacted signatures, images/documents, cache_control, nonempty -stop_sequences, server tools, metadata, structured-output options, -beta headers and unknown fields are rejected before GEN. This does not implement all Messages features or certify a Claude SDK agent. - -`POST /v1/messages/count_tokens` follows the [token count response shape](https://platform.claude.com/docs/en/api/messages/count_tokens) -and returns `{"input_tokens": N}`. It accepts `model`, `messages`, optional `system`, -`tools`, `tool_choice` and disabled `thinking` from the subset above. Generation -fields (`max_tokens`, `stream`, sampling options) and unknown fields are rejected. -It uses the same serving conversion, prompt template and configured local tokenizer; -the count includes system/tool overhead and the generation prefix, without a cache -discount. It is not a Claude tokenizer estimate or a context/VRAM fit guarantee. -No worker generation or response-history writes occur, and it works while the -worker is unavailable if the tokenizer is configured. The same Messages version, -key/Bearer, body limit, admission/drain and error rules apply. CPU HTTP fixtures -compare the count to actual GEN input IDs with tolerance zero, including tool history. - -JSON returns ordered text/tool_use blocks with `end_turn`, `tool_use` or -`max_tokens` stop reasons and null stop_sequence. SSE uses message_start, -content_block_start/delta/stop, message_delta and message_stop (no `[DONE]`). -Text streams before DONE; validated tool inputs arrive as one complete JSON string -in an input_json_delta. There is no fine-grained unvalidated tool streaming. -Errors use `{"type":"error","error":{"type":"...","message":"..."}}` and a named -SSE error event; failed streams never emit a successful message_stop. Partial -text can precede a final validation error. Malformed or incomplete tool syntax -fails explicitly instead of publishing a tool block. - -Engine counters become known at DONE: message_start usage is provisional zero, -and the final message_delta supplies cumulative input/output/cache totals. -This uses the [SDK's optional cumulative input/cache usage fields](https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/types/message_delta_usage.py). -Clients must replace these totals, not add them. input_tokens excludes native -reused tokens, cache_read_input_tokens reports reuse, cache_creation_input_tokens -is zero (no provider cache-directive contract), and output_tokens is native total -output. Older clients that ignore final input/cache updates may display zero input -usage during streaming. JSON carries final totals directly. - -The existing local key can be sent as `x-api-key` **only on this route**, or as -Bearer. When authentication is configured, duplicate keys or a key combined with -Authorization are rejected; other API routes retain Bearer authentication. -The route shares the 16 MiB body limit, admission/drain and cancellation rules. -The bounded native SSE reader (64 MiB/event) is shared with Chat; each adapter -buffers at most eight output events. Disconnect releases the native consumer, -sends STOP and preserves the next request. No request/response history is stored. - -The actual CPU HTTP gate compares GEN tokens and fixture output to equivalent -Responses (tolerance zero), reconstructs ordered JSON from named SSE, and checks -Unicode, system/combined turns, tools/continuation, usage, headers/errors, -admission/drain and live disconnect→STOP→fresh generation. Existing Chat/auth -regressions run alongside it; real-model/harness/GPU qualification remains open. - -## Sampling controls - -Every route that generates (Responses, Chat Completions, Messages) takes the Original server's -sampling fields at the top level of the request body, with the Original's defaults (an absent field -keeps the engine's greedy default) and ranges, and fails closed on a value outside them -(`crates/sampler-ref` `RequestSampling`, `docs/sampler-reference.md`): - -| Field | Range | Notes | -| --- | --- | --- | -| `temperature` | 0..2 | `0` is greedy (Messages: 0..1) | -| `top_p` | 0..1 | `1` disables nucleus filtering | -| `top_k` | integer >= 0 | the sampler keeps at most 64: `0` and values above 64 use 64 | -| `min_p` | 0..1 | | -| `repetition_penalty` | > 0 | `1` is off | -| `frequency_penalty`, `presence_penalty` | -2..2 | | -| `penalty_last_n` | 0..2147483647 | a penalty without a window uses the last 64 tokens; the kernel caps the history at 4096 | -| `seed` | unsigned integer | `0` or absent draws a fresh clock seed per request | -| `strata_tune` | `{pcie_frac, spec_min_p}` in 0..1 | engine settings for this request only | -| `experimental_speed_projection` | boolean | switches a loaded control vector for this request (`cvec=0|1`) | -| `reasoning_budget_tokens` | whole number, `0` = none | see "Reasoning budget" | - -The worker `GEN` line is built by the same code the Python server's `StrataEngine.sampling_keys` -is checked against (`control-plane/tests/fixtures/golden/gen_lines.json`, produced by running that -code). The Chat route no longer refuses nonzero presence/frequency penalties. - -Server-wide defaults fill what a request leaves out: the config `sampling` block, then the Chat -settings shared through `POST /settings`; the request always wins and an explicit `temperature: 0` -stays greedy. A shared `max_tokens` and `reasoning_effort` apply to Responses requests that carry none -(Chat and Messages fix their own effort). - -### Reasoning budget - -With thinking on, a request's `reasoning_budget_tokens` (else the config's) caps how long the model -may think. At the budget, on a clean token boundary (no `` prefix held back, no UTF-8 -character split), the worker stops the pass, appends the Original's wrap-up text -(`"I have thought about this long enough; time to give my answer.\n\n\n"`) to the output -and continues from `prompt + generated + wrap-up`, so the engine keeps its cached prefix. If the -wrap-up leaves no room to answer the request ends as `length`. The client sees one token stream and -one `DONE`: `generated` counts delivered tokens, `prompt_tokens`/`reused` are the first pass's, -timings are summed. - -## Operational surface - -Ported from `engine/strata/serve/server.py` and replayed against the real Python handlers in -`control-plane/tests/http_surface.rs`: - -- `GET /props` (llama-server compatible: default generation settings from the config and shared - settings, chat template, `models_autoload`, `is_sleeping`), `GET /slots`, `GET /v1/status`, - `GET /api/health` (the Python `/health` body; `/health` keeps the minimal liveness body); -- `GET|POST /settings` (shared Chat settings, persisted next to the config; JSON from the server's - own page or a `trusted_origins` origin only); -- `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload` (own page, JSON object, `409 - model_busy` while a request runs or waits), lazy start (`engine.lazy_load`), idle unload - (`engine.idle_unload_s`), reload gates (`engine.before_load`, `engine.min_free_vram_mib`); the next - request after an unload loads the engine again; -- CORS for `/v1/*` (`cors_origins`, `"*"` allowed) with the preflight answered before - authentication; model `aliases`; unknown paths answer `{"error":{"message":"not found"}}`; -- engine stall watchdog (`engine.stall_timeout_s`): no engine line for that long during a request - ends the engine, fails the request with a clear error and uses the restart budget. -- MCP hub (`control-plane/src/mcp.rs`, tested against `engine/strata/serve/mcp_fake_server.py` in - `control-plane/tests/mcp_hub.rs`): `mcp_servers` / Claude Desktop's `mcpServers` / `mcp_config_file` - and the `mcp` block (`timeout_s`, `max_result_chars`, `max_rounds`, `start_timeout_s`) are - validated at start; stdio and Streamable HTTP servers start in the background, tools are listed - (all pages) and namespaced `__`, a server that stopped is started again by its next - call, results are text capped at `max_result_chars`, failures become `error:` text, a cancelled call - sends `notifications/cancelled`. `GET /mcp` (authenticated) reports servers, state and tools - (`{"servers":[],"tools":0}` when none). Not ported on purpose: the server-side tool loop - (`strata_mcp: true`, `run_with_mcp`) of the Python web page. Responses, Chat and Messages return - tool calls to the client, so no endpoint executes MCP tools on a client's behalf. - -Differences from the Python server: authentication is Bearer on every path except `/health` and -`/api/health` (the Messages routes also take `x-api-key`), unknown paths need authentication too, and -error bodies of the Rust authentication layer are its own. - -## Model discovery - -`GET /v1/models` returns the single configured `model` / `STRATA_MODEL_ID`, or -an empty `data` array when no ID is configured. `GET /v1/models/{id}` returns -the same record; percent-encode the ID as one path segment (including `/`). -Unknown IDs return JSON `404 model_not_found`. Both routes use existing optional -bearer authentication. Nonempty query parameters return `400 unsupported_query`; -POST and DELETE are unsupported and never install or remove a model. - -The response follows the [Models list](https://developers.openai.com/api/reference/resources/models/methods/list) -and [retrieve](https://developers.openai.com/api/reference/resources/models/methods/retrieve) -object shapes: `id`, `object: "model"`, `created: 0`, `owned_by: "local"`, wrapped -in `{"object":"list","data":[...]}` for the list. `created: 0` is this runtime's -explicit unknown-timestamp sentinel; `local` identifies a local deployment, -not the upstream model owner. No model provenance metadata is inferred. - -This is configuration discovery. It stays available while the worker is loading, -failed or draining and does not acquire a generation slot or touch model files. -Use `/ready` to check inference availability. Listing does not download, start, -test or certify the model, and does not expose filesystem paths or credentials. - -## Input token counting - -`POST /v1/responses/input_tokens` returns -`{"object":"response.input_tokens","input_tokens":123}` using the same native -history expansion, prompt template and tokenizer as generation. The shape follows -the [Responses input token count endpoint](https://developers.openai.com/api/reference/resources/responses/subresources/input_tokens/methods/count). -The local subset requires `model` and `input` and accepts the supported create-request -fields; unknown fields and unsupported live features are rejected. Instructions, -reasoning, text format and tool definitions contribute exactly as they do to the -rendered generation prompt. `previous_response_id` includes the saved transcript -and new input; new instructions replace prior instructions. Missing, deleted or -evicted parents return `404 response_not_found`. - -Counting requires a configured tokenizer, but does not require a ready worker, -queue inference, create a response ID or modify history (`store` has no effect). -It always returns ordinary JSON, including when `stream: true` is supplied. -Generation-only settings are validated but do not generate output. The count is -for the full rendered prompt, not only newly evaluated tokens or a prediction of -cache reuse, output length, model quality or available context space. It does not -truncate input or guarantee the request fits the worker's context. - -The route shares optional bearer auth, the 16 MiB body limit and bounded HTTP -admission with create: drain returns 503 and exhausted admission returns 429. -It remains available during worker failure when the service is not draining. -The isolated CPU test compares counts against actual `GEN` token IDs, with exact -integer equality; this does not qualify real-model inference. - -## Engine activity metrics - -`GET /metrics` returns JSON (`schema_version: 1`), protected by the same optional -bearer key as `/status`. This is a native JSON endpoint, not Prometheus text. -`/status` remains a stable discovery response. Metrics require the new binary; -the preserved console trial has not been upgraded to this feature. - -- `active` and `active_elapsed_ms` cover an admitted generation from the attempt - to write `GEN` until engine `DONE`, `ERR`, or supervisor interruption. They - do not indicate GPU utilization or HTTP response completion. -- `queue_capacity` and `queue_used` describe the bounded command channel - (including reserved capacity), excluding the active command and HTTP handlers - waiting to enqueue. An unconfigured channel reports null. These snapshots - are observations, not an admission or safe-restart guarantee. -- `generation.started` counts admitted attempts. Context/validation rejections, - abandoned queued requests and requests rejected during restart are excluded. - `completed` counts non-cancelled DONEs, including length stops. `cancelled` - counts DONEs with cancel finish or a disconnected consumer. `failed_or_interrupted` - counts started attempts without DONE, including engine ERR, protocol failure, - expired cancellation drain and shutdown. Each attempt enters one terminal - bucket. Engine completion does not imply valid JSON/tool calls or task success. -- `done_generated_tokens`, `done_prompt_tokens`, `done_decode_ms`, and - `done_prefill_ms` sum engine DONE values, including cancelled generations. - Counts for failed attempts are unknown and excluded. Prompt counts are engine - input counts, not necessarily newly evaluated tokens. Integer totals saturate - at u64 max and timing totals at the largest finite f64. -- `done_decode_tokens_per_second` is total DONE tokens divided by total DONE - decode seconds. `last_done` exposes the last DONE's counts, milliseconds, - decode rate, raw finish reason, optional reused-token/draft/expert counters. - Unavailable counters and zero-duration/nonfinite rates are null. There is no - instantaneous token speed, prefill rate, TTFT, percentile or quality score. - -Counters survive supervised child restarts and reset when the control-plane -process restarts. They contain no prompts, generated text, token IDs or keys. -Updates happen at generation boundaries; no per-token metrics lock is added. -Existing `T`/`PP`/`DONE` events are forwarded unchanged. These metrics support -observation; paired workload and quality measurements remain necessary for any -performance claim. - -### Monitor members, Prometheus text and `GET /api/requests` - -`/metrics` also carries the members of the Python service's Monitor (`engine/strata/serve/server.py` `Service.metrics`), added beside the -native ones above, which are unchanged (`schema_version` stays 1): - -| member | content | -| --- | --- | -| `engine` | `model`, `max_context`, `images`, `version`, `api_monitor`, and `settings` (the settings the engine reports: context, prefill chunk, caches, workers) | -| `live` | `state` (`idle`, `reading`, `generating`, or the worker state while it is not ready), `active`, `queued` (generations waiting for the engine), `phase`, `prompt_tokens`, `generated`, `elapsed_s`, `tok_s`, `tok_s_mean`, `prefill_tok_s_mean`; `prompt_read`, `prompt_total`, `max_tokens` and `tok_s_window_s` are `null` (the runtime does not report them) | -| `requests`, `requests_kept` | the last 12 settled generations, newest first (`?requests=all`: every one kept, up to 500): `time`, `duration_s`, `finish` (`stop`, `length`, `cancel`, `disconnect`, `error`), `prompt_tokens`, `reused`, `output_tokens`, `engine_generated`, `prompt_ms`, `decode_ms`, `decode_tok_s`, `hit_rate`, `drafts_offered`, `drafts_accepted`; `null` where the engine did not say or the attempt had no DONE. Counts and timings only, no payload | -| `totals` | since the process started: `requests`, `prompt_tokens`, `reused`, `output_tokens`, `prompt_ms`, `decode_ms`, `drafts_offered`, `drafts_accepted` | -| `hardware`, `hardware_static`, `history` | the engine's telemetry document (GPU, host RAM, CPU, throughput) in the Python names and units (bytes, percent, watts, degrees Celsius): `gpu_util`, `gpu_mem_used`, `gpu_mem_total`, `gpu_temp`, `gpu_power`, `cpu`, `ram_used`, `ram_total`, `tok_s`, `prefill_tok_s_mean`, ...; `gpu_name`, `gpu_count`, `threads`; and `history`, the last 60 samples of the headline series (one per engine health tick, 2 s by default; a burst of ticks within a second counts once). A figure the engine does not report is absent, never zero; the three are empty while the engine publishes no telemetry (it publishes once the model is loaded) | -| `telemetry`, `time` | the raw telemetry document (the same as `/v1/status` `machine`, without its age) and the wall-clock second | - -The GPU block comes from NVML; where `libnvidia-ml` cannot be loaded (WSL2, containers without the management library) the engine polls -`nvidia-smi --query-gpu=...` instead (at most every 2 s, `leleka-memory/src/smi.rs`), so the block is present on those hosts too. - -**Prometheus.** `GET /metrics?format=prometheus`, or any request whose `Accept` asks for `text/plain` or OpenMetrics before JSON (what a -Prometheus scraper sends), returns the text exposition (`text/plain; version=0.0.4`) of the same document under the same bearer-key rule: -counters `leleka_generations_{started,completed,cancelled,failed}_total`, `leleka_prompt_tokens_total`, -`leleka_prompt_tokens_reused_total`, `leleka_generated_tokens_total`, `leleka_{prefill,decode}_seconds_total`, draft counters, -`leleka_memory_gate_rejections_total`; gauges `leleka_up`, `leleka_generation_active`, `leleka_requests_queued`, `leleka_queue_used`, -`leleka_context_{max,live}_tokens`, `leleka_context_used_percent`, `leleka_gpu_{utilization_percent,memory_used_bytes,memory_total_bytes,temperature_celsius,power_watts,sm_clock_megahertz}`, -`leleka_host_{memory_used_bytes,memory_total_bytes,swap_used_bytes,cpu_busy_percent}`, `leleka_engine_{resident_bytes,pinned_bytes,cpu_busy_cores}`, -`leleka_decode_tokens_per_second{window=live|last|average|lifetime}`, `leleka_prefill_tokens_per_second{window=last|average|lifetime}`, -`leleka_prefix_cache_*`, `leleka_engine_phase{phase=...}` and `leleka_info{model=...}`. Unmeasured figures are not exposed (no zeros for "unknown"). -The table in `control-plane/src/prometheus.rs` is the contract. JSON stays the default for every other client. - -**`GET /api/requests`** is the Python service's opt-in request monitor. It is off unless the config sets `"api_monitor": true` (then -the route answers 404, as the Original's does): it keeps prompts and answers in memory. It records `/v1/chat/completions`, -`/v1/messages` and `/v1/responses` (the Original: the first two), the last 100 of them, bounded to 256 KiB per captured text -(`input_truncated`, `output_truncated`, `reasoning_truncated`, `response_truncated`). Without `id` it lists them newest first without -payload (`{"requests": [...], "retention": 100, "persistent": false, "loaded": ..., "auto_load": ...}`); `?id=ID` returns one whole -record (`input` as pretty JSON, `output`, `reasoning`, `response` of a buffered reply, `usage`, `error`, `http_status`, -`first_token_s`, `wallclock_s`), or 404 `request no longer retained` once evicted. States: `queued` until the first generated text, -`generating`, then `completed`, `error` (an error body or HTTP status >= 400) or `disconnected` (the consumer left before the stream -ended). Headers and API keys are never captured. Differences from the Python monitor: `queue_s` and `load_s` are `null` (the wait for -the engine is not attributed per request; `live.queued` shows the queue), and there is no `/api-monitor` HTML page. - -The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker `DONE`. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return `501 unsupported_live_feature`; a ready worker without tokenizer returns `501 inference_adapter_missing`. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open. - -The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility. - -For native Qwen tool parameters, a direct property `type: "string"` preserves -raw text, including quotes. A direct type array containing `"string"` now does -the same unless the text parses as a declared **non-string** JSON type. Thus -`["string", "null"]` preserves `123`, `false`, `{}` and quoted text as strings, -while the literal `null` selects null. `["string", "integer"]` selects an integer -for `123` and a string for `1.5`. This is a deterministic interpretation of an -ambiguous raw-text format, not a search for any schema-valid coercion. Full-schema -validation still runs before publishing a callable item; enum/range violations -are not retried as strings. Scalar declarations and untyped handling retain -their previous behavior. Type inference through `$ref`, `anyOf` or `oneOf` is -not added by this rule. JSON and both live SSE paths use the same decoder; -CPU fixtures verify argument equality, not real-model tool-call quality. - -`control-plane/src/wire.rs` encodes the upstream `GEN` request line and parses the current `T`, `PP`, `DONE`, and `ERR` output lines. The supervisor accepts an internal token-ID generation command, checks its context budget, and sends it to a resident worker. It can return a buffered result or stream bounded token events. Dropping the SSE receiver cancels generation. Native Qwen prompt assembly matches pinned text-only and one representative tool golden case byte-for-byte. The live Qwen parser holds split call markers and rejects incomplete calls; it validates full argument objects before publishing function-call events. - -Current request parsing supports `model`, string or array `input`, `stream`, `instructions`, `max_output_tokens`, `previous_response_id`, `parallel_tool_calls`, `reasoning`, `text`, named function `tools`, `tool_choice`, `temperature`, `top_p`, `truncation`, `metadata`, and `store`. Unknown fields are rejected. Terminal responses are stored by default; `store: false` disables this. `previous_response_id` replays a stored response with the new input, including function calls and matching results. By default the store is process-local and bounded to 64 responses or 128 MiB, whichever is reached first; old IDs become unavailable after eviction or restart. Multimodal input remains unsupported. The body limit is 16 MiB. - -### Opt-in durable history (Unix preview) - -Set `response_history_dir` in the serve config or `STRATA_RESPONSE_HISTORY_DIR` -(environment wins) to an absolute dedicated directory whose parent already exists. -The service creates it with mode `0700`; an existing directory must be owned by -its user with exactly that mode. Snapshot and lock files must be owned regular -`0600` files with one link. Symlinks are refused. An OS lock permits only one -service to use the directory. `check-config` reports `durable_unchecked` without -opening, creating or locking it. `provision` also leaves history untouched. - -This explicitly persists **plaintext input, tool results, and terminal responses**; -use a private external volume, outside Git. It has the same single-operator API -key scope as memory history, with no encryption or tenant separation. Changing -API keys does not erase the store. `store: false` writes nothing. Omitting the -option retains memory-only behavior. Windows durable storage is not supported. - -Completed/incomplete responses, expanded continuation transcripts and input-item -IDs survive service restarts. DELETE and oldest-entry eviction are committed too. -The existing limits remain 64 responses and 128 MiB of serialized response plus -transcript data. A versioned snapshot is bounded to 129 MiB including metadata; -this is not a total resident-memory bound. Each mutation writes a full snapshot -on a blocking pool, flushes it, atomically renames it and flushes the directory -before acknowledging success. Budget space for the current and staged snapshots. -This feature is not a throughput optimization. - -Startup validates the store before asset preparation, worker or listener startup. -Invalid schema, SHA-256 checksum mismatch, corruption, insecure files, excess size or an occupied lock fail -startup without resetting history. An interrupted unpublished stage is discarded -under the lock; the committed snapshot is restored. Disk failures produce the -existing `response_storage_failed` JSON error or terminal SSE `response.failed`, -never a false successful commit. Earlier text deltas may already be visible. -A failed store fences further mutations until restart; existing in-memory GETs -remain available. Failure before rename preserves the previous snapshot. Failure -after rename while flushing the directory has an **uncertain outcome**: the -request was not acknowledged, but its record can be present after restart. -A disconnected client can likewise miss an already committed result. DELETE is -logical deletion, not secure erasure of filesystem blocks or backups. -No in-progress stream, worker state, KV state or automatic retry is restored. - - -Before switching the testing runtime, exercise all engine stop conditions and tool calls with the real tokenizer and model on Linux GPU, and compare sanitized real Codex replays against the upstream Python server. Native reasoning now has its own output items, streaming events and continuation path. Do not mark Gate A complete based on synthetic fixtures. - -## Engine prefix metadata - -The engine's `RESUME ` and `REUSED ` lines are validated as nonnegative -prefix counts and treated as nonterminal metadata. Usage counters come from -`DONE`. These lines must not fail or finish a generation; unknown wire tags -and malformed counts still fail the protocol. - -## Stored response resources - -`GET /v1/responses/{response_id}` returns the exact saved completed or incomplete -response object, including output, tool call IDs/arguments, reasoning, metadata -and usage. `DELETE` on the same path returns -`{"id":"...","object":"response.deleted","deleted":true}` and removes that -entry's response and continuation transcript. These route shapes follow the -official OpenAI [retrieve](https://developers.openai.com/api/reference/resources/responses/methods/retrieve) -and [delete](https://developers.openai.com/api/reference/resources/responses/methods/delete) -references; the implementation supports the bounded history subset described here. - -- Both routes share the optional bearer authentication policy. They remain - available while draining or when the worker is unavailable; they do not invoke - the model. There is still one operator credential, without tenant isolation. -- Unknown, deleted, evicted, memory-only restarted and `store:false` IDs return - `404 response_not_found`. Repeated deletion also returns 404. Failed generations - are not stored; these routes do not poll or cancel in-progress jobs. -- Nonempty query strings return `400 unsupported_query`. Retrieval streaming, - stream resumption and optional include/query fields are not implemented. -- The shared FIFO limit is 64 entries or **128 MiB of serialized response plus - transcript data**. Both objects count toward the budget; this is not a process - RSS cap. Oversized records fail storage before publishing a successful terminal - response. Eviction removes both objects together; retrieval does not refresh - retention order. Disk storage is disabled unless explicitly configured above. -- Deletion prevents subsequent continuation using that ID. It does not erase - copies already included in descendant responses or an in-flight request that - obtained the transcript before deletion, and does not cancel generation. - -These routes require the newer preview; the preserved user trial is unchanged. -CPU verification: `python3 scripts/smoke-response-history.py /path/to/leleka-api`; -add `--durable` for actual process restart, corruption and disk-failure coverage. - -### Input item listing - -`GET /v1/responses/{response_id}/input_items` returns an authenticated list with -`data`, `first_id`, `last_id`, and `has_more`, following the documented -[OpenAI input-items route](https://developers.openai.com/api/reference/python/resources/responses/subresources/input_items/methods/list). -It accepts `order=asc|desc` (default `desc`), `limit=1..100` (default 20), and an -`after` item cursor. Unknown, duplicate or malformed query options and foreign -cursors return `400 invalid_input_items_query`; optional `include` is not supported. - -This is a projection of the stored effective input, including expanded -`previous_response_id` history and excluding this response's own output. -Instructions remain a separate request field and are not added to the list. -Message text is projected into role-appropriate typed text parts. List item IDs identify occurrences -within this response and remain stable while it is retained; they replace -client item IDs in this view so duplicate IDs cannot make pagination ambiguous. -Tool `call_id`, name, namespace, arguments and custom input are unchanged. -The transcript used to render subsequent model prompts is never modified. - -The route shares the configured history retention, deletion and authentication -policy. It works during drain/worker outage without generating tokens. Missing, -`store:false`, deleted and evicted responses return 404. Restart clears default -memory history; the opt-in durable store described above also preserves these -input pages. No payload logging or tenant isolation is added. -CPU HTTP coverage includes both response modes, exact tool-payload replay, -pagination, stable cursors, failure cases and no extra worker generation. - -## Cancellation failure isolation - -Dropping a generation receiver sends `STOP` and drains that generation's output -for at most 20 seconds. Tokens or progress emitted after `STOP` are discarded -and do not extend the deadline. A terminal line before the deadline permits the -next queued request. If the worker does not terminate in time, readiness is -revoked, the process is killed and reaped, and queued receivers are closed. -The supervisor never reuses an unaligned output stream. - -Both text and function-call SSE relays observe the HTTP consumer closing even -while the engine produces no events. They then drop their generation receiver -so cancellation reaches the supervisor immediately. - -A sanitized shell worker that consumes `STOP` without reporting `DONE` covers -this failure path. This regression does not qualify full-model soak stability. - -## Worker recovery policy - -After a failure of a worker that previously sent `READY`, the supervisor can -start a fresh process. The default lifetime budget is three restarts, with -delays of 2, 4 and 8 seconds. Set `engine.max_restarts` in the JSON config or -`STRATA_MAX_WORKER_RESTARTS` to an integer from 0 through 3; zero disables -recovery. Environment overrides the file. Successful requests do not replenish -the lifetime budget. Initial or replacement startup failure stops recovery. - -An active failed generation is not retried. Queued commands are failed during -recovery; requests arriving while restarting or starting are rejected. The -worker reports `restarting` during backoff, then `starting`, with no context or -readiness until a new positive `READY` handshake. Shutdown interrupts backoff. -After the lifetime budget is exhausted, the runtime must be restarted by its -operator. A real-model reload has passed; sustained soak remains open. - -## Date in the system prompt - -The gpt-oss template writes `Current date: YYYY-MM-DD` into the system message, so the date is part of the prefix on which -a worker's KV cache is matched: with the default `prompt_date: "utc"` (or `STRATA_PROMPT_DATE=utc`) every cache misses after -it once a day, at midnight UTC. Two other values exist: - -* `"YYYY-MM-DD"` pins the date for the life of the process (stable prefix; the model believes it is that day); -* `"none"` (experimental) leaves the line out, keeping the blank line that follows it, for clients that offer the date as a - function tool instead. The control plane does not host tools: the client (an agent harness or its MCP server) supplies - something like `get_current_date()` and returns an ISO date, and the model calls it when it needs the date. - -The model is trained with the line. Teacher-forced on four prompts of 770-957 tokens, leaving it out moves the next-token -distribution by mean KL 0.034-0.056 (best token unchanged at 89-90% of positions); changing only the date value moves it -by 0.023-0.040 (92-93%); both are above the numerical noise of 0.005-0.023 (93-97%). Task quality was not measured, so -`none` is not the default (`benchmarks/results/prompt-date-sensitivity-2026-10-17.txt`). - -## Worker pool (experimental) - -`engine.extra_workers` (a list of `{ "executable": ..., "args": [...] }`, at most 7) starts further workers with the -engine's timeouts and restart budget, served together with `engine` through one dispatcher -(`control-plane/src/pool.rs`). Each worker runs one generation at a time. A request goes to an idle, ready worker, -preferring the one whose last prompt shares the longest prefix with it (each worker reuses only its own cache), with -ties to the worker listed first; while every worker is busy, requests wait in arrival order. `/ready` and `/status` -report ready only when every member is ready; status and metrics otherwise describe the first worker. A worker that -fails is restarted by its own supervisor as above; while no member can come back, waiting requests fail. Measured use: -`docs/worker-pool.md`. - -The pool feeds stdio engine children through `worker::run_with_requests`, which has no administrative channel, so the -config rejects `extra_workers` together with `runtime` (a `leleka-inference` backend), `engine.lazy_load`, -`engine.idle_unload_s` (no load/unload on demand) and `vision` (images are read by the single supervised worker). - -## Model families in one control plane - -`engine.tokenizer_dir` selects the Qwen3.5 family (ChatML template, control-token marks, pictures, reasoning budget, the -`runtime` backend); `engine.gptoss_gguf` selects gpt-oss (Harmony prompt, tokenizer read from the GGUF) through the same -`codec::TextCodec` seam, and the two exclude each other. The gpt-oss worker's `GEN` line carries `temperature`, `top_p` and -`seed` only: a request that sets `top_k`, `min_p` or a repetition, frequency or presence penalty is refused with -`400 unsupported_parameter`, and defaults for those from the `sampling` block or the shared settings are dropped for that -family. The Qwen-only features (`vision`, `reasoning_budget_tokens` wrap-up, `runtime`) are not available for gpt-oss. - -## Live structured text - -Requests may select `text.format.type` as -`json_object` or `json_schema`. The runtime adds JSON-format instructions and, -for schemas, the schema itself to the model prompt. Invalid schemas and external -references are rejected before worker admission. Completed text must parse as -an object and, in schema mode, pass the supplied schema. The same validation -applies with `strict` true, false, or omitted. This implementation uses prompt -guidance and final validation; it does not yet constrain next-token sampling -with a JSON grammar and cannot guarantee successful generation for every schema. - -JSON requests return HTTP 502 if completed model output fails validation. -Structured SSE sends `response.created` / `response.in_progress` immediately, -then buffers output until engine DONE. Valid output is emitted with the normal -item/text/terminal events. Invalid completed output emits `response.failed` -without publishing text or function-call items. This buffering trades token-by- -token structured output for validation before publication. Plain text streaming -is unchanged. Disconnect still cancels the active generation while buffering. - -A token-budget stop returns `response.incomplete` with -`incomplete_details.reason: "max_output_tokens"`; its partial text may be invalid -JSON and must not be treated as a schema-valid completed result. Tool-only turns -remain valid: their arguments are checked against the tool schema, while the -text format applies to the eventual answer after tool results. History stores -successful and incomplete responses, never schema-failed responses. - -Example format: - -```json -{"text":{"format":{"type":"json_schema","name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}} -``` - -The field names and incomplete-result handling follow the -[OpenAI structured output contract](https://developers.openai.com/api/docs/guides/structured-outputs). -Recorded Codex/MCP replay remains a separate milestone. - -## Native Qwen reasoning - -`reasoning.effort` accepts `none`, `low`, `medium`, `high`, or `xhigh`. -Omitted/null effort uses upstream's `xhigh` default. The pinned model template -maps `high` to its xhigh instruction; `none` closes the thinking block in the -prompt. Effort is a template instruction, not a separate token budget. -`max_output_tokens` includes both reasoning and answer tokens. - -Generated reasoning is returned as an output item with `type: "reasoning"`, -`content: [{"type":"reasoning_text","text":"..."}]` and `summary: []`. -SSE emits `response.reasoning_text.delta` during generation, followed by its -text/content/item done events and the normal answer or function-call events. -The current reasoning path buffers the final answer/tool items until DONE; -structured answers are validated before publication. `effort: none` plain-text -and tool streaming retain their incremental behavior. Disconnect during -reasoning cancels the worker generation. - -The first Qwen `` marker separates reasoning from answer text, even -when split over tokens. A normal stop without that marker fails, unless the -text ends on whole tool calls of declared tools (see "Tool-call parsing"); a -token-budget stop while thinking returns an incomplete reasoning item and no -invented final answer. `usage.output_tokens_details.reasoning_tokens` counts original emitted -tokens up to and including the closing-marker token; if one token straddles the -boundary it is assigned to reasoning. Truncated thinking counts all its tokens. -EOS tokens remain in total output usage, not reasoning usage. - -Stored continuation and stateless replay preserve raw reasoning alongside -assistant messages/tool calls in the Qwen template. Reasoning-only incomplete -turns can precede a new user message. Summary-only and encrypted reasoning -cannot reconstruct this local model's raw context and are rejected explicitly. -`reasoning.summary: "auto"` or null is accepted, but no summarizer is implemented: -summary remains empty, and raw text is never mislabeled as a summary. Explicit -`concise`/`detailed` summaries are unsupported. - -The reasoning content and event shapes follow the -[Responses raw-reasoning extension](https://developers.openai.com/cookbook/articles/gpt-oss/handle-raw-cot). -This local Qwen implementation does not provide OpenAI encrypted reasoning. - -## Console request compatibility - -The native route accepts the console's `include`, `prompt_cache_key`, and -string-valued `client_metadata` fields. It also accepts, validates and ignores the hosted-service hints a Codex -configuration may add: `service_tier` (`auto`, `default`, `flex`, `priority`, `scale`), `user`, `text.verbosity` (`low`, -`medium`, `high`; `text.format` may then be absent and means plain text), `reasoning.effort: minimal` (served as `low`, the template's -brief-thinking instruction) and `reasoning.summary: none`. Still refused: `concise`/`detailed` summaries, `max_tool_calls`, -other `include` values and unknown fields. Only `reasoning.encrypted_content` is -accepted in `include`: it is an optional inclusion hint, and this runtime still -returns **raw reasoning content, not encrypted content**. Metadata is not added -to the model prompt or persisted by the runtime. The cache key is a routing hint; -it does not partition the single worker's token-verified prefix cache. - -Function namespaces are lowered to deterministic, collision-checked aliases for -the Qwen template. Output items retain the original function `name` and -`namespace`, and replay uses the same alias even for historical functions no -longer advertised. Duplicate identities, alias collisions, nested namespaces, -custom/free-form tools, and server-side web search are rejected. Typed argument -validation applies after namespace lowering on both JSON and SSE paths. -`function_call_output.output` accepts text or an array of `input_text` parts; -parts are joined with a newline. Image/file parts remain unsupported. - -When `max_output_tokens` is omitted, generation reserves up to 32,768 tokens, -limited by the remaining context minus the worker's eight-token margin. An -explicit output limit is preserved. Configuring `model` (or `STRATA_MODEL_ID`) -exposes that identity in `/status` and rejects requests for another model. -An omitted configured identity preserves the earlier single-worker API behavior. - -The opt-in console integration is installed with -`python3 scripts/install-qwen-native.py`. It adds the `strata-native` backend to -`qwen-codex-ctl` and uses a direct Responses provider in `qwen-codex`. This path -has no Python serving bridge. The launcher itself remains a local convenience -script. Existing selections remain unchanged, and an installation backup is -retained. `QWEN_CODEX_PROFILE` selects a separate console profile for tests. - -The native preview requires a loopback connection (an SSH tunnel for a remote -GPU). Optional bearer authentication is described below; it does not add TLS. -Native discovery uses -`/status`, requires a configured model identity and a ready 256K worker, and does -not synthesize legacy `/props` or `/slots`. `stop` refuses to operate on this -externally managed runtime; `logs` identifies its host-side logs. - -### Optional bearer authentication - -Set `api_key_file` in the server JSON configuration or `STRATA_API_KEY_FILE` -(takes precedence) to enable one operator credential. The source must be a -regular private file (no group/other permissions on Unix), containing 32–512 -printable ASCII bytes without whitespace; an optional trailing LF/CRLF is -accepted. Total file size is bounded at 514 bytes. Invalid/missing sources fail -startup before binding or launching the engine. FIFO sources fail without -blocking. Without a configured file, previous authentication-free behavior is -unchanged; the existing trial remains in that mode on loopback. - -All routes except minimal `/health` require `Authorization: Bearer TOKEN`. -Missing, wrong, malformed or repeated Authorization headers return a generic -401 `invalid_api_key` and `WWW-Authenticate: Bearer` before request parsing. -`/status` and `/ready` are protected as well. No supplied credential is echoed. -The server's retained credential state is a SHA-256 digest, compared using -`subtle::ConstantTimeEq`; the key is never sent to the engine. This is one shared -operator credential, not multi-user authorization or response-history isolation. -Changing the key requires a deliberate server restart; hot rotation is not -implemented. - -Rerun `scripts/install-qwen-native.py` to upgrade an existing native launcher; -fresh installs also include key-file support. Then an authenticated endpoint can -be selected with `qwen-codex-ctl connect strata-native --url LOOPBACK_URL ---key-file PRIVATE_FILE`. Discovery validates file permissions and uses the -credential header. Agent launch configures `/bin/cat` as the provider's auth -command, with only the absolute key-file path in its arguments. The token is -not written to launcher argv, environment or generated configuration. Existing -`--no-auth` connections and `native-service` commands remain unchanged. - -Approval/review requests can append developer messages after user input. The -native adapter stably coalesces these instruction messages into the leading -Qwen system section, preserving their content and order. It does not demote -approval instructions to user messages or bypass the console's review step. - -Stateless replay keeps adjacent assistant commentary and function calls in one -assistant turn, with their reasoning content attached. The commentary-to-call -separator matches the pinned Qwen template, including trimming commentary's -trailing whitespace. The sanitized `commentary-tool-prompt.json` fixture checks -this against an independently rendered upstream template, byte for byte. - -Parallel tool outputs are matched by `call_id` and replayed in their original -call order. Qwen's tool-response markup has no ID field, so retaining arrival -order would swap results when parallel tools finish in another order. A -regression checks that ordered and reversed delivery produce identical prompts. - -An omitted `temperature` uses the engine's greedy default (`0`), and response -metadata reports `0`. Explicit temperature values are preserved. This reflects -the existing engine protocol rather than changing sampling for console runs. - -## Custom text tools - -Native Responses accepts `{"type":"custom","name":"run"}` with an optional -string description and optional `"format":{"type":"text"}`. Namespace -containers may include custom tools. Regex format has the validation-only -preview described below. Lark, unknown custom fields and non-text outputs are -explicitly rejected. `tool_choice` supports `auto`, `none`, `required`, `allowed_tools`, and forced top-level custom -tools; see [Tool choice and call count](#tool-choice-and-call-count). - -Custom calls expose `type: custom_tool_call`, `input`, `name`, `call_id` and -optional `namespace`; they never expose the internal JSON `arguments` wrapper. -SSE uses `response.custom_tool_call_input.delta` and -`response.custom_tool_call_input.done`, bracketed by the normal output-item -events. The names and public fields follow the official -[custom tools contract](https://developers.openai.com/api/docs/guides/function-calling) -and [streaming events](https://developers.openai.com/api/reference/resources/responses/streaming-events). - -Internally, the Qwen template receives a function with one required string -parameter named `input`. Its complete envelope is validated before a callable -item is published. The public input is unwrapped without trimming or interpreting -its contents. This uses the engine's existing tool markup and its delimiter -limitations; it adds no grammar-constrained decoding. In ordinary text streaming, -validated complete calls can appear before engine DONE. Reasoning/structured -paths retain their existing buffering rules. - -Replay accepts `custom_tool_call_output` with a string or `input_text` parts, -including `previous_response_id` continuation. Call IDs, namespace identities -and function/custom output kinds must remain paired; mixed parallel outputs -are reordered by call order. No custom tool is executed by the runtime. - -CPU fixtures verify transport and replay, including multiline Unicode and -whitespace, with exact equality. Real-model custom-tool quality and constrained -sampling remain unqualified; the existing GPU user trial has not been upgraded. - -### Regex custom input validation preview - -The native preview also accepts -`"format":{"type":"grammar","syntax":"regex","definition":"[0-9]+"}`. -The request shape and Rust regex dialect follow the official -[Regex CFG documentation](https://developers.openai.com/api/docs/guides/function-calling#regex-cfg). -Strata provides prompt guidance and complete-input validation; it does **not** -constrain token sampling. A mismatch fails the response rather than repairing -or retrying the call. This distinction applies to this preview even though the -wire format uses `grammar`. - -The entire input must match, including whitespace and Unicode; a substring match -is insufficient. Valid input is returned byte-for-byte. A completed call is -validated before its item-added, input delta or done events. Invalid input -produces a JSON generation failure or terminal `response.failed`; no callable -item for that invalid call is published. Earlier valid calls/text in a stream -cannot be retracted. Namespace lowering and continuation preserve their existing -identities and exact inputs. Replayed historical calls are not revalidated under -new tool definitions. - -Definitions must be nonempty single-line strings, at most 8192 bytes; use escaped -`\n` to match newlines. Each request allows at most 32 regex tools and 64 KiB of -definitions, including namespaced tools. Each compiled regex and DFA cache has a -1 MiB limit; AST nesting is limited to 64. Lookarounds, backreferences, lazy -repetitions, verbose (`x`) and swap-greed (`U`) flags are rejected before inference, -as are malformed/unknown format fields and Lark. These are compilation/cache -bounds, not a total runtime memory or latency guarantee. Existing unformatted -and explicit text custom tools retain their semantics. - -## Tool choice and call count - -`tool_choice` omitted or `"auto"` preserves automatic tool selection. -`"none"` hides current tool declarations from the prompt and prevents any -generated callable item from being published. Declarations are still validated, -response metadata preserves the caller's tools/choice, and historical calls and -results remain in the replay transcript. Literal text that resembles tool markup -with no declared tools remains text, as in the existing no-tools path. - -`parallel_tool_calls: false` permits zero or one function/custom call per -response, across all namespaces. Prompt guidance asks for at most one call; -the server enforces the count. Default/true permits multiple calls. These wire -semantics follow the official [tool-choice and parallel-call documentation](https://developers.openai.com/api/docs/guides/function-calling#tool-choice). - -`"required"` requires at least one function/custom call at successful completion. -It needs a nonempty callable catalog (400 otherwise); together with -`parallel_tool_calls: false` it requires exactly one call. Namespaced calls -participate in the same count. - -`{"type":"function","name":"lookup"}` forces exactly one call to the declared -top-level function `lookup`, regardless of the parallel flag. Missing/unknown -names, custom tools selected as functions and extra selector fields fail with -400 before inference. A name is never treated as an internal namespace alias. -`{"type":"custom","name":"patch"}` likewise forces exactly one declared -top-level custom tool. Its text input is restored without modification; an -optional supported regex format is still validated before publication. The -selector must match the original tool's type, not its internal function lowering. -This [official custom selector example](https://developers.openai.com/cookbook/examples/partners/aws/openai_models_with_amazon_bedrock#44-use-a-custom-text-tool) -uses the same type/name shape. Forced namespaced selectors remain unsupported. -Unsupported choice kinds return 501; no choice is silently replaced with auto. - -`{"type":"allowed_tools","mode":"auto","tools":[{"type":"function","name":"lookup"}]}` -restricts new calls to a subset of declared top-level function/custom tools. -`mode: "required"` also requires at least one allowed call on successful -completion, as specified in the official [allowed-tools mode schema](https://github.com/openai/openai-python/blob/main/src/openai/types/responses/tool_choice_allowed_param.py). -The full declarations and historical calls/results remain in the prompt and -response metadata. Prompt guidance identifies the subset; the server rejects -disallowed calls before publishing their item or input/argument events. -This does not guarantee prompt-cache reuse or model compliance. - -The envelope accepts exactly `type`, `mode`, and `tools`; each selector accepts -exactly `type` and `name` matching its original declaration. Missing fields, -unknown names, wrong types, duplicate selectors, namespaced/internal aliases, -built-in tool selectors and extra fields return 400 before generation. -An empty auto subset permits text only; an empty required subset is rejected. -Multiple allowed calls are permitted unless `parallel_tool_calls: false`. - -These policies add prompt guidance while retaining declarations and history. -Their minimum count applies only to successful completion: a token-limit -`incomplete` response may contain no complete call. Wrong names and excessive -counts remain invalid even for incomplete responses. Initial streaming envelopes -are not subjected to a completion minimum. Original choice metadata is echoed. - -Buffered output that violates the policy fails with 502 before any callable -output is returned. In ordinary live SSE, a first valid call may already have -been published: a second call is rejected before its item/argument/input events, -and the stream ends with `response.failed`. Forced choice rejects a wrong first -call before publishing it; required choice with zero calls fails at completion. -Under none, no callable item is -published. Earlier valid text/calls cannot be retracted. Reasoning/structured -paths keep their existing buffering behavior. The runtime does not truncate -or retry tool calls and repairs them only as listed under "Tool-call parsing"; these policies do not implement constrained sampling -or parallel GPU requests. - -## Tool-call parsing - -The Qwen model writes a call as ``, ``, one `` ... `` per argument, -``, ``. `crates/gateway-text/src/tool_output.rs` reads it; a call is published only after it is whole, and an -argument value is the exact text between its tags. The specimens that pin this are listed in -[tool-call-corpus.md](tool-call-corpus.md). This section is what a client can observe. - -**Quoted calls inside a string argument stay inside it.** A `write` whose `content` documents or tests the call format -(a quoted whole call, a heredoc that prints one) is delivered with its `content` exact, in a streamed and a buffered response -alike. Before this change the argument was cut at the first quoted close and the rest -was published as plain text without an error. A value ends at the first `` that is followed by the next -`` and that does not belong to a call the value itself quotes (the quoted `` -openers before it, each followed by ``, must not outnumber the `` closers before it). -A call whose value opens a quoted call and never closes it is treated as unterminated, and is an error, not cut at the first -plausible close. Known limits: a value that quotes only the tail of a call (`` with no opener) still ends there; and a -value that reopens its own parameter (`` inside `content`) is still a parameter written twice, -which is refused as `duplicate tool parameter` and not merged into one argument. - -**Accepted although a delimiter is missing.** Each of these used to fail the response (`response.failed` or 502 -`tool_call_parse_failed`) and is now a call. Each is logged on the server's stderr as -`tool call accepted beyond the template form (closers supplied: N, arguments repaired: M)`; nothing else changes in the response. - -* `` left out: `` followed by `` ends the value and the call, but only when no `` - followed by `` ends the value (so a value that quotes `` and has a real - close later is read whole). A streamed response delivers such a call when the generation ends, not when its `` - arrives, because only the end of the generation can tell the two readings apart. -* `` left out: the call is whole when the next `` follows its ``, or when its - `` is the end of a generation that stopped by itself (finish `stop`). A generation cut by the token limit (finish - `length`) never gets this; it stays an error. -* A call inside the reasoning: a generation that stops by itself without `` and whose text ends on whole calls of declared - tools is read as reasoning followed by those calls, when the first call stands at the start of a line outside a code fence and - outside inline code and nothing but whitespace or further calls follows. The reasoning item is the text before the calls - and is `completed`. The calls' text has already been streamed as `response.reasoning_text.delta` (a stream cannot take it - back), so the deltas of that response contain the call markup that the final reasoning item and its `done` events do not. Without - such calls the old failure (`reasoning ended without `) stands; so does a `` that follows the calls. -* A slightly damaged array or object argument: for a parameter declared `array` or `object` (and not a union with `string`), - a trailing or doubled comma, single quotes, Python's `True`/`False`/`None`, extra closing brackets at the end, and an - array or object written as a JSON string of itself are read as written. Nothing is invented or dropped: brackets left open, - a bare string where a member belongs, a missing colon, an unknown word and a string cut short are not repaired and are - delivered as before (a string, which the argument schema then rejects). String parameters are never touched. - -**Not accepted (unchanged): a call for an undeclared tool** is an error, `undeclared function in tool call: NAME`, as a failed -response; it is never run and never published as text. Upstream Strata returns it as plain text and counts it. The choice here -is deliberate: text without a call ends an agent's turn as if it were the answer, while a failed response is retried by the client -(a recorded session survived one such failure that way, `docs/e2e-run.md`). The exception stays that an undeclared `apply_patch` is -run through the declared shell tool. Also unchanged: a call cut by the token limit, a duplicate parameter, prose that names the -`` tag, and a call that quotes a code fence are not recovered (they stay failures or are read as before); see the table in -[tool-call-corpus.md](tool-call-corpus.md). - -### Tool-call recovery (experimental) - -`tool_call_recovery` is **off by default and experimental**. It is not part of the default contract above and has not passed a quality -gate. Turn it on with `"tool_call_recovery": true` in the control-plane config file, or with `STRATA_TOOL_CALL_RECOVERY=1` in the -environment (`0`/`false` turns it off and wins over the file; any other value stops the start). It is read once at start, so a -change needs a restart; the start logs `tool_call_recovery is ON (experimental)` when it is on. - -With it on, a call for a **declared** tool that the model wrote next to the template form is read as that call instead of failing the -response or being shown as text: - -* `` where `` belongs (after ``); -* `` followed by `<=NAME>`, ``, `` or ``; -* a JSON object `{"name": NAME, "arguments": {...}}` inside `` (also in a Markdown fence; `arguments` may be a JSON string); -* a bare `` ... `` with no ``, only at the start of a line outside a code fence and outside - inline code (a stray `` after it is dropped); -* a second call in the same `` (opened by `` after the first ``); -* for array/object arguments, also brackets left open at the end (closed) and a bare string where an object member belongs (dropped). - -An undeclared name is still an error in every form; nothing is run that the request did not declare. Every call read this way is -logged as `tool call accepted beyond the template form (... drifted forms recovered: N)`. A streamed response delivers a batch when its -`` arrives and a bare call when the text after it shows it is over (or at the end). - -Risks, which is why it stays off: a bare `` that starts a line is run even when the model only meant to show it (outside -a code fence); closing open brackets can drop elements the model never finished; and these readings were checked only against the -41 Qwen specimens of the upstream corpus ([tool-call-corpus.md](tool-call-corpus.md): 24 read as upstream expects with it off, 30 with it -on), not on this model's own sessions. Upstream turned its equivalent on by default in 0.2.8 on a reporter's 1,462-turn corpus -(98.3 % of turns read as intended with it, 92.9 % without; Qwen3.8 under Claude Code). Before this is made the default here it needs the -charter's treatment: replay of captured failed outputs (`STRATA_DEBUG_FAILED_OUTPUT=1`) with and without it, and a paired run of a real -agent workload with a quality result. - -## Active generation deadline - -An operator can opt into `engine.generation_timeout_s` / -`STRATA_GENERATION_TIMEOUT_S` (1–86400 seconds, absent means disabled). -The deadline covers an active command, including worker pipe and result-channel -backpressure. It excludes request parsing, tokenization and command queue wait. -It is an absolute execution budget, not an idle-token timer or client end-to-end -deadline. Timeout fails the worker, kills/reaps it and uses the existing finite -restart policy. No active or queued request is replayed. - -For a connected client consuming its response, buffered requests return 502 -`generation_failed` with `generation exceeded configured execution deadline`; -SSE ends in `response.failed`, retaining its preceding event sequence. The -generation counts once as failed/interrupted. Failure delivery after process -cleanup is bounded to one second; a full streaming channel is then closed, -and the adapter emits a failure once the consumer drains buffered events. -Delivery cannot be guaranteed to a disconnected/non-reading client. This setting -does not replace HTTP/proxy timeouts. The default leaves existing long-context -generation behavior unchanged. - -## Admission lifecycle - -`POST /admin/drain`, `POST /admin/resume` and `GET /admin/lifecycle` expose the -native [maintenance drain protocol](../deploy/README.md#drain-before-maintenance). -They use the existing optional bearer gate. During drain, new Responses -requests fail with 503 `runtime_draining` before request-body validation; -previously admitted work continues. `/ready` returns 503 and `/status.ready` -becomes false. Response protocol events and worker output remain unchanged. - -The configured `max_in_flight_requests` (default 17, range 1–256, overridden by -`STRATA_MAX_IN_FLIGHT_REQUESTS`) bounds concurrent POST Responses handlers before -JSON parsing or tokenization. A request holds capacity through response-body -completion/drop. When full, additional POST requests receive HTTP 429, -`Retry-After: 1`, and error code `runtime_overloaded`. Authentication runs first; -drain's 503 takes precedence over overload. Transient overload does not change -readiness. Health, management and stored-response GET/DELETE remain accessible. -Lifecycle reports `max_in_flight_requests` and `available_request_slots` (capacity -minus tracked requests, independent of drain mode); `check-config` reports the -configured maximum. - -This bounds HTTP inference handlers, not GPU slots or generation jobs. The -worker still executes serially. On disconnect the HTTP guard can be released -while a generation's separate guard waits for STOP cleanup. This is not a cap -on TCP connections, total process memory, or GPU memory, and does not implement -batching. Admitted requests retain the existing queue and response semantics. - -### Signal shutdown grace - -Top-level `shutdown_grace_s`, overridden by `STRATA_SHUTDOWN_GRACE_S`, accepts -integer seconds 0–20; default 0 preserves immediate worker interruption. -`check-config` reports the effective value. With positive grace, SIGTERM/SIGINT -sets irreversible admission drain, makes readiness false and waits for both -tracked HTTP requests and generation jobs to reach zero, up to the deadline. -Already admitted requests can enqueue and finish during this interval. New -requests receive 503 `runtime_draining` while the listener remains open. - -Lifecycle adds `shutting_down`. After a signal, `/admin/resume` returns the -current lifecycle with both `shutting_down` and `draining` true; it cannot reopen -admission. Ordinary administrative drain/resume remains reversible. The wait -ends early when both counters clear (checked every 25 ms), or on expiry proceeds -to existing worker interruption/QUIT and HTTP shutdown. A signal does not imply -that every request will finish: expiry can produce failed responses. - -This setting bounds the admission drain phase only. Worker/process and HTTP -connection cleanup follow it. The rendered systemd unit retains its 45-second -hard stop; the 20-second grace cap reserves time for worker cleanup. Standalone -execution has no new overall exit deadline. For longer maintenance, explicitly -drain and wait before sending the stop signal. - -## Runtime backend (text-level engine) - -With a `runtime` block in the configuration (`control-plane/config.runtime.example.json`) the same Responses, Chat and Messages -routes run in front of a `leleka-inference` process over the `leleka.runtime.v1` gRPC contract instead of a stdio engine child. -The engine contract is text in, text out, so the surface differs from the stdio engine in these ways (see -`docs/api-over-rust-engine.md`): the prompt is sent as the rendered template text after a round-trip check against the token ids -that were counted; text deltas are re-tokenized for the HTTP layer with a byte-equality check, `<|im_end|>` / `<|endoftext|>` -end the text and cancel the engine generation, `usage.output_tokens` is the engine's own count and `reasoning_tokens` an -approximation bounded by it; images, `reasoning_budget_tokens`, `strata_tune` and `experimental_speed_projection` are -refused with an error; a default `max_output_tokens` is clamped to `runtime.max_output_tokens` (4096, the runtime's cap) and a larger -explicit value is refused; `/unload` is `unsupported` because the runtime's lifecycle belongs to its operator. A terminal event -(`response.completed`, `response.incomplete` or `response.failed`) ends every stream, including when the engine dies. diff --git a/docs/api-over-rust-engine.md b/docs/api-over-rust-engine.md deleted file mode 100644 index dffb4d93..00000000 --- a/docs/api-over-rust-engine.md +++ /dev/null @@ -1,157 +0,0 @@ -# One API in front of the Rust engine: options and decision - -Status 2026-10-16, branch `claude/api-over-rust-engine` (base `claude/m2-control-plane`). Design note for the finding in -[`delivery-gap-audit.md`](delivery-gap-audit.md) section 0.1 ("two serving stacks"). No GPU, model or engine run is involved in -anything written here; nothing is a performance or quality claim. - -## The two stacks today - -| | `leleka-api` (`control-plane/`) | `leleka-daemon` (`desktop-core/src/runtime_gateway.rs`) | -| --- | --- | --- | -| API surface | Responses (JSON+SSE, stored, `previous_response_id`, `input_tokens`), Chat Completions, Messages, tools (function, custom, regex), `text.format`, reasoning, MCP hub, drain, history, metrics | Responses text subset; Codex-shaped bodies get 400; `max_output_tokens` <= 4096; tools off by default | -| Engine link | child process, stdio lines `GEN ` / `T ` / `DONE` (`wire.rs`, `worker.rs`) | gRPC `leleka.runtime.v1` (`runtime.proto`) to `leleka-inference` | -| Unit of exchange with the engine | **token ids** in, **token ids** out | **text** prompt in (`GenerateRequest.prompt`), **text** deltas out (`TextDelta`) | -| Where the chat template is rendered | `leleka-api` (minijinja, `prompt.rs`) | the daemon (a path-included copy of `prompt.rs`) | -| Where text is tokenized | `leleka-api` (`leleka-tokenizer`, `encode(prompt, parse_special=true)`) | the engine (`backend.rs` `prepare_prompt`: `encode(prompt, true)`, same crate) | -| Where output is detokenized | `leleka-api` (`decode_bytes` per token, incremental UTF-8) | the engine (`TextDelta`, UTF-8 safe) | -| Stop handling | engine emits the stop token; `leleka-api` treats `<|im_end|>`/`<|endoftext|>` ids as the end | engine stops at its single `eos` id and never emits it; no other stop handling | -| Tool-call parsing | `leleka-api` from decoded text (`tool_output.rs`, incremental) | the daemon adapter, from text (`runtime_tools.rs`); `ToolCallDelta` is unused by the engine (`supports_tool_call_streaming` false) | -| Reasoning budget, images | token-level wrap-up (`worker.rs`), `GENI` embeddings | absent | - -The engine contract (`crates/backend-api`, version 2) is therefore **text-level**: one prompt string, `TextDelta` strings, -a terminal with usage and a finish reason (`Stop`/`Length`/`ToolCalls`), `cancel(request_id)`, and a model handle plus epoch. - -## Options - -### A. A runtime backend for `leleka-api` (the whole existing API in front of the Rust engine) - -Add a second implementation of the worker seam of `leleka-api` (the `GenerationCommand` channel plus `WorkerStatus`/`Control`, -today fed only by the stdio supervisor `worker::run_supervised`). It drives any `leleka_backend_api::Backend`; the production -`Backend` is a gRPC client of `leleka-inference` (`leleka-runtime-client`, extracted from `desktop-core` so both binaries share -one proto and one frame validator), and tests drive an in-process scripted engine implementing the same trait. - -* Protocol correctness: all of `responses.rs`/`chat.rs`/`messages.rs` and their ~600 unit tests, fixtures and smokes stay the - single implementation. The new code is only the engine edge: request mapping, event mapping, terminal guarantees. -* Token-level semantics: the HTTP layer needs token ids (context accounting, reasoning budget, usage) and the engine speaks text, - so the edge must convert both ways (section "Token-level edge" below). This is the one real cost of A. -* Risk: the engine edge becomes the place where subtle divergence can hide (double tokenization, stop markers, finish reasons). - It is small (hundreds of lines) and testable without a GPU. - -### B. Extend `leleka-daemon` with the missing API surface - -Grow `runtime_gateway.rs` until it accepts Codex bodies, stores responses, serves Chat/Messages, tools, `text.format`. - -* Protocol correctness: a second implementation of ~10k lines of wire behaviour. The daemon already path-includes three - `control-plane` source files (`prompt.rs`, `response_tools.rs`, `tool_output.rs`) which is a fragile form of sharing: every - change of those files recompiles inside two crates with different feature sets. Every API fix must be made and tested twice, - and Gate A (100% terminal events, tool arguments intact, schema validation) would need the whole fixture set ported. -* Token-level semantics: natural (text in, text out, same as the engine) but the daemon has no token ids at all, so context - accounting, `input_tokens`, reasoning budgets would need a tokenizer added there anyway. -* Upside: keeps `leleka-daemon`'s lifecycle/epoch/operation semantics and one fewer hop. - -### C. A shared API crate used by both binaries - -Extract the Responses/Chat/Messages implementation into a library with an `Engine` trait, link it into `leleka-api` and -`leleka-daemon`. - -* Cleanest end state; also the largest blast radius: `responses.rs` is 5.7k lines wired into axum state, `WorkerStatus`, - lifecycle, history and settings. Not achievable as a reviewable slice, and it would be designed against two engine edges - that do not exist yet in one place. -* It is where A leads: A introduces exactly the seam C needs (the engine edge behind one trait) while keeping everything green. - -## Decision: A, with C as the direction - -Reasons: - -1. It is the only option that gives Codex the complete, already-tested native API on top of the Rust engine without rewriting it - and without a compatibility bridge or Python. -2. All existing `leleka-api` tests stay valid by construction: the stdio worker is untouched, and the new worker is selected by - an explicit configuration block (`runtime`), mutually exclusive with `engine.executable`. -3. The engine contract stays the engine's: `crates/backend-api` and `leleka-runtime/src/backend*.rs` are not modified. The - things the contract cannot express are refused or documented, not papered over (below). -4. Lifecycle stays with the operator tooling: the new worker **attaches** to an already loaded runtime (snapshot, epoch, handle) - and never issues `Load`/`Unload`, so a 55 GB sealed-archive start is never a side effect of an HTTP request. It follows the - runtime across engine restarts (new epoch, model not ready) and reports `not ready` meanwhile. - -`leleka-daemon` remains the lifecycle gateway (`/runtime/load|unload|operation`, nodes, tunnels) until its remaining roles -move into `leleka-api`; it is not extended with API surface. - -## Token-level edge (the part that needs care) - -Prompt direction. `leleka-api` renders the chat template and encodes the whole prompt with `parse_special=true`; the engine -encodes the `prompt` string again with `parse_special=true` using the same `leleka-tokenizer` crate. The worker therefore -decodes the ids back to text and **verifies** `encode(decode(ids), true) == ids` before sending. A prompt that does not survive -the round trip (for example ids that are not the canonical encoding of any text, or an image-expanded prompt) fails the request -instead of being served with different tokens than the ones that were counted. Both sides must also use the same tokenizer -assets; the contract carries no tokenizer fingerprint (open item). - -Output direction. The engine returns text deltas; the HTTP layer consumes `Event::Token(id)`. The worker re-encodes each delta with -`encode(text, parse_special=false)` and checks that decoding gives back exactly the same bytes, so every byte that reaches the -client is a byte the engine produced. The ids themselves are not the engine's sampled ids: token counts in `usage` come from the -engine's terminal usage (`output_tokens`), not from the re-encoding; `reasoning_tokens` in usage details is approximate for -the same reason. Passing the engine's ids in `TextDelta` (additive field) is the contract change that removes this -approximation; it is listed as a follow-up, not done here. - -Stop handling. The engine stops at its `eos` id. `leleka-api` additionally ends the text at `<|im_end|>` or `<|endoftext|>`. -The worker scans the delta stream for those two literals (holding back a possible partial prefix across deltas), truncates the -text, cancels the engine generation and reports `stop`. Consequence: a model that spells one of those literals with ordinary -byte tokens is cut as well (the engine contract gives no way to tell the special token from its spelling). - -Finish reasons. `Stop` -> `stop`, `Length` -> `length`, `ToolCalls` -> `stop` (tool calls are parsed by `leleka-api` from the -text; an engine `ToolCallDelta` while `supports_tool_call_streaming` is false is a protocol violation and fails the request), -`Cancelled` after a client disconnect -> cancel, `Failed` -> error, a stream that ends without a terminal event -> failure and -the worker leaves `ready` until the runtime is attached again. SSE termination is guaranteed by the HTTP layer, which already -ends every stream with `response.failed` when the worker side closes without a `Done`. - -Not expressible over the text contract, refused (fail closed, with an explicit message, never silently dropped): image input -(`GENI` embeddings), `reasoning_budget_tokens` wrap-up (needs `prompt + generated ids` continuation), `strata_tune`, -`experimental_speed_projection`, and sampling values that are not exact thousandths/millionths (same rule as the daemon). - -## What the slice delivers and what it does not - -### Delivered (branch `claude/api-over-rust-engine`) - -| piece | where | -| --- | --- | -| worker for a text-level engine, selected by the `runtime` config block; same `GenerationCommand` channel, `WorkerStatus` and `Control` as the stdio supervisor | `control-plane/src/backend_worker.rs`, `runtime_config.rs`, `main.rs` (`serve`) | -| `Backend` over the real gRPC contract that **attaches** to a loaded runtime (no Load/Unload RPC), re-reads epoch and handle before every generation | `crates/runtime-client` (`GrpcBackend`); the proto, conversions and validated client moved here from `desktop-core`, which re-exports them unchanged | -| in-process scripted engine implementing the same `Backend` trait (feature `scripted`) | `crates/backend-api/src/scripted.rs` | -| literal stop markers across deltas | `crates/serving-policy/src/stop.rs` | -| harmless Codex hints accepted (`service_tier`, `user`, `text.verbosity`, `reasoning.effort: minimal`, `summary: none`) | `control-plane/src/responses.rs` | -| a test-only fake `leleka-inference` over the real `RuntimeServer`, driven by the existing scripted `engine.sh` programs | `desktop-core/examples/fake_runtime.rs`, `scripts/test-api-over-runtime.py`, `fixture.runtime_stack()` in `scripts/smoke-worker-cancel.py` | - -### Tests (no GPU, no model; commands run from the repository root) - -| layer | command | what it covers | -| --- | --- | --- | -| API + worker over the scripted engine, real HTTP/SSE | `cargo test -p leleka-control-plane --test backend_worker_http` (27) | Responses JSON/SSE, Chat, tools (function and custom), `text.format` valid/invalid, finish reasons, stop literals, client disconnect, generation deadline, wedged engine, dying engine, native tool-call delta, refused features, output cap, sampling fixed point, token counting, Codex-shaped two-turn exchange with stateless replay, `tool_choice` / `parallel_tool_calls` | -| `GrpcBackend` over loopback HTTP/2 | `cargo test -p leleka-runtime-client` (11) | attach checks, no Load RPC, frame mapping, missing terminal, drop/cancel, stale epoch, unreachable runtime | -| whole chain: router -> worker -> `GrpcBackend` -> gRPC -> real `RuntimeServer` -> scripted engine | `cargo test -p leleka-engine-host --test api_over_runtime` (6) | streaming, finish reasons, tool call, stop marker, disconnect through gRPC, failure and engine death, runtime restart and re-attach, the 256-generation limit | -| existing HTTP smokes, unchanged assertions, engine moved behind the runtime | `python3 scripts/test-api-over-runtime.py target/debug/leleka-api target/debug/examples/fake_runtime` (10 scripts) | replay driver and corrupted-stream rejection, custom tools, Chat, Messages, 216 tool-policy cases, input tokens, stored responses across a restart, keep-alive, drain, queue deadline | - -The ten scripts are the ones whose assertions do not depend on `leleka-api` owning the engine process. Not moved: -`smoke-worker-cancel.py` (a wedged engine ends the stdio supervisor; the runtime backend re-attaches instead), -`smoke-signal-drain.py` (expects `QUIT` on the engine's stdin) and `smoke-generation-deadline.py` (the deadline is a -`runtime.generation_timeout_s` here, covered by `backend_worker_http`). - -### Not covered / known gaps - -* **No real engine ran.** Nothing here loads a model or touches CUDA. Tokenizer agreement between `leleka-api`'s assets and the - engine's GGUF tokenizer is checked per request (prompt round trip) and by the input-token counter comparison (`the engine counted - N input tokens, the control plane M` on stderr), but never against the real vocabulary. -* **Output budget.** `RuntimeServer::generate` refuses `max_output_tokens > 4096`; the worker carries that cap - (`runtime.max_output_tokens`), clamps default budgets to it and refuses larger explicit ones. Codex's 32768 default is therefore - not reachable until the runtime's cap is raised (its value belongs to the engine owner). -* **Generation identity ledger.** Found by the e2e run: `RuntimeServer` (`MAX_IDS`) and the engine backend (`seen`) used to remember - every accepted request id for the whole epoch and refused new work after 256 (`generation_capacity`). Both now hold a bounded - window (`leleka_backend_api::RecentIds`, 16384 most recent ids, oldest forgotten first), so an agent session no longer ends the - runtime; a repeat of a recent id is still refused (`api_over_runtime::serves_more_than_256_generations_in_one_runtime_epoch`). -* **Token ids.** `usage.output_tokens` is the engine's; `reasoning_tokens` is derived from re-tokenized text, approximate, and clamped - to the engine total. Reasoning-budget wrap-up, images, `strata_tune` and control vectors are refused (fail closed). -* **No prefix reuse and no prefill progress.** The runtime resets to position 0 per request (`original-serve.md`), and the text - contract has no progress events, so the stall watchdog is off by default; `: keep-alive` comments still flow. -* **Sampling precision** is refused at generation time (502), not at admission (400), for values that are not exact - thousandths/millionths. -* **Lifecycle** stays with the operator: `/unload` reports `unsupported` and `/load` is a no-op while attached; the runtime must - already be loaded (`leleka-cli load-mtp`) with the mode named in the `runtime` block. -* `leleka-daemon` is unchanged and still has its narrow Responses subset; retiring that route is a separate step. diff --git a/docs/architecture/gateway-ports.md b/docs/architecture/gateway-ports.md deleted file mode 100644 index 5dc54ef2..00000000 --- a/docs/architecture/gateway-ports.md +++ /dev/null @@ -1,106 +0,0 @@ -# Gateway ports (STRA-338 S16) - -The layers, the engine-side ports and the architecture gates are on `hexagonal.md`; this page is the gateway half. - -The HTTP/Responses gateway (`leleka-control-plane`, binary `leleka-api`) talks to everything outside the request through five -small traits in `control-plane/src/ports/`. `AppState` holds `Arc` (type aliases `SharedClock`, -`SharedEngine`, `SharedResponseStore`, `SharedToolHub`, `SharedVisionEncoder`), never a concrete adapter. The real -adapters are chosen in one place, `serve()` in `control-plane/src/serve.rs` (the composition root, called from `main.rs`). - -`AppState` (`app/state.rs`) is grouped by responsibility, and the ports sit in the group they belong to: - -| Group | Holds | Ports | -|---|---|---| -| `lifecycle` | admission, drain, in-flight count | | -| `engine: EngineLink` | `client`, `control` channel, `worker` status, `pool`, `queue_timeout` | `EngineClient` (`engine.client`) | -| `http: HttpPolicy` | `api_key`, `cors`, `trusted_origins` | | -| `model: ModelView` | `name`, `aliases`, `tokenizer`, `chat_template`, `prefix_cache`, `memory` | `VisionEncoder` (`model.vision`) | -| `services: Services` | `settings`, `monitor`, `started_at` | `ResponseStore`, `ToolHub`, `Clock` | - -The pure part of the gateway (request sampling, the reasoning budget, the model-family codec, JSON ordering, the Chat -Completions translation) is the crate `leleka-gateway-domain` (layer L2); `leleka-control-plane` re-exports it under the old paths. - -| Port | Trait file | What the gateway asks | Real adapter | -|---|---|---|---| -| `EngineClient` | `ports/engine.rs` | `submit(command, queue budget)`, `queue_capacity()`, `queue_used()` | `adapters/channel_engine.rs`: the `mpsc` channel plus `queue::enqueue_with`. The worker supervisor, the runtime backend worker and the pool dispatcher read the other end; they stay behind the port. | -| `ResponseStore` | `ports/response_store.rs` | `transcript`, `response`, `input_page`, `insert`, `delete`, `count` | `responses/history_adapter.rs`: `ResponseHistory` (64 entries, byte limit) and, with `response_history_dir`, the checksummed disk snapshot of `history_store.rs`. A durable commit runs on the blocking pool. | -| `Clock` | `ports/clock.rs` | `now()` (tokio `Instant`), `system_time()`, `unix_time()` | `adapters/system_clock.rs` | -| `ToolHub` | `ports/tool_hub.rs` | `status`, `template_tools`, `call`, `close` | `mcp::Hub` (`adapters/mcp_tool_hub.rs`) | -| `VisionEncoder` | `ports/vision.rs` | `encode_all(sources)` (takes the engine/encoder GPU gate), `combine(images)` | `vision::Vision` (`adapters/vision_encoder.rs`); the resident process lifecycle (`start`, `unload`, `restart`, `close`) is not a port and stays with the worker supervisor and `main`. | - -## Dependency picture - -``` - HTTP (axum) composition root: main.rs serve() - routes: app::router, responses::*, | - server_api::*, models_api::* -- State ----+--- picks the adapters below - | - v - domain handlers (responses/, server_api/, ...) - | call only the traits - v - +-----------+---------------+-------------+---------+--------------+ - | Clock | EngineClient | ResponseStore| ToolHub | VisionEncoder| control-plane/src/ports/ - +-----------+---------------+-------------+---------+--------------+ - ^ ^ ^ ^ ^ - | | | | | - SystemClock ChannelEngine HistoryResponse- mcp::Hub vision::Vision adapters, one per port - (mpsc channel) Store (memory + (stdio/ (strata-vision - | disk snapshot) http) process) - v - worker::run_supervised / backend_worker::run_backend_worker (gRPC runtime-client) / pool::dispatch -``` - -## Rules - -* A port is called once per request or once per process. No port is called per token or per stream event: the streaming - loops read the plain `mpsc` receiver of the command, so the trait objects cost one virtual call per request. -* A port method returns a boxed future (`ports::BoxFuture`) so the trait is object safe without a new dependency. -* `EngineClient::submit` keeps the queue semantics of `queue::enqueue`: with a budget the worker must claim the command - before the deadline; the deadline is measured on the injected `Clock`. -* Fakes for every port are in `ports/fakes/` (`ScriptedEngine`, `MemoryResponseStore`, `ManualClock`, `FakeToolHub`, - `FakeVisionEncoder`). `control-plane/tests/ports_fakes.rs` drives the real `/v1/responses`, `/mcp` and metrics handlers - through them, and `queue.rs` has a test of the queue deadline on a `ManualClock`. -* The request's own stamps read the `Clock`: `Observe.clock` (the router builds it from `services.clock`) goes into the - request record `ReqCtx`, which stamps `admitted`, `engine_start`, `first_token` and the line written at the end with it. - The backend worker's `serve_one` and `conclude` and the stdio worker's `combine_done` take the start and end of a - request, and the `last_activity` stamps at the start and the end of a request, from `ObsHandle::now()` (the clock of the - request's record; the system's when the request has none). Those are a few stamps per request and none per streamed token - or event. -* Still direct `Instant::now()`, tracked with the `instant-now` ratchet in `architecture-baseline.json`: the activity - stamps of the worker supervisors at attach or `READY` and per engine line, the per-event progress stamps and the cancel and stop-drain deadlines - inside the streaming loops, the metrics counters, the MCP hub and server, the model fetch, the memory, prefix and - hardware views, the request monitor and the stage trace. - -## Composition root - -`serve()` in `control-plane/src/serve.rs` is the list of start-up phases in the order they must run (load the config and -the history, check the host, resolve the embedded engine, provision, bind, build the state, MCP, codec, vision, prompt -switches, runtime worker, worker or pool, idle unload, serve, stop). Each phase is a function of at most 30 lines in -`serve/state.rs`, `serve/engine.rs` or `serve/http.rs`; `serve` keeps no logic of its own. The order matters: the image -encoder starts before the engine (a GPU encoder takes its VRAM first), and the state is handed to the router by value so -that the engine channel closes when the server stops. - -## The offline commands stay in `leleka-control-plane` (S10, STRA-352) - -The offline KAR/GGUF commands (the `model_*` and `kar_*` groups under `control-plane/src/cli/`, with the code they call: -the ggml bridge, `kar*`, `native_pack`, `derived_*`, `mtp_*`, `tensor_export`, `gguf_*`) are not moved out of -`leleka-control-plane`. This is the owner default the integration session gave for S10: one crate and one binary, -`leleka-api`, with the offline groups beside the service group (`operations`). The seam for a later move is the dispatch -in `cli.rs`: each group owns its own `run`, so a second binary or a feature split can take the offline groups without -touching the gateway. Nothing in the gateway track depends on that move, and it needs a release decision (a second -binary to package), so it stays open. - -## Domain crate - -`leleka-gateway-domain` (layer L2) holds the pure protocol: sampling, the reasoning budget, the model-family codec, JSON -ordering, the Chat Completions translation and, since S21 wider, `responses/` (the `CreateRequest` type and its -validation, the prompt rendering, the reading of tool calls and reasoning out of the model text, the response object with -its event stream). `leleka-control-plane` keeps `responses::*` as re-exports and wrappers: the HTTP handlers, the history, the -streaming loops, the process switches (tool-call recovery, prompt date) and the log lines stay there. The Harmony prompt -of a gpt-oss request (`harmony_conversation`, `harmony_render`, `PromptDate`, `civil_date`) is in the domain too; only the -process-wide prompt date, `today()` and `render(request)` (which reads them) stay in `responses/harmony_prompt.rs`, next to -the byte-exact prompt tests. The pure part of the Anthropic Messages adapter (`messages/`: the request as a Responses request, and the reply fields, -stop reason, usage and error envelope) is in the domain as well; the route layers, the SSE adaptation and the HTTP error -responses stay in `leleka-control-plane`. What is not moved: `ReasoningStream` and the SSE loops of `responses/stream/`, the -Chat Completions handler around the domain translation, and `harmony_family::GptOssCodec` (it reads a GGUF from disk). diff --git a/docs/architecture/hexagonal.md b/docs/architecture/hexagonal.md deleted file mode 100644 index 688f0b77..00000000 --- a/docs/architecture/hexagonal.md +++ /dev/null @@ -1,238 +0,0 @@ -# Hexagonal architecture of the Leleka runtime and gateway (STRA-338) - -One page: the layers, the ports, how to add an engine family, what the gates check, and what the verification asked for. -Every statement was read from the code, `architecture.json`, `architecture-baseline.json` or the commits it names. -Detail pages: `gateway-ports.md` (the five gateway ports), `tech-debt.md` (what a step moved but did not fix), -`output-event.md` (the canonical model output of the gateway, S23), `../experiments/stra-338-gateway-track.md` (the gateway track report). - -## Layers - -The policy is `architecture.json`. A normal dependency points to the same or a lower layer. L0 to L2 are the pure layers: they -may not use `tokio`, `axum`, `tonic`, `tonic-prost`, `reqwest`, `hyper`, `libc`, `rustix`, `windows-sys`, `sysinfo` or `wgpu`. -Inside L3 a crate may use another L3 crate only through an edge listed in `adapter_edges`. Every workspace package is in exactly one layer. - -| Layer | Role | Crates (package names) | -|---|---|---| -| L0 contract | wire and trait contracts | `leleka-backend-api` (the `Backend` trait), `leleka-worker-protocol` | -| L1 leaf libraries | pure or std-only libraries | `leleka-obs` (`Clock`), `leleka-memory` (`MemoryPressure`), `leleka-context`, `leleka-sampler-ref`, `leleka-quant-core`, `leleka-serving-policy`, `leleka-harmony`, `leleka-tokenizer`, `leleka-gguf`, `leleka-kar-codec`, `leleka-experimental-ref`, `leleka-cpu-sys`, `leleka-cpu-kernels`, `leleka-shm`, `leleka-openvino`, `leleka-gateway-text`, `leleka-cuda-model` (the pure host-side models peeled out of `leleka-cuda-driver`: `Error`, projection formats and geometries, serving context, schedules and kernel specifications) | -| L2 domain | pure domain of one side | `leleka-engine-core` (prefix cache, conversation policy, prompt plan, speculative-decoding policies, request lifecycle, `EngineFamily`), `leleka-gateway-domain` (sampling, reasoning budget, codec, `OutputEvent` and the output decoders, Responses and Messages protocol) | -| L3 adapters | OS, device, process and file access | engine: `leleka-engine-qwen35-cuda`, `leleka-engine-fake`, `leleka-cuda-driver`, `leleka-model-format` (`WeightSource`), `leleka-native-cpu-expert`, `leleka-libc-shim`, `leleka-memory-os` (page locking, glibc heap and Win32 host facts for the memory governor); gpt-oss workers: `leleka-gptoss`, `leleka-gptoss-igpu`, `leleka-gptoss-npu`, `leleka-cpu-worker`, `leleka-igpu-worker`, `leleka-npu-worker`, `leleka-gpu-npu-worker`, `leleka-npu-service`, `leleka-igpu`; also `leleka-offline-tools`, `leleka-runtime-client` (gRPC client) | -| L4 hosts | composition roots and facades | `leleka-runtime` (facade), `leleka-engine-host` (the `leleka-inference` binary), `leleka-control-plane` (gateway, binary `leleka-api`), `leleka-deploy` (the `leleka` binary), `leleka-native-parity-bench` | - -`leleka-runtime` is one line, `pub use leleka_engine_qwen35_cuda::*;` (S22), so the binaries keep importing `leleka_runtime::...`. -`leleka-engine-fake` is a dev-dependency of `leleka-engine-host` only; no production crate depends on it. - -`leleka-engine-qwen35-cuda` has a default-on cargo feature `preview-path` (S25) for the legacy Rust-native "preview" decoder chain -(`docs/original-serve.md`): its spawn tier, `Qwen35CudaStart::Native` and the native serve loop. Off, the crate serves the Original path only -and refuses `--backend-mode preview` and the `auto` fallback with a clear error; the feature adds no edge between crates. - -## Dependency picture - -Selected edges of `python scripts/check-architecture.py --report`; every arrow points to a lower or equal layer. The dotted edge is a dev-dependency. - -```mermaid -flowchart TB - subgraph L4[L4 hosts] - ctl[leleka-control-plane
gateway root] - dcore[leleka-engine-host
engine process root] - rt[leleka-runtime
facade] - end - subgraph L3[L3 adapters] - q35[engine-qwen35-cuda] - fake[engine-fake] - cuda[cuda-driver] - mfmt[model-format
WeightSource] - cpux[native-cpu-expert] - rtc[runtime-client
gRPC] - end - subgraph L2[L2 domain] - core[engine-core
EngineFamily, run_request,
prefix cache, conversation] - gdom[gateway-domain] - end - subgraph L1[L1 leaf libraries] - obs[obs
Clock] - mem[leleka-memory
MemoryPressure] - gtext[gateway-text, harmony,
tokenizer, ...] - cudam[cuda-model
Error, shapes, schedules] - end - subgraph L0[L0 contract] - api[backend-api
Backend] - end - dcore --> rt --> q35 - dcore --> core - dcore --> rtc - dcore -.-> fake - ctl --> gdom - ctl --> rtc - q35 --> core - q35 --> cuda - q35 --> mfmt - q35 --> cpux - q35 --> mem - q35 --> obs - fake --> core - core --> api - fake --> api - rtc --> api - gdom --> gtext - cuda --> mfmt - cuda --> cudam -``` - -`engine-qwen35-cuda` reaches `cuda-driver`, `model-format` and `native-cpu-expert` through three declared adapter edges. `engine-core` -depends on `leleka-backend-api` and `serde` only. `leleka-engine-host` is the composition root of the engine process; `leleka-control-plane` -is the composition root of the gateway process (`serve()` in `control-plane/src/serve.rs`). - -## Ports and seams - -| Seam | Trait or type, and where | Dispatch | Why | -|---|---|---|---| -| Clock (engine) | `leleka_obs::time::Clock`; `SystemClock`, `ManualClock`, `AnyClock`, `Stopwatch` (`crates/obs/src/time/clock.rs`) | generic (`C = SystemClock` by default); `AnyClock` is an enum for owners that cannot be generic | read at coarse points (request, decision, tick); hot loops take one reading and compare it | -| Settings / EnvSource | `EnvSource`, `ProcessEnv`, `MapEnv`, `Settings` (`crates/engine-qwen35-cuda/src/settings/`, crate-private) | generic (`&impl EnvSource`) | the operator namespace is captured once; parsers are tested with `MapEnv` | -| MemoryPressure | `leleka_memory::pressure_port::MemoryPressure`; `ProcPressure`, `ScriptedPressure`; Windows adapter `leleka_memory_os::WindowsProc` | `Arc` inside `Governor` | read at sampler and admission cadence, never per token | -| PageLocking | `leleka_memory::lock::PageLocking` (`mmap`, `mlock`, `mincore`, `madvise`, `munmap`, `setrlimit` on plain addresses); adapter `leleka_memory_os::LinuxPageLocking`; `leleka_memory_os::real_governor(cfg)` is the composition | `SharedPageLocking` (`Arc`) held by `Governor` and `FdMapping` | called at archive guard time (startup lock, residency tick, heal), never per token; `leleka-memory` has no `libc` and no unsafe | -| WeightSource | `leleka_model_format::weight_source::WeightSource`; file, shard, resident-tensor and KAR adapters, an in-memory double | generic (`S: WeightSource + ?Sized`) | opened once per load; no method returns an owning copy of the bytes | -| ServeDevice | `ServeDevice` (`crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs`, crate-private), implemented by `OriginalServeStack` | generic (`&mut impl ServeDevice`) | one call per request; tests drive the real `generate` over a scripted device | -| Lifecycle / run_request | `leleka_engine_core::request::{Lifecycle, run_request, ServeError, admit}` | generic, no trait object | admission, reset or resume, prefill, decode, finish: the order and the failure classes run over any owners | -| EngineFamily + `spawn::` | `leleka_engine_core::family::{EngineFamily, spawn}`; families `Qwen35Cuda` and `EngineFake` | `F` is generic; the result is `Box` | the root is monomorphised over the family; the trait object is the process boundary | -| Backend | `leleka_backend_api::Backend` (`crates/backend-api/src/lib.rs`) | `Box` in `RuntimeServer` (`desktop-core`) | methods are request-level (`load`, `start_generation`, `cancel`, `unload`, reports); tokens travel in the `GenerationStream` | -| Gateway ports | `EngineClient`, `ResponseStore`, `Clock`, `ToolHub`, `VisionEncoder` (`control-plane/src/ports/`) | `Arc` in `AppState`, boxed futures | called once per request or per process; streaming loops read the plain `mpsc` receiver | -| OutputDecoder | `leleka_gateway_domain::output::{LiveDecoder, AtEndDecoder, OutputEvent}`, made by `TextCodec::live_decoder` and `at_end_decoder` (`output-event.md`) | enum over the families (`Qwen`, `Harmony`) behind two decoder types; no virtual call per token | one decoder per generation; the adapters of the families produce the canonical `OutputEvent` that the Responses answers consume | - -Inside the Qwen3.5 adapter there are three more device traits, all crate-private: `RequestOwners` (admission to finish), `PrefixDevice` -(the prefix cache) and `OriginalServePort` (the verify round). The rule behind the table is the `dyn-trait` pattern in -`architecture.json`: dynamic dispatch is for start-up composition and request-level boundaries, not for a round, a chunk or a token. -Two carve-outs are counted by the ratchet instead of hidden: `RequestOwners::prefill` and `decode` take `&mut dyn FnMut` callbacks, and the -`conversation` code in `engine-core` takes `&mut dyn StateMemory` and `&mut dyn SessionEngine`. - -There are two `Clock` traits on purpose: the engine one (std `Instant`, `leleka-obs`) and the gateway one (tokio `Instant`, `control-plane/src/ports/clock.rs`). - -## What is deliberately not a port - -* Kernels and their launch order, and CUDA graph capture and replay. They stay concrete in `leleka-cuda-driver` and the adapter. The STRA-338 - item says not to abstract graph capture until it is measured; nothing here measures it. -* The glue `prefill_actions` and `decode_phase` of `OriginalServeStack`. They hold the CUDA owners, the verifier assembly and the expert-tier - hooks, so they stay in the adapter; the test device mirrors them (`tech-debt.md`, S15). -* Shard open and bind, KAR verification and the CPU expert bank are not behind `WeightSource` yet; each is its own step (`tech-debt.md`, S18). -* The gpt-oss CPU/iGPU/NPU runtime is reached through the worker line protocol (`leleka-worker-protocol`, L0) and `codec::TextCodec` in the - gateway, not through `EngineFamily`. -* `RECONFIGURING`, `INSTANCE`, `settings::process()` and `Governor::global()` are still process-wide in the adapter (`tech-debt.md`, S13 and S14). - -## How to add an engine family - -Today `spawn::` is the only registered family of the engine process: `desktop-core/src/bin/leleka-inference.rs` calls it for the -Original and native paths, and its experimental paths still call the `spawn_backend_*` functions directly. There is no family `enum`; the root -chooses by its own logic, and a second family adds a second arm there. - -1. **Crate.** Create `crates/engine--` (package `leleka-engine--`), add it to `[workspace] members` in `Cargo.toml` - and to layer `L3` in `architecture.json`. Depend on `leleka-engine-core`, `leleka-backend-api` and L1 libraries. Another L3 crate only through an - `adapter_edges` pair that is a real port (the Qwen3.5 crate has three: `cuda-driver`, `model-format`, `native-cpu-expert`). Never depend on L4. -2. **Domain first.** Take policy from `leleka-engine-core` (`prefix_cache`, `conversation`, `prompt`, `spec`, `request`). Anything that needs the OS, - a device, `std::env` or `Instant::now()` goes behind the existing ports (`EnvSource`, `Clock`, `MemoryPressure`, `WeightSource`). -3. **Implement the seam.** A zero-sized marker `struct Family;` with `impl EngineFamily for Family { type Config = ..; const NAME: &'static str = ..; - fn spawn(config) -> Result, BackendError> }`, and `Backend` for the engine it returns. For the request path implement - `Lifecycle` on the family's owners and call `run_request`. Models: `crates/engine-fake/src/lib.rs` (smallest) and - `crates/engine-qwen35-cuda/src/backend/family.rs`. -4. **Register.** Add the crate to `desktop-core/Cargo.toml` and call `spawn::(config)` where the root picks the engine; the result goes to - `RuntimeServer::new` unchanged. -5. **Fake-engine test.** A GPU-free test that starts the family through `spawn::` and drives a request, in the style of - `crates/engine-fake/src/tests.rs`; for lifecycle behaviour implement `Lifecycle` on a scripted owner, as the `lifecycle_fake` device of the - Qwen3.5 adapter does. `desktop-core/tests/api_over_runtime.rs` is the full-chain test (real API router, real `RuntimeServer`, scripted engine). -6. **Gates** (next section): `python scripts/check-architecture.py`, `python scripts/check_architecture_test.py`, `python scripts/check-ci-coverage.py` - (add the package to `scripts/ci-coverage.json` and name it with `-p` in `scripts/check-local.sh`), `cargo test -p `, clippy with `-D warnings`. -7. **GPU rule (AGENTS.md).** A non-lossy change compares greedy output or tensor values with the defined baseline and records the tolerances. Nothing - is called a performance change without paired A/B measurements on the same workload, a quality result, and the hardware, software, model digest, - configuration, cache state, token counts and distributions the charter asks for. Lossy modes stay off by default and are marked experimental. - -## What the gates check - -`scripts/check-local.sh --product` (CI workflow `Product`, `.github/workflows/product.yml`) runs `scripts/check-ci-coverage.py`, -`scripts/check_architecture_test.py` (22 self-tests) and `scripts/check-architecture.py`. Run the last one alone for a local answer. - -| Check | Rule | Source | -|---|---|---| -| layers | every package has one layer; an edge to a higher layer is an error | `architecture.json` `layers` | -| adapter edges | L3 to L3 only through a listed pair | `adapter_edges` | -| purity | L0 to L2 use none of the `forbidden_in_pure` crates | `forbidden_in_pure` | -| size ratchet | no `.rs` file over 400 lines; a file already over may not grow past its baseline entry; a shrunk file is reported stale | `max_lines`, baseline `oversize` | -| mechanical file names | no new `.rs` file named by a mechanical split: `impl_*.rs`, `*_fn.rs`, `*_.rs` / `*__.rs` (a name must say what the module is and what it is for); the baseline lists the existing 964 files (`mechanical_names`) and an entry goes away when the file is renamed; `scripts/dev/rustsplit` now names the modules it creates after what they hold (`foo`, `thing_methods`, `display_for_thing`, `thing_methods_from_`) and disambiguates with a word (`_more`), never a number | `mechanical_names`, baseline `mechanical_names` | -| source ratchets | per-crate counts of `env-read`, `instant-now`, `path-include`, `process-global`, `dyn-trait`, `glob-super-import` (`use super::*;`) and `allow-unused-imports` (`#[allow(unused_imports)]`) over production code in `src/`; a count may only fall | `source_patterns`, baseline `source` | -| baselined violations | none: the two `leleka-memory` dependencies (`libc`, `windows-sys`) were removed on 2026-11-13 by the `PageLocking` port and the `leleka-memory-os` adapter | baseline `violations` | - -Commands: `python scripts/check-architecture.py` (0 errors expected), `--report` (layer graph, oversize census, ratchets), `--update-baseline` -(lowers numbers, refuses to raise one), `--update-baseline --allow-increase` (raising needs a reason in review). Test-only modules (a `mod x;` -under a test cfg, `tests.rs`, `*_tests.rs`, `tests/`) are not counted by the ratchets. - -Limits gate and Clippy ratchet (STRA-367). Function at most 30 lines, complexity 10, nesting 4, line 120 columns for new and changed code, a falling -census for legacy, and an opt-in Clippy ratchet (`too_many_lines`, `cognitive_complexity`, `too_many_arguments`). The files are -`scripts/check-limits.py`, `scripts/check-clippy-limits.sh` and `docs/architecture/limits-gate.md`, and `check-local.sh --product` runs the gate. -At the time of writing they exist on branch `claude/hexagonal-integ-lints` (commits `334af80d3`, `054b57bec`, `48b2ce9f4`) and not in this tree; their -census predates S19 to S22. After that branch is merged: `python scripts/check-limits.py`, and `scripts/check-local.sh --clippy-limits` for the Clippy side. - -## Verification evidence rules - -* **Identity is bitwise.** A step that must not change behaviour is compared with the reference binary on the teacher-forced replay of the - `night5-long-256k` capture: 5 requests, 240 forced tokens each, top-16 logprobs of every row and the draft trace. The reference A/A noise floor is - measured first (2057 logprob rows and 1036 draft-trace lines identical, 0 argmax flips), so any difference seen for a candidate is real. Recorded in - the LeaseVibe comments of STRA-344 as `HX-ID1`, `HX-ID2`, `HX-ID3`, `HX-ID-C2` and `HX-GATE2`. -* **Speed is paired.** A/B at 245k, 5 turns, each arm alone on the GPU, order alternating by block, block-paired differences with a confidence - interval. n = 10 blocks can exclude a slowdown of about 1% and shows nothing smaller; the charter's bar for claiming 1% is n >= 30. The records - (`HX-AB`, `HX-AB-C2`, `HX-GATE2`) state non-regression bounds, not speed-ups, and name what they do not cover (other workloads, sampling paths - other than greedy, the laptop 3080). -* **GPU-free steps** are covered by `cargo test`, clippy, `cargo fmt --check`, the architecture gate and, where one was recorded first, a golden - fixture (S21 `responses_pure.json`, the S5a digest goldens, the S2 round transcripts). -* **Not yet recorded.** The STRA-344 thread as read for this page ends with `HX-GATE2` at `17296a58f` (S14, S15, S18), with a note that the commits - after it up to `fc591f4e9` do not touch the engine process. It holds no identity or A/B record for S19 to S22 (`38eb771a4` to `a4ceeab69`), which - move code inside the engine process. The decision comment on STRA-338 puts that batch behind "A/B n=10 first, n=30 only with spare GPU time", with the - identity gate never dropped. Until that run exists, these four steps are verified by the compiler and the GPU-free tests only. - -## State after S22 - -`python scripts/check-architecture.py --report` on `a4ceeab69` (the S22 tip) against the first recorded baseline, commit `55dbadc43` (S1), whose -message states "3 layer violations, 329 oversize files, 65 ratchets" and which was built on `main` `731f060b7`. The two are not strictly comparable: -from S13 the ratchets count production code only, and the `path-include` pattern now skips `tests.rs` and `dir/name.rs`. - -| Measure | main `731f060b7` (S1 baseline) | S22 tip | -|---|---|---| -| `.rs` files over 400 lines | 329 | 121 | -| lines in those files | 303,231 | 96,649 | -| layer violations | 3 | 2 (`leleka-memory` to `libc`, `windows-sys`) | -| ratchet keys | 65 | 73 | -| `env-read` (total) | 492 | 205 | -| `instant-now` | 294 | 201 | -| `process-global` | 303 | 265 | -| `dyn-trait` | 229 | 219 | -| `path-include` | 205 | 231 (cause not analysed here) | - -Update of 2026-11-13 (`tech-debt.md`, debt register): layer violations 2 -> 0 (`leleka-memory` is pure; `leleka-memory-os` is the adapter), `process-global` 246 after the gate stopped counting names in `use` lists (the explicit imports of the pass would have raised it), `dyn-trait` 202, `env-read` 200, `instant-now` 188, `path-include` 234; two new ratchets, `glob-super-import` 1,136 and `allow-unused-imports` 1,590. - -Where the runtime went (oversize files and their lines, from the two baselines, and the ratchets per crate): - -| Crate | oversize files / lines | `env-read` | `instant-now` | `process-global` | `dyn-trait` | `path-include` | -|---|---|---|---|---|---|---| -| `leleka-runtime` at S1 | 87 / 82,652 | 239 | 74 | 102 | 71 | 94 | -| `leleka-runtime` now (facade) | 0 / 0 | 0 | 0 | 0 | 0 | 0 | -| `leleka-engine-qwen35-cuda` | 17 / 14,089 | 1 | 17 | 59 | 52 | 100 | -| `leleka-engine-core` | 4 / 3,714 | 0 | 0 | 0 | 19 | 0 | -| `leleka-engine-fake` | 0 / 0 | 0 | 0 | 0 | 1 | 0 | -| `leleka-gateway-domain` | 1 / 405 | 0 | 0 | 3 | 5 | 0 | -| `leleka-cuda-driver`, S1 to now | 97 / 91,850 to 30 / 19,617 | 126 to 76 | 44 to 31 | 108 to 110 | 51 to 48 | 102 to 115 | -| `leleka-control-plane`, S1 to now | 40 / 42,971 to 10 / 10,764 | 21 to 19 | 37 to 23 | 16 to 11 | 29 to 16 | 0 | - -Size of the new crates (all `.rs` under `src/`, tests included): `engine-core` 11,245 lines, `engine-qwen35-cuda` 113,374, `engine-fake` 92. -`engine-core` has no environment, clock or global in its code, which the zero counts reflect. The largest oversize file of the workspace is -`crates/native-cpu-expert/examples/kernel_ab.rs` (3,347 lines); the largest in the engine crates is -`crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs` (1,648). - -## Commits of the engine recut (S19 to S22) - -| Step | Commit | What | -|---|---|---| -| S19a | `38eb771a4` | prefix cache and pure memory admission to `leleka-engine-core` (L2) | -| S19b | `d717c6977` | Original prompt plan to `engine-core::prompt` | -| S19c | `93afb07bf` | conversation policy to `engine-core::conversation`; 17 `dyn` uses and 3 oversize test files moved with it | -| S19d | `8987e9ab0` | draft policy and adaptive window policy to `engine-core::spec`; `LELEKA_SPEC_*` parsing stays in the adapter | -| S19e | `58e3d864e` | admission, stop set, `ServeError`, `run_request` over `Lifecycle` to `engine-core::request` | -| S20 | `e049e24fe` | `EngineFamily` and `spawn::`, `Qwen35Cuda`, `leleka-engine-fake`; `leleka-inference` and the full-chain test start engines through the seam | -| S21 | `ff6cb3dcb` and later | `leleka-gateway-domain` (gateway track) | -| S22 | `a4ceeab69` | the engine moves to `leleka-engine-qwen35-cuda` (L3); `leleka-runtime` becomes the facade | diff --git a/docs/architecture/independent-nvidia-engine.md b/docs/architecture/independent-nvidia-engine.md deleted file mode 100644 index 766bb151..00000000 --- a/docs/architecture/independent-nvidia-engine.md +++ /dev/null @@ -1,222 +0,0 @@ -# Independent NVIDIA engine: architecture handoff - -**Status:** architecture proposal, awaiting Tech Lead review. This is a source -inventory and migration design; it does not claim a working inference engine. - -**Decision already made by the project owner:** Rust owns the runtime. Strata is -an upstream source for selected behavior and algorithms, not a build, runtime, -or deployment dependency. The new implementation repository is the private -Gitea repository `git@vezha.io:para/leleka.git`; its remote is reachable and was -empty when checked on 2026-10-05. Keep this architecture record and the existing -Strata provenance in `leleka-api`; implement the replacement in Leleka. - -## 1. Options and recommendation - -| Option | Benefits | Costs and risks | Decision | -| --- | --- | --- | --- | -| Keep the current C++ Strata engine and Rust control plane | Reuses the most inference code; shortest path to the existing Qwen setup | Production remains coupled to Strata's executable, `--serve` wire format, build and model profile | Reject as the target; preserve only as the behavior/reference baseline | -| Rust-owned engine and scheduler, with CUDA C++ kernels behind a narrow internal ABI | Rust owns model loading, tensors, routing, KV, admission, scheduling, lifecycle and API integration; existing CUDA kernels can be ported in measured steps | Initial CUDA kernels still need the CUDA build toolchain; FFI ownership, shape and stream contracts need tests | **Recommend.** This meets the owner's independence goal without pretending CUDA kernels can be safely rewritten in one pass | -| Rewrite all runtime and kernels in Rust immediately | One main language and fewer long-term language boundaries | Rust does not remove the need for CUDA/PTX; kernel parity and performance need separate proofs, and a big-bang rewrite delays a usable runtime | Reject as the first migration stage; replace individual kernels only after parity and paired performance gates | -| Rust host with a separate Python/C++ serving engine | Can compose existing libraries quickly | Keeps a second runtime, protocol bridge, process lifecycle and extra packaging dependencies; violates the desired self-contained production runtime | Reject for production. Python remains allowed only for offline research/evaluation where useful | - -This is a staged C++/Python-to-Rust migration, not a literal syntax -translation. Move ownership of serving behavior first. Keep CUDA C++ only at a -small kernel boundary while each kernel is ported or replaced against a numeric -oracle. The shipped Linux runtime should need an installed NVIDIA driver, not -the CUDA toolkit, a compiler, Python, or a Strata installation. Build-time CUDA -toolkit use is acceptable. The release gate must inspect the final artifact's -ELF dependencies to prove the driver-only installation claim. - -## 2. Existing coupling inventory - -The current repository is an intermediate product. These references explain -what Leleka must replace; they are not a requirement to copy the imported tree. - -| Area | Current source | What it means for independence | -| --- | --- | --- | -| CPU engine build | [`scripts/build-cpu.sh`](../../scripts/build-cpu.sh#L13) configures CMake from `engine/strata/` | Remove this from the Leleka build and release path | -| CUDA engine build | [`scripts/build-static-cuda.sh`](../../scripts/build-static-cuda.sh#L14) compiles target `strata`; its checks run the imported engine's ELF audit and `--help` | Replace the engine source and qualify the new binary; do not call `--help` an inference test | -| Hosted CUDA package workflow | [`.github/workflows/linux.yml`](../../.github/workflows/linux.yml#L139) builds the actual Strata engine; later steps combine and package it | Leleka CI must build its own runtime from pinned sources and retain build provenance | -| CLI image license | [`deploy/Dockerfile.static-cli`](../../deploy/Dockerfile.static-cli#L13) copies the imported engine license into the CLI-only image | Preserve required notices for any source actually reused; remove the Strata license copy only when no Strata code is shipped | -| Worker process boundary | [`worker.rs`](../../control-plane/src/worker.rs#L84) accepts an executable and arguments; the worker process is supervised and generation is sent to it | Replace the serving child process with an in-process Rust `InferenceBackend`; keep process isolation as an optional later boundary | -| Strata serving wire | [`wire.rs`](../../control-plane/src/wire.rs#L1) explicitly implements the resident Strata `--serve` stdin/stdout protocol | Delete this adapter from the replacement path; the public API must not inherit this private wire protocol | -| Embedded engine package | [`embedded_engine.rs`](../../control-plane/src/embedded_engine.rs#L1) stores and starts a separately built engine executable, and says model/shared libraries are not bundled | Package the Rust engine directly; model assets remain independently acquired and SHA-verified | -| Qwen-only model prep | [`native_model.rs`](../../control-plane/src/native_model.rs#L30) has one `RuntimeProfile::Qwen4expFlashNext`; GGUF/native pack helpers are preparation code, not an inference implementation | Keep Qwen import/preparation behind a model adapter or offline tool; define a versioned model descriptor instead of extending a single-profile enum | -| Build-time GGML C code | [`build.rs`](../../control-plane/build.rs#L6) compiles a vendored pinned `ggml-quants.c` plus `ggml_bridge.c`; [`ggml_bridge.rs`](../../control-plane/src/ggml_bridge.rs) uses it for GGUF quant conversion | This is a preprocessing dependency rather than serving inference. Move it to an optional offline packer crate so the shipped serving CLI does not need a C compiler or GGML bridge | -| Offline scripts | [`compare-real-tokenizer.py`](../../scripts/compare-real-tokenizer.py), [`prepare-keyless-routing.py`](../../scripts/prepare-keyless-routing.py), and pack smoke scripts import Strata tools or inspect Strata sources | Replace or retire them one at a time; keep them out of serving and never silently treat their output as production support | -| KAR experimental adapters | [`gpu/kar/README.md`](../../gpu/kar/README.md#L3) documents a narrow experimental expert component and explicit limits | Port the file/container concepts and proven kernels selectively; do not port the Strata callback as the new runtime boundary | -| Provenance | [`docs/upstream.md`](../upstream.md#L1) pins the imported Strata SHA and describes subtree update procedure | Preserve this historical record unchanged. Add a separate Leleka source/provenance manifest; do not rewrite the old upstream identity | - -`responses.rs` is a Rust protocol layer that currently consumes worker/tokenizer -types. Its role can remain in the Rust control plane, but it must call the new -backend API rather than depend on Strata's tokenizer, worker executable or -wire format. The public `/v1/responses`, SSE, cancellation, auth and health -contracts need their own replay tests; the model engine should not implement -HTTP semantics. - -## 3. Leleka backend boundary - -### Ownership - -Leleka is a Rust workspace with at least these logical crates: - -1. `leleka-api`: versioned request, model descriptor, capability, memory-plan, - error and event types. No CUDA or model implementation dependency. -2. `leleka-engine`: Rust-owned model loader, tensor/layout registry, tokenizer - integration, router, KV allocator, scheduler, sampling and lifecycle. -3. `leleka-cuda`: safe Rust wrappers over a narrow private CUDA C ABI. It owns - device/context/stream/event/buffer lifetimes; kernels cannot retain pointers - after the wrapper's borrow or stream completion. -4. `leleka-server`: HTTP/API translation, SSE, auth, cancellation and - observability. It talks to `leleka-api`, not to model-specific tensor layouts. -5. `leleka-tools`: offline conversion/evaluation only. It is not a dependency - of the serving binary and may contain Python during the transition. - -The initial backend is compiled into the process. Rust trait objects are not a -stable cross-version plugin ABI; if external native plugins are needed later, -define a layout-safe C ABI with explicit size/version fields and opaque handles. - -### Versioned contract (proposal) - -`leleka-api` has an explicit `API_MAJOR` and a capability-schema version. -Incompatible event, layout or error semantic changes increment the major -version. Release metadata records engine commit, CUDA kernel source digests, -toolchain, model adapter version and supported quantization IDs. - -The backend contract contains these operations: - -- `capabilities() -> CapabilitySet`: architecture IDs, quantization/layout - identifiers, attention/KV forms, limits, cancellation and streaming support. -- `load(ModelArtifact, ModelConfig) -> LoadedModel`: validate artifact digest, - descriptor, hardware/driver constraints and required tensors before publishing - a ready model. Partial failure drops all owned allocations. -- `memory_plan(ModelDescriptor, RequestDemand) -> MemoryPlan` and - `admit(MemoryPlan) -> Result`: account for - weights, cache, KV, scratch/workspace, simultaneous slots and safety margin; - reject before mutation when the request cannot fit. -- `health()`, `readiness()` and `model_metadata()`: readiness is false until - weights, kernels, tokenizer and required runtime state are verified. -- `generate(Request, CancellationToken) -> Stream`: stream - token IDs and optional token bytes/diagnostics plus a single terminal result. - The server maps those events to Responses/chat SSE. The stream has bounded - backpressure and a request ID. -- `cancel(request_id)` and `drain(deadline)`: stop future work, cancel active - work at a documented safe boundary, then release allocations exactly once. -- `unload()`: reject new admissions, drain/cancel according to policy, release - model/KV/cache ownership, then report unloaded. - -Errors are typed: `UnsupportedArchitecture`, `UnsupportedQuantization`, -`UnsupportedCapability`, `ArtifactMismatch`, `InsufficientMemory`, -`DriverIncompatible`, `LoadFailure`, `Cancelled`, `DeadlineExceeded`, -`DeviceLost`, `BackendFault`, and `ProtocolViolation`. No unsupported format -may silently fall back to a lossy conversion. Every accepted generation emits -exactly one terminal event (`completed`, `cancelled`, `length`, or `failed`); -after a terminal event no more deltas for that request are legal. Error details -are machine-readable and safe for API mapping; raw prompts, model tensors and -secret values are never diagnostics. - -The model descriptor is immutable per loaded model and includes architecture -family/revision, layer and expert geometry, router semantics, attention/KV -layout, tokenizer/template digests, tensor names/shapes, quantization scheme, -packing schema, context bound, required auxiliary heads and artifact digest. -Model-family names alone do not authorize tensor reinterpretation. - -## 4. Capability and optimization portability - -| Concept | Reusable part | Model/quantization-specific part | Safe behavior until qualified | -| --- | --- | --- | --- | -| Compressed weights resident in VRAM | Block store, byte-range validation, residency planner and bounded scratch allocation | Archive/tensor mapping, scale/group geometry, codebook and dequant arithmetic | Accept only exact versioned pack schema and tensor digest; otherwise reject or use an explicitly supported native format | -| Bounded expert cache | LRU/admission/eviction accounting and metrics | Expert IDs, dimensions, routing semantics, packed payload size and CUDA tile geometry | Cache only verified experts from the loaded descriptor; evict or fall back to a verified native path | -| KAR decoder | Container reader and generic bounded decode orchestration after schema validation | Current KAR top-down group-32 expert shape, levels, quant bytes and F32 accumulation; current code does not establish model-quality parity | Experimental opt-in only; reject shape/schema mismatch; never claim full-model residency or speed from the component probe | -| Expert routing and scheduling | Queue, batching windows, cancellation, fair admission and cost accounting | Router weights, top-k, shared/routed experts, normalization, correction bias and token-to-expert mapping | Use the model adapter's exact reference routing; unsupported router versions fail closed | -| KV allocation/streaming | Page/slot allocator, budget policy, asynchronous transfer lifecycle and accounting | MHA/GQA/MLA tensor layout, head sizes, position encoding, quantization, scales and block packing | Select only a declared KV format supported by that adapter; otherwise reject or use its verified lossless/default format | -| PLE | Sparse table paging/cache and row-request abstraction | Table meaning, lookup geometry, packing and exact association with model layers/experts | Disable unless manifest binds PLE artifact to model digest and adapter validates geometry | -| MTP/speculative decoding | Draft/verify scheduler mechanics and accepted-token counters | Trained draft heads, tokenizer, logits alignment, depth and model-specific verification semantics | Disable by default; enable only for an artifact declaring compatible heads and after exact greedy/quality gates | -| Value-only KV / lossy KV | Cache policy experiments and measurement hooks | Quality behavior depends on the exact model, workload, context and cache policy | Keep disabled; the existing Qwen V-only pretrained quality screen failed | -| Tokenizer and chat template | Byte streaming and API event mapping | Vocabulary, merge rules, special tokens, template and tool-call grammar | Require matching digests; no approximate tokenizer/template fallback | - -“MoE-compatible” means the model uses sparse experts, not that its weights, -router, attention, tokenizer, cache, quantization or speculative heads can be -reused. Every matrix row must be keyed by a model and pack manifest, not a broad -architecture label. - -## 5. Candidate model families and evidence gaps - -These are adapter/evaluation candidates, not supported models. - -| Candidate | Public artifact and license evidence | Compatibility and the first port-specific work | Evaluation feasibility and blocker | -| --- | --- | --- | --- | -| Mistral Mixtral-8x7B-v0.1 | Official [model card](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1) lists Apache-2.0 and describes a sparse MoE; official weights are available | Conventional attention plus sparse expert feed-forward gives a second-vendor router/weight-map adapter. Validate safetensors mapping and select a documented quant pack; do not reuse Qwen IQ3 conversion | Public reference weights and a reference runtime make tensor/logit and greedy-token oracle generation feasible. No Mixtral tensor map, converted artifact, quality corpus, or protocol trace is currently checked in; 32-GB fit at useful context depends on quantization and remains unproven | -| DeepSeek-V2-Lite | Official [model card](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) lists 16B total / 2.4B active parameters, safetensors and the DeepSeek model license; the [paper](https://arxiv.org/abs/2405.04434) describes MLA + DeepSeekMoE | Distinct latent-attention KV state and DeepSeekMoE routing require a separate attention/KV and router adapter. Published model context is 32K; do not assume Qwen's 256K/512K profile | Public reference weights/paper permit an adapter smoke and deterministic oracle suite. The model license has use-based conditions; compliance review and the exact license must accompany any distribution. No converted artifact or project quality/protocol evidence exists; 32-GB quantized launch and long-context target are unproven | - -If the owner wants the first extra family to be easier to serve on a 32-GB -card, Qwen3 MoE is a lower-variance adapter step but does not demonstrate a -second vendor or distinct attention family. Mixtral and DeepSeek-V2-Lite are -therefore the stronger architecture-coverage candidates; lawful artifact -selection and evaluation-data availability remain explicit gates. - -## 6. Migration and qualification stages - -1. **Repository and interface foundation (Leleka).** Create a clean Rust - workspace in the new Gitea repo, record licenses/provenance, pin Rust/CUDA - build inputs, define the API/capability schema, and add mock-backend - lifecycle/cancellation/memory-admission tests. No model or GPU is needed. -2. **Qwen correctness path.** Add a Qwen adapter and one explicit lossless - quant/pack path. Compare tokenizer IDs, tensor loads/dequant bytes, routing, - logits and greedy token IDs against the pinned reference. Then replay - sanitized real protocol traces: non-streaming, SSE terminal events, tool - calls/results, cancellation, timeout, reconnect and worker/device failure. -3. **Linux NVIDIA runtime artifact.** Build a reproducible self-contained - executable/image in CI. On a clean Linux host with an NVIDIA driver, audit - ELF dependencies, load the model, verify readiness, exercise API/cancel, - stop/restart and rollback. Host installation must not need Strata, Python, - CUDA toolkit or compilers. Model assets remain separately pinned and - integrity-checked. -4. **Port optimizations one at a time.** Start with bounded expert residency, - then KV policy/streaming, then exact-format KAR work, then optional PLE/MTP. - Each stage has a numeric oracle and its own isolated quality gate; lossy or - experimental arms remain off by default. Port CUDA kernels only when exact - output/tensor requirements pass and paired end-to-end measurements justify - keeping them. -5. **Model-family expansion.** Land Mixtral adapter + exact quant path and - protocol/quality suite; separately land DeepSeek-V2-Lite with MLA/KV tests - and license review. Passing one family does not imply support for other MoE - variants. -6. **Cutover.** Preserve Strata as the reference until the same sanitized API, - model, quality and deployment suites pass. Run a controlled paired workload - comparison with engine/model/config/cache/token counts recorded. Canary on a - separate port/service with artifact rollback; keep the last accepted - runtime selectable until the new build passes gates. Only after acceptance - remove Strata from the Leleka production/release path; retain historical - source provenance in `leleka-api`. - -No stage claims performance from compilation, synthetic kernels, mock-backend -tests, source inspection, or model loading alone. Required project profiles -remain `1 x 512K` and `2 x 256K` on the stated target; `1 x 256K` is an interim -local profile and cannot stand in for them. - -## 7. Immediate implementation work breakdown - -The next implementation tasks belong in Leleka, after this handoff receives -Tech Lead acceptance: - -1. Establish clean repo/CI and the versioned `leleka-api` crate with a mock - backend; verify no Strata import/build/runtime dependency. -2. Move the Rust control-plane event/API contract behind `leleka-api`; add - lifecycle, cancellation, single-terminal-event and admission tests. -3. Split offline GGUF/tokenizer preparation from the serving build; pin source - and artifact digests, with no production Python import. -4. Add the Rust-owned engine/model-loader skeleton and CUDA safe-wrapper crate; - first acceptance is CPU/mock behavior plus CUDA driver/toolchain contract, - not GPU inference. -5. Implement one Qwen lossless model path, exact numerical/token parity, then - run its real NVIDIA/protocol/quality gates on a host explicitly reserved for - qualification. -6. Create separately scoped Mixtral and DeepSeek adapter tasks only after the - corresponding legal artifact, supported quantization and evaluation corpus - are pinned. - -These are proposed bounded work items, not evidence that the deliverables -already exist. The new repository was empty at the time of this handoff; no -model files, traces, credentials, build artifacts or user workload data are -copied into it. diff --git a/docs/architecture/limits-gate.md b/docs/architecture/limits-gate.md deleted file mode 100644 index a10b57d6..00000000 --- a/docs/architecture/limits-gate.md +++ /dev/null @@ -1,212 +0,0 @@ -# Limits gate (STRA-367) - -Lawbook chapter 301 limits the size of code: a function has at most 30 lines, cyclomatic complexity at most 10 and -nesting at most 4, a function has at most 5 parameters (`self` counted) and a line is at most 120 columns wide. The workspace does not meet them today (see the census -below), so the gate is erroring for **new and changed code** and a **falling ratchet for legacy**. It is offline tooling -(stdlib Python, no cargo needed for the diff part, no network, no GPU); the production build does not depend on it. - -``` -scripts/check-limits.py diff gate + allowlist ratchet + census ratchet (what check-local.sh --product runs) -scripts/check_limits_test.py the self-tests (64 tests) -scripts/check-limits.py --report census per crate and the worst functions -scripts/check-limits.py --base REF diff against REF instead of the default base (env LIMITS_BASE does the same) -scripts/check-limits.py --update-baseline rewrite limits-baseline.json (never raises a total) and tighten the allowlist -scripts/check-limits.py --allowlist-add --reason R --owner STRA-nnn - allowlist what the diff gate rejects (moved verbatim legacy) -scripts/check-clippy-limits.sh opt-in Clippy ratchet (check-local.sh --clippy-limits) -``` - -Files: `limits.json` (the policy), `limits-allowlist.json`, `limits-baseline.json`, `clippy-limits-baseline.json`, -`clippy.toml`, `scripts/limits/` (the tool). The tool holds itself to the limits: `scripts/limits/`, -`scripts/check-limits.py`, `scripts/check_limits_test.py` and the architecture gate scripts are in `python_include`, -so they are measured with the same five measures (Python measures below) and the gate runs on its own commits. - -## What is enforced - -| Part | Applies to | Result | -| --- | --- | --- | -| Diff gate | every function that is added or has a changed or deleted line inside its span, in a `.rs` file (and the Python of `python_include`); every added or changed line | an error for each limit missed, unless the function is allowlisted | -| Allowlist ratchet | every entry of `limits-allowlist.json`, touched or not | an error when a recorded number grows; stale (reported, not failing) when the function is within the limits, gone, or smaller than recorded | -| Census ratchet | the whole tree, per crate and scope (`prod`, `test`) | an error when the **total** over all crates of any count rises above `limits-baseline.json` | - -Out of scope (`limits.json`, `exclude`): `engine/strata/` (the imported Original, never edited), `target/`. Test code is -in scope like production code (a function in `tests/`, `benches/`, `examples/`, `tests.rs`, `*_tests.rs` or under a -`#[cfg(test)] mod` is a `test` function in the census, and the diff gate treats it the same). - -### The diff - -The diff is `git diff --unified=0 -M BASE` against the **working tree** (so staged, unstaged and committed changes -count) plus untracked files (all their lines are added). The default `BASE` is `git merge-base HEAD R` for the first -ref `R` that exists in `claude/hexagonal-integ`, `main`, `origin/main`; `--base REF` or `LIMITS_BASE=REF` uses `REF` as -given. A pure rename (`git mv`, no edit) has no changed lines and is not checked. Moving a function to another file is -adding it there: allowlist it (below) or fix it. - -A function is **touched** when an added or changed line is within its span, or when lines were deleted between two of its -own lines. Touching a legacy function that misses a limit is an error: fix it, or allowlist it with a reason. A line is -checked for width only when it was added or changed. - -### Measures (the exact rules) - -A function is found from the Rust tokens (the lexer of `scripts/dev/rustsplit`, no parser). Its **span** runs from the -`fn` keyword to the closing brace of its body. - -* **fn_lines**: the number of lines of the span (signature plus body, comments and blank lines included). -* **complexity**: 1 plus the decision points of the body: every `if` (an `else if` or `if let` counts once), `while`, - `for` loop, `loop`, `&&`, `||`, `?`, and every `match` arm after the first of its `match`. `&&` and `||` count only - when they follow an operand (so `&&x` and `|| body` do not). A nested `fn` is measured on its own and is left out of - the function that contains it; closures belong to their function. -* **nesting**: the deepest chain of blocks inside the body (the body is depth 0). The block of `if`, `else`, `while`, - `for`, `loop`, `match`, `unsafe`, `async`, a closure `{ }` and a bare block each add one. A match arm block `=> { }`, a - struct literal or pattern `Foo { .. }` and a macro `name! { .. }` add nothing. -* **params**: the number of parameters in the signature, `self` (any form: `self`, `&self`, `&mut self`, `self: Box`) - counted like the others. Only the top-level, non-empty comma-separated parts of the list count, so commas inside - generics, tuples, arrays, patterns (`Foo { x, y }: Foo`) and `impl Fn(A, B)` types do not; a trailing comma is free; - generics before the list are skipped. `extern "C" fn` with a body and test functions count like any other function - (a declaration without a body, such as the ones in an `extern "C" { }` block, is not a function and is not counted). - In Python it is the number of positional, keyword-only, `*args` and `**kwargs` parameters, `self` and `cls` included. -* **width**: the columns of a line; a tab is 4, the line ending is not counted, 120 is allowed, 121 is not. For a - function `width` is the number of its lines wider than 120. - -Python (`python_include` only) uses the same names: lines are `def` to the last line; complexity is 1 plus `if`, -conditional expression, `for`, `while`, `except`, `match` case, every comprehension (and each of its `if`s) and every -extra operand of `and`/`or`; nesting is the deepest chain of `if`, loop, `try`, `with`, `match` (an `elif` chain is flat). - -These counts include `?` and the boolean operators, so they are higher than the hand counts in `tech-debt.md` written -before the gate existed (for example `render_request_with` is complexity 93 here, 58 there). - -A **key** names a function inside its file: the enclosing `impl`/`trait`/`mod`/`fn` names and its own name -(`Type::method`, `Trait for Type::method`, `module::helper`, `outer::inner`); a repeated key gets `#2`, `#3` in order of -appearance. The scanner is a heuristic (no macro expansion): a struct pattern directly after an uppercase constant in an -`if let ... {` condition, `for` in an `impl .. for` inside a function body, `let .. else` and `match` arms written -inside `macro_rules!` bodies are not modelled. It errs by a point or two, never by a function. - -## The allowlist - -`limits-allowlist.json` lists functions that may miss a limit, with the numbers they have today: - -```json -{"path": "crates/x/src/a.rs", "name": "Type::method", "fn_lines": 120, "complexity": 31, "nesting": 5, "width": 2, "params": 7, - "reason": "moved verbatim from backend.rs by S19", "owner": "STRA-367"} -``` - -* `reason` and `owner` (the work item that removes the debt) are mandatory; an entry without them is an error. -* A recorded number may only fall. The function growing in any of the five measures is an error, touched or not; the - entry also covers the wide lines inside the function. -* The entry named `` covers the wide lines that are in no function (consts, attributes, imports); only `width`. -* An entry whose function is within the limits (or gone) is **stale**: the gate says so and - `scripts/check-limits.py --update-baseline` drops it. The same command lowers recorded numbers that fell. It never - raises one. -* A new entry is made with `scripts/check-limits.py --allowlist-add --reason "..." --owner STRA-nnn`, which writes an entry - with today's measures for everything the diff gate rejects. Review the diff of `limits-allowlist.json` like code. - -On the default base (the tip of `claude/hexagonal-integ`) the allowlist is **empty**: nothing on this branch is -rejected. Against a main-like base (`--base main`) the gate rejects 5382 lines and functions in 1533 files, because the -whole hexagonal integration is new code relative to `main`; seeding the allowlist for that comparison is -`scripts/check-limits.py --base main --allowlist-add --reason ... --owner STRA-338`: 2736 entries (2354 functions and -382 `` entries), after which the gate passes with `--base main`. Whoever merges the integration into `main` runs it -once; it is not committed here, because the entries would only describe code that the integration's census already counts. - -## The census (legacy) - -`limits-baseline.json` counts, per scope and crate, the functions over each limit (`fn_lines`, `complexity`, `nesting`, `params`) -and the lines over the width. Only the **total over all crates** is ratcheted (code that moves between crates keeps its -total, like the source ratchets of the architecture gate), and `--update-baseline` refuses to raise a total unless -`--allow-increase` is given and justified in review. The tool reads the package list from `cargo metadata`; a file belongs -to the deepest package directory that contains it; the Python of `python_include` is the crate `python`. - -Census at the commit that introduced the gate (production / test; functions are counted once per limit they miss, so a function can be in several columns; the last column counts lines, not functions): - -| Crate | Functions over 30 lines | Complexity over 10 | Nesting over 4 | Lines over 120 columns | -| --- | --- | --- | --- | --- | -| `leleka-backend-api` | 3 / 5 | 2 / 0 | 0 / 0 | 16 / 0 | -| `leleka-context` | 6 / 12 | 6 / 1 | 0 / 0 | 10 / 1 | -| `leleka-cpu-kernels` | 1 / 8 | 0 / 3 | 0 / 5 | 0 / 1 | -| `leleka-cpu-sys` | 19 / 16 | 3 / 0 | 2 / 0 | 5 / 2 | -| `leleka-cpu-worker` | 7 / 6 | 5 / 1 | 0 / 2 | 6 / 11 | -| `leleka-cuda-driver` | 657 / 134 | 668 / 32 | 32 / 6 | 2561 / 188 | -| `leleka-deploy` | 105 / 89 | 53 / 0 | 7 / 0 | 387 / 67 | -| `leleka-experimental-ref` | 15 / 14 | 11 / 2 | 1 / 2 | 19 / 58 | -| `leleka-gateway-domain` | 16 / 3 | 13 / 0 | 6 / 0 | 53 / 1 | -| `leleka-gateway-text` | 15 / 13 | 16 / 0 | 1 / 2 | 64 / 21 | -| `leleka-gguf` | 6 / 5 | 6 / 0 | 0 / 0 | 3 / 1 | -| `leleka-gptoss` | 13 / 16 | 6 / 4 | 1 / 0 | 1 / 7 | -| `leleka-gptoss-igpu` | 1 / 5 | 1 / 0 | 0 / 0 | 2 / 3 | -| `leleka-gptoss-npu` | 5 / 4 | 3 / 0 | 2 / 0 | 3 / 6 | -| `leleka-gpu-npu-worker` | 3 / 2 | 1 / 1 | 0 / 0 | 3 / 4 | -| `leleka-harmony` | 4 / 3 | 6 / 0 | 2 / 0 | 1 / 5 | -| `leleka-igpu` | 12 / 12 | 1 / 1 | 0 / 0 | 5 / 0 | -| `leleka-igpu-worker` | 2 / 0 | 1 / 0 | 0 / 0 | 1 / 0 | -| `leleka-kar-codec` | 4 / 0 | 3 / 0 | 0 / 0 | 0 / 0 | -| `leleka-libc-shim` | 2 / 0 | 2 / 0 | 0 / 0 | 35 / 2 | -| `leleka-memory` | 21 / 2 | 11 / 1 | 1 / 1 | 164 / 67 | -| `leleka-model-format` | 84 / 83 | 62 / 14 | 4 / 4 | 100 / 70 | -| `leleka-native-cpu-expert` | 6 / 26 | 84 / 22 | 24 / 6 | 1106 / 325 | -| `leleka-native-parity-bench` | 0 / 0 | 0 / 0 | 0 / 0 | 9 / 0 | -| `leleka-npu-service` | 6 / 3 | 5 / 0 | 0 / 1 | 14 / 1 | -| `leleka-npu-worker` | 2 / 2 | 1 / 0 | 0 / 0 | 2 / 0 | -| `leleka-obs` | 4 / 0 | 4 / 0 | 1 / 0 | 16 / 7 | -| `leleka-offline-tools` | 8 / 3 | 5 / 0 | 0 / 0 | 1 / 0 | -| `leleka-openvino` | 2 / 0 | 0 / 0 | 0 / 0 | 1 / 0 | -| `leleka-quant-core` | 1 / 11 | 0 / 1 | 2 / 0 | 0 / 0 | -| `leleka-runtime` | 633 / 131 | 616 / 27 | 30 / 6 | 1995 / 250 | -| `leleka-runtime-client` | 9 / 9 | 4 / 0 | 0 / 0 | 4 / 0 | -| `leleka-sampler-ref` | 9 / 14 | 4 / 1 | 0 / 2 | 0 / 0 | -| `leleka-serving-policy` | 13 / 9 | 10 / 0 | 0 / 0 | 6 / 1 | -| `leleka-shm` | 2 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | -| `leleka-tokenizer` | 13 / 10 | 7 / 1 | 0 / 0 | 21 / 10 | -| `leleka-worker-protocol` | 3 / 1 | 3 / 0 | 0 / 0 | 0 / 0 | -| `python` | 0 / 0 | 1 / 0 | 0 / 0 | 2 / 1 | -| `leleka-control-plane` | 187 / 214 | 135 / 17 | 17 / 30 | 199 / 133 | -| `leleka-engine-host` | 81 / 65 | 59 / 3 | 6 / 3 | 54 / 30 | -| **total** | **1980 / 930** | **1818 / 132** | **139 / 70** | **6869 / 1273** | - -The numbers come from `scripts/check-limits.py --report` and are the content of `limits-baseline.json`. The Clippy side, measured on Linux with the opt-in script, is in `clippy-limits-baseline.json` (3675 warnings in 36 crates: `too_many_lines` 2441, `cognitive_complexity` 730, `too_many_arguments` 504); Clippy skips blank and comment lines and counts arguments, so its numbers differ from the table. - -## Clippy (opt-in) - -`scripts/check-clippy-limits.sh` runs `cargo clippy --workspace --all-targets --no-deps` with -`-W clippy::too_many_lines -W clippy::cognitive_complexity -W clippy::too_many_arguments` on the command line (no -`#![warn]` in any source), counts the distinct warning sites per crate, and fails when the total of a lint rises above -`clippy-limits-baseline.json`. Run it with `scripts/check-clippy-limits.sh [--update-baseline [--allow-increase]]` or -`scripts/check-local.sh --clippy-limits` (alone, or after `--product`). It takes about two minutes on a warm machine, but it is a full Clippy build of every target, so it -is not part of the default gate. `CLIPPY_LIMITS_ARGS="-p crate"` restricts the packages. - -Three details keep the count honest. The extra `-W` flags are not part of cargo's fingerprint, so the script builds in -its own `clippy-limits` directory under `CARGO_TARGET_DIR` (or `target/`) and every run uses the same flags; units -cached by a run with other flags would replay old diagnostics and undercount. `--cap-lints warn` lets a crate that denies -warnings compile with the extra lints on. And the counts are used only when `cargo clippy` succeeded: a failed build -exits 1 and writes nothing, so a partial run can never become the baseline. The baseline was measured on Linux (WSL -Ubuntu, Clippy 0.1.99); a Windows run differs by the `cfg(windows)` code. - -Clippy 0.1.99 keys: `too-many-lines-threshold`, `cognitive-complexity-threshold`, `too-many-arguments-threshold`. -The root `clippy.toml` sets the first two to 30 and 10; they belong to allow-by-default lints, so they change nothing for -the existing `-D warnings` gates. The third (5) lives in `scripts/limits/clippy/clippy.toml`, which the script passes as -`CLIPPY_CONF_DIR`: `too_many_arguments` is **on by default**, and a root threshold of 5 makes `leleka-control-plane` and -`leleka-engine-host` (functions with 6 and 7 arguments) fail the hard Clippy gates of `check-local.sh --product`. -A self-test keeps the two files in step. Crates that carry `#![allow(clippy::too_many_arguments)]` are not counted. - -`rustfmt.toml` with `max_width = 120` is deliberately absent: it would reformat the workspace and conflict with every -open branch. The 120-column rule is enforced by the diff gate on added and changed lines only. - -## Tightening - -* Lower the numbers in `limits.json` (the census rises, so `--update-baseline --allow-increase` once, in a reviewed - commit that also seeds the allowlist if a diff needs it). -* Fix a legacy function (or split it): its allowlist entry becomes stale; `--update-baseline` drops it, and the census - total falls with it. -* Add a path to `python_include` to hold more Python to the limits. -* When a crate is clean, nothing more is needed: the census row is gone and the total can only stay at zero for it. - -## Decision (STRA-367) - -Owner order of 2026-11-06: encode the chapter 301 limits as machine-enforced gates, without asking. - -* **Erroring for new and changed code.** A function that is added or touched, and a line that is added or changed, must - be within 30 lines, complexity 10, nesting 4, 5 parameters and 120 columns. Legacy that is moved verbatim is exempt only through an - allowlist entry with a reason and an owner, and the entry can only shrink. -* **Ratchet for legacy.** The census of what already misses the limits is recorded and its totals may only fall. -* **No workspace reformat.** No `rustfmt.toml` with `max_width = 120`; the width rule applies to changed lines only. -* **Clippy is an opt-in ratchet.** `too_many_lines`, `cognitive_complexity` and `too_many_arguments` are counted by an - opt-in script, not turned into errors (every crate would fail) and not added as `#![warn]` attributes. The argument - threshold is kept out of the root `clippy.toml` because the lint is on by default. -* Not done here: seeding the allowlist for a `main` base; a CI job (the gate runs in `check-local.sh --product`). \ No newline at end of file diff --git a/docs/architecture/naming.md b/docs/architecture/naming.md deleted file mode 100644 index 057b23e2..00000000 --- a/docs/architecture/naming.md +++ /dev/null @@ -1,70 +0,0 @@ -# Naming (STRA-338) - -Whoever comes back to this code in a month must understand **what a thing is and what it is for** from its name, without reading the -body. This page is the rule set (owner order of 2026-11-08), a "bad -> good" table taken from our own code, and the review checklist -used for every change. Domain words are defined once in [`docs/glossary.md`](../glossary.md); use them exactly. - -Sources: Robert C. Martin, *Clean Code*, ch. 2 "Meaningful Names"; Rust API Guidelines, "Naming" (RFC 430 casing and the `as_` / `to_` / -`into_` conventions, ); John Ousterhout, *A Philosophy of Software Design*, -ch. 14 "Choosing Names" (); the SSW rule "avoid generic -names" (). - -## Checklist (paste into a review; every item is a yes/no) - -1. **Intent.** The name says what it is, what it is for and how it is used, without a comment to explain it. -2. **Precision.** No `status`, `flag`, `data`, `info`, `tmp`, `val`, `ret`. Say which: `is_` / `has_` / `can_` for booleans, so that `true` - reads as an obvious statement (`is_resident`, not `flag`). -3. **One term per concept**, project-wide, from the glossary (expert, tier, slot, round, window, draft, commit, prefill, decode); never - one word for two different things, never two words for one thing. -4. **Banned vague words** in type, module and function names: `Manager`, `Helper`, `Util(s)`, `Handler`, `Processor`, `Service`, `Data`, - `Info`, `Misc`, `Common`, `Base`, `Impl`, `Wrapper`, `Stuff`, and numbered suffixes (`_2`, `_N`, `w01`). (`Service` stays where it is the - domain word, for example the NPU service process; say so in the doc comment.) -5. **Length follows scope.** `i` and `j` only in a loop of about three lines; no abbreviations (`qkv`, `rms`, `idx` are allowed only - as an established domain term listed in the glossary). Units are part of the name: `timeout_ms`, `size_bytes`, `rate_tokens_per_s`. -6. **Role, not type.** `selected_experts`, not `vec_of_experts` or `v`; `bank`, not `arc_vec`. -7. **Rust conventions** (RFC 430): `UpperCamelCase` types, `snake_case` functions and modules, `SCREAMING_SNAKE_CASE` consts; - acronyms as a word (`Gpu`, `Uuid`, `Kv` in a type name); no `get_` prefix for a plain getter (`slot.owner()`); `as_` is free and - borrows, `to_` is costly and allocates, `into_` consumes; constructors `new`, `with_`, `from_`; a builder ends in `.build()`. -8. **Shape by kind.** A module or file is a noun for what it holds (`expert_slot_cache.rs`); a function is a verb phrase - (`evict_cold_slots`); a type is a noun. A file name never repeats a type with a mechanical suffix (`_fn`, `impl_`, `_2`): the - architecture gate rejects new files named `impl_*.rs`, `*_fn.rs` and `*_.rs` (`mechanical_names` in `architecture.json`). -9. **Searchable.** A name is unique enough to grep; no magic numbers: a named constant carries the unit - (`const MTP_RING_CELLS: usize = 20480;`). -10. **If you cannot name it, split it.** A function or type without a short honest name does two things. A function with more than 5 - parameters is the same signal: give the arguments an owner (a method on it) or a DTO with a domain name, never `Args`, `Params`, - `Ctx`, `Opts`, `Input`. -11. **Documented.** Every new DTO and public function has a 1-2 line doc comment: what it is and why it exists. - -## Bad -> good (our code) - -| Where | Bad | Good | Rule | -| --- | --- | --- | --- | -| `cuda-driver/src/bringup_trace_enabled_fn.rs` | file `..._fn.rs` | `bringup_trace_enabled.rs` | 8 | -| `cuda-driver/src/q6_k_shape_fn.rs` | file `..._fn.rs` | `q6_k_shape.rs` | 8 | -| `qwen_forward/original_serve_stack/impl_originalservestack_4.rs` | file named after the type and a counter | `decode_steps.rs` (the one child that already has this name shows how) | 4, 8 | -| `.../impl_originalservestack_2_2.rs` | `impl_`, `_2_2` | what the impl block does: `request_accounting.rs` | 4, 8 | -| `engine-qwen35-cuda/.../qwen4exp_mtp/impl_mtpweights.rs:58` | `let mut data = Vec::new();` | `let mut expert_chunk_bytes = Vec::new();` | 2, 6 | -| `bringup_trace_enabled_fn.rs:108` | `fn set(&self, v: bool)` | `fn set(&self, is_enabled: bool)` | 2 | -| `native-cpu-expert/.../alloc_fn.rs` | struct `Target { x, w }` | `QuantTarget { values, weights }` (renamed in the params pass) | 4, 6 | -| `gptoss/src/weights.rs:43` | `pub bk: &[f32]` | `pub key_bias: &[f32]` | 5 | -| `leleka-memory/src/governor/governor_methods/governor_admit_and_relieve.rs` | file named after its function list | `governor/operations/admission.rs` (the per-request half of `Governor`; its siblings are `setup`, `status_report`, `archive_guard`) | 4, 8 | -| `cuda-driver/src/api/enabled.rs` and six more `enabled.rs` | says nothing about what is enabled | `driver_backed.rs`: the implementation that calls libcuda, built only with the `cuda-driver` feature | 1, 8 | -| `cuda-driver/src/original_expert_stager/original_expert_stager_methods.rs` | `_methods` | `original_expert_stager_lifecycle.rs` (start, drain, close), the worker side is `stager_workers.rs` | 4, 8 | -| `tokenizer/src/gguf_bpe/tokenizer_error_display_error.rs` | trait impls and a list of functions | `error_messages.rs` | 8 | -| any function with 6+ arguments | `fn run(a, b, c, d, e, f)` | split the work, or `fn run(&self, request: ExpertSlotRequest)` | 10 | -| any new DTO | `struct Args { .. }` | `struct LaunchGeometry { grid, block, shared_bytes }` | 3, 4, 10 | -| config | `timeout: u64` | `timeout_ms: u64` | 5 | -| magic number | `if cells > 20480` | `if cells > MTP_RING_CELLS` | 9 | -| getter | `fn get_len(&self)` | `fn len(&self)` | 7 | -| conversion | `fn to_str(&self) -> &str` | `fn as_str(&self) -> &str` (`to_` only when it allocates) | 7 | - -## For tooling - -* `scripts/dev/rustsplit` names the modules it creates after what they hold (`foo`, `thing_methods`, `display_for_thing`, - `thing_methods_from_`); a taken name gets a word (`_more`), never a number. -* After `scripts/dev/rustsplit`, run `python scripts/dev/explicit_imports.py `: it replaces the generated - `use super::*;` by the names the file uses and the generated header by a doc comment built from what the file defines; write the real - "what and why" sentence over it. The `glob-super-import` and `allow-unused-imports` ratchets count what is left. -* The architecture gate rejects new mechanical file names and counts the existing ones down to zero - (`architecture-baseline.json`, `mechanical_names`). -* The limits gate caps a function at 5 parameters, `self` included (`docs/architecture/limits-gate.md`). diff --git a/docs/architecture/output-event.md b/docs/architecture/output-event.md deleted file mode 100644 index 781c5fe1..00000000 --- a/docs/architecture/output-event.md +++ /dev/null @@ -1,207 +0,0 @@ -# OutputEvent: the canonical output of a model in the gateway (STRA-338 S23) - -One page: how model output reaches the Responses and Messages answers for each family, every place that branched on the family, the -canonical `OutputEvent` that replaced the family-specific text between the decoder and the answer, and what is left. -Every statement was read from the code at `cbc1a9587` (before) and at the tip of `claude/hexagonal-s23` (after). Detail pages: -`hexagonal.md` (layers and ports), `gateway-ports.md` (the five gateway ports), `tech-debt.md` (what a step moved but did not fix). - -## How output flows today - -The engine side hands the gateway `wire::Event::{Token(id), Done, Error}` (gRPC `EngineClient`, or the worker pool for gpt-oss). The -gateway turns ids into a response in four places that differ only in when they publish: - -| Consumer | Source file | Chosen when | Publishes | -|---|---|---|---| -| plain-text stream | `responses/stream/text.rs` | no tools, no reasoning, no structured output | text deltas as UTF-8 completes | -| tool-call stream | `responses/stream/tool_run.rs` | tools declared, no reasoning | text and each whole call as it completes | -| buffered stream | `responses/stream/buffered.rs` | reasoning on or structured output | reasoning deltas live; the rest after DONE | -| buffered answer | `responses/create/answer.rs` | `stream: false` | the whole response | - -Chat Completions (`chat/`) and Messages (`messages/`) do not read model output at all: they call the Responses handler and rewrite its -JSON or SSE events, so they never knew the family. - -| Question | Qwen3.5 | gpt-oss | -|---|---|---| -| Generation ends on | `<\|im_end\|>`, `<\|endoftext\|>` (`terminal_ids`) | `<\|return\|>`, `<\|call\|>`, `<\|endoftext\|>` | -| Ids to bytes | tokenizer, one id at a time, no state | `HarmonyDecoder`: parses Harmony messages, writes Qwen-style markup | -| Reasoning | the prompt opens `` (effort other than `none`); the model closes with `` | always: the analysis channel becomes the text before `` | -| Tool calls | `..` read by `tool_output` | commentary channel JSON becomes the same markup (`tool_markup`), read by the same parser | -| Usage | `Done` (prompt, generated, reused); reasoning tokens counted from the ids up to `` | the same | -| Finish | `Done.finish` Stop, Length, Cancel | the same | -| Errors | `Event::Error` or a closed source: `response.failed`, or a 502 / memory refusal when buffered | the same | - -Before S23 the markup text (``, ``) was the canonical form: every stream loop owned a piece of the reader -(`drain_utf8`, `ReasoningStream`, `tool_output::Incremental`, `decode_generation_noted`), and gpt-oss worked only because its decoder -wrote that markup. - -## Where the family was asked (before) - -| Site | What it did | After S23 | -|---|---|---| -| `gateway-domain/responses/effort.rs` `reasoning_enabled(request, family)` | `family == GptOss` means always reasoning; used by `text.rs` (which stream), `buffered.rs`, `answer.rs`, `reasoning.rs` | `reasoning_enabled(request, codec)` reads `TextCodec::always_reasons()` | -| `responses/create/admit.rs` `check_live_features` | gpt-oss: refuse samplers the worker `GEN` line lacks (a hard-coded field list in `effort.rs`) | `TextCodec::sampling_limit()` returns the set of samplers and the message; `sampler_limit::unsupported_sampler` reads it | -| `responses/create/admit.rs` `apply_sampling_defaults` | gpt-oss: drop the samplers it lacks (a second hard-coded list) | `sampler_limit::drop_unsupported_samplers` reads the same set | -| `responses/stream/*.rs`, `create/answer.rs` | `tokenizer.decoder()` bytes, then `` and `` scanning in each loop | `TextCodec::live_decoder` / `at_end_decoder`; the loops read `OutputEvent` | -| `responses/intake/intake_stages.rs` `render_prompt` | `match family`: ChatML template with control-token marks, or the Harmony renderer | unchanged (input side, see below) | -| `responses/intake.rs` `expand_images` | needs the Qwen tokenizer (`qwen()`) for pictures | unchanged (input side) | -| `responses/reasoning.rs` `reasoning_plan` | reasoning budget uses the Qwen tokenizer (`qwen()`) | unchanged (Qwen-only feature) | -| `serve/engine.rs` | the runtime backend counts with the Qwen tokenizer (`qwen()`) | unchanged (composition) | -| `serve/state.rs` | builds `GptOssCodec` when `gptoss_gguf` is set | unchanged (composition root) | -| `config/*`, `preflight.rs` | `gptoss_gguf` option checks | unchanged (configuration) | - -## The canonical type - -`leleka_gateway_domain::output` (pure, no IO, no tokio): - -```text -OutputEvent::ReasoningDelta(String) a piece of reasoning to show; not an item -OutputEvent::Reasoned { text, complete, tokens } the reasoning of the response, whether the model closed it, its tokens -OutputEvent::Text(String) answer text -OutputEvent::Call { name, arguments: Value } one whole call of a declared tool - -OutputError::Decode(msg) the ids could not be read, the reasoning never ended, or the generation already ended -> 502 detokenization_failed -OutputError::Parse(msg) a tool call in the text is not acceptable -> 502 tool_call_parse_failed -``` - -A family hands out one decoder per generation and per reading: `TextCodec::live_decoder(LivePlan) -> LiveDecoder` and -`TextCodec::at_end_decoder(AtEndPlan) -> AtEndDecoder`. Both sit on the same private `TokenBytes` enum (`Qwen`, `Harmony`), so a -token costs a `match`, not a virtual call, and what one reading offers cannot be asked of the other. `live_decoder` has the default -`None`: a model that always reasons (gpt-oss) is read at its end, and the two live streams fail the response if they are ever given -`None`: - -* `LiveDecoder` (`LivePlan { tools, recovery, keep_raw }`): text and whole calls as the bytes arrive (UTF-8 completion, then - `tool_output::Incremental`). Every event of `push` and `finish` is final; `finish` also takes the bytes the family held back. - Accessors: `notes()` and `raw_text()`. Used by the plain-text stream and the tool-call stream. -* `AtEndDecoder` (`AtEndPlan { reasoning, preview, tools, recovery, keep_raw }`): the answer is read once the generation is over. - `push` returns only `ReasoningDelta` previews (none when `preview` is off, which the buffered answer sets: nobody watches it); - `finish(Finish)` returns the events that make up the response (`Reasoned`, then `Text` and `Call` as `tool_output::parse_with` - reads them, or one `Text` when the request declared no tools; an answer always has at least one text event). Accessors: - `notes()`, `accepted_call_in_reasoning()`, `split_text()`. Used by the buffered stream and the buffered answer. The two readings - stay apart because the incremental and the batch tool-call readers are not the same function (a `` left out is - accepted only at the end). - -A generation ends once: `push` or `finish` after `finish` is a decode error (in the buffered stream it is a `response.failed`, not a -panic). `output_items(events, response_id)` turns the events into `OutputItem`s and the reasoning token count. The cut of a finished -generation into reasoning and answer is text-level code in `output/cut.rs` (`cut_text`, one `CutGeneration`, also exposed as -`cut_reasoning_for_corpus` for the tool corpus tests; the tokens are counted from its `extent`); the `` search and hold-back are in `think_marker.rs`, used by the reasoning previewer, the cut and the -reasoning budget. - -Adding a family touches, for the output side: a `TokenBytes` arm and the constructors `LiveDecoder::` and -`AtEndDecoder::`, all inside `gateway-domain` (the enum is private to it, so those constructors are the only way in); a -`TextCodec` implementation in the crate that holds the family's tokenizer (`harmony_family.rs` in `leleka-control-plane` for gpt-oss) with -`at_end_decoder`, `live_decoder` only if the family can be read live, `always_reasons`, `sampling_limit`, `terminal_ids`, `encode` and -`family()` (a `Family` variant); and the choice of the codec in `serve/state.rs`. The stream loops and the answer builder do not -change. The input side (`render_prompt`, pictures, the reasoning budget) still has its own `Family` and `qwen()` branches. - -## Migrated sites - -| Step | Site | What it reads | -|---|---|---| -| golden | `control-plane/tests/output_golden/`, `tests/fixtures/golden/output_{cases,events}.json` | the proof harness (below) | -| 1 | `stream/text.rs` | live, no tools: `Text` | -| 2 | `stream/tool_run.rs`, `stream/tools.rs` | live, tools: `Text`, `Call` | -| 3 | `create/answer.rs`, `tool_recovery.rs` (`at_end_plan`, `finish_generation`) | at end: all events | -| 4 | `stream/buffered.rs` | at end: `ReasoningDelta` live, the rest at DONE | -| 5 | `reasoning_enabled`, `admit.rs` | `TextCodec::always_reasons`, `sampling_limit` | -| 6 | the replaced readers | `decode_generation_noted`, `decoded_items`, `ReasoningStream`, `drain_utf8` copies removed | -| 7 | the first review | live and at-end decoder types, `TokenDecoder` and the legacy item builder removed, the tool corpus on the gateway's cut, the sampler set | -| 8 | the second review | names, one `CutGeneration`, `sampler_limit.rs`, no gpt-oss live reading, 29 more golden cases and the tests of the store, the worker's sampling and the disconnect at `DONE` | - -## Identity proof - -`control-plane/tests/output_golden` (a test binary of its own, because the cases switch the process-wide tool-call recovery) drives -the real `create` handler with 159 scripted token sequences, each as a stream and as a buffered answer: 318 captures of status, -content type and body bytes, SSE framing included. **The expected captures were recorded on `08afbf216`** (`cbc1a9587`, the code before -S23, plus the first harness) in a temporary worktree, and are checked against the new code; none was recorded on it and none differs. `regenerate_output_golden` -refuses to run unless `OUTPUT_GOLDEN_RECORD` names the pre-S23 commit and the tree has no `output` module, and -`output_events.recorded_on` names the commit the captures were recorded on (a test pins it). - -Volatile text is normalised so that nothing identity-relevant is lost: every distinct id becomes `_ID` by order of first -appearance and **keeps its numeric suffix** (`call_ID3_1`), so the index inside `call__` is pinned, and -`two_calls_of_one_response_have_different_call_ids` checks the call ids Codex pairs tool outputs by; timestamps become 0. - -The scripts cover: plain text; a terminal token followed by more tokens (also with reasoning, tools and structured output on); tools -with text, one call, two calls, unknown tool, schema violation, an unfinished call at the length limit, a missing closer, a custom -tool; reasoning that closes, that never closes (length and natural stop), that ends on whole calls, that closes and is followed by a -call cut at the length limit; the request's `max_output_tokens` reached in every reading; a second `` in the answer and inside a tool argument; structured output valid and invalid, also with reasoning on and for gpt-oss, also with tools; namespaced tools; `DONE` before the first -token and an error after `DONE`; a worker that reports fewer generated tokens than the reasoning took (the clamp of the reasoning -tokens); the -tool-call recovery on and off with two drifted forms in the live tool stream, the buffered stream and the buffered answer; non-ASCII -call arguments, also as multi-byte tokens; **a vocabulary with multi-byte tokens** (a euro sign, an emoji, a token holding the whole -`` and a token that ends in the middle of it, with `reasoning_tokens` asserted: 2 and 3) and raw byte tokens; characters cut -at the length limit and at stop in the live text, the live tool stream, the reasoning preview, the structured stream and gpt-oss -channels; a lone continuation byte in reasoning and in the answer; an id outside the vocabulary in the middle of a script; a source -that closes without `DONE`; `Finish::Cancel`; worker failures (also a memory refusal); and for gpt-oss the analysis, commentary and -final channels in their combinations, calls with and without declared tools, invalid arguments and the rest of the earlier list. -Scripts are synthetic. - -Timing, which captures cannot show: with a worker that waits for a gate before `DONE`, the first `response.reasoning_text.delta` -(both families), the first text delta and the first whole call reach the client before `DONE` is sent; a client that leaves closes the -source in five stream modes, and also when it leaves at `DONE`; a stored response equals the one the client was sent (streamed and -not); a gpt-oss request that sets a sampler the worker lacks gets a 400 that names the first one; the server defaults for those -samplers do not reach the gpt-oss worker (top_k 20 and penalty_last_n 64 among them), neutral values are accepted, and Qwen keeps all -five samplers. All fifteen tests of the binary pass on `08afbf216` and on the new code. - -Results on the tip: `cargo test --no-fail-fast --all-targets` for `leleka-control-plane`, `leleka-gateway-domain`, `leleka-gateway-text`, -`leleka-harmony`, `leleka-tokenizer` and `leleka-runtime-client` on Linux (WSL), before (`cbc1a9587`) and after, compared with -`scripts/dev/test-outcomes.py compare`: 0 missing, 0 outcome changes, 38 new ids; 515 ok / 1 ignored before, 552 ok / 2 ignored -after. The ids of the first golden harness moved to the new binary; the tests that read the replaced code (`reasoning_marker_and_unicode_split_at_every_byte`, -the unclosed-reasoning test, the utf8 test, the Harmony decoder tests) keep their ids and now read through the new decoders. -`cargo check --all-targets` and `cargo clippy --no-deps --all-targets -- -D warnings` for `leleka-control-plane` and `leleka-gateway-domain`: -0 warnings. `check-limits.py --base origin/claude/hexagonal-integ`, `check-architecture.py` and `check-ci-coverage.py`: green; -`architecture-baseline.json` tightened (`dyn-trait` gateway-domain 5 to 2, leleka-control-plane 14 to 11). - -Not covered end to end: `STRATA_DEBUG_FAILED_OUTPUT` (read once per process through a `OnceLock`, so a test binary cannot switch it -beside other tests); the `keep_raw`, `raw_text()` and `split_text()` paths have unit tests in `leleka-gateway-domain`. - -## Behaviour that changed or moved - -No response byte changes (the golden). What changes besides: - -* **Decoding time.** Per-token decoding as the ids arrive is new only for the structured-output stream on Qwen (it kept the ids and - decoded them at DONE); the reasoning stream already decoded every token as it arrived, and the buffered (non-stream) answer still - decodes all ids at the end, inside `spawn_blocking`. A decode error therefore surfaces at the offending token in the structured - stream and not at DONE; the failure code and message and every response byte are the same (the golden has an id outside the - vocabulary in `q-structured-oov-id` and the other modes). -* **The `post_decode` stage** (`buffered.rs`, `docs/cp-latency.md`, `scripts/cp/summarize.py`) now times only `finish` (the cut and the - batch parse), because the bytes are decoded as they arrive. It is not comparable with numbers measured before S23. -* **Logs.** A refused tool call in the buffered stream now also writes the `STRATA_DEBUG_FAILED_OUTPUT` debug copy to stderr when that - variable is set (the non-stream answer already did). In the non-stream answer the debug copy is written before the - generation-failure line instead of after it. -* **Flags are read at stream start.** The buffered stream builds its plan (tool-call recovery, debug copy) when the stream starts and - not at DONE; the tool-call stream already read the recovery when it started. A recovery switch flipped during a request therefore - no longer reaches that request's buffered stream (only the tests flip it). -* **The worker sees an out-of-vocabulary id as a client that left.** In the structured-output stream on Qwen the new code fails at - the offending token and drops the source then; `backend_worker/generation_run.rs` sees the closed result (`Wake::ClientGone`) and - cancels the engine's generation at that point, and `conclude.rs` counts the request as `disconnected` (`metrics.rs`: outcome - `disconnect`, `cancelled` plus one) where the code before S23 let the generation run to `DONE` and counted a finished generation with - its stop or length. So the worker metrics of such a request differ (earlier cancel, `disconnect` instead of the finish reason) while - the client sees the same `response.failed`. The reasoning stream and the live streams already behaved so for a decode or parse - error. -* **A generation ends once.** `finish` twice, or `push` after it, is a decode error. - -Behaviours kept on purpose (they are in the golden): - -* gpt-oss: a call when the request declares no tools is not an error: its markup stays in the answer text. -* gpt-oss: invalid JSON, a non-object, or an argument name that cannot be passed on is a decode error (`detokenization_failed`) at - the end of the call, while an unknown tool or a schema violation is a parse error (`tool_call_parse_failed`) after the whole - generation was read. A decode error wins over an earlier parse problem because decoding finishes first. -* Reasoning that never closes: at the length limit it is an incomplete reasoning item; on a natural stop it is an error, unless the - text ends on whole calls of declared tools, which then become the answer (the live reasoning deltas have already shown the call - text). -* The index in `call__` counts answer items in the buffered readings and all items in the tool-call stream, as before. -* Reasoning tokens are the tokens up to the one that completed `` (for gpt-oss, the one that closed the analysis). -* gpt-oss: a literal `` inside the analysis text ends the reasoning there, because the Harmony decoder writes markup that the - shared cut reads (a latent defect, pinned by `g-two-markers-analysis`). - -## Not done, and why - -* **The gpt-oss adapter still writes the Qwen-style markup inside the decoder.** `HarmonyDecoder` (moved unchanged from - `control-plane/src/harmony_family.rs` to `gateway-domain/src/output/harmony.rs`; `push` and `finish` are its own methods now) turns - Harmony messages into `` and `` text, and the shared cut and parse read that. Reading the channels directly - would change two corners that the golden pins: the `` inside the analysis text above, and the call-without-tools quirk. Both - are behaviour changes, so they are left for a step with an owner decision. -* **Prompt rendering is still chosen by `Family`** (`intake/intake_stages.rs`), and the picture expansion, the reasoning budget and the - runtime backend still ask for the Qwen tokenizer (`qwen()`). They are the input side of the codec; they need a prompt-rendering - port, not an output one. -* **`GptOssCodec` lives in `leleka-control-plane`** because it loads the BPE from a GGUF file; the decoder it hands out is in the domain. diff --git a/docs/architecture/size-fn.md b/docs/architecture/size-fn.md deleted file mode 100644 index 3d9438c0..00000000 --- a/docs/architecture/size-fn.md +++ /dev/null @@ -1,188 +0,0 @@ -# Function size pass (STRA-338, batch size-fn) - -Every `.rs` file of the crates below was already within 400 lines (batches `size-split-*`). This batch brings the -**functions** within the limits of `limits.json` (30 lines, complexity 10, nesting 4, 120 columns), longest first, with -the behaviour unchanged: one helper per rule, stage or item kind, a small context struct for the values a long function -threads through, builder and assert helpers for tests, big literals as constants. Entries of `limits-allowlist.json` of the -fixed functions are gone. - -Crates: `leleka-control-plane`, `leleka-engine-host`, `leleka-deploy`, `leleka-gateway-text`, `leleka-gateway-domain`, -`leleka-worker-protocol`, `leleka-runtime-client`, `leleka-offline-tools`, `leleka-gptoss`, `leleka-cpu-sys`, -`leleka-cpu-kernels`, `leleka-cpu-worker`, `leleka-igpu*`, `leleka-gptoss-igpu`, `leleka-gptoss-npu`, `leleka-npu-*`, -`leleka-gpu-npu-worker`, `leleka-gguf`, `leleka-kar-codec`, `leleka-harmony`, `leleka-tokenizer`, `leleka-shm`, -`leleka-openvino`, `leleka-serving-policy`, `leleka-sampler-ref`, `leleka-quant-core`, `leleka-experimental-ref`, -`leleka-native-parity-bench`. - -## Numbers - -* Allowlist entries: 429 (all "moved verbatim ... not yet decomposed") -> 133 (115 older entries that remain, 18 new ones for - the functions this pass touched and could not finish; the entries of the unfixed deploy tests are the largest group). -* Functions over a limit in these crates, from the first line of the table: production fn>30 486 -> 17, complexity 340 -> 11, - nesting 46 -> 0; test code fn>30 507 -> 122, complexity 35 -> 3, nesting 47 -> 4. Total functions listed by the census - tool 1037 -> 144. -* `limits-baseline.json` and `architecture-baseline.json` were regenerated with `--update-baseline` only (nothing raised). - -Per crate (before -> after; production columns, then test columns; "wide" counts lines over 120 columns): - -| Crate | prod fn>30 | cx>10 | nest>4 | wide | test fn>30 | cx>10 | nest>4 | wide | -|---|---|---|---|---|---|---|---|---| -| `leleka-cpu-kernels` | 1 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 8 -> 6 | 3 -> 1 | 5 -> 3 | 1 -> 1 | -| `leleka-cpu-sys` | 11 -> 0 | 3 -> 0 | 2 -> 0 | 3 -> 3 | 16 -> 16 | 0 -> 0 | 0 -> 0 | 2 -> 2 | -| `leleka-cpu-worker` | 7 -> 0 | 5 -> 0 | 0 -> 0 | 6 -> 5 | 6 -> 0 | 1 -> 0 | 2 -> 0 | 11 -> 5 | -| `leleka-deploy` | 101 -> 0 | 48 -> 0 | 7 -> 0 | 305 -> 247 | 89 -> 64 | 0 -> 0 | 0 -> 0 | 63 -> 60 | -| `leleka-experimental-ref` | 15 -> 0 | 11 -> 0 | 1 -> 0 | 19 -> 4 | 14 -> 9 | 2 -> 1 | 2 -> 1 | 37 -> 37 | -| `leleka-gateway-domain` | 15 -> 0 | 12 -> 0 | 5 -> 0 | 45 -> 16 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 1 | -| `leleka-gateway-text` | 14 -> 0 | 16 -> 0 | 1 -> 0 | 64 -> 61 | 12 -> 0 | 0 -> 0 | 2 -> 0 | 20 -> 6 | -| `leleka-gguf` | 6 -> 0 | 6 -> 0 | 0 -> 0 | 3 -> 1 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 1 | -| `leleka-gptoss` | 12 -> 0 | 6 -> 0 | 1 -> 0 | 1 -> 1 | 14 -> 5 | 4 -> 0 | 0 -> 0 | 8 -> 7 | -| `leleka-gptoss-igpu` | 1 -> 0 | 1 -> 0 | 0 -> 0 | 2 -> 2 | 5 -> 1 | 0 -> 0 | 0 -> 0 | 3 -> 3 | -| `leleka-gptoss-npu` | 5 -> 0 | 3 -> 0 | 2 -> 0 | 3 -> 2 | 4 -> 1 | 0 -> 0 | 0 -> 0 | 6 -> 5 | -| `leleka-gpu-npu-worker` | 3 -> 0 | 1 -> 0 | 0 -> 0 | 3 -> 2 | 2 -> 0 | 1 -> 0 | 0 -> 0 | 4 -> 1 | -| `leleka-harmony` | 4 -> 0 | 6 -> 0 | 2 -> 0 | 1 -> 0 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 5 -> 0 | -| `leleka-igpu` | 10 -> 1 | 1 -> 0 | 0 -> 0 | 5 -> 5 | 12 -> 12 | 1 -> 1 | 0 -> 0 | 0 -> 0 | -| `leleka-igpu-worker` | 2 -> 0 | 1 -> 0 | 0 -> 0 | 1 -> 1 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-kar-codec` | 4 -> 0 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-native-parity-bench` | 0 -> 0 | 0 -> 0 | 0 -> 0 | 9 -> 9 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-npu-service` | 6 -> 0 | 5 -> 0 | 0 -> 0 | 14 -> 3 | 3 -> 0 | 0 -> 0 | 1 -> 0 | 1 -> 1 | -| `leleka-npu-worker` | 2 -> 0 | 1 -> 0 | 0 -> 0 | 2 -> 2 | 2 -> 2 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-offline-tools` | 8 -> 0 | 5 -> 0 | 0 -> 0 | 1 -> 0 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-openvino` | 2 -> 1 | 0 -> 0 | 0 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-quant-core` | 1 -> 0 | 0 -> 0 | 2 -> 0 | 0 -> 0 | 11 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-runtime-client` | 9 -> 0 | 4 -> 0 | 0 -> 0 | 4 -> 3 | 6 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-sampler-ref` | 9 -> 0 | 4 -> 0 | 0 -> 0 | 0 -> 0 | 14 -> 0 | 1 -> 0 | 2 -> 0 | 0 -> 0 | -| `leleka-serving-policy` | 13 -> 0 | 10 -> 0 | 0 -> 0 | 6 -> 5 | 9 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 1 | -| `leleka-shm` | 1 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-tokenizer` | 13 -> 0 | 7 -> 0 | 0 -> 0 | 21 -> 14 | 10 -> 0 | 1 -> 0 | 0 -> 0 | 10 -> 2 | -| `leleka-worker-protocol` | 3 -> 0 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-control-plane` | 146 -> 0 | 122 -> 0 | 17 -> 0 | 185 -> 50 | 194 -> 0 | 17 -> 0 | 30 -> 0 | 131 -> 17 | -| `leleka-engine-host` | 62 -> 15 | 56 -> 11 | 6 -> 0 | 52 -> 13 | 63 -> 6 | 3 -> 0 | 3 -> 0 | 27 -> 0 | -| **total** | 486 -> 17 | 340 -> 11 | 46 -> 0 | 756 -> 449 | 507 -> 122 | 35 -> 3 | 47 -> 4 | 332 -> 150 | - - -## Pass 2 (drive the census of these crates to zero) - -Same method, then the owner's single-responsibility rule: one function does one action, a helper is named verb + object, a name -that needs "and" or "then" is split again, the decision (which branch) is separate from the execution (how), a `check_*` is a -predicate and does not mutate or compute, a test is setup, action and assertion as named steps. - -* `leleka-engine-host`: the 15 production functions and the 6 test functions left by pass 1 (`ToolResponse::complete` and - `preflight` with the new module `runtime_tool_response/preflight.rs`, `hardware::inventory`, node `respond` with the new - module `node/respond.rs`, `node_connection::session`, `node_proxy::respond`, `planner::plan`, `Pool::new`, `cli::node`, `main`, - `managed_worker` start/run, ...). -* Test functions and examples over 30 lines in `leleka-deploy` (64), `cpu-sys`, `cpu-kernels`, `igpu`, `experimental-ref`, - `gptoss`, `gptoss-igpu`, `gptoss-npu`, `npu-worker`, `npu-service`: builder, step and assert helpers; test names, ids and - assertions unchanged. `cpu-sys/tests/attention.rs` keeps its test ids and moved its non-test helpers to - `tests/attention/kernel_checks.rs`; `leleka-deploy/tests/e2e_windows.rs` moved its checks to `tests/e2e_windows/checks.rs`. -* Lines over 120 columns: 599 -> 38 in these crates. Comments are re-filled by paragraph; a long message string is broken at a - space with a trailing backslash (Rust strips the leading whitespace of the next line, so the evaluated text is byte-identical) - or split with `concat!`; JSON macros are re-wrapped. A lexer comparison of the evaluated string literals of every changed - file against the previous commit found identical sequences in 234 of 295 files and identical multisets in 34; the other 27 - are files whose code changed (a helper took the format arguments, a literal moved to another function) and were read. The - probe script of `desktop-core/src/remote.rs` is a raw string; its `nvidia-smi` line is continued with a shell backslash - (the same command, not the same bytes). -* Single responsibility (review of pass 1): about 50 two-action test helpers split (for example `assert_response_status` and - `assert_response_headers`). `check_*` functions that mutated, computed or did I/O were made predicates or renamed for what - they do. Pure predicates (take `&self` or plain values, no I/O, return `Result<(), _>`): `trace_items::check_call`, - `check_snapshot_is_attached`, `check_context_budget`, `check_pool_bounds`, `check_workers_fit_their_group`, the per-field - `CreateRequest::check_*` of `gateway-domain/src/responses/validate.rs`. Renamed because they act: `cancel_stalled_generation` - (was `check_stall`), `probe_host` (`check_host`), `fail_if_api_exited` and `fail_if_engine_exited` (they reap a child), - `read_assistant_text`, `detach_if_unattached` (an RPC, then it detaches), `abort_cold_preparation` (journal write); - `record_call_id` was split out of `check_call`. Decision apart from execution in `runtime_rpc` (`judge_load`, - `admit_generation`), the backend worker (`count_failed_start`, `served_after_refusal`, `judge_request`, - `report_stopping`, `report_engine_lost`), `harmony`, `gateway-text` and `gptoss` (`softmax_scores_in_place` says it rewrites - the scores; `rotate_queries` is pure and `store_rotated_kv` writes the cache; arithmetic and attributes unchanged). - The three `Supervisor` types are now `AttachLoop` (`backend_worker/attach.rs`), `SessionSupervisor` - (`worker/run_supervised.rs`) and `ServiceSupervisor` (`leleka-deploy`). -* Regression of pass 1 fixed: `spawn_engine` turned a spawn error into `StartupFailed` with `map_err`, which cannot await, so - the status stayed `Starting`; the original set `Failed` first. Restored, with the test - `a_failed_engine_spawn_marks_the_worker_failed`. - -Per crate (pass 1 end -> pass 2; production fn>30, cx>10, wide, then test fn>30, cx>10, nesting>4, wide): - -| Crate | prod fn>30 | cx>10 | wide | test fn>30 | cx>10 | nest>4 | wide | -|---|---|---|---|---|---|---|---| -| `leleka-cpu-kernels` | 0 -> 0 | 0 -> 0 | 0 -> 0 | 6 -> 0 | 1 -> 0 | 3 -> 0 | 1 -> 0 | -| `leleka-cpu-sys` | 0 -> 0 | 0 -> 0 | 3 -> 0 | 16 -> 0 | 0 -> 0 | 0 -> 0 | 2 -> 0 | -| `leleka-cpu-worker` | 0 -> 0 | 0 -> 0 | 5 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 5 -> 0 | -| `leleka-deploy` | 0 -> 0 | 0 -> 0 | 247 -> 33 | 64 -> 0 | 0 -> 0 | 0 -> 0 | 60 -> 0 | -| `leleka-experimental-ref` | 0 -> 0 | 0 -> 0 | 4 -> 0 | 9 -> 0 | 1 -> 0 | 1 -> 0 | 37 -> 0 | -| `leleka-gateway-domain` | 0 -> 0 | 0 -> 0 | 16 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 0 | -| `leleka-gateway-text` | 0 -> 0 | 0 -> 0 | 61 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 6 -> 0 | -| `leleka-gguf` | 0 -> 0 | 0 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 0 | -| `leleka-gptoss` | 0 -> 0 | 0 -> 0 | 1 -> 0 | 5 -> 0 | 0 -> 0 | 0 -> 0 | 7 -> 0 | -| `leleka-gptoss-igpu` | 0 -> 0 | 0 -> 0 | 2 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | 3 -> 0 | -| `leleka-gptoss-npu` | 0 -> 0 | 0 -> 0 | 2 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | 5 -> 0 | -| `leleka-gpu-npu-worker` | 0 -> 0 | 0 -> 0 | 2 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 0 | -| `leleka-igpu` | 1 -> 1 | 0 -> 0 | 5 -> 5 | 12 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-igpu-worker` | 0 -> 0 | 0 -> 0 | 1 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-native-parity-bench` | 0 -> 0 | 0 -> 0 | 9 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-npu-service` | 0 -> 0 | 0 -> 0 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 0 | -| `leleka-npu-worker` | 0 -> 0 | 0 -> 0 | 2 -> 0 | 2 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-openvino` | 1 -> 1 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-runtime-client` | 0 -> 0 | 0 -> 0 | 3 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| `leleka-serving-policy` | 0 -> 0 | 0 -> 0 | 5 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 1 -> 0 | -| `leleka-tokenizer` | 0 -> 0 | 0 -> 0 | 14 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 2 -> 0 | -| `leleka-control-plane` | 0 -> 0 | 0 -> 0 | 50 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | 17 -> 0 | -| `leleka-engine-host` | 15 -> 0 | 11 -> 0 | 13 -> 0 | 6 -> 0 | 0 -> 0 | 0 -> 0 | 0 -> 0 | -| **total** | 17 -> 2 | 11 -> 0 | 449 -> 38 | 122 -> 0 | 3 -> 0 | 4 -> 0 | 150 -> 0 | - -Allowlist entries: 133 -> 1 (`OpenVino::load`); the entries of functions that only had wide lines went when the lines were -wrapped. `limits-baseline.json` and `architecture-baseline.json` were regenerated with `--update-baseline` only (nothing raised). - -## What stays over a limit, and why - -* `igpu/src/shaders/gemm.rs :: gemm` (175 lines, five lines over 120 columns): WGSL shader text returned as one string; data, not - logic. It has no allowlist entry because no diff touches it; the census baseline holds it. -* `openvino/src/library.rs :: OpenVino::load` (84): FFI symbol table of about 25 `dlsym` lookups; the table is the point - (allowlist entry, owner STRA-338). -* `leleka-deploy/src/cli.rs` `USAGE` (33 lines over 120 columns): the `--help` text is user-visible and - `scripts/release/package-5090.sh` parses it by line. -* Open (single responsibility, not done): `check_*` that still do I/O or take `&mut self` and are not renamed: - `check_free_vram` (reads the GPU), `check_unit_not_failed`, `check_load_not_failed` and `check_load_progress` (call the CLI), - `check_discovery`, `RuntimeGeneration::check_frame` (advances the sequence state). Names that are composers or return a decision - together with an effect: `become_ready` (flag, log line, status, answers to waiting loads), `store_rotated_kv` (rotates K and writes the - cache), `pin_engine_gpu` (rechecks the GPU, pins it and records `Failed` on refusal), `measure_checked_call` - (validates one call item and returns its size), `encode_bounded_frame` (returns the frame and whether it was replaced). - -## Kernels - -The owner allowed the hot numeric kernels to be split. Rule used: helpers keep the arithmetic order (no reassociation, no -change of FMA or accumulation order), keep the `unsafe` blocks and `SAFETY` comments with their code, and are -`#[inline(always)]` where the original was one body in a hot loop (`#[inline]` with the same `#[target_feature]` for AVX2 -and AVX-VNNI helpers, because `inline(always)` cannot be combined with `target_feature`). Tensor identity was proven per function -with a throwaway test that compiled the original files from git next to the new ones and compared output bits on fixed -xorshift inputs: - -| Crate | Functions | Proof | -| --- | --- | --- | -| `leleka-cpu-sys` simd x86 | `attn_weighted_sum_avx2`, `attn_weighted_sum_f16_avx2`, `dot_i8i8_avxvnni`, `dot_i4i8_avxvnni`, `dot_mxfp4_q8r4_avxvnni`, `dot_mxfp4_q8r4_avx2`, `quantize_q8_0_avx2` | 792 cases bit-identical in debug and release (attention heads 1-4, hd 1-192, n 1-40; dots n 0-513; mxfp4 0-33 blocks; quantize 0-33 blocks incl. zero and -0.0). The host CPU has no AVX-VNNI: the three VNNI variants were compared with `vpdpbusd` replaced by a scalar emulation (proves the restructuring, not the instruction), and the real VNNI path was only compiled | -| `leleka-cpu-kernels` | `Dispatch::with_isa` (three tables moved unchanged) | existing parity tests | -| `leleka-quant-core` | `iq3_s::decode_block`, `iq3_xxs::decode_block` | 40000 random blocks per format bit-identical (iq3_s also 845 identical error texts) | -| `leleka-gptoss` | `attend_group_with_sink`, `kar_roundtrip` | 6 shapes x ISA levels (12 cases) and 46 round-trip cases, outputs and error paths identical | - -**No performance claim is made.** The codegen effect of the splits is not A/B-measured; the kernels on the serving path need -a paired A/B (same workload, quality result) before anything is said about speed. - -## Verification - -* Test ids and outcomes: `cargo test --no-fail-fast --all-targets` on Linux (WSL) for the 28 crates and for `leleka-deploy - --features test-fakes`, before (`0c594d351`) and after, compared with `scripts/dev/test-outcomes.py compare` - : 0 missing, 0 new, 0 outcome changes (`leleka-control-plane` and the 27 other crates: 1067 ok before, 1078 ok after, the 11 differences - are tests that the base log could not resolve or that failed once on the base; `leleka-deploy`: 213 ok / 5 failed / 2 ignored - before and after). The five `leleka-deploy` e2e failures - (`dry_run_prints_the_plan_and_changes_nothing` and four in `reconfigure_flow`) fail on the base too: they report the free - VRAM of the host GPU. The `leleka-control-plane` lib suite had one flaky failure on the base run - (`responses::tests::history::durable_history_roundtrip_delete_eviction_and_faults`). -* `cargo clippy --no-deps --all-targets -- -D warnings` clean for the crates above; `result_large_err` is allowed in the - modules of the `/v1/responses` handler and the gateway relay of `leleka-engine-host` because the error value is the finished - HTTP response. `cargo fmt --check` for `leleka-control-plane`, `leleka-engine-host`, `leleka-runtime-client` and `leleka-deploy` - differs only in files this batch did not change. -* Gates: `scripts/check-limits.py --base origin/claude/hexagonal-integ` 0 errors, 0 stale; `scripts/check-architecture.py` - 0 errors (the `dyn-trait` ratchet of `leleka-engine-host` is held by spelling `dyn leleka_backend_api::Backend` in the - binaries); `scripts/check-ci-coverage.py` green. - -## Method note - -The work was split by directory over parallel branches (`claude/szfn-*`), each in its own worktree with its own target -directory, then merged here. Functions were fixed longest first; helpers are placed in new sibling modules where a file -would pass 400 lines. New modules are listed in the commits. diff --git a/docs/architecture/size-split-control-plane-desktop-core.md b/docs/architecture/size-split-control-plane-desktop-core.md deleted file mode 100644 index 6acdecc7..00000000 --- a/docs/architecture/size-split-control-plane-desktop-core.md +++ /dev/null @@ -1,65 +0,0 @@ -# Size split of control-plane and desktop-core (STRA-338, batch GW-1) - -The owner order: no `.rs` file over 400 lines, no function over the limits of `docs/architecture/limits-gate.md`. This -page records how the 19 oversize files of `leleka-control-plane` (`control-plane/`) and `leleka-engine-host` -(`desktop-core/`) were split, and how the test ids moved. Every module is named after what it holds, never `_2`/`_3`. - -## Test ids - -A test id is `::`. A split changes the module path and nothing else: - -* 543 tests before and after in the two crates (`cargo test -p leleka-control-plane -p leleka-engine-host --all-targets`, - Linux): 0 missing, 0 new, 0 outcome changes; 241 ids differ only in the module path (the topic module is inserted). -* Cargo test targets keep their names: `tests/.rs` became `tests//main.rs`, which Cargo discovers under the - same target name. -* Two families of tests start themselves as a child process with `--exact `. `credential_child("")` in - `runtime_gateway_sdet` and `native_tools_retry_sdet` now names `"::"`; the `fixture` test of - `managed_worker` stays in the target root (`main.rs`) so its id (`fixture`) is unchanged. -* A shared module holds what several topics use: `fixtures` for unit tests, `harness` for integration targets (the - `tests/common/` module of control-plane stays where it was and is loaded with `#[path = "../common/mod.rs"]`). - -## Unit tests (`/tests.rs` becomes `/tests/`) - -| Was | Now (`tests/` modules) | -| --- | --- | -| `control-plane/src/responses/tests.rs` | `fixtures`, `tool_policy`, `custom_tools`, `tool_replay`, `input_items`, `history`, `stateless_replay`, `validation`, `text_preview`, `sampling`, `live_endpoint`, `reasoning`, `reasoning_live`, `structured_output`, `stream_termination`, `live_tools`, `control_tokens` | -| `control-plane/src/ggml_bridge/tests.rs` | `iq3`, `iq4`, `q8_iq4xs`, `k_quants`, `q6_q2`, `iq2s_iq3xxs` | -| `control-plane/src/gguf_f32_stream/tests.rs` | `iq3_iq4`, `q8_iq4xs`, `k_quants`, `q6_q2`, `iq2s_iq3xxs` | -| `control-plane/src/prepare_preview/tests.rs` | `fixtures`, `convert`, `source_kinds`, `sharded`, `overlay`, `ple_partition` | -| `desktop-core/src/runtime_rpc/tests.rs` | `fixtures`, `load_dedup`, `lifecycle`, `auth_and_capacity` | - -## Integration targets (`tests/.rs` becomes `tests//main.rs` plus topic modules) - -| Target | Modules next to `main.rs` | -| --- | --- | -| `control-plane/tests/backend_worker_http` | `harness`, `text_answers`, `engine_failures`, `tool_calls`, `text_formats`, `runtime_status`, `prompt_limits`, `codex`, `monitor` | -| `control-plane/tests/vision_http` | `harness`, `delivery`, `encoder`, `rendering` | -| `control-plane/tests/memory_gate_http` | `harness`, `gate`, `soak` | -| `control-plane/tests/tool_corpus` | `harness`, `corpus`, `quoted_values` | -| `control-plane/tests/mcp_hub` | `harness`, `stdio_servers`, `http_and_config` | -| `desktop-core/tests/api_over_runtime` | `harness`, `streaming`, `engine_loss`, `scale_and_prefix` | -| `desktop-core/tests/runtime_gateway_sdet` | `harness`, `text_flow`, `dispatch_faults`, `lifecycle` | -| `desktop-core/tests/native_tools_sdet` | `harness`, `declarations`, `calls_and_history`, `publisher` | -| `desktop-core/tests/native_tools_retry_sdet` | `harness`, `retry`, `usage_accounting` | -| `desktop-core/tests/managed_worker` | `harness`, `lifecycle`, `stop_and_cli` | -| `desktop-core/tests/gateway` | `harness`, `routing`, `failures` | - -## Sources - -* `desktop-core/src/bin/leleka-inference.rs` became `src/bin/leleka-inference/main.rs` (flags and `main`) with one module - per operator option group: `arguments`, `execution`, `sources`, `streamed_spill`, `retained_scratch`, - `resident_owners`, `adaptive_slots`, `original_serve`, `evaluation_output`. Each module starts with `use super::*;`; - the root re-exports the module items it calls. -* `control-plane/examples/cp_replay.rs` became `examples/cp_replay/main.rs` with `instant_backend`, `stack`, `client`, - `live` and `verify`; `desktop-core/examples/cp_replay_grpc.rs` loads it from the new path. -* `desktop-core/src/runtime_rpc/impl_proto_runtime_server_runtime.rs` (one 463-line trait impl) became `service.rs`, whose - `Runtime` impl delegates each RPC to `handle_` in `session_rpc`, `model_rpc` and `generate_rpc` (bodies unchanged). -* Mechanical child modules renamed after what they hold: `kar_overlay/base_provenance`, `messages/count_tokens`, - `model/manifest_fetch`, `mtp_fetch/fetcher`, `request_monitor/{record,capture}`, `gateway/in_flight`, - `runtime_tools/{tool_policy,tool_plan}`, `runtime_rpc/server`. Paths re-exported by the parents are unchanged. - -## Why the limits allowlist grew - -The diff gate treats a function that moved to another file as added. The test and source functions that moved -verbatim and still miss a limit are in `limits-allowlist.json` (owner STRA-338, reason "moved verbatim"). Each entry can -only fall; `scripts/check-limits.py --update-baseline` drops an entry when its function is brought within the limits. diff --git a/docs/architecture/size-split-deploy.md b/docs/architecture/size-split-deploy.md deleted file mode 100644 index 6afbe37b..00000000 --- a/docs/architecture/size-split-deploy.md +++ /dev/null @@ -1,86 +0,0 @@ -# Size split of leleka-deploy (STRA-338, batch deploy-1) - -The owner order: no `.rs` file over 400 lines, no function over the limits of `docs/architecture/limits-gate.md`. This page -records how the 15 oversize files of `leleka-deploy` (`crates/deploy/`) were split and how the test ids moved. Every module -is named after what it holds, never `_2`/`_3`. The method is that of `size-split-control-plane-desktop-core.md`. - -## Test ids - -A test id is `::`. A split changes the module path and nothing else: - -* 220 tests before and after (`cargo test -p leleka-deploy --all-targets --features test-fakes`, Linux): 0 missing, 0 new, - 0 outcome changes; 122 ids differ only in the module path (the topic module is inserted). -* Six tests fail on the Linux/WSL development host before and after, for host reasons: five in `e2e` (`dry_run_*` and - `reconfigure_flow::*`, the preflight of the fake host is blocked) and `recipe::the_pinned_archive_digest_of_the_stamps_is_the_one_the_engine_pins`. - Their outcome is part of the parity record; they were not touched. -* `tests/e2e.rs` did not compile before the split (`lifecycle` matched `KarSource` without the `None` variant that - the experimental GGUF-PLE profile added); the one-line fix is the first commit of the batch, so that the baseline exists. -* Cargo test targets keep their names: `tests/e2e.rs` became `tests/e2e/main.rs`; the `leleka-fake-runtime` binary moved to - `src/bin/fake_runtime/main.rs` (`Cargo.toml` names the path). -* A shared module holds what several topics use: `harness` for the integration target, the parent `tests.rs` (fixtures and - imports) for unit tests. - -## Unit tests (`/tests.rs` or an inline `mod tests` becomes `/tests.rs` + `tests/`) - -| Was | Now (`tests/` modules) | -| --- | --- | -| `cli/tests.rs` | `flags`, `reconfigure_args` | -| `expert_profile/tests.rs` | `embedded_table`, `sources`, `report` | -| `preflight/tests.rs` | `gpu_and_driver`, `host_resources`, `windows_host` | -| `reconfigure/tests.rs` | `settings_ranges`, `planning`, `recording` | -| `plan.rs` (inline) | `plan/tests.rs` with `install_steps`, `expert_profile_steps`, `mode_resolution` | -| `profile.rs` (inline) | `profile/tests.rs` with `builtin_profiles`, `selection`, `budget_arguments`, `sparse_memfd` | -| `resources.rs` (inline) | `resources/tests.rs` with `presets_and_workers`, `ram_fit`, `windows_presets` | -| `config.rs`, `supervisor.rs` (inline) | `config/tests.rs`, `supervisor/tests.rs` (unchanged ids) | -| `app.rs` (three inline modules) | `app/{version_tests,machine_tests,status_tests}.rs` (unchanged ids) | -| `sealed.rs` `linux` module with its tests | `sealed/linux.rs`, `sealed/linux/tests.rs` (unchanged ids) | - -## Integration target - -| Target | Modules next to `main.rs` | -| --- | --- | -| `tests/e2e` | `harness`, `supervisor_lifecycle`, `sealed_archive`, `engine_supervision`, `verify_commands`, `up_flow`, `expert_profile_install`, `dry_run_and_usage`, `reconfigure_flow` (+ `reconfigure_flow/service`) | - -`reconfigure_flow` stays one module with its tests inside, so those ids are `reconfigure_flow::` as before. - -## Sources - -| Was | Now | -| --- | --- | -| `supervisor.rs` (1863 lines) | `supervisor/` `logfile`, `cli_output`, `startup`, `signals`, `status`, `children`, `sparse`, `supervise`, `engine`, `api`, `live_reconfigure` | -| `app.rs` (1490) | `app/` `entry`, `preflight_report`, `install_flow`, `status_report`, `settings_change`, `verify_flow`, `stop_flow` | -| `plan.rs` (1483) | `plan/` `scope`, `gather_state`, `step_state`, `step_plan`, `host_steps`, `model_steps`, `service_steps`, `expert_table_step`, `render` | -| `profile.rs` (1035) | `profile/` `memory_budget`, `catalog`, `profile_limits` | -| `resources.rs` (964) | `resources/sizing` | -| `config.rs` (793) | `config/` `engine_launch`, `service_documents` | -| `sealed.rs` (592) | `sealed/` `linux`, `unsupported_host`, `exec_arguments` | -| `facts.rs` (430) | `facts/` `linux`, `windows`, `parsers` | -| `preflight/evaluate_fn.rs` (one 665-line function) | `preflight/` `evaluation` (the order of the checks) and one module per check family: `platform`, `gpu`, `resource_preset`, `memory`, `kar_source`, `cuda_libraries`, `wsl_filesystem`, `disk`, `service_host`, `download_hints` | -| `bin/fake_runtime.rs` (426) | `bin/fake_runtime/` `main`, `engine_double`, `cli_double`, `gateway_double` | - -`plan_steps` (369 lines) and `evaluate` (665 lines) were rewritten as one function per step or check; the texts, the -order of the steps and checks and the commands they print are unchanged (the plan and preflight tests pin them). - -## Renamed mechanical modules - -The earlier mechanical splits left names that said nothing (`*_fn`, `impl_*`). They are renamed after what they hold; the -paths the parents re-export are unchanged: `cli/{flag_parsing,dispatch,subcommands}`, -`expert_profile/{provisioning,tier_report}`, `facts/parsers`, `logview/{collection,logs_command,report,entries}`, -`reconfigure/{settings,plan_and_persist}`, `steps/{downloads,service_unit,model_assets,preparation,probes_and_tools,stamps_and_state}`, -`winfront/{doctor_command,session,routing,commands}`, `wsl/{distros_and_paths,bridge}`, `preflight/report`. The -`#[allow(unused_imports)]` re-export lines of the parents became one `use module::{names};` per module, and the lines -nothing used were dropped. - -## Why the limits allowlist grew - -The diff gate treats a function that moved to another file as added. The functions that moved verbatim and still miss a limit -are in `limits-allowlist.json` (owner STRA-338, reason "moved verbatim"). Each entry can only fall; -`scripts/check-limits.py --update-baseline` drops an entry when its function is brought within the limits. - -## Checks run - -Compiled and checked on both targets, because `winsys`, `winfront`, `winservice` and `facts::windows` build only on Windows: -`cargo check -p leleka-deploy --all-targets --features test-fakes` on Linux (WSL) and on the Windows host: no new warning (the -one `lab_holder_running` dead-code warning of the Windows build exists before the batch). `cargo clippy --no-deps -D warnings` -is clean on Linux; on Windows it reports the same three findings as before (`lab_holder_running`, `layout.rs` `return`, -`winsys.rs` `is_multiple_of`). diff --git a/docs/architecture/size-split-rest.md b/docs/architecture/size-split-rest.md deleted file mode 100644 index f33910c9..00000000 --- a/docs/architecture/size-split-rest.md +++ /dev/null @@ -1,69 +0,0 @@ -# Size split of the remaining crates (STRA-338, batch size-rest) - -The owner order: no `.rs` file over 400 lines. This page records how the 24 oversize files of the CPU, iGPU and NPU -runtime crates, the formats and the gateway libraries were split, and how the test ids moved. Every module is named after -what it holds, never `_2`/`_3`. The method is that of `size-split-control-plane-desktop-core.md` and -`size-split-deploy.md`; no logic was edited except in `leleka-gateway-domain` (below). - -## Test ids - -A test id is `::`. A split changes the module path and nothing else: - -* `cargo test -p --all-targets` on Linux (WSL) for the 27 crates of the batch, before and after, compared with - `scripts/dev/test-outcomes.py compare`: 0 missing, 0 new, 0 outcome changes. Ids that differ only in the module path - (the topic module is inserted) are the integration targets and test files listed below; unit tests moved to - `tests.rs` keep their ids. -* Integration targets keep their Cargo target names: the children sit in a directory named like the target and are loaded - with explicit `#[path]` attributes from the target root, which stays `tests/.rs`. -* `igpu` runs 21 tests on the Linux host without an adapter (the GPU tests skip); `openvino`, `gptoss-igpu` and `gptoss-npu` - have no hardware on the host either. All of them are also type-checked with `cargo check --all-targets` on Windows and - Linux with no new warning. - -## Sources - -| Was | Now | -| --- | --- | -| `gptoss/src/lib.rs` (1788 lines) | `model_bytes`, `config`, `weights`, `tensor_loading`, `quant_probes`, `model`, `profile`, `decode_state`, `scalar_numerics`, `parallel_jobs`, `parallel_region`, `prefill`, `forward_pass`, `generation`, `tests` | -| `cpu-sys/src/lib.rs` (1007) | `checks`, `portable`, `x86_dot_kernels`, `checked_attention_kernels`, `tiles`, `oracle`, `tests`; the `with_avx2!` and `with_avxvnni!` macros stay in `lib.rs` so every kernel module sees them | -| `cpu-sys/src/simd.rs` (1503) | `simd/scalar_dot_kernels`, `simd/scalar_tile_kernels`, `simd/x86` (the former inline module) with `simd/x86/{int_dot_kernels, mxfp4_q8_dots, q8_0_dot_kernels, tile_kernels, attention_kernels, f16_attention_kernels, quantize_q8_0}` | -| `igpu/src/lib.rs` (1386) | `gpu_error`, `handles`, `params`, `repacking`, `device`, `readback`, `matrix_uploads`, `recorder_core`, `recorder_activation_passes`, `recorder_moe`, `recorder_attention`, `tests`; the long `impl Gpu` and `impl Recorder` blocks are cut between methods | -| `igpu/src/shaders.rs` (440) | `shaders/{rmsnorm_rope_shaders, kv_store, attention, quantize_shaders, expert_routing_shaders, f16_round}` (WGSL text constants) | -| `gguf/src/lib.rs` (560) | `error`, `value`, `tensor_type`, `file`, `reader` | -| `tokenizer/src/lib.rs` (840) | `construction`, `encoding`, `decoding`, `bpe_merge`, `vocabulary`, `tests` | -| `quant-core/src/iq2s_grid.rs` (1032) | the same table, four entries per line under `#[rustfmt::skip]` (265 lines); the entries and their order are unchanged and the SHA-256 test of the crate still pins them | -| `openvino/src/lib.rs` (676) | `error`, `c_api_types`, `library`, `inference_runtime`, `tensor`, `tests` | -| `cpu-kernels/src/lib.rs` (464) | `isa`, `dispatch`, `tests` | -| `shm/src/lib.rs` (432) | `unix`, `windows` (each loaded as `imp` through a `use ... as imp`), `tests` | -| `gptoss-igpu/src/lib.rs` (524) | `prefill_pass`, `tests` | -| `gptoss-npu/src/lib.rs` (809) | `npu_prefill_setup`, `service_transfers`, `prefill_part_pass`, `expert_pass`, `accelerator`, `tests` | -| `gateway-domain/src/responses/render.rs` (405, one function of 385 lines) | `render.rs` (the entry), `render/instructions` (one function per system message), `render/replay` (one method per input item kind) | - -Every `unsafe` block and its `SAFETY` comment moved verbatim with the code it belongs to (the `unsafe` counts of `cpu-sys` -`lib.rs` and `simd.rs` are 12 and 58 before and after over the files they became; `openvino` 110). - -## Test files - -| Was | Now (modules next to the target root or under `tests/`) | -| --- | --- | -| `runtime-client/tests/grpc_backend.rs` | `attach_and_reconfigure`, `generation`, `stream_lifecycle`, `runtime_restart_and_loss`, `fixtures`, `scripted_service`, `server_and_frames`, `scripted_types` | -| `gateway-text/src/tool_output/tests.rs` | `upstream_fixtures_and_undeclared_calls`, `call_terminators`, `array_arguments_and_typed_values`, `string_unions_and_incremental_parsing`, `quoted_values_and_drifted_forms`, `bare_function_recovery` | -| `cpu-worker/tests/serve_loop.rs` | `generation_and_cancellation`, `failure_shutdown_and_speculation` | -| `experimental-ref/tests/emulated_kernels.rs` | `fwht_and_q4_append`, `int8_and_k8v4_append`, `kv_stream_and_keyless_routing`, `cvec_reduction`, `quantized_attention` | -| `gguf/tests/synthetic.rs` | `metadata_and_headers`, `hostile_input_and_tensor_layout`, `limits_and_inventory` | -| `gptoss/tests/synthetic_model.rs` | `decoder_and_prefill`, `prefix_reuse_and_generation`, `prefix_copy`, `world_types`, `gguf_builder`, `synthetic_world`, `reference_forward`, `decoder_runs` | - -## The one rewrite: `render_request_with` - -`render_request_with` of `leleka-gateway-domain` was a single function (385 lines, complexity 93). It is now an entry -function of 40 lines that calls `instructions::push_system_messages` and `replay::replay_items`; the replay is a `Replay` -value whose methods handle one item kind each (`reasoning_item`, `message_item`, `call_item`, `output_item`) and whose -helpers parse one part (`message_content`, `call_identity`, `call_arguments`, `call_markup`, `output_text`, -`flush_exchange`). The order of the checks, the error texts and the rendered text are unchanged. Evidence: the -`leleka-gateway-domain` tests (17) and the `leleka-control-plane` `responses` unit tests (72, which render through this function) -pass before and after; no function in the new files is over 30 lines, complexity 10 or nesting 4. - -## Why the limits allowlist grew - -The diff gate treats a function that moved to another file as added. The functions that moved verbatim and still miss a -limit are in `limits-allowlist.json` (owner STRA-338, reason "moved verbatim"). Each entry can only fall; -`scripts/check-limits.py --update-baseline` drops an entry when its function is brought within the limits. diff --git a/docs/architecture/tech-debt.md b/docs/architecture/tech-debt.md deleted file mode 100644 index 5343f141..00000000 --- a/docs/architecture/tech-debt.md +++ /dev/null @@ -1,816 +0,0 @@ -# Architecture tech debt (STRA-367) - -Debt that a hexagonal step moved but did not remove. A line here names the file, the limit it misses, and what -removes it. The size and ratchet numbers themselves live in `architecture-baseline.json`; the overview is `hexagonal.md`. - -Limits for new and changed code: function at most 30 lines, cyclomatic complexity at most 10, nesting at most 4, -line at most 120 columns, file at most 400 lines. - -Crate names after S22: the sections below that say `leleka-runtime` describe code that now lives in `crates/engine-qwen35-cuda` (package -`leleka-engine-qwen35-cuda`); `leleka-runtime` is a one-line facade. The sections keep the wording they had when they were written, paths such as -`backend/` and `settings/` are relative to the new crate, and the ratchet keys read `...:leleka-engine-qwen35-cuda`. The layers, the ports and the -numbers after S22 are on `docs/architecture/hexagonal.md`; the S19 to S22 section below says what the engine recut moved and what it left. - -## Debt register of the architecture rework (owner request 2026-11-13) - -The three debts the rework still carried, each with the state it was left in. Numbers are from `scripts/check-architecture.py`. - -### (a) Pure layer using OS crates: 2 violations -> 0 (done) - -`leleka-memory` (L1) depended on `libc` and `windows-sys`. It now owns the ports and no OS crate: `lock::PageLocking` -(`mmap`/`mlock`/`mincore`/`madvise`/`munmap`/`setrlimit` over plain integer addresses, `SharedPageLocking` = `Arc`), -`ProcSource::trim_working_set` (Windows working-set trim, default `false`) and the pure `winproc` text formatters; `FdMapping` keeps the -bounds checks and lock bookkeeping, now safe Rust. The adapter is the new L3 crate `crates/memory-os` (`leleka-memory-os`): `LinuxPageLocking`, -`WindowsProc` (Win32 facts as `/proc` text), `heap` (glibc `mallinfo2`/`malloc_trim`, moved verbatim with its `LELEKA_MEMORY_NO_TRIM` read), -`HostProc` (the real host of this platform) and `real_governor(cfg)`, which the engine's `memory_governor::install` calls instead of -`Governor::real` (removed: it had no page-locking adapter). `Governor::with_page_locking` is the composition point; without an adapter the archive -guard reports `NotAttempted` exactly as a failed `mmap` does. `telemetry::start` takes the host as its third argument. The sparse-archive test and the -`swap_ab` example moved to `memory-os` with the code they exercise. Behaviour is unchanged: same calls, same order, same messages (the `mlock: ...` -text is built from the same `io::Error`); the page-locking calls are per archive guard and heal tick, not per token. `leleka-memory` is edge-free of `unsafe` -(`lock` no longer opts in) and runs under Miri in full. Gate: `forbidden-dep` entries gone from `architecture-baseline.json`; `leleka-memory-os` is in -`ci-coverage.json` and the product test and Clippy lists. - -### (c) Files left by the mechanical splits (headers 1,111 -> 0, glob imports 1,465 -> 961) - -Start of the pass (main `fc79029eb`): 1,111 `.rs` files whose header said "Moved out of the parent module by STRA-338: fn a, fn b ..." and 1,465 files -carrying the pair `#[allow(unused_imports)] use super::*;` (3,576 `#[allow(unused_imports)]` in all, the other 2,100 or so on the `pub use child::name;` -re-exports that keep the old paths). The names of the split files already say what they hold (`mechanical_names` is 0), the headers and the glob -imports were the debt. - -What the pass did, by `scripts/dev/explicit_imports.py` (with `scripts/dev/rust_modtree.py`, an offline refactoring aid, Python as allowed for tooling): - -* **Header.** Every "Moved out of the parent module" header is replaced by two `//!` lines generated from what the file defines (`Methods of T: - a, b, c`, `Implements Trait for T`, `Functions: ...`, `Defines ...`, `Groups the submodules ...`), or, when a person had written a sentence under - the generated list, by that sentence. `tests.rs` files say "Unit tests of `parent`". The lines say what the file holds and that it was split for the - size limit; they do not say why the code is a separate responsibility, which only an author can write (see "What is left"). -* **Glob import.** `#[allow(unused_imports)] use super::*;` becomes `use super::{A, B, ...};` with exactly the names the file uses: the tool reads the - module tree (`mod x;`, `#[path]`, `pub use x::*;` chains, `extern` blocks, item-defining macro calls, traits imported for method calls and `as _` - imports), takes the identifiers of the file (and of the glob children below it, and of the `macro_rules!` bodies above it), imports the candidates, compiles - `cargo check --lib --bins` and `--tests` (all features where the crate has features) and removes every name the compiler reports unused. A name used - only by `#[cfg(test)]` code gets a `#[cfg(test)] use`; a name used only with some cargo features stays under a narrow `#[allow(unused_imports)]` with a - comment. A compile error reverts the file and every ancestor that still holds a glob, and the pass repeats until the crate compiles. -* **Safety.** No logic, signature or numeric code is touched: the diff of every file is the header and the `use` lines. The crates were checked with - `cargo check --all-targets` and the tests of each crate ran; the two-binary identity run (2057 of 2057 logprob rows and 1036 of 1036 draft lines bitwise identical, at 1 and at 15 CPU workers) is in `docs/experiments/step-ledger.md`. - -| Crate | "Moved out" headers | `#[allow(unused_imports)] use super::*;` files | What stays a glob | -|---|---|---|---| -| `cuda-driver` | 471 -> 0 | 564 -> 564 | all: the compile-and-prune loop reached a state it could not close (glob sources the tool cannot trace, `macro_rules!` and item-defining macro calls, 172 files under cfg-gated names, 17 under platform cfg); two attempts with the failing top-level modules excluded were interrupted by the laptop GPU stretch, so the crate got the doc headers only; second pass: 571 -> 3 production globs, see below | -| `engine-qwen35-cuda` | 343 -> 0 | 407 -> 236 | 127 platform cfg, 105 under cfg-gated names; `open_phase_steps.rs` (was `open_parts.rs`) stays a glob on purpose (it is at the 400-line limit and the explicit list would put it over) | -| `leleka-control-plane` | 66 -> 0 | 113 -> 22 | 5 platform cfg, 17 under cfg-gated names (the `responses` and `messages` trees) | -| `leleka-model-format` | 54 -> 0 | 77 -> 10 | platform cfg (`bulk_read`, `gguf_resident`, `kar`) | -| `leleka-native-cpu-expert` | 58 -> 0 | 62 -> 34 | 10 behind an `extern "C"` glob chain, the rest macro-defined names | -| `leleka-engine-core`, `leleka-engine-host`, `leleka-gateway-text`, `leleka-memory`, `leleka-cuda-model`, `leleka-tokenizer`, `leleka-backend-api`, `leleka-context`, `leleka-serving-policy`, `leleka-obs`, `leleka-runtime-client`, `leleka-harmony`, `leleka-gateway-domain`, `leleka-npu-service`, `leleka-experimental-ref`, `leleka-deploy`, `leleka-libc-shim` | 114 -> 0 | 158 -> 14 | `leleka-context` 1, `leleka-experimental-ref` 5, `leleka-runtime-client` 8 | -| `leleka-cpu-sys` | 4 -> 0 | 16 -> 13 | opaque glob chain, cfg-gated names | -| `gptoss`, `igpu`, `gguf`, `gptoss-npu`, `openvino`, `cpu-worker`, `cpu-kernels`, `gpu-npu-worker`, `gptoss-igpu` | none | 74 -> 74 | not touched: the CPU/iGPU/NPU runtime is another stream's code and has no "Moved out" header; the tool works on them unchanged | - -Left as a glob, and why (counts above): a module under a `cfg(windows)`, `cfg(target_os = ...)` or `not(...)` platform attribute (the tool compiles on -Linux only, so it cannot prove the explicit list there: 5 to 20 files a crate); a module whose parent chain declares names under a `cfg` attribute (an -explicit import would need the same `cfg`); a glob that comes from a crate outside the module tree (`use libc::*` style, `opaque`). Next step for -each: one author-side pass per crate, adding the cfg on the import or a platform-aware compile (a Windows `cargo check` for the crates that build there: -`leleka-deploy`, `leleka-control-plane`, `leleka-model-format`); estimate one to two days for `cuda-driver` (group by top-level module, bisect the failing group), an hour for each other crate. - -#### Second pass: the low-level crates (owner order 2026-11-14, branch `claude/arch-names-low`) - -The owner ordered the rework finished for the crates below the engine: the files with `#[allow(unused_imports)] use super::*;`, the names left by the -mechanical splits, and the cheap ratchets. Counts are production code, from `scripts/check-architecture.py`; the other agent's crates -(`engine-*`, `leleka-runtime`, `runtime-client`, `control-plane`, `desktop-core`, `deploy`, `gateway-*`) are not in these tables. - -| Ratchet, all low-level crates together | before | after | -|---|---|---| -| `glob-super-import` | 674 | 3 | -| `allow-unused-imports` | 1,097 | 552 (the rest are `pub use` re-exports and names of other cargo feature sets) | -| `env-read` | 122 | 28 (five crates now have one reader each, see below) | - -| Crate | `glob-super-import` | `allow-unused-imports` | -|---|---|---| -| `cuda-driver` | 571 -> 3 | 863 -> 410 | -| `native-cpu-expert` | 15 -> 0 | 89 -> 75 | -| `model-format` | 16 -> 0 | 32 -> 22 | -| `cpu-sys` | 13 -> 0 | 48 -> 35 | -| `igpu` | 18 -> 0 | 20 -> 2 | -| `gptoss` | 17 -> 0 | 16 -> 0 | -| `gptoss-npu`, `gptoss-igpu`, `openvino`, `gguf`, `cpu-kernels`, `gpu-npu-worker` | 24 -> 0 | 36 -> 0 | -| `cpu-worker`, `tokenizer`, `leleka-memory` | 3 -> 0 | 0 | - -**Imports.** `scripts/dev/explicit_imports_lowlevel.py` (with `rust_modtree_lowlevel.py`; the other branch grew `explicit_imports.py` and `rust_modtree.py` in parallel, and the two cfg models were not merged: use the `_lowlevel` pair for `cuda-driver` and the crates below it) now converges on `cuda-driver`. What it learned, each from a failure of the first pass: - -* *Names behind a cfg.* A name that exists only under a `cfg` (the `cuda-driver` feature gate of the root exports) is imported without an attribute when the - module itself sits under the same gate, and with `#[cfg()] use super::..;` otherwise. It no longer treats every CamelCase or - CONSTANT import as a possible trait: it follows the `use` path to the definition (the 172 "cfg-gated names" files were mostly this). -* *Module paths.* Children declared by `#[path]` are ordered by module depth, not directory depth; a name reached through a glob chain (`pub use x::*` in a - `#[path]` module) resolves; a file declared by several parents is left alone; `include!`d files count as part of the includer (the four `ffi` files); - `std::arch` intrinsics (`_mm256_*`, `_CMP_*`) come through the glob of the parent and are imported by name; `static mut NAME` in an `extern` block is a name. -* *Test builds.* The cause of the old non-convergence: `cargo check --tests` also builds the library for the integration tests and prints a warning - that two units share only once, so a name that only the unit tests use looked unused and was removed. The prune now takes "unused" from the build without - `cfg(test)` and keeps a name as `#[cfg(test)] use` when the test items of the file mention it (a trait is kept for the test build to judge). -* *Gates.* The tool waits while `.git/laptop-gpu-wanted.flag` or `laptop-gpu-run.lock` exist (the laptop is the GPU test machine too) and while Windows has - less than 2.5 GB free (at most two minutes per build). `--prune` re-runs on an expanded crate; `ONLY` and `EXCLUDE` select top-level modules; - `BASE_CONFIG="--features cuda-driver"` is the smallest feature set that builds, where names used only by other feature sets get a narrow - `#[allow(unused_imports)]` with a comment. - -Left, with the next step: - -| Item | Why | Next step | -|---|---|---| -| `cuda-driver/src/root_exports.rs` (glob) | it re-exports `serving_context` (a module of `leleka-cuda-model` and a function of the same name); an explicit import clashes | re-export the function by its full path and name the module import differently in `lib.rs` | -| `cuda-driver/src/mtp_original_full_head_dispatch.rs` (glob) | declared as a module by three parents (`mtp_original_full_forward`, `mtp_original_prefill`, `mtp_original_scalar_prefill`), so its names differ per parent | one parent declares it; the others `use` it | -| `cuda-driver/src/mmq_original_group/copy_ring_layer.rs` (glob) | exactly 400 lines; the explicit list would put it at 403 | move its free functions (`format_index`, the projection handles) to a file of their own, then expand | -| 410 `allow(unused_imports)` in `cuda-driver`, 75 in `native-cpu-expert`, 35 in `cpu-sys`, 22 in `model-format` | `pub use` re-exports of the split files (the old paths), a few names of other cargo feature sets, `c_reference` | the re-exports stay while other crates and tests use the old paths; replace them one module at a time by the real path | -| `cuda-driver` in the default feature set | does not compile at the base commit either (`root_exports.rs` re-exports `original_verify::sm120::set_overrides` without the feature gate); the product builds with `--features cuda-driver`, which was checked, with `sm86` and with all features | put the missing `#[cfg]` on that line | -| the Windows-only code (9 platform-cfg files of `cuda-driver`) | the tool compiles on Linux; their unused names were kept under a narrow allow | a native Windows `cargo check -p leleka-cuda-driver --features cuda-driver` and a prune on it | -| `crates/libc-shim` | Windows only, nothing to expand | none | - -**Names.** 61 modules were renamed with `git mv` (the file, its directory, the `mod` line and the `#[path]` of its parent, the paths that name it, the doc -comment), by `scripts/dev/rename_module_map.py` and a mapping written by hand from what each file holds. Examples: `leleka-memory` -`governor/governor_methods/governor_admit_and_relieve.rs` -> `governor/operations/admission.rs` (with `setup`, `status_report`, `archive_guard`, -`archive_residency_tick`); `cuda-driver` `api/enabled.rs` and five more `enabled.rs` -> `driver_backed.rs`; the `*_methods.rs` files of `cuda-driver` -> -`*_lifecycle.rs`, `*_operations.rs` (a group of files that implement one type) or `window_launches.rs`; `native_parity/state.rs` -> `parity_session.rs`; -`original_expert_stager/shared.rs` -> `stager_workers.rs`; `tokenizer/.../tokenizer_error_display_error.rs` -> `error_messages.rs`; -`model-format/.../kar_error_display_error.rs` -> `inspection.rs`; `native-cpu-expert/src/rust_ggml_extra.rs` -> `rust_ggml_iq1_ternary_fp4.rs`. Every renamed -file has a doc comment that says what it holds and why it is a file of its own. Left on purpose: - -* the 55 `*_and_*.rs` names (33 in `cuda-driver`, 7 in `cpu-sys`, 7 in `igpu`, the rest elsewhere): each names the two things the file holds and its doc - line says so; a single word would need a split, which is a design change (next step with the owner of each crate); -* `cuda-model/src/mmq_original_prefill_misc.rs`: named after the CUDA source `mmq_original_prefill_misc.cu` and its PTX, which the sm86 table and the oracle script quote; -* `cuda-driver/src/qsa_resident_transfer/enabled.rs`: its parent also declares an inline `mod enabled` for the build without the feature, so only the pair can be renamed together; -* the `*_types.rs` and `*_drop.rs` files (a file of one type's definitions, a file of one `Drop`): the name says what is in it; -* test files named by the sentence of their test. - -**Cheap ratchets.** `env-read`: `cuda-driver` (67 -> 2), `native-cpu-expert` (19 -> 2), `cuda-model` (5 -> 2), `gptoss` (6 -> 1) and `model-format` (5 -> 1) read -the environment only in their new `settings.rs` (`settings::var`, `settings::var_os`: `#[inline]` pass-throughs; `scripts/dev/funnel_env_reads.py`). The reads, their -parsing and the `OnceLock` switches are where they were; the step to a parsed `Settings` value is the one listed in (b). `instant-now`, `process-global` -and `dyn-trait` did not move: the `Instant::now()` calls of these crates are stall and profile spans in the launch paths and the expert pool, which -this order said not to touch; they need a clock parameter that is designed once for the pool and the driver. - -**Identity.** Renames, imports and the settings funnel do not change generated code. The checks are `cargo check --all-targets` of the touched crates (the -driver with `--features cuda-driver`, with `sm86` and with all features), their tests, and the unchanged public paths. No GPU identity job was queued (the -server is busy with the owner's service); the laptop two-binary identity gate (base `23bdbb308`, new = main after both refactor branches) is the check -for the end state. - -### (b) Source ratchets: measured, classified, not moved in this pass - -The numbers did not fall in this pass (the only change is the code that moved from `leleka-memory` to `leleka-memory-os`: XX -of the `heap` module, counted there now). What the census shows (production code of `src/`, counts of `architecture-baseline.json`): - -| Pattern (total) | What it is made of | Next step | Estimate | -|---|---|---|---| -| `process-global` 265 | about 42 are the switch idiom `static ON: OnceLock` read from one environment variable (`cuda-driver` 25, `native-cpu-expert`, `libc-shim`, `cuda-model`, `model-format`), the rest are lazily built tables and caches (`OnceLock>`, regex, parse tables), the settings capture (`settings::process()`), and a few real singletons (`Governor::global()`, `Inventory`, the serve loop `INSTANCE`/`RECONFIGURING`, the load-time lap printer) | one `EnvSwitch` type (name, rule `fn(Option<&OsStr>) -> bool`, `OnceLock` inside, `get()`) in `leleka-cuda-model` for the switches; keep the tables (they are pure caches); the singletons need the injection of S13/S14 (a settings handle and a clock through the engine stack) | EnvSwitch: one day for about 25 sites plus an identity run, because several (`up8`, `fused_commit`, `commit_sync_forced`, `daily_mtp`) sit on the decode path that this pass must not touch; singletons: the S13/S14 follow-up, several days | -| `env-read` 200 | `cuda-driver` 67 (25 switch idiom, the rest option parsers such as `OriginalStagerOptions`), `deploy` 41 (CLI and child environment on purpose), `native-cpu-expert` 19, `leleka-control-plane` 19, `leleka-engine-host` 15 | per crate a `settings` module that is the only reader (the engine has one: `EnvSource`, `ProcessEnv`, `MapEnv`); `deploy` sets the child's environment, which stays | one day per crate; `cuda-driver` waits for the `EnvSwitch` type and for a settings crate below the driver (S13 follow-up) | -| `instant-now` 188 | `deploy` 28, `native-cpu-expert` 27 (per-window and per-miss timers of the CPU expert pool), `cuda-driver` 25 (stall and profile spans), `leleka-control-plane` 22, `engine-qwen35-cuda` 16, `gptoss-npu` 12 | `leleka_obs::time::Clock` (generic, `SystemClock` by default) for the coarse points (deploy, control, desktop-core: one reading per request or probe); the timers inside the decode loop and the pool stay on `Instant` until a clock parameter is designed, because each is one reading per kernel or miss | half a day for `deploy` + `strata-*`; the pool and driver timers are a design decision | -| `path-include` 234 | `cuda-driver` 118 and `engine-qwen35-cuda` 100 are `#[path = "dir/file.rs"] mod x;` declarations of the files the splits made, `model-format` 12 | declare the children through the directory layout (`mod x;` with the file at `parent/x.rs`) and drop the attribute; `git mv` per module; mechanical but it renames paths that the ledger and the identity scripts quote | one day with `rustsplit`'s layout rule; no behaviour change | -| `dyn-trait` 207 | `engine-qwen35-cuda` 53, `cuda-driver` 45, `engine-core` 18, `deploy` 17, `leleka-memory` 17 (the `&dyn ProcSource` of the host reads, the `SharedPageLocking`), `leleka-control-plane` 11 | request-level and start-up composition only (the policy); the `&dyn ProcSource` parameters of `leleka-memory` can become generics (two were changed in this pass: `HostFacts::probe`, `Census::take`, `HostSample::take`) | half a day for `leleka-memory`; the rest are the carve-outs listed in `hexagonal.md` | - -No source ratchet was raised. `leleka-memory`: `dyn-trait` 17 -> 12 (`HostFacts::probe` and its cgroup helpers, `Census::take` and `HostSample::take` are generic over -`ProcSource` now), `env-read` 3 -> 2 and `process-global` 10 -> 8 (the trim switch and its cache moved to `leleka-memory-os`, which counts `env-read` 1 and `process-global` 2). - -### (c2) Second pass over the engine, gateway and deploy side (owner order 2026-11-14, branch `claude/arch-names-high`) - -**Tools** (`scripts/dev/`, offline aids, Python allowed): `explicit_imports.py` now (1) reads the crate-wide gate `cfg(all(any(target_os = "linux", -target_os = "windows"), target_arch = "x86_64"))` as always true (it made 127 engine files look platform-specific and blocked most of the 105 -"cfg-gated names" files), (2) also expands the bare `use super::*;` that has no `#[allow(unused_imports)]` above it (what `deploy` and part of the -engine carry), and (3) carries the `cfg` of a name declared in the parent onto the import (`#[cfg(feature = "preview-path")] use super::{..};`), so a file -that needs a feature-gated name no longer stays a glob. `rename_module.py` renames a module file to what it holds (`git mv`, the `mod` line, the -`#[path]` string, the path uses in the parent's subtree; `--any-ident` and `--crate-wide` for a name that is imported in lists). `set_header.py` replaces -the generated doc block by the real sentence. `wsl-cargo.sh` limits `CARGO_BUILD_JOBS` (default 4). - -**Numbers** (`architecture-baseline.json`, before -> after this pass): `glob-super-import` engine 328 -> 70, `leleka-deploy` 79 -> 15, -`leleka-control-plane` 37 -> 9, `leleka-engine-host` 16 -> 0 (its `leleka-inference` binary has its own crate root: `ROOT_FILE=src/bin/leleka-inference/main.rs`), -`leleka-gateway-domain` 2 -> 0; `allow-unused-imports` engine 396 -> 224, `leleka-control-plane` 63 -> 48; `env-read` `leleka-control-plane` 19 -> 14 (the run -configuration reads `STRATA_*` only in `config/process_env.rs`), `leleka-engine-host` 15 -> 13 (one `node_credential`). The two engine files that sit at the -400-line limit (`cache_profile_fill/profile_build.rs`, `original_serve_stack_methods/open_phase_steps.rs`) stay globs on purpose. Checks: `cargo check ---workspace --all-targets` clean, tests of `leleka-deploy`, `leleka-control-plane`, `leleka-engine-host`, `leleka-gateway-domain`, `leleka-engine-core`, -`leleka-context`, `leleka-experimental-ref`, `leleka-engine-qwen35-cuda`: 1759 passed, 2 failed (the two known `mtp::backing` NTFS tests, red on base too). -The tool also had two defects that this pass fixed and that explain why the first pass stopped at 236 files: a file given back its glob was not -rewritten (the explicit list stayed on disk and kept failing), and a test-only import was never pruned. - -**Names.** Files that said "part of a function" (`*_parts.rs`, `*_inner.rs`, `*_support.rs`, `*_glue.rs`, `shared.rs`, `preview_common.rs`, `stream_parts.rs`, -`chunk_modules.rs`, `*_display_error.rs`, truncated test names) are renamed to the responsibility, with a doc comment that says what the file is and why it is -separate (the generated "split for the size limit" line is gone from them): `tile_parts` -> `prefill_tiles_and_windows`, `reconfigure_parts` -> -`reconfigure_command`, `open_parts` -> `slot_sizing_and_open_retry` / `open_phase_steps`, `decode_parts` -> `decode_phase_steps`, `assemble_parts` -> -`assembly_steps`, `finish_parts` / `commit_parts` / `verify_parts` -> `finish_round_steps` / `commit_round_steps` / `verify_round_steps`, `stream_parts` -> -`kar_shard_plan`, `intake/parts.rs` -> `intake_stages.rs`, `original_serve_engine_original_spec_engine` -> `spec_engine_for_serve_engine`, and the others in -`git log --follow`. Left as they are, on purpose: the `*_sdet.rs` and `tests/*_sdet.rs` names (the established name of the deterministic test targets that -CI and the docs call by name), `qwen4exp_*` (the model family name, shared with `model-format`), the `*_methods` group modules (they say what they group; -their doc comment now says by which phase), `ConversationManager` (a domain type of `engine-core`; renaming it is an API change of its own). - -**Left, with the next step.** - -| What | Why it stays | Next step | -|---|---|---| -| globs in the engine that the compile-guided loop gave back (about 100 files: GPU-proof and `cfg(test)` names such as `BindingIdentity::test_identity`, `super::session` of the proof modules) and 9 behind mixed cfg | the tool imports a name once; a name that exists only under an inner cfg of the file needs the cfg on that name | read the compiler's "consider importing" help instead of the module tree for these files, or move the proofs to their own `tests/` crate | -| globs in files under a platform cfg (engine 12, `deploy` 12, `leleka-control-plane` 6) | the tool compiles on Linux only | a Windows `cargo check` pass for `leleka-deploy` and `leleka-control-plane`; for the engine files (`mtp::backing`, `kar_ple`) edit by hand with the cfg on the import | -| `Governor::global()` and `serving_cells()` (engine `process-global` 59) | the S13/S14 injection: a governor handle and the context bound through the engine stack | the S13/S14 step in (d); not a cheap change | -| `Instant::now()` in `leleka-control-plane` (22), `desktop-core` (14), `deploy` (28) | the gateway `Clock` port is tokio's `Instant`, the views and the engine use `std::time::Instant`; most sites are deadlines of `tokio::time` | one `Clock` per crate with the instant type of its runtime; half a day per crate with the time-paused tests | -| env reads of `deploy` (41), `desktop-core` (evaluation and seal-exec hooks), the one-line reads of `leleka-control-plane` | the CLI and the child environment are the product; the others are test hooks | per-crate `settings` module that is the only reader | -| `path-include` (engine 100, `desktop-core` 2) | not in the owner's list for this pass | `mod x;` through the directory layout with `git mv`, one directory at a time | -| generated doc headers (`Methods of ...`, `Functions: ...`) in about 430 files of these crates | the sentence on why the file is separate needs the author's knowledge | by directory, together with the next feature that touches it | - -### (c3) Stage 10 for the low-level crates (owner order 2026-11-14, branches `claude/debt-low` and `claude/debt-hot-low`) - -The order: every ratchet of `architecture-baseline.json` goes to zero in the code, or to a named entry of the `exceptions` list of `architecture.json` -(crate, file, ratchet, reason; the gate reads it, an entry that excuses nothing or has no reason is an error). Numbers are production code of the -low-level crates (`cuda-driver`, `cuda-model`, `model-format`, `native-cpu-expert`, `leleka-memory`, `memory-os`, `libc-shim`, `cpu-sys`, the gpt-oss -workers and the small libraries), before -> after, from `scripts/check-architecture.py`. - -| Ratchet | Before | After | How | -|---|---|---|---| -| `allow-unused-imports` | 552 | 0 | `scripts/dev/prune_unused_imports.py`: strips the allow, compiles with one job per feature set (`cuda-driver`, `sm86`, all features), deletes the imports the compiler reports in every compilation unit, puts `#[cfg(test)]` on the ones only the library's unit tests use. Most of the 410 `cuda-driver` allows sat on `pub use` re-exports that needed no allow at all | -| `glob-super-import` | 3 | 2 (`cuda-driver`: `head_dispatch` and `copy_ring_layer`, on `claude/debt-hot-low`) | `root_exports.rs` names its paths (`crate::x`, `leleka_cuda_model::serving_context`) | -| `path-include` | 132 | 0 counted (1 in `cuda-driver`: the shared `head_dispatch`, on `claude/debt-hot-low`) | `scripts/dev/path_to_layout.py`: walks the module tree (a file loaded by `#[path]` resolves its children next to itself, a default file in a directory of its name), moves the module files to `/.rs` with `git mv`, drops the attribute, rewrites `include_*!` paths and the paths scripts quote (`scripts/dev/update_path_refs.py`). 502 files moved (`cuda-driver` 472, `model-format` 27, `native-cpu-expert` 3); module paths did not change. The gate now treats `#[cfg(test)] #[path = "../tests/x.rs"] mod x;` as test code | -| `env-read` | 30 | 0 outside the named exceptions | one reader per crate: new typed `settings.rs` in `cpu-worker`, `tokenizer`, `gptoss-npu`, `gpu-npu-worker`, `igpu`, `npu-service`, `leleka-memory`, `gptoss`, `model-format` (functions named after the variable, returning parsed values); `obs` parses `LELEKA_LOG*` in `level.rs`; `cuda-model` has `env_switch::EnvSwitch` (the name, a typed rule, the answer cached on first read). Exceptions: the readers above, `cpu-kernels` (parses the ISA request), `libc-shim` and `memory-os` (platform adapters), the `npu-worker` and `native-parity-bench` roots | -| `dyn-trait` | 52 outside `cuda-driver` | 0 outside the named exceptions | callbacks and probes became generics (`&mut (impl FnMut(..) + ?Sized)`, `&(impl ProcSource + ?Sized)`); what stays is a port boundary (`MemoryPressure`, `ProcSource`, `PageLocking`, `ModelBytes`, `PageSource`, `PrefillAccelerator`, `LayerCache`, the GPU probe closure), a trait method that must be dyn-compatible, `Box` of a library boundary, or the type-erased job of the worker pool | -| `instant-now` | 54 outside the driver and the CPU pool | 0 outside the named exceptions | the clock adapter (`obs/time/clock.rs`) and measurement timers (stage laps and wall times printed in the workers' timing lines, load reports); each carries a comment that says so. `leleka-memory` reads `SystemClock` | -| `process-global` | 50 outside the driver and the CPU pool | 0 outside the named exceptions | immutable tables (regex, half table), operator settings read once, the process-wide logger, the process singletons the S13/S14 injection is for (`Governor::global()`, `Inventory`, the serving context, the verify stamps) | - -The test run (`cargo test`, slim profile) of `cuda-model`, `obs`, `leleka-memory`, `tokenizer`, `model-format`, `gptoss`, `cpu-worker`, `igpu`, -`memory-os`, `experimental-ref` and `npu-service`: all green except the three known `qwen_artifact_binding` tests of `model-format` -(`cargo check --workspace --all-targets` is clean). The `dyn-trait`, `instant-now` and `process-global` rows exclude `cuda-driver` and `native-cpu-expert`: their changes and exceptions are on `claude/debt-hot-low`, which waits for the identity gate; the final table replaces this one when it is merged. - -### (e) Stage 10 pass: control-plane, desktop-core, deploy and the small crates (owner order 2026-11-14, branch `claude/debt-control`) - -Crates: `leleka-control-plane`, `leleka-engine-host`, `leleka-deploy`, `leleka-gateway-domain`, `leleka-gateway-text`, `leleka-backend-api`, `leleka-runtime-client`, `leleka-npu-service`. Numbers are from `scripts/check-architecture.py`; a site that must stay is a named entry of `exceptions` in `architecture.json` (crate, file, ratchet, reason), not a baseline number. - -| Ratchet | before | after (outside the exceptions) | -|---|---|---| -| `glob-super-import` | `deploy` 15, `control` 9 | 0 | -| `allow-unused-imports` | `control` 48, `desktop-core` 9, 4 small crates 9 | 0 | -| `env-read` | `deploy` 41, `control` 14, `desktop-core` 13, `gateway-text` 2, `npu-service` 1 | 3 (`control`, hot files, see below); each crate has one reader module | -| `dyn-trait` | `deploy` 17, `control` 11, `gateway-domain` 2, `desktop-core` 2, `backend-api` 1 | 0 | -| `path-include` | `desktop-core` 2 | 0 (`evaluation_measurement` is a module of the library; both binaries use it) | -| `instant-now` | `deploy` 28, `control` 22, `desktop-core` 14, `npu-service` 5, `backend-api` 2 | `control` 15 and `desktop-core` 4 in hot files, see below; the rest 0 | -| `process-global` | `control` 8, `gateway-text` 4, `gateway-domain` 2 | 2 (`control`, hot files) | - -**One reader per crate.** `env_settings.rs` in `leleka-control-plane`, `leleka-engine-host`, `leleka-deploy`, `leleka-gateway-text` and `leleka-npu-service` is the only file that calls `std::env::var`; the other modules ask for a typed value (`env_settings::number::("STRATA_QUEUE_TIMEOUT_S")`, `supervisor_status_file()`, `hub_token()`, `stage_trace()`, `home_dir()`, `hf_token_set()`). The reads stay live, so the order of the checks and the messages of the run configuration are as before. `leleka-deploy` passes its `LELEKA_*` lookup around as `EnvLookup = fn(&str) -> Option` (a function pointer, no `dyn`), the tests pass `env_settings::nothing` or a non-capturing closure. - -**Clock.** `leleka-deploy`: the supervisor owns an `AnyClock` (a manual one in tests) and the command flows read `SystemClock` of `leleka-obs`. `leleka-control-plane`: the MCP hub and servers and the hardware series hold an `AnyClock`; `model/file_download.rs` uses the gateway `SystemClock`. `leleka-engine-host`: the node's inventory cache holds an `AnyClock`, the asynchronous deadlines read `clock::RuntimeClock` (tokio's clock, which `tokio::time::pause` controls). Exceptions: the two adapters and the manual clock fixture, the node subscription's freshness stamps, the NPU profile laps and the scripted engine's pacing. - -**Exceptions (reasons in `architecture.json`).** `dyn-trait`: the five `Shared*` ports of `leleka-control-plane` and `AppState`'s codec (composition), `SharedCodec`, the error source chain, the per-request token-bytes closure, the two tonic streaming types of `desktop-core`, the scripted engine's responder. `process-global`: the compiled pinned chat template, the schema validity cache, the request metrics registry, the gpt-oss prompt date set at start-up, the stage-trace table. - -**Names and docs.** About 150 generated doc headers (`Methods of ...`, `Functions: ...`, `Unit tests of this module (split out ...)`) are real sentences that say what the file holds and why it is separate. 60 modules were renamed by what they hold with `scripts/dev/rename_module.py` (`worker/generation_result.rs` -> `worker_entry.rs`, `model/fetch_one.rs` -> `file_download.rs`, `mtp_fetch/mtime_ns.rs` -> `command_line.rs`, `server_api/slots.rs` -> `status_routes.rs`, `desktop-core` `gateway/secret.rs` -> `pool_gateway.rs`, ...). `*_methods` group modules and `ConversationManager` are in `engine-core`/the engine, not in these crates. - -**Left, with the next step.** - -| What | Why | Next step | -|---|---|---| -| hot-path sites (`env-read` 3, `instant-now` 15 + 4, `process-global` 2 in `control`/`desktop-core`) | admission, streaming and the gRPC client are held back until the two-binary identity run | branch `claude/debt-hot-control` | -| Windows-only files (`key_init/windows.rs`, `facts/windows.rs`, `winfront/*`, `winservice/*`) | edited by hand (names read from the code); no Windows `cargo check` could run because `leleka-memory` and `leleka-model-format` do not compile for Windows at this commit (`governor/operations.rs`, `qwen4exp_*`: unresolved imports under `cfg(windows)`) | a Windows `cargo check -p leleka-deploy -p leleka-control-plane` once those two crates compile there | -| deploy end-to-end tests `dry_run_*` and `reconfigure_flow::*` | need free VRAM and a quiet GPU (host checks read `nvidia-smi`); they fail on the busy laptop with "GPU memory: ... free but the engine needs ..." | run on the 5090 | - -### (f) Stage 9: the historical Strata names in our own code (owner decision 2026-11-14, branch `claude/debt-rename`) - -| Old | New | Where | -|---|---|---| -| binary `strata-next` | `leleka-api` | `control-plane/Cargo.toml` (`[[bin]]`, `default-run`), the usage texts, the service unit names (`leleka-api.service`, `leleka-api-NAME.service`), `leleka up`/`leleka run` calls (`leleka-api model ...`, `api-key init`), the installed file list and MANIFEST, `install.sh`, the Windows scripts (`leleka-api.exe`), the release and runtime-image build scripts, the CI workflows, the e2e harness scripts, the fake runtime double (`leleka-api` symlink) and the docs | -| crate `strata-control` | `leleka-control-plane` (identifier `leleka_control_plane`) | `Cargo.toml` of the workspace and of every dependent, `Cargo.lock`, `use` paths, `-p` arguments of scripts and CI, `architecture.json` and the baselines | -| crate `strata-desktop-core` | `leleka-engine-host` (identifier `leleka_engine_host`) | the same; the crate hosts the engine process `leleka-inference` (and `leleka-daemon`, `leleka-cli`, `leleka-seal-exec`) with the node, pool, managed worker and gateway services around it, so the name says what it hosts; the `strata-desktop` binary keeps its name (not part of the order) | - -Done by `scripts/dev/rename_strata_names.py` (a plain text replacement over the tracked files, rerunnable, which also catches what a branch merged later adds). `STRATA_*` environment variables stay. Not touched: `engine/strata` (the Original, including its Python package `strata_control`), `docs/experiments/` and `docs/e2e-data/` (records of what was run, with the names of that day), `docs/ledger*`, `docs/upstream/` and every `*.patch` (diffs against the Original). **Compatibility:** no `leleka-api` alias is shipped, because nothing outside the repository calls the binary by that name; a prefix installed by an older `leleka` is complete in itself (its `leleka`, its MANIFEST and its `leleka-api`), and a new `leleka up` takes the binaries from the package it was built in, which carries `leleka-api`; mixing a new `leleka` with an old package directory is not supported (the MANIFEST lists different files). The owner's running service (`leleka.service` on rnr5090) runs a package built before the rename and was not touched. -### (c3) Stage 10 pass over the engine crates (owner order 2026-11-14, branch `claude/debt-engine`) - -The order: the debt of the engine is brought to zero in the code, or listed as a named exception in `architecture.json` -(`exceptions`: crate, file, ratchet, reason; an entry that excuses nothing is an error). Crates: `leleka-engine-qwen35-cuda`, -`leleka-engine-core`, `leleka-engine-fake`, `leleka-runtime`. - -| Ratchet (production code) | before | after, in the code | named exceptions | -|---|---|---|---| -| `glob-super-import` | 70 (193 files with the glob, tests and GPU proofs included) | 0 | none | -| `allow-unused-imports` | engine 224, engine-core 18 | 0 | none (re-exports nobody used are deleted, names only the tests need are `#[cfg(test)]`, names only another platform needs sit under their `cfg`) | -| `path-include` | 100 | 0 (420 files moved to the place their module name gives) | none; five `#[path]` remain in test-only modules: two files of the crate's `tests/` directory, the file two proofs share (`native_down_pair_io.rs`, one copy of its state each) | -| `env-read` | 1 | 0 | `settings/source.rs`: the one reader of the process environment | -| `instant-now` | 16 | 0 | 8 files of measurement timers in hot loops (round, miss, kernel; each one a log line or counter); load laps and the resident-RAM log line read `SystemClock` | -| `dyn-trait` | engine-core 18, engine-fake 1, engine 53 | engine-core 0, engine-fake 0, engine 9 | `Box` of the five factory files, `EngineFamily::spawn` and the fake family (process boundary); two stored host callbacks (measurement sink, GPU probe). The 9 left are on the hot branch, see below | -| `process-global` | 59 | 0 | 37 files, in three groups: reads of the serving context that is fixed at start-up (`serving_cells()`), `Governor::global()` (the S13/S14 injection of a governor handle is not done), and the settings capture, one tuning cache, one trace epoch, four per-instance `OnceCell` fields | - -What was done, with the tools that did it (all under `scripts/dev/`, offline aids): - -* **Imports.** `unglob_by_errors.py` replaced every `use super::*;` by the names the file uses. It seeds the list from the module - tree, builds the crate, adds what rustc says is missing, removes what no build uses, and gives a name only the tests need - `#[cfg(test)]`; it also handled the 12 files under a platform `cfg` (the names the other platform needs sit under - `#[cfg(not(target_os = "linux"))]`) and the test modules. `drop_allow_unused.py` removed `#[allow(unused_imports)]` and what it hid - (about 170 re-exports). The size gate caught three files that the lists pushed over 400 lines; `open_cache_steps.rs` was split off - `open_phase_steps.rs` and the other two lost a comment line. -* **Modules without `#[path]`.** `path_to_modules.py` moved each `#[path]` module to the file its name gives and its children with it (a - file loaded through `#[path]` owns its directory like a `mod.rs`, so the children move too); 420 files, no code changed. The GPU proofs - now sit beside the code they prove (`backend/native_down_*`), and they compile against `leleka-gateway-text` (a dev-dependency) instead of - including its `prompt.rs` as a module, which also stops its 33 tests from running twice. A `cfg(feature = "preview-path")` attribute had been - read as a `#[path]` attribute by `rust_modtree.py`, which hid two modules from every earlier tool; fixed there and in the low-level copy. - Gates that quote source paths follow: `smoke-groups.json` (directory patterns), the `docs/gpu-bringup.md` table, the oracle pin path, the - source scan of `tests/bringup_prints_gated.rs`. -* **Names.** 50 modules renamed with `rename_module.py` for what they hold: the `*_methods` groups (`moe_cache_ops`, `stack_phases`, - `round_steps`, ...), the `*_and_*` files (`dense_cache_teardown`, `chunk_run`, `mirror_compute`, ...), the `*_sdet` test targets - (`reset_replay_proof`, `directory_limit_tests`, ...), the `*_types` files and `qwen4exp_input` / `qwen4exp_kar_ple` (`weight_binding`, - `kar_ple_source`). The test ids of the renamed test modules changed with their path. Not renamed: 50 more `*_and_*` / repeated-prefix names - that six readers proposed (the list is in the commit `claude/debt-docs`); each needs its callers read. -* **Docs.** 449 generated headers (`Methods of ...`, `Functions: ...`, `Split out of ... to keep its files under the line limit`) are real - descriptions of what the file is and why it is separate; six readers wrote them from the code, the diff is comment lines only. -* **`dyn`.** `&mut dyn StateMemory` / `dyn SessionEngine` of `engine-core` are generics; the `cancel` / `emit` callbacks of the request - layer (`RequestOwners`, the stack's prefill and decode entry points) are `impl FnMut`; the prompt composer is generic over its callback and - hooks. - -Left, with the reason: - -| What | Why | Next step | -|---|---|---| -| `Governor::global()` (22 sites in 12 files) | the handle has to travel through `StackConfig`, the request environment and `PrefixServe`; each site is cold, but the plumbing touches the load path | one `MemoryHandle` built from what `memory_governor::startup` returns and carried in `StackConfig`; then `memory_governor`'s free functions become its methods | -| `serving_cells()` (33 sites in 27 files) | the bound is an immutable process constant after start-up; the call sites are position and prompt-length checks on the decode and prefill paths | a `ServingBound` handle on the session and the request, with the identity gate | -| 9 `dyn` of the hot path: `OriginalServePool` (host), `GdnGemm` (prefill batch), `Drain` (prefill profile) | per-round and per-layer calls; the change is semantics-neutral but touches the decode loop and the prefill ring | branch `claude/debt-hot-engine`, not merged before the laptop identity run | -| `settings::process()` | leaf code that cannot take a parameter | S13/S14 | - -### (d) Other open items of this file (unchanged by the pass; the owner's order for them) - -1. S13/S14 injection: `settings::process()`, `Governor::global()`, `INSTANCE`/`RECONFIGURING` and the clock into the engine stack (sections S13, S14, S19 below). Blocks most of the `process-global` and `instant-now` numbers of (b). -2. The decode-phase glue and the MTP window loop: `generate_mtp_resume` (250 lines, complexity 44), `generate`, `OriginalServeStack::open` (section `backend/`); needs the GPU identity and A/B gates, so it is a step of its own. -3. `WeightSource` follow-ups: shard open and bind, KAR verification, the governor's mappings (section S18). -4. Gateway: `create` (391 lines), `render_request_with` (385) and the other entries of the limits table at the end of this file. -5. Done in the second pass of (c): the `leleka-memory` governor is `governor/operations/{admission, setup, status_report, archive_guard, archive_residency_tick}.rs`. - -## crates/engine-qwen35-cuda `backend/` (formerly leleka-runtime; STRA-338 S5a, S5b) - -`backend.rs` (3797 lines) is a parent of 258 lines plus responsibility-named children. `serve_load` is decomposed -into `load.rs` (the order of the phases) and `load_admit`, `load_sources`, `load_identity`, `load_bind`, `load_cuda`, -`load_weights`, `load_moe`, `load_moe_gates`, `serve_loop`, `serve_generate`, `serve_run`, `serve_report`, -`serve_close`; all of them are inside the -limits except the one line named first. What was moved verbatim in S5a and is still outside the limits: - -| Where | Misses | Removed by | -| --- | --- | --- | -| `load_moe_gates.rs`, the `learned_main_lru` constructor call | one line of 127 columns: the method name of `MoeWeightCache` is 119 characters | renaming the constructor in `qwen_forward/moe_weight_cache` (its own step) | -| `generate_mtp.rs` `generate_mtp_resume` | 250 lines, complexity 44 | splitting the MTP window loop into phases (still open after S19: the loop holds CUDA owners and stayed in the adapter; GPU identity and A/B gates apply) | -| `generate.rs` `prefill_chunk`, `generate`, `step`, `target_step` | 90, 60, 55, 34 lines; complexity 14 and 10 | same step as above | -| `spawn.rs` `spawn_backend_configured` | 100 lines; recomputes the policy flags that `PolicyFlags::of` now owns | use `PolicyFlags::of`, split the owner hand-over | -| `spawn_optimized.rs` | seven factories of 32 to 39 lines repeating one precondition block | one `OptimizedSelection` check shared by the factories | -| `sources.rs` `verify_sources_parallel` | 42 lines | splitting the scoped verification (the profile read moved to the WeightSource port in S18 and is within the limits) | -| `proxy.rs` `start_generation`, `validate.rs` `validate_handle` | 44 lines; 46 lines and complexity 14 | splitting the checks into predicates | -| `config.rs` | the `*_EXECUTION` identity strings are single lines of 120 to 200 columns | string continuation, with the golden digest test as the guard | - -Process-wide state and reads that the policy file `architecture.json` counts and that this directory still holds: -`RECONFIGURING` and `INSTANCE` (process atomics that `config.rs` still owns, see S14 below), and the -`Box` returned by the factories (startup composition only). The `Instant::now()` sites of `generate*.rs`, -`utf8.rs`, `sources.rs` and `GPU_ORDINAL` moved in S14. The environment reads that were here (`LELEKA_ORIGINAL_SERVE_GGUF_PLE`, `LELEKA_PUBLIC_EVALUATION`) now read `Settings` -(S13, below). - -`qwen_forward/moe_weight_cache.rs` gained three `pub(crate) use` lines (`AdaptiveWitness`, `LearnedMainWitness`, -`SharedPermanentWitness`) so the witness gates in `load_moe_gates.rs` can name the types; no code changed there. - -## crates/engine-qwen35-cuda `settings/` (formerly leleka-runtime; STRA-338 S13) - -Production code in leleka-runtime no longer calls `std::env`. `settings.rs` holds the port (`EnvSource`, with the -`ProcessEnv` adapter and the `MapEnv` fixture) and `Settings`: the operator namespace (`LELEKA_*`, `STRATA_*`) is -captured once, the plain switches and numbers are typed fields of five topic structs (`serve`, `decode`, `memory`, -`kv`, `diagnostics`), and the parsers that report errors (conversation cache, PLE reader, expert tier, memory -governor, the speculative engine, adaptive config, NaN guard, sampler path) read the capture through -`Settings::env()`. Each topic has golden tests with a `MapEnv` (`settings/*_tests.rs`, `tier_env_tests.rs`, -`original_serve_engine/env_tests.rs`). The `env-read:leleka-engine-qwen35-cuda` ratchet (`env-read:leleka-runtime` when this was written) is 1: `ProcessEnv::get_os` is the only -`std::env::var_os` left (`vars_os` in `entries_with_prefix` does not match the pattern). The ratchets now count -production code only: a file declared under a test cfg, and everything it declares, is skipped. - -What is still outside the port, and why: - -| Where | What | Removed by | -| --- | --- | --- | -| `settings::process()` | one `OnceLock`: leaf code (the nine `driver_error` functions, the GDN/prefill switches, the serve loop traces) cannot take a parameter without threading it through hundreds of `map_err(driver_error)` calls; `LoadEnv::settings` carries it on the load path, the rest asks `process()` | injecting the settings (and the clock, S14) into the executors and the stack. S19 extracted the pure policy only and `engine-core` takes no `Settings`, so this is still open | -| `leleka-cuda-driver` (76 reads, 96 keys) | the driver parses its own options (`OriginalStagerOptions`, `OriginalResidentOptions`, the draft vocabulary, `logpos_topk_from_environment` and others); runtime never calls them, the driver does | a settings crate below the driver (L1) that both crates use, then the same capture-and-topic move | -| `leleka-native-cpu-expert` (19), `leleka-gptoss` (6), `leleka-model-format` (5), `leleka-libc-shim` (4), `leleka-memory` (3), `leleka-deploy` (41), `leleka-control-plane` (19), `leleka-engine-host` (15) and the other CPU/iGPU/NPU crates | same pattern in their own crates; deploy sets the child's environment on purpose | follow-up steps per crate, after the settings crate exists | -| `memory_governor`, `ResidentPolicy::from_environment` | public or crate-wide entry points keep their signature and read `settings::process().env()` | callers pass the capture once the load path owns a `Settings` reference everywhere | -| replay and GPU proof modules (`backend_original_serve_replay.rs`, `gpu_proofs/`) | read their operator inputs from `std::env` | test-only, not counted | - -Keys whose spellings differ on purpose (kept as they were, not unified): - -- `LELEKA_SPEC` is read twice: as a number (trimmed, malformed ignored) and as set-ness (decides whether the adaptive - window is the default, so a malformed value still switches it off). -- On-by-default switches use three families: off only for exactly `0` (prefill group, per-layer sizing), off for `off` - or `0` (overlap, adapt defer, span cache, swap wait, eager admission), packed unless `0` or `off` (dense slab). - Opt-in switches use exact words: `1`, `on` (loan tiers, refill defer, locked-only), `1|on|yes` (embed alias), - trimmed `1|on|yes|true` (legacy footprint), `on|1` (draft after commit), `serial`, `full`, `lag`. -- Trimming differs per number: trimmed for `LELEKA_SPEC*`, tail skip, prefix retention, `STRATA_PREFILL_STREAM_MIN`; - untrimmed for the CPU worker count, the GiB budgets, the cache-fail count, the logprob depth and the adaptive tuning. -- Set-ness switches (`LELEKA_BRINGUP_TRACE`, the trace group, `STRATA_CKPT_REREAD`) are on for any value, `0` and the - empty string included; `LELEKA_SPEC_TRACE`, `_STATS` and `LELEKA_SERVE_PROFILE` are off for `0` and empty. -- `LELEKA_PCIE_AUTO` selects two modes by two words (`lag`, `on`); `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED` accepts NaN; - `LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB` only counts over a file-mapped bank (the check stays at the call site). -- A malformed value is refused (conversation cache, PLE reader, expert tier, memory governor), logged and replaced by - the default (NaN guard, adapt decay), or ignored (everything else), exactly where it was before. - -No key is re-read at run time through the port. Reads that used to happen per request, per chunk or per error and are -now fields of the capture: `LELEKA_CAPTURE_DIR`, `STRATA_OLD_SAMPLER` and `STRATA_SAMPLER_ONE_BLOCK` (per request), -`LELEKA_PREFILL_STREAM`, `STRATA_PREFILL_STREAM_MIN`, `LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED`, -`LELEKA_TRACE_PREFILL_R`, `LELEKA_PLE_AHEAD_VERIFY` (per prefill chunk or batch), `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED` -(per decode phase), `LELEKA_TRACE_DRIVER_ERRORS` (per error). Nothing in the process sets an environment variable -after start, so the values are the same. The one live toggle is the file named by `LELEKA_CPU_PREFETCH_OFF_FILE`: the -path is a setting, its existence is still asked of the file system on every call. The replay harness overrides -(`set_span_cache_override`, `set_pool_override`, `set_sized_override`, `set_tail_skip_arm`, `PREFILL_STREAM_OVERRIDE`) -keep their atomics; with no override they follow the settings. - -Functions this step touched that were already over the limits (a few lines changed inside each, not made worse): -`memory_governor::startup` (63 lines), `backend_original_serve::{generate, run}`, `OriginalServeStack::open` -(259 lines), `OriginalPromptExecutor::forward`, `KarPleCache::stage_batch`, `DirectTier::with_path`, -`ExpertTierConfig::from_source` (67 lines, 16 branches: it was `from_environment`), `seed_residency`, -`spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots`, and three lines of 144 to 173 columns that -were already there (`impl_default_for_ttftmarks.rs` header, `impl_originalservestack_2.rs` arm lines, -`backend_original_serve.rs` capture call). - -## Clock and MemoryPressure (STRA-338 S14) - -**Clock** (`leleka_obs::time`, `time/clock.rs`): `trait Clock { fn now(&self) -> Instant; fn since(&self, earlier: Instant) -> Duration }` -with `SystemClock` (zero-sized, the only production `Instant::now()` of the port), `ManualClock` (shared timeline, -`advance`, and `ticking(step)` which moves after every reading so a polling loop with a deadline ends in a known number -of rounds), `AnyClock` (an enum of the two, for the owner that cannot be generic) and `Stopwatch` (a clock plus its -start: "milliseconds since"). The reading stays a plain `Instant`, so values from either clock are stored and compared -as before. Rule: a clock is read at coarse points (a request, a tile, a decision, a sampling tick); hot loops compare -against the reading taken at their start (`run.clock.since(start)` is a statically dispatched call on a generic `C` -that is `SystemClock` in production). - -Where it is injected: - -| Place | How | -| --- | --- | -| `Generation` (`generate.rs`, `generate_mtp.rs`) | the request start and the per-step deadline checks; `LoadEnv::clock` hands `SystemClock` to `build_run` | -| `emit_terminal`, `emit_event` (`utf8.rs`; the second one replaces two identical copies in `generate.rs` and the Original serve loop) | the 30 s backpressure limit | -| `verify_sources_parallel` | one reading per phase, passed to `load_clock::span` | -| `measurement::Recorder` | prefill and decode durations of an observed request | -| Original serve loop (`backend_original_serve.rs`, `Run::clock`) | request deadline, telemetry instants, reconfigure duration, `idle_sweep::IdleSweep` (the 15 s housekeeping cadence, its own tested type) | -| `StackConfig::clock: AnyClock` | TTFT marks, the seed plan timers, the prefix device phase timers, and the clock of `PrefixServe` | -| `PrefixServe::with_clock` (a `Stopwatch`) | the retention scale (`wall_ms`, now milliseconds since the cache was built instead of a process `OnceLock`: only differences are used) and the lookup, import and park timers | -| leleka-memory: `Governor::with_parts`, `Ledger::with_clock`, `telemetry::start_with_clock`, `request_started_at`/`tokens_delivered_at`, `smi::probe_with_clock` | uptime and shed cadence, stage timing, the sampler tick, the in-flight request clocks (the old entry points call the same code with `SystemClock`) | - -Still on `std::time::Instant` on purpose: the per-window and per-miss timers of the CPU expert pool, lookahead, -residency lag and the verify engine, the prefill/GDN profile spans, `owner_wall_profile` (diagnostics inside the -decode loop, one reading per kernel or per miss: a clock parameter there is a later step: S19 extracted the pure policy only and `engine-core` has no clock); `load_clock.rs` -(a process-wide lap printer behind a `Mutex`); `DBG_T0` (debug trace epoch); `open_tier_fn` (one startup log line); -`smi::query` (a subprocess wait loop, real I/O). The gateway and control-plane crates keep their own sites for the -gateway track. - -**MemoryPressure** (`leleka_memory::pressure_port`): `trait MemoryPressure: ProcSource + Send + Sync { fn facts(&self) -> HostFacts }`. -`ProcPressure` is the production adapter (`/proc` and `/sys` on Linux, the Win32 text renderings of -`winproc.rs` on Windows, parsed by `HostFacts::probe` exactly as before); `ScriptedPressure` hands out one scripted -reading per probe, the last one repeating (`available_mib(&[..])`). The governor reads the host only through it -(`probe`, `available_now`, the sample, the lock allowance and the heal check); it is also a `ProcSource` because the -residency guard and the census still read single files (`smaps`). `Governor::new(cfg, Arc)` keeps its -signature; `with_pressure` and `with_parts(cfg, pressure, AnyClock)` are the composition points. Tests drive rising, -falling and flapping pressure, the once-a-second shed step, the stale-sampler fallback and the admission decisions -without a sleep (`governor/pressure_tests.rs`). - -Process globals: `GPU_ORDINAL` is gone (the ordinal travels in `Run`, the value it always had), and the retention -`OnceLock` with it. Left, and why: `RECONFIGURING` (one flag for every backend of the process; moving it into -`Shared` would make concurrent backends independent, which is a behaviour change for a process that hosts two), -`INSTANCE` (the owner id counter that `spawn_backend_configured` draws from; it needs a spawner object that the callers -do not have), `Governor::global()` (about twenty calls in the runtime; they need a memory handle on the stack, the -conversation manager and the prefix cache, the same open move as `settings::process()`, which S19 did not make), `serving_cells()` (30 reads of -one validated constant), the two `std::cell::OnceCell` fields (per-instance lazy cells that the pattern also matches), -`NO_TRIM_FILE`, `heap::OFF` and `TUNING` (environment caches that belong to the Settings follow-up). - -Ratchets (totals over the workspace): `instant-now` 242 -> 209 (leleka-runtime 42 -> 17, leleka-memory 12 -> 1, -leleka-obs 0 -> 3 for the three adapters), `process-global` 267 -> 265, `dyn-trait` 215 -> 215. Functions this step -touched that were already over the limits and are not made worse: `Governor::with_parts` (35 lines, the old `new` had -34), `seed_residency` (34, as before), `guard_archive_extents`, -`residency_tick`, `telemetry::render`, the Original serve `generate` and `run`, `decode_phase`, `OriginalServeStack::open`. -Follow-ups: thread one clock and one memory handle through the engine stack (S19 extracted the pure policy only, so this is still open), after which -`StackConfig::clock` and `LoadEnv::clock` become the generic parameter of the stack; a settings crate for the -environment caches above; `RECONFIGURING` and `INSTANCE` with a spawner object. - -## Request lifecycle seams and the FakeDevice (STRA-338 S15) - -**What was found.** The engine already has a device seam at every granularity the lifecycle needs, each a trait that -the real CUDA path implements and that production code is generic over (no `dyn` per round, chunk or token): - -| Granularity | Trait (file) | Real implementer | Driven by (production code) | -| --- | --- | --- | --- | -| request | `RequestOwners` (`original_serve_request.rs`): `is_fresh`, `reset`, `resume`, `prefill`, `decode`, `finish` | `OriginalServeStack` | `run_request`: admission, cancel, resume or reset, finish | -| request layer | `ServeDevice` (same file, new in S15): `serve`, `reused_tokens`, `last_timing`, `expert_tier_stats` | `OriginalServeStack` (delegates to its inherent methods) | `generate` of the Original serve loop: events, usage, deadline, telemetry | -| prefix cache | `PrefixDevice` (`original_serve_prefix.rs`): `position`, `park_*`, `import`, `restore_draft` | `OriginalServeStack` | `PrefixServe`, `PromptPlan` | -| verify round | `OriginalServePort` (`original_serve_engine.rs`): `run_window`, `commit_window`, `draft_committed`, checkpoints | `NativeServePort` | `OriginalServeEngine`, `OriginalSpecController`, `serve_request` | - -S15 added only `ServeDevice`: `generate` took `&mut OriginalServeStack` and now takes `&mut impl ServeDevice`; the four -calls it makes (one per request) go through the trait, the stack's methods are the same functions called by the same -code. `serve` is generic over the two closures (no `dyn` was added). The runner module is `pub(super)` so the tests can -call `generate`. Nothing in the hot decode loop, the kernels, the launch order, the log text or the environment reads -changed, so the production path is the same code as before (checked: the lib test ids and the warning count are -unchanged, see below; no GPU run was possible). - -**Decision: the CUDA path was not moved onto a new trait.** It is already on the four above. What stays concrete is the -glue between them, `prefill_actions` and `decode_phase` of `OriginalServeStack`, because both hold CUDA owners -(`executor`, `session`, the verifier assembly with its fallback, the expert tier lend/refill/seed). Making that glue -generic touches the decode phase (engine construction, `settle_state`, tail checkpoint) and the prefill phase (tier -hooks), which is the S19 step and needs the GPU identity and A/B gates. So the test device mirrors the glue instead -of sharing it (see "What the fake mirrors"). - -**FakeDevice** (`qwen_forward/original_serve_stack/lifecycle_fake*.rs`, `cfg(test)`): - -- `FakeDevice` implements `OriginalServePort` and `PrefixDevice` over one scripted state: a positional buffer of one - token per cell, a digest of the tokens read in order (the recurrent state), the committed branch, an asynchronous - commit published by `wait_commit`, and a log of what the lifecycle asked of it. -- The model is a fixed permutation of the printable ASCII range (`model`), so the text of any request is known whatever - the acceptance pattern. `Script` says how long a chunk and a round take on a `ManualClock`, how many drafted tokens - each draft call gets accepted (`accept`, the last entry repeats), and where one chunk or one round fails or the client - cancels (`fail_chunk`, `fail_round`, `cancel_in_round`; each fires once). -- `FakeStack` implements `RequestOwners` and `ServeDevice` over it, with the prefix cache on a 256-token grid when asked. -- Tests (`backend/lifecycle_tests.rs`, `lifecycle_tests/ends.rs`, `lifecycle_tests/prefix.rs`) drive the real - `generate` and `run_request`, `PromptPlan`, `PrefixServe`, `OriginalServeEngine`, `OriginalSpecController` and - `serve_request`: normal completion and the order of resume, prefill, rounds and finish; the length limit at exactly - `max_new` for three acceptance patterns; an EOS inside a round (counted, no text); partial acceptance (the committed - rows per round `1, 3, 1, 2, 4` for the script `2, 0, 1, 3`, windows of 1 then 4 rows, text unchanged); client cancel - in a decode round, then the next request after a reset; the 24 h deadline expiring between rounds and between - prompt chunks (a `ManualClock`, no sleep); a device error mid-prefill and mid-round (both checkpoints restored, the - next request served); a request refused by admission and one cancelled before the first owner call (no owner touched); - `prefill_ms` and `decode_ms` and the number of rounds against the clock; a prefix hit (deepest grid point, reuse of - 512 tokens, the cells written back after another session, the resumed read ending in the full read's digest); a - cancelled request keeping the checkpoints and a failed one dropping them. - -**What the fake mirrors, and what it does not cover** (the list S19 and S20 work from): - -| Gap | Where | Removed by | -| --- | --- | --- | -| `FakeStack::read_prompt`/`serve_rounds` repeat the plan, cancel, chunk and prefix bookkeeping of `prefill_actions` and the engine/controller/serve-loop part of `decode_phase` | `lifecycle_fake/stack.rs` (about 100 lines) | S19, below | -| text stop sequences | the gateway, not the engine: the engine stops on the EOS ids, `max_new` and the context | gateway track | -| `TailMode::Reply` (`after_decode`), the conversation cache (`ResumeDevice`), the lend/refill/seed hooks of the expert tier | fake has no decoded cells, no `ServeConversation`, no tier | S19 hooks below | -| NaN guard retry, adaptive window, the `broken` poison of the stack | `Script` has no non-finite output, `FakeStack` has no `mark_broken` | `Script::nonfinite_round`, then the stack's `broken` once the owners are behind a trait | -| telemetry and the `PREVIOUS_TIER` static written by `generate` | process-wide, tests assert nothing on them | S19: pass a request sink to `generate` | -| `generate` (about 140 lines), `OriginalServeStack::open` | unchanged | S19 | - -**Status after S19e, S20 and S22.** The design below was not carried out as drawn. S19e moved the sequencing of one request into -`leleka-engine-core::request` (`Lifecycle`, `run_request`, generic); the adapter's `RequestOwners` reach it through the wrapper struct `Owners` -(`original_serve_request.rs`). `PromptDevice`, `DecodeDevice`, `read_prompt` and `decode_request` do not exist in the code, `prefill_actions` and -`decode_phase` are still methods of `OriginalServeStack`, and `FakeStack` still mirrors them (`lifecycle_fake/stack.rs`), so the gaps in the table -above are open. The design text is kept as the plan for that step. - -**S19 design: one generic lifecycle for the stack and the fake.** Move the glue out of `OriginalServeStack` into -`qwen_forward/original_serve_lifecycle.rs`, generic over the device (monomorphised, called once per request or per -chunk, never per token): - -```rust -/// Condition prompt[resume..n-1] into the session, one chunk per action (prefill_actions without the CUDA setup). -pub(crate) trait PromptDevice: PrefixDevice { - fn position(&self) -> Result; // session.target_origin()?.next_position() - fn read_chunk(&mut self, prompt: &[i32], first: usize, count: usize, cancel: &mut impl FnMut() -> bool) -> Result<()>; - fn after_action(&mut self, prompt: &[i32], action: &PromptAction); // conversation cache hook -} -pub(crate) fn read_prompt( - dev: &mut D, prefix: Option<&mut PrefixServe>, plan: PromptPlan<'_>, prompt: &[i32], - cancel: &mut impl FnMut() -> bool, -) -> Result<(), SpecError>; - -/// Open the decode side for one request and close it again (decode_phase: assemble ... settle_state/disassemble). -pub(crate) trait DecodeDevice { - type Port: OriginalServePort; - fn open(&mut self, request: &ServeRequest) -> Result; - fn close(&mut self, port: Self::Port, result: &Result, want_tail: bool); -} -pub(crate) fn decode_request( - dev: &mut D, controller: &mut OriginalSpecController, settings: &OriginalServeSettings, request: &ServeRequest, - emit: &mut impl FnMut(&[i32]) -> Result<()>, cancel: &mut impl FnMut() -> bool, clock_ms: impl FnMut() -> f64, -) -> Result; // OriginalServeEngine::new(port, ..), set_min_p, serve_request, close -``` - -`OriginalServeStack::prefill_actions` and `decode_phase` become thin wrappers that build the plan options, call the two -functions and keep the tier lend/refill/seed, the verifier assembly and `settle_state` in `open`/`close`; `FakeStack` -calls the same two functions with the `FakeDevice` and the 100 mirrored lines go. The serve loop itself -(`serve_request`) and `OriginalServePort` are untouched, so the per-round path keeps its shape. Gates for that step: -GPU identity (greedy output and tensor values against the baseline) and a paired A/B on the 5090 before it is merged. - -Checked for S15 (WSL, no GPU): `leleka-runtime` lib test ids 767 -> 781 (14 added, none missing; the two known failures -`failed_cleanup_or_replaced_inode_never_deletes_unowned_file` and `frozen_same_fd_hash_owner_and_source_independence` -fail on both sides); `cargo check --all-targets -p leleka-runtime -p leleka-deploy` warnings unchanged (243 lines -starting with `warning`); clippy on `leleka-runtime --all-targets` gives the same warning set as the S14 tip and none in -the new files; the architecture gate reports 0 errors and no ratchet moved (`dyn-trait` stays at 68: `ServeDevice::serve` -is generic over the closures). Functions touched and already over the limits, not made worse: `generate` (about 140 lines). - -## WeightSource (STRA-338 S18) - -**The port** (`leleka_model_format::weight_source`, layer L3 next to the code that owns the files; no new crate edge): - -```rust -pub trait WeightSource { - fn identity(&self) -> WeightIdentity; // sha256, bytes, Verification, BackingKind - fn region(&self, range: Range) -> Result, WeightError>; - fn len(&self) -> u64; fn live_len(&self) -> Result; // live_len: did the store grow or shrink? -} -pub enum Region<'a> { - Resident(&'a [u8]), // addressable store: the slice, the same address every call - Positional { file: &'a File, offset: u64, len: u64 }, // file / sealed memfd: read_at(..) fills the CALLER's buffer -} -pub fn sha256_of(source: &S, scratch: &mut [u8]) -> Result<[u8; 32], WeightError>; -``` - -`BackingKind` is `Memory | HugePages | MappedFile | File | SealedMemfd`; `Verification` is `Unverified | FullPass | Stamp | -AttestedMemfd | SparseExtents` (`From`). The trait has no `Send`/`Sync` bound (a mapped tensor owns a raw -mapping). It is generic, not `dyn`: callers write `S: WeightSource + ?Sized`, so `&dyn WeightSource` also works, and the -`dyn-trait` ratchet did not move. A source is opened once per load and read at load time; nothing is on the decode path. - -**No second copy by accident.** A source lends borrowed views of its single backing store and has no method that returns -an owner of the bytes. The only owned buffers are the caller's: the scratch of `sha256_of` / `for_each_chunk`, the -staging packet of `stage_window`, the profile buffer of `read_ranked_expert_profile`, each created and sized by the -caller. Tests: `memory_source_...`, `mapped_tensor_source_...` and `retained_tensor_source_returns_the_same_address_for_every_call` -(the same pointer on every call, and sub-ranges are offsets into the first), `positional_sources_expose_no_address_...` -(a file or memfd region has no slice, only `read_at` into the caller's buffer), `every_adapter_reports_the_same_digest_for_the_same_bytes` -(mem double, file, verified shard, all against `Sha256::digest`, with scratch sizes 1, 7, 33 and 4096), and -`the_production_port_has_no_owning_copy_method`, which scans the production files of the port for `to_vec`, `to_owned`, -`into_boxed_slice`, `Vec`, `Box<[u8]>`, `Arc<[u8]>`, `Rc<[u8]>` and `Cow<` (only the double in `mem.rs` owns bytes). - -**Adapters (all wrap existing code; none changes what a load maps, copies or reads):** - -| Adapter | Over | Backing, verification | -| --- | --- | --- | -| `FileWeightSource>` | any open file or sealed memfd, owned or borrowed (`&File`) | `File` or `SealedMemfd`; the identity the caller gives, `unverified(..)` or `hashed(..)` | -| `impl WeightSource for VerifiedGgufFile` (`gguf/impl_verifiedgguffile/port.rs`) | the retained verified descriptor of a shard, positional | `File`, `FullPass` (matched at open, by hash or by a current stamp: the stamp case is not recorded, see below) | -| `ResidentWeightSource` (`VerifiedGgufFile::{mapped,retained}_tensor_source`) | the `ResidentTensor` the bank already owns | `MappedFile`, `Memory` or `HugePages`; digest of the artifact, `bytes` of the tensor | -| `impl WeightSource for KarInspection` | the archive descriptor of the KAR reader | `File`, `Unverified` with a zero digest (inspection checks structure and CRCs, the pin lives with the verifier) | -| `InheritedKarArchive::weight_source()` (runtime) | the admitted sealed memfd or read-only file, borrowed | `SealedMemfd` or `File`, `Unverified`, the pinned archive digest (the digest of the extents when sparse) | -| `MemWeightSource` | an owned `Vec` or `&'static [u8]` | `Memory`, `FullPass`; the test double | -| `WeightRange<'a, S>` | any source as a `kar_levels::RangeSource` | the refusals of `KarInspection::read_exact_at` (range, overflow, changed length) | - -**Migrated:** `read_ranked_expert_profile` (load phase `read_profile`, once per load) opens the pinned profile through -`FileWeightSource` and reads it with `read_pinned_profile`; same refusal texts in the same -order (`unrecognized`, `unavailable`, `extent mismatch`, `exhausted`, `read failed`, `digest mismatch`, `domain mismatch`), -same buffer (`try_reserve_exact(len + 1)`, one `Vec` of `len`), same digest; a file that ended early or grew after the -length check is the digest refusal, as when the profile was read to its end (`live_len`). Tests in `backend/profile_tests.rs`. -`stage_window` (the KAR expert staging) accepts any source through `WeightRange`; `KarExpertSource` still passes its two -`KarInspection`s, which keep their own `RangeSource` impl, so its behaviour did not move. - -**Deferred, and why (each is a step with its own gates; none is half-done):** - -1. Shard open and bind. `VerifiedGgufFile::open(path, digest)` hashes and indexes by path, and `Qwen4ExpArtifact::bind` - takes the concrete files; `stream_tensor` / `read_tensor_into` read through the retained descriptor with a seek - and a 16 MiB stream buffer. Moving them onto `Region::read_at` changes syscalls (seek+read to pread) and on Windows the - shared file cursor (`seek_read` moves it; `read_exact_at` of the port documents that), and `bind` reads the metadata - with the cursor. Plan: (a) give `VerifiedGgufFile` a `StreamSource` seam in the same file that the port impl uses, keep - the stream buffer; (b) switch `stream_tensor` to the port with an strace/read-count comparison on the laptop file; - (c) let `ExpertFileOwner` and the bank keep a `ResidentWeightSource` instead of a `ResidentTensor` (same value, the type - rename); (d) record stamp-vs-hash in `VerifiedGgufFile` so `identity().verification` can say `Stamp`. -2. KAR verification and row reads. `load_pinned_inherited_archive` re-opens the admitted descriptor into an owned `File` - that `KarInspection::inspect` consumes, and `verify*` hashes with `bulk_read` (O_DIRECT, many threads: it needs the - `File`, not slices); `KarPleRowReader` duplicates 16 handles. Plan: `Region::file()` for the bulk strategy, `verify*` - taking `&impl WeightSource`, the row reader taking the port; the 55 GB hash time and the `leleka-kar-startup` line are - the A/B guard. `sparse` archives need an `extents()` accessor on the identity (a hole reads as zeros through the port). -3. CPU expert tier (`leleka-native-cpu-expert`, `ExpertFileOwner`): the bank is C++-owned memory filled from the GGUF by - native code, so the port would have to lend raw pointers across FFI. Needs its own review of lifetimes; left alone. -4. The memory governor's mappings (`archive_handle()`, `guard_archive*`) still take the `File`; they map, they do not read. - -Checked for S18 (WSL, no GPU): `leleka-runtime` lib test ids 781 -> 787 (6 added, none missing; the two known failures -`failed_cleanup_or_replaced_inode_never_deletes_unowned_file` and `frozen_same_fd_hash_owner_and_source_independence` -fail on both sides); `leleka-model-format` lib 155 -> 166 passed (11 added; the three `qwen4exp` tests that replace -files under `/mnt/c` fail with "size changed after verification" on the S15 tip and on this one alike); -`cargo check --all-targets -p leleka-runtime -p leleka-deploy` warnings unchanged (243 lines starting with `warning`); -clippy on both crates reports nothing in the new or changed files; the architecture gate reports 0 errors and no ratchet -moved (`dyn-trait` unchanged: the port is generic); no `unsafe` was added (the only mapping owner stays `FileSpan`). -Functions touched and already over the limits, not made worse: `verify_sources_parallel` (42 lines, not edited). - -## Engine core, family seam and adapter crate (STRA-338 S19 to S22) - -Layer picture, ports and numbers: `docs/architecture/hexagonal.md`. This section records what each step moved, what it left, and why. - -**What moved to `leleka-engine-core` (L2; depends on `leleka-backend-api` and `serde` only).** Each step is one commit; the old paths -are re-exported by the adapter (`pub use leleka_engine_core::...` in `crates/engine-qwen35-cuda/src/lib.rs` and `crates/engine-qwen35-cuda/src/conversation/mod.rs`). - -| Step | Commit | Module in `engine-core` | Left in the adapter | -|---|---|---|---| -| S19a | `38eb771a4` | `prefix_cache` (hash chain, budget, store, summary), `memory` (pure admission, `memory_admit`) | `PrefixServe` and `PrefixDevice` (`qwen_forward/original_serve_prefix`): they drive the CUDA state | -| S19b | `d717c6977` | `prompt` (`PromptPlan`, `PromptOptions`) | the serving-context cell bound is a separate constructor the adapter calls (it needs `leleka-context`) | -| S19c | `93afb07bf` | `conversation` (cache, manager, snapshot, kv, state, model, binding, retention) | the CUDA-owner bindings (`conversation/original.rs`, `conversation/resident`) | -| S19d | `8987e9ab0` | `spec` (draft policy, adaptive window policy) | `LELEKA_SPEC_*` parsing (a free function reading `Settings`), the controller and the device round | -| S19e | `58e3d864e` | `request` (`admit`, the stop set, `ServeError`, `Lifecycle`, `run_request`) | `RequestOwners` and the `Owners` wrapper that implements `Lifecycle` over them | -| S20 | `e049e24fe` | `family` (`EngineFamily`, `spawn::`) | `Qwen35Cuda` (`backend/family.rs`) wraps `spawn_backend` and `spawn_backend_original_serve` | - -**Why the rest stayed in `leleka-engine-qwen35-cuda`.** It holds CUDA owners and the owner thread (`backend/`, `qwen_forward/`), reads the process -environment through `Settings`, uses `Instant::now()` (17 sites) and process globals (59), includes files with `#[path]` (100), and calls the -driver, the model-format reader and the native CPU expert. None of that can be in a crate that is built and tested without a GPU. The fake lifecycle -device (`lifecycle_fake`, S15) keeps mirroring the glue `prefill_actions` and `decode_phase`. - -**What S19 did not do.** `settings::process()` (a `OnceLock` read by leaf code), `Governor::global()`, `RECONFIGURING`, `INSTANCE`, -`StackConfig::clock` and `LoadEnv::clock` are all still in the adapter, and `engine-core` takes no `Settings`, clock or memory handle. The S13 and S14 -follow-ups that said "when the engine core is extracted (S19)" are therefore open. `generate_mtp_resume` (250 lines, complexity 44) and `generate` -did not move either. - -**The `dyn-trait` increase of S20 (+4).** The commit message of `e049e24fe` says the ratchets were raised by the `Box` signatures of the -seam; the baseline diff of that commit shows `dyn-trait:leleka-engine-core` 17 to 19, `dyn-trait:leleka-engine-fake` 0 to 1 and -`dyn-trait:leleka-runtime` 51 to 52. The four lines are `EngineFamily::spawn` and the free function `spawn` in `crates/engine-core/src/family.rs`, -`EngineFake::spawn`, and `Qwen35Cuda::spawn`. The same commit raised the size baseline of `desktop-core/tests/api_over_runtime.rs` from 644 to 646 -lines (the "2 test lines": the full-chain test starts its engine through `spawn::`); that is a size entry, not a `dyn` count. `Backend` -is the trait object the process already had at its boundary: `RuntimeServer` holds `Box` (`desktop-core/src/runtime_rpc.rs`) and the -existing `spawn_backend*` factories return it. Its methods are request-level and the tokens travel in the returned stream, so the seam adds no -dynamic dispatch per round or per token; the four lines are signatures. S22 renamed the five ratchet keys of `leleka-runtime` to `leleka-engine-qwen35-cuda` with the -same values (`dyn-trait` 52, `env-read` 1, `instant-now` 17, `path-include` 100, `process-global` 59). - -**Found after S22 and fixed in S26 (docs and scripts only).** `scripts/ci-coverage.json` named neither the three engine crates nor -`leleka-gateway-domain`, so `scripts/check-ci-coverage.py` failed on the S22 tip; `scripts/chain/build_rt.sh`, `scripts/decode-sm120/build_rt.sh` and -`scripts/profile/build_rt.sh` still looked for a test binary called `leleka_runtime-`; the bring-up scripts (`remote_sync.sh`, `regress_3080.sh`, -`run_gpu_smokes.sh`, `linux-tests/run.sh`) and the smoke inventory (`smoke_inventory.py`, `smoke-groups.json`) named `leleka-runtime`, whose lib target -has no tests since S22. Several documented commands did too (`docs/memory-safety.md`, `docs/original-serve.md`, `docs/windows.md`, -`docs/prefix-cache.md`, `docs/gpu-bringup.md`). Left on purpose: dated measurement records (`docs/ci-audit.md`, `docs/experiments/`, -`docs/prefill-throughput.md`, `docs/rope-and-memory-plan.md`, `docs/sampler-reference.md`, `docs/memory-safety-unsafe.md`, `docs/port-remaining.md` section 8) -and the doc comments in `crates/` (`crates/engine-core/src/family.rs` names `leleka_runtime::backend::Qwen35Cuda`; the `#[ignore]` text of -`crates/engine-core/src/prefix_cache/store/tests.rs` gives `-p leleka-runtime`). Those are code and stay for a code step. - -## leleka-gateway-domain `responses/` (STRA-338 S21, wider scope) - -The pure Responses protocol moved from `leleka-control-plane` to `crates/gateway-domain/src/responses/` with the code text -unchanged; only what the compiler or the gate forced was edited. The functions below keep the shape they had and miss the -limits (function 30 lines, complexity 10, nesting 4, 120 columns). A line count is the function as measured by -`scripts/dev` style counting (signature to closing brace). - -| File | Function | Lines | Complexity | Removes it | -|---|---|---|---|---| -| `responses/render.rs` | `render_request_with` | 385 | 58 | one function per input item kind (`message`, `reasoning`, `function_call`, `*_output`) and a small state struct for `calls`, `outputs`, `custom_calls`, `reasoning`; the file is also over 400 lines (baseline entry 405) | -| `responses/trace.rs` | `ResponseTrace::build_with_terminal` | 246 | 40 | split the checks, the item loop (one function per `OutputItem` variant) and the usage block | -| `responses/validate.rs` | `CreateRequest::validate` | 159 | 46 | one function per field group (`text.format`, tools, tool_choice, limits) | -| `responses/tool_calls.rs` | `decode_generation_noted` | 72 | 8 | the two token-count loops into one helper; nesting 5 | -| `responses/tool_calls.rs` | `parse_output_items_with` | 35 | 3 | segment to item mapping into a function | -| `responses/effort.rs` | `reasoning_effort` | 39 | 5 | field checks and the effort table as two functions | -| `messages/request.rs` | `Request::into_responses` | 156 | 28 | turn merging, block flushing, tool and choice mapping as separate functions; nesting 6 | -| `messages/reply.rs` | `message` | 22 | 10 | content blocks of an output item as a function; nesting 6 | -| `responses/harmony_conversation.rs` | `conversation` | 142 | 22 | one function per input item kind; nesting 7 | -| `responses/harmony_render.rs` | `instruction_texts`, `render_dated` | 43, 51 | 13, 5 | the constraint sentences and the tool list as separate functions (the sentences repeat `render.rs`; keep the two in step) | - -Lines wider than 120 columns remain in the `json!` bodies of `trace.rs`, in `render.rs` (string literals and a `json!`), -and in the doc comment of `tool_schema_accepted`; they are moved text. - -What changed in the move, apart from `pub(super)` becoming `pub`: - -* `render_request` -> `render_request_with(request, marks, template_span)`: the `render_template` stage span is created - by the closure the caller passes (`leleka-control-plane` keeps `render_request` with the old signature and passes - `stage_trace::span`), so the domain does not read the stage trace global. -* `parse_output_items_after` -> `parse_output_items_with(.., options) -> (items, notes)` and `decode_generation_with` -> - `decode_generation_noted(.., natural_options, on_call_in_reasoning)`: the recovery flag is the caller's - (`TOOL_CALL_RECOVERY` stays in `leleka-control-plane`) and so are the log lines (`elog!`). `leleka-control-plane` keeps both old - names as wrappers. The log line for a call written inside the reasoning is now emitted by a closure at the same point. -* `CreateRequest::apply_defaults(&Settings)` -> `apply_defaults(&MergedDefaults, &SharedDefaults)`; the one caller passes - `settings.merged()` and `settings.shared()` in that order, as the method did. -* `codec::decode_all` is generic over `C: TextCodec + ?Sized` (it took `&dyn TextCodec`), so the `dyn-trait` count of the - domain crate did not rise. -* `tool_schema_accepted` keeps its process-wide memo (a coding agent sends the same tool schemas on every request and the - schema is validated three times per request). It moved with the function, so `process-global:leleka-gateway-domain` is - 3 and `process-global:leleka-control-plane` fell from 14 to 11 (`--allow-increase` was used for the new key only; the sum is - unchanged). Removing it needs the memo owned by the gateway state and passed to `validate`, which changes every caller. - -## OutputEvent and the output decoders (STRA-338 S23) - -`crates/gateway-domain/src/output/` is new (pure, L2): `event.rs` (`OutputEvent`, `OutputError`), `token_bytes.rs` (the family's bytes), -`live.rs` (`LiveDecoder`) and `at_end.rs` (`AtEndDecoder`) with `cut.rs` (the cut of a finished generation), `harmony.rs` (the -gpt-oss decoder, moved from `control-plane/src/harmony_family.rs`), `reasoning_preview.rs`, `utf8.rs`, `fold.rs` (`output_items`); the -`` marker is `think_marker.rs`; the sampler limit of a worker is `sampler_limit.rs`. The four consumers in `leleka-control-plane` read events; `docs/architecture/output-event.md` has -the flow analysis, the table of the sites that asked for the family, the identity proof, the behaviour changes and the list of what -was kept on purpose. What it did not do: - -| Left | Why | Removes it | -|---|---|---| -| `HarmonyDecoder` writes Qwen-style markup that the shared cut and parse read | reading the channels directly changes a `` inside the analysis text and the calls-without-tools quirk; both are pinned by the golden | an owner decision, then one `Bytes` arm that emits events | -| `intake/intake_stages.rs` `render_prompt` still matches `Family`; `qwen()` for pictures, the reasoning budget and the runtime backend | input side of the codec | a prompt-rendering port | -| `GptOssCodec` lives in `leleka-control-plane` | it holds the BPE loaded from a GGUF file (`std::fs`), which the pure domain may not read | none needed; the decoder it hands out is in the domain | - -## leleka-control-plane `responses/` (STRA-338 S6, rest) - -`responses.rs` is 97 lines (module list and re-exports); its children are named for what they do: `route`, `create`, -`intake`, `render`, `reasoning`, `tool_recovery`, `stream/`, `history`, `history_adapter`, `resources`, `errors`, -`harmony_prompt`. The text of every function is unchanged (moved only); the fields and constants that siblings read -became `pub(super)`. Functions that still miss the limits (30 lines, complexity 10, nesting 4): - -| File | Function | Lines | Complexity | Removes it | -|---|---|---|---|---| -| `responses/create.rs` | `create` | 391 | 29 | admission, history lookup, prompt preparation, command build, buffered answer and stream start as separate functions | -| `responses/intake.rs` | `prepare_input_tokens` | 99 | 7 | text prompt, picture expansion and context check as three functions | -| `responses/intake.rs` | `expand_images`, `parse_request`, `count_input_tokens` | 62, 53, 34 | 2..5 | one step per function | -| `responses/history.rs` | `StoredResponse::input_page` | 76 | 18 | cursor parsing, order and limit as helpers (nesting 6) | -| `responses/history.rs` | `ResponseHistory::open`, `insert_with_limit` | 63, 55 | 19, 9 | snapshot decode and entry check as functions | - -## Limits gate and the legacy sites listed here (STRA-367) - -The limits of this page are enforced by `scripts/check-limits.py` (rules, measures, allowlist and census: -`limits-gate.md`). The sites listed in the sections above and below are legacy that was moved verbatim: none of them -is in `limits-allowlist.json` today, because the allowlist is empty on the default base (the tip of the integration -branch) and the census total in `limits-baseline.json` already counts them. They become allowlist entries the moment a -change touches or relocates them (`scripts/check-limits.py --allowlist-add --reason ... --owner STRA-338`), with the -numbers below as the starting point. Measures are the gate's own (`?` and the boolean operators count, so complexity is -higher than the hand counts above): - -| Gate key (path, name) | Lines | Complexity | Nesting | Wide lines | Listed in | -| --- | --- | --- | --- | --- | --- | -| `crates/leleka-runtime/src/backend/generate_mtp.rs` `generate_mtp_resume` | 250 | 70 | 4 | 0 | S5a | -| `crates/leleka-runtime/src/backend/generate.rs` `Generation::prefill_chunk` | 91 | 24 | 3 | 0 | S5a | -| `crates/leleka-runtime/src/backend/generate.rs` `generate` | 60 | 19 | 2 | 0 | S5a | -| `crates/leleka-runtime/src/backend/generate.rs` `Generation::step` | 55 | 10 | 2 | 0 | S5a | -| `crates/leleka-runtime/src/backend/generate.rs` `Generation::target_step` | 34 | 7 | 1 | 0 | S5a | -| `crates/leleka-runtime/src/backend/spawn.rs` `spawn_backend_configured` | 100 | 11 | 1 | 0 | S5a | -| `crates/leleka-runtime/src/backend/sources.rs` `verify_sources_parallel` | 42 | 1 | 3 | 0 | S5a | -| `crates/leleka-runtime/src/backend/proxy.rs` `Backend for Proxy::start_generation` | 44 | 10 | 1 | 0 | S5a | -| `crates/leleka-runtime/src/backend/validate.rs` `validate_handle` | 46 | 17 | 2 | 0 | S5a | -| `control-plane/src/responses/create.rs` `create` | 391 | 35 | 2 | 5 | S21 | -| `control-plane/src/responses/intake.rs` `prepare_input_tokens` | 99 | 9 | 2 | 0 | S21 | -| `control-plane/src/responses/intake.rs` `expand_images` | 62 | 7 | 2 | 1 | S21 | -| `control-plane/src/responses/intake.rs` `parse_request` | 53 | 6 | 1 | 0 | S21 | -| `control-plane/src/responses/intake.rs` `count_input_tokens` | 34 | 4 | 2 | 0 | S21 | -| `control-plane/src/responses/history.rs` `StoredResponse::input_page` | 76 | 21 | 6 | 0 | S21 | -| `control-plane/src/responses/history.rs` `ResponseHistory::open` | 63 | 25 | 3 | 0 | S21 | -| `control-plane/src/responses/history.rs` `ResponseHistory::insert_with_limit` | 55 | 12 | 2 | 0 | S21 | -| `crates/gateway-domain/src/responses/render.rs` `render_request_with` | 385 | 93 | 6 | 4 | S21 | -| `crates/gateway-domain/src/responses/trace.rs` `ResponseTrace::build_with_terminal` | 246 | 51 | 4 | 15 | S21 | -| `crates/gateway-domain/src/responses/validate.rs` `CreateRequest::validate` | 159 | 51 | 3 | 0 | S21 | -| `crates/gateway-domain/src/responses/harmony_conversation.rs` `conversation` | 142 | 42 | 5 | 0 | S21 | -| `crates/gateway-domain/src/responses/tool_calls.rs` `decode_generation_noted` | 72 | 11 | 5 | 1 | S21 | -| `crates/gateway-domain/src/responses/tool_calls.rs` `parse_output_items_with` | 35 | 6 | 1 | 0 | S21 | -| `crates/gateway-domain/src/responses/effort.rs` `reasoning_effort` | 39 | 13 | 2 | 0 | S21 | -| `crates/gateway-domain/src/messages/request.rs` `Request::into_responses` | 156 | 41 | 5 | 2 | S21 | -| `crates/gateway-domain/src/messages/reply.rs` `message` | 22 | 11 | 6 | 1 | S21 | - -The wide lines the sections list (the `learned_main_lru` call of `load_moe_gates.rs`, the `*_EXECUTION` strings of -`config.rs`) are covered, when a change touches them, by the `width` number of the entry of their function, or by the -`` entry when they are in a constant outside any function. `scripts/check-limits.py --report` prints the same -measures for the worst functions of the whole tree. \ No newline at end of file diff --git a/docs/backend-capability-admission.md b/docs/backend-capability-admission.md deleted file mode 100644 index d4755e1f..00000000 --- a/docs/backend-capability-admission.md +++ /dev/null @@ -1,11 +0,0 @@ -# Backend capability admission - -The `leleka-backend-api` contract at API version 2 describes supported models as explicit `SupportedModelTuple` entries in `BackendCapabilities.supported_models`. Each entry binds family, architecture and weight format together. Entries do not imply combinations assembled from different entries, and the default empty list supports no models. - -`supports` first validates the descriptor: identifiers must be nonempty and contain no whitespace or control characters, and the artifact digest must use the existing `sha256:` prefix with exactly 64 hexadecimal characters. It then requires one exact declared tuple. Matching is case-sensitive for tuple identifiers, with no wildcard, alias or family inference. - -The public capability layout replaces the version 1 independent lists. `BACKEND_API_VERSION` advances from 1 to 2, and `BackendIdentity::supports_current_api` rejects version 1 identities. A backend must migrate its declarations to explicit combinations; generating their Cartesian product would recreate the old admission bug. This is a Rust scaffold contract, not a stable dynamic plugin ABI or serialized protocol. The crate package version remains controlled separately by repository release policy; no backend consumer or production model declaration currently uses this scaffold. - -Compatibility declaration is only one load prerequisite. `supports` does not read or hash model bytes, validate tensors or a tokenizer, check hardware, reserve memory/concurrency, qualify experimental modes, or publish readiness. Backend implementations must perform those checks before loading succeeds. A declared tuple is a backend assertion, not proof that a real model works. - -Tests use two synthetic declared tuples and independently enumerate all eight combinations: only the two explicit entries are admitted. They also cover unknown formats, empty capabilities, malformed identifiers even when explicitly advertised, invalid digests, and refusal of obsolete/future API versions. No real family support, inference quality, numerical result or performance claim is introduced. diff --git a/docs/build-validation.md b/docs/build-validation.md deleted file mode 100644 index 70037d39..00000000 --- a/docs/build-validation.md +++ /dev/null @@ -1,959 +0,0 @@ -# Build validation - -## 2026-10-07 — Gitea Python 3.11 archive validation - -- Exact-head Gitea run `2700` (`8ec9ab5bce6442acf3629b3b03967cdc42311918`) ran in - `node:24-bookworm` / Debian 12 with Python `3.11.2`. `verify` exposed that - `tarfile.extractall(filter="data")` requires Python 3.12; the CUDA bootstrap - now validates member paths, link containment, topology, types, and modes before - using the Python 3.11-compatible standard-library extractor. No PyPI packages - are added for this script. -- The focused archive suite passed on the same `node:24-bookworm` image. It covers - valid file/symlink/hardlink trees, traversal and link-parent attacks, privileged - mode rejection, conflicting merges, download integrity, and lock validation. -- The manual keyless-GPU path is now preceded by a CPU-side input gate and depends - on `verify`; a false selection must be resolved as skipped before any GPU runner - is eligible. This gate does not execute GPU checks or imply GPU availability. -- Exact-head Gitea run `2703` (`712de0f6bc4f16686d52c3c98bed2643147178cc`) - passed `verify` and the CPU gate; both keyless GPU jobs were skipped. The hosted - PLE job exposed that the Docker daemon cannot bind-mount the runner container's - `$GITHUB_WORKSPACE`; the build now streams a tracked-source archive into a - private Docker volume and supplies the exact source SHA as provenance. The same - run found the static CLI target path mismatch and an incomplete scratch-image - workspace (missing the root lockfile and local tokenizer workspace crate); the - workflow and Dockerfile now use one explicit target directory and include the - complete Cargo workspace manifests/sources. -- Run `2703` produced no hosted package artifact. The new fixes require one fresh - exact-head Gitea run; no GPU inference, model-quality or rollback claim follows - from these CPU/build checks. - -## 2026-10-03 — experimental PLE quality arm - -The imported engine builds on Linux CUDA 13.2/sm_120 with the optional -`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON` flag. The ordinary build still succeeds -with the flag off. A synthetic KAR-2 archive with four 160-value PLE rows in -two parts was generated by the Rust CLI. The independent Rust decoder and the -new Strata `PleTable` probe matched FNV-1a checksums for all four rows, including -the boundary between parts: `20c844888ce711a5`, `6a219cbf159362a5`, -`62bed3d23ae584a5`, and `68137da89d55afa5`. The fixture was deleted from -both hosts after the check. This verifies row layout, bit order, scale/book -reconstruction, and part indexing on a synthetic archive; real-model output -and paired throughput remain unmeasured. - -## 2026-10-02 — source-only build - -- Strata upstream commit: `d9ab8435f654c368c586340d490915f6addf56a3`. -- Host: macOS arm64; AppleClang 21.0.0; CMake 3.31.10; Ninja 1.13.2. -- Command: `PATH="$PWD/artifacts/tool-venv/bin:$PATH" scripts/build-cpu.sh`. -- CMake flags: CUDA off, HIP off, upstream broad test suite off, conversation tests on. -- Built: `strata-gguf`, `strata-dequant`, `strata-plan`, and five CPU test executables. -- Result: 5/5 CTest tests passed. -- Scope: source compilation and CPU tests only. No CUDA build, model inference, or performance measurement was performed. - -The test toolchain was installed into ignored `artifacts/tool-venv/` for this run; it is not a production dependency. - -## 2026-10-02 — Rust control-plane smoke test - -- `cargo fmt --check` and `cargo check --locked` passed with Rust 1.95.0. -- With no worker configured: `/health` returned 200 and `/ready` returned 503. -- With an ignored local fake engine that emitted `READY 262144 stop`: `/ready` returned 200 with `max_context: 262144`; Ctrl-C shut down both processes. -- With a fake engine that exited after `READY`: `/ready` returned 503 with `worker: failed`. -- `/v1/responses` is not implemented and returned 404. No model inference was tested. - -## 2026-10-02 — local worker contract checks - -- Added JSON file configuration with environment overrides and a bounded startup timeout. -- Four local tests pass against a fake engine process: valid `READY` handshake, graceful `QUIT`, worker exit, and startup timeout. -- The tests require neither the RTX 5090 nor model files. - -## 2026-10-02 — Responses contract and Rust 1.99 - -- Pinned Rust 1.99.0 with `rust-toolchain.toml` and `rust-version = "1.99"`. -- `scripts/check-local.sh` passed: rustfmt, Clippy with warnings denied, 12 Rust tests, synthetic Responses SSE replay, and 5 CPU CTest tests. -- The replay checks the local response builder and Strata pipe parser only. `/v1/responses` still returns an explicit 501 when the worker is ready because the inference adapter is not connected. -- No CUDA build, model inference, real Codex replay, or performance measurement was performed. - -## 2026-10-02 — internal worker generation exchange - -- A fake resident worker accepted a `GEN` command and returned `PP`, `T`, and `DONE` through the Rust supervisor. -- Context admission rejected a request exceeding the worker's `READY 262144` limit without failing the worker. -- Rust 1.99 Clippy with warnings denied and all 13 Rust tests passed. This is a pipe test only; the HTTP inference adapter is still absent. - -## 2026-10-02 — model CLI and Linux delivery preparation - -- Added an embedded, commit-pinned IQ3_S manifest, resumable `model fetch`, full-size/SHA-256 `model verify`, and bounded GGUF v3 `model inspect`. -- `scripts/check-local.sh` passed on macOS arm64 with pinned Rust 1.99.0: rustfmt, Clippy with warnings denied, 18 Rust tests, synthetic Responses SSE replay, and 5 CPU CTest tests. -- The interrupted-transfer test resumes a local HTTP fixture and rejects a corrupted final file. The GGUF test parses a synthetic v3 header and rejects truncation. -- The real 83.6 GB model was not downloaded or inspected. The Hub-provided LFS ETags are recorded as expected SHA-256 values but have not been measured locally. -- The Linux/arm64 Docker musl CLI image built and its `--version` command ran inside a `scratch` container. The current source was also cross-compiled locally for `aarch64-unknown-linux-musl`; `file` reported a statically linked ELF, and `readelf` found no interpreter or dynamic section. -- Mounted the current binary into that `scratch` image. It fetched Rust 1.99.0's pinned README over HTTPS (`3,304` bytes), verified the manifest SHA-256 (`b3f6ef2fef88b98cb9ec013a5c86213095e53e40eb228679574e4d06517f33c8`), and matched the host reference byte for byte. This verifies embedded TLS roots and the small-file acquisition path, not the 83.6 GB model transfer. -- The Strata Next GitHub repository does not exist yet. This local checkout has only the `strata-upstream` remote, so the workflow has not run on GitHub Actions. No GPU node was used. - -## 2026-10-02 — worker cancellation contract - -- A dropped generation receiver now causes `STOP`, drains the worker's terminal `DONE`, and leaves the resident worker ready for a second request. -- Shutdown during an active generation sends `STOP` before `QUIT` and closes the pending result receiver. -- The two focused fake-worker tests pass, along with Rust 1.99 Clippy with warnings denied. No GPU inference was used. - -## 2026-10-02 — native tokenizer asset extraction - -- Added `model extract-tokenizer` for validated GGUF v3 `gpt2`/`qwen35` metadata. It writes five tokenizer files into a staging directory and publishes the directory on completion. -- A synthetic GGUF with vocabulary, merges, token types, special ID, and chat template produced the same parsed JSON and exact text files as the pinned upstream `tools/strata_tokenizer.py` (5/5 files). The upstream comparison used Python `regex` only as an offline test dependency under ignored `artifacts/tool-venv/`. -- Rust 1.99 formatting, Clippy with warnings denied, and 21 Rust tests passed at this stage. The real model tokenizer and packed weights were not validated. - -## 2026-10-02 — native BPE parity - -- Added qwen35 byte-level BPE encoding and decoding in Rust, including rank-ordered merges, a heap path for long pieces, control and user-defined literal handling, and a CLI path for text on standard input. -- Compared 20 corpus strings in both special-token modes against the pinned upstream Python tokenizer with a synthetic complete byte vocabulary: 40/40 token-ID sequences and decoded strings matched. Cases included multilingual text, emoji, combining marks, C0 bytes, long repeated text, and near-miss literals. -- Added fixed oracle ID cases to Rust tests. The real IQ3_S tokenizer and end-to-end generation remain untested. -- `scripts/check-local.sh` passed after this change: rustfmt, Clippy with warnings denied, 24 Rust tests, synthetic SSE replay, and 5 CPU CTest tests. -- Rebuilt the current source as a statically linked Linux/arm64 musl CLI. Mounted it into the `scratch` image and confirmed `model tokenize` returned the oracle IDs for `Hello, world!`. The actual model weights and GPU were not used. - -## 2026-10-02 — text inference preview and KAR-2 verification - -- Qwen text-only prompt assembly matches eight pinned upstream golden cases byte for byte. A synthetic in-process worker receives the expected native token IDs through the HTTP Responses route and returns a completed non-streaming text response. Live streaming, reasoning output, tools, and real-model inference remain unverified. -- Added bounded KAR-2 metadata inspection, streaming CRC-32 verification of every tensor section, and optional source-manifest verification. The latter checks each shard's size and SHA-256, then hashes the shards in ascending byte-wise filename order against the archive's source digest and byte count. -- Independently generated a 1,280-byte two-tensor RAW/NESTED archive with koference `r08/code/kar_container.py` at commit `806d2398ae1daaceb2917242911e5680cbfb3608`. Its Python reader and the Rust `model verify-kar` both accepted the archive and both tensor CRCs. A two-file synthetic source manifest passed the Rust source-identity check. The temporary archive and source bytes were kept out of Git. -- Rust 1.99 formatting, Clippy with warnings denied, and 31 Rust tests pass after adding a disk-space preflight that rejects an impossible model transfer before networking. The full `scripts/check-local.sh` cannot reach CPU engine tests on this machine because CMake ≥3.24 is absent; the local GitHub Actions workflow installs CMake, but it cannot run on a hosted runner until the Strata Next GitHub repository exists. -- Rebuilt the current CLI as a Linux/arm64 musl executable in a `scratch` image. `--version`, KAR-2 payload verification, and the optional two-shard source-identity check all ran successfully inside the image against the synthetic koference archive. This proves the current static CLI starts without a user-space loader, not that a GPU engine or real model runs. No model weights or GPU node were used. -- Ported the koference KAR-2 container writer for already encoded RAW/NESTED tensor slices to Rust. A native two-tensor archive has the same SHA-256, `013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2`, as the independently generated reference archive at koference commit `806d2398ae1daaceb2917242911e5680cbfb3608`. The writer's temporary output passes native payload verification before publication. This fixture is synthetic and does not establish model quality or a bounded-memory full-model conversion. -- Rust 1.99 formatting, Clippy with warnings denied, and all 32 Rust tests pass with the native writer. -- Added a GGUF tensor index that checks exact source block lengths and can hash one tensor with a fixed 1 MiB buffer. A synthetic mixed F32/IQ3_S fixture verifies offsets, lengths, and rejection of overlapping sections, a misaligned quantized row, and an unsupported type. All 33 Rust tests and Clippy with warnings denied pass; this is a source-layout check, not a KAR encoder or model conversion. -- The `model index /tmp/leleka-api-index-smoke.gguf --hash` CLI emitted the expected two JSON records: F32 at absolute offset 128 with 16 bytes, and IQ3_S at 160 with 110 bytes; both SHA-256 values matched the synthetic zero payloads. `cargo check --locked --target aarch64-unknown-linux-musl` passed with this source. -- The KAR writer's file-backed RAW path generated the same complete archive bytes as its in-memory path, rejected a changed source digest without publishing a destination, and passed a separate 1,048,580-byte input crossing the 1 MiB copy boundary. Rust 1.99 formatting, Clippy with warnings denied, all 34 tests, and Linux/arm64 musl cross-check pass. NESTED encoded data is still in-memory, so full-model conversion is not bounded yet. -- Added a file-backed NESTED path for already coded KAR sections. A synthetic file-backed section produces the same complete archive bytes as the in-memory writer; corrupted scale, nonzero padding, and wrong section digest each fail before publication. The path streams through 1 MiB and retains no full encoded tensor in RAM. All 35 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The source-to-NESTED encoder is still missing, so this does not complete model conversion. -- Added an experimental native f32-to-KAR bit-plane encoder with supplied thresholds. A synthetic four-cell pattern produced the koference word layout (`0xcccccccc`, `0xaaaaaaaa`), then passed through the KAR writer and verifier. IEEE f16 scale conversion tests include the smallest subnormal and ties-to-even. All 37 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Calibration fitting, IQ3_S decoding, bounded source conversion, and full-model quality remain open. -- Added bounded CPU prefix decoding for the synthetic tensor: a five-value slice reconstructed at levels 1 and 2 exactly as the supplied f16 books specify, and an out-of-range slice was rejected. This oracle has not yet been compared with the koference GPU decoder on hardware. -- Ported top-down nested boundary and book fitting for a supplied normalized sample. Two pinned koference Python fixtures match the Rust f32 boundary bits and f16 book values; a degenerate sample is rejected. The f64-to-f16 path avoids double rounding of fitted means. All 38 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This only establishes synthetic calibration parity, not representative model sampling or a quality result. -- Connected a small synthetic F32 GGUF to `model prepare-f32-preview`: it produced a verified KAR-2 archive with source SHA-256 `f2bff437d5a53e8ddf7f43ee41acf3baebb7fb5f27eefb079f5bc1634def6f2c` and archive SHA-256 `fe049ca40305d5380caaa278f34a9149ae2d5761ea9544b58a0eb73775cd6810`. The separate `model verify-kar` command passed. A valid synthetic IQ3_S GGUF was rejected by the F32 preview, without creating an archive. All 40 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This is a bounded experimental integration path, not full-model preparation. -- Refactored the F32 preview to write each tensor's canonical NESTED section to a private staging directory, then assemble the KAR archive from file-backed sections. The native section bytes match the in-memory writer. A two-tensor fixture succeeds and leaves no staging directory; corrupting the second tensor to NaN fails after the first section and also cleans staging without publishing an archive. The preview source-size and per-tensor limits remain; IQ3_S source decoding and full-model quality remain open. -- Added a native IQ3_S CPU block decoder with the pinned ggml grid table (SHA-256 `bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f`). A deterministic mixed 110-byte block produced 256 F32 values whose byte digest `cfee2753d1b389fe4ee30994ff3387d4400745b8432aeb32cb4d7fced39949ec` matches an independent Python calculation from the upstream layout; constant, sign, multi-block, and malformed-scale cases also pass. All 41 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This has not been compared with a real tensor or GPU. The ggml MIT license is copied into the control binary and shown by `--ggml-license`. -- Added `model derive-iq3-identity` for a single all-IQ3_S GGUF. It hashes the original GGUF and a virtual contiguous little-endian F32 stream, with per-tensor original/derived digests and offsets, using a 256-block input buffer; no expanded file is written. A two-tensor fixture with reversed physical and directory order matched an independently assembled F32 stream digest. All 42 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Mixed tensor types, shard sets, real-model parity, and KAR publication remain unverified. -- Added `model prepare-iq3-preview` for a small all-IQ3_S GGUF. A synthetic one-tensor input produced a KAR-2 archive with the virtual F32 source digest and a provenance sidecar binding the original GGUF, derived stream, and archive SHA-256 values. The archive passed payload verification. A preexisting sidecar blocked publication and the newly written archive was removed. All 43 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The source decoder and compressed output have not passed a real-model quality gate or GPU test. -- Added `model verify-iq3-preview` to recompute the original and virtual F32 identities, check KAR per-tensor source records and payload CRCs, and compare the provenance sidecar with the archive hash. The synthetic IQ3 preview verified; changing the sidecar's archive digest caused rejection, and restoring it passed again. A separate `cargo build --locked` CLI smoke generated and verified a temporary one-tensor archive: virtual F32 SHA-256 `9d1f76b4ef22e4b0e1f7e8d13cd3ff91516c884e9b8aa8107c8932bfd64fed85`, archive SHA-256 `c4d4e843165aa2599206458f0550c24eaafe95c3dacffec5e736950e16d1769c`. All 43 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check passed. This is identity/integrity verification, not an assessment of model quality or GPU behavior. -- Added `model derive-mixed-identity` for one GGUF containing IQ3_S and F32/F16/BF16 tensors. A four-tensor fixture with directory order different from physical order matched the independently assembled F32 byte-stream SHA-256, including half and bfloat conversions, and the all-IQ3-only derivation rejected it. The command uses a fixed 28,160-byte source buffer and writes no expanded file. All 44 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Mixed KAR preparation, real-model parity, and GPU quality remain open. -- Added `model prepare-mixed-preview` and `model verify-mixed-preview`, with a separate versioned sidecar carrying each original tensor kind and digest. A four-type synthetic GGUF passed preparation and verification in Rust tests. A separate two-type CLI smoke produced a KAR archive whose virtual F32 SHA-256 was `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7`; the verifier matched the source, sidecar, KAR source records, and payload CRCs. All 45 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The preview remains capped at 64 MiB input and is not approved for serving. -- Added `model derive-sharded-identity` for manifest-pinned GGUF shards. A two-file fixture deliberately listed IQ3_S before F32 in its manifest; native derivation sorted filenames, checked both size/SHA-256 values, and assigned global F32 offsets 0 and 128. Replacing a manifest SHA-256 with the wrong value was rejected. A separate CLI smoke emitted the expected derived stream SHA-256 `e529f5e2f7aac1aa5509fabe728d84ab876c64754635963825e265cd70cb8b05`. All 46 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. No sharded KAR archive or real-model conversion was attempted. -- Extracted the shared one-tensor preview encoder and reconstruction check for future sharded preparation. Existing F32, IQ3_S, and mixed preview tests passed. Rebuilt the CLI and reran the pinned two-type mixed fixture: the derived F32 SHA-256 remained `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7` and the full KAR archive SHA-256 remained `4053e787d46b2cf2bca3d67e38d06e1ee96a157e80e3155c8dbdbf36835df88c` byte for byte. This is a non-lossy refactor of the preview implementation, not a quality result for the lossy format. -- Added a CI-only synthetic mixed GGUF/KAR smoke script for the Linux musl release binary. The workflow is configured to reject an ELF interpreter or `NEEDED` dynamic library, run the CLI through derivation, preparation, and source/provenance/archive verification, and check the pinned derived/archive SHA-256 values before uploading. The script passed locally against the current macOS debug CLI. The hosted workflow cannot run until the Strata Next GitHub repository exists and this checkout is connected to it. Python is used only to create the CI fixture, not by production serving. -- Added `model prepare-sharded-preview` and `model verify-sharded-preview` for two or more manifest-pinned GGUF files under the existing 64 MiB preview limit. A two-shard synthetic Rust test passed archive preparation, provenance verification, and source-record checks; changing a pinned manifest digest caused rejection. A separate CLI smoke built and verified an archive with derived F32 SHA-256 `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7` and archive SHA-256 `49206cc99935dad8ddc1cb342dfc263548285e04767237c2c377c23d33a88479`. All 47 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check passed. No full-model conversion, CUDA decode, or throughput comparison was performed. -- Added `model prepare-sharded-streamed` and `model verify-sharded-streamed`: the experimental path samples at most 65,536 normalized values per tensor, writes nested or exact RAW F32 sections from bounded GGUF chunks, checks per-tensor physical/virtual digests, rehashes each shard, assembles a KAR-2 archive, and binds a separate versioned sidecar. The two-shard F32/IQ3_S synthetic test verifies the archive, reconstructs a dense tensor on CPU, rejects a changed preparation level and pinned shard digest, and refuses to overwrite the archive. All 56 Rust tests and Clippy with warnings denied passed locally. The CLI reports actual archive bytes and accounted bits per weight. Real Qwen shards have not been converted, and no GPU quality or speed result exists. -- Extended the existing static-CLI smoke script with two manifest-pinned synthetic shards. The local macOS CLI prepared and independently verified their streamed archive; its SHA-256 is pinned as `51688d265860172feca39e296f9142b1ed16800496bae4b06b4b8d8fa11d806e`. This script is wired into the Linux musl workflow, but hosted GitHub Actions has not run because this checkout has no remote repository. The fixture is synthetic and says nothing about full-model size or quality. -- Added opt-in `model ensure-sharded-streamed`: fetches pinned GGUF shards, verifies source bytes, creates and verifies the streamed archive, then rehashes and checks source/provenance/payload on reuse. A local CLI smoke created and reused the synthetic two-shard archive and rejected a rerun with a changed level without modifying the existing file. Full 83.6 GB model preparation has not run; the local checkout had about 121 GiB free at this step, insufficient for source plus staged and final archive. No full-model size is reported yet. -- Began the pinned Qwen3.8 IQ3_S model download into a local model directory outside Git. Read only the header/directory bytes from the partially downloaded first shard and an HTTPS range of the second: 1,223 and 1 tensors respectively, 13 GGUF types, and 176,943,899,520 total elements. The second shard omits `general.architecture`. Summing the KAR-2 level-2 nested layout over these unverified directory entries gives 55,295,262,208 payload bytes (55.30 GB); this assumes every tensor uses nested encoding, excludes small container overhead, and is **not** an observed archive size or a quality result. The full shard hashes still need to match the manifest. -- The KAR writer now has an internal consuming mode for private file-backed sections: after each verified copy into its temporary archive, it removes that staged section, reducing peak disk use. The normal non-consuming writer remains available. A dedicated test verifies staged RAW removal and a valid published archive; the two-shard test now also covers a shard with no architecture metadata. Local targeted tests and Clippy with warnings denied pass. Real mixed quantization types beyond F32/F16/BF16/IQ3_S still need native decoding before the full archive can be prepared. -- Vendored the pinned llama.cpp/ggml C dequantizer source and required headers at Strata's upstream ggml commit `3cf03257f219afbe7334045ff7c6a06ac68c627d`, recorded checksums and license, and linked it statically through Cargo for offline preparation. The bounded visitor now handles every quantized kind found in the two actual Qwen headers: 8, 12, 13, 14, 18, 20, 21, 22, 23, and 42, in addition to F32/F16/BF16. A synthetic IQ3_S block matched the independent Rust decoder exactly; Q8_0 and Q2_0 matched known values; one zero block of each actual kind decoded through the visitor. The streamed two-shard test exercises an IQ4_NL RAW fallback. All 60 Rust tests and Clippy with warnings denied passed locally. The static CLI smoke now includes an IQ4_NL shard, with pinned archive SHA-256 `07751adc1f7115258b95613203c935f05cbe28a364f77717e8a1bc64cb79c8fa`. Real model source SHA-256 remains unmeasured. -- On a **provisional real-data sample** from the partially downloaded first Qwen shard, a 28,835,840-byte leading slice of `blk.17.ffn_gate_exps.weight` (IQ3_S, starting at absolute GGUF offset 19,192,385,920) and the 921,600-byte `blk.0.ffn_down_shexp.weight` (IQ4_NL, offset 1,385,570,304) were wrapped as two minimal GGUF shards outside Git. Their GGUF bytes total 29,757,760 and their level-2 KAR-2 archive is 21,485,056 bytes (72.1998% of this sample, 2.500179 accounted bits per weight), SHA-256 `ebacd3cd488274a21bc94630c841d157b5633ce62721bb991c39b78dad8cef23`. The dedicated verifier matched manifest source hashes, derived-F32 identity, provenance, KAR source records, and payload CRCs. The maximum tensor relative L2 error was **0.40491666**, so this level is not approved for serving. The full source shard hash has not yet been checked; this sample is not representative of whole-model size or quality. `scripts/measure-real-sample.py` reproduces this measurement into an output directory outside Git; pass `--index-gguf` only while the source is a partial download, and `--source-sha256` after its full hash is known. The chosen source GGUF offsets are absolute as printed by `model index`; no data-start offset is added. -- Repeated the same sample through `scripts/measure-real-sample.py`: level 2 reproduced the same 21,485,056-byte archive and SHA-256. Level 3 gave a 30,078,464-byte archive (101.0777% of sampled GGUF input), SHA-256 `3e6bc55254ba30bea5ed4f40c970ac9290ad4b1fd160e5c92e71caaaff0328e2`, and maximum tensor relative L2 error **0.18060363**. Both archives passed the dedicated manifest/provenance/payload verifier. These measurements show a sample rate/error tradeoff, not a whole-model compression or agent-quality result; neither rate is enabled for serving. -- `cargo run --locked --release --example compare-iq3-s -- 262144` compared every block in the sampled real IQ3_S slice: **262,144 blocks / 67,108,864 F32 values were bit-identical** between the independent Rust decoder and the pinned ggml C decoder. This is a non-lossy decoder parity check on source bytes from the incomplete first shard; the complete shard still needs manifest SHA-256 verification. -- Built the committed static-CLI Dockerfile on an arm64 Linux container with `RUST_TARGET=aarch64-unknown-linux-musl`. The resulting single `leleka-api` ELF is 14 MiB (`file` reports `statically linked`), SHA-256 `3faa76d410f08134cb39bc77009674ffba8e9a3190bfa7af0099028ed5282285`. The `scratch` image ran `--version` successfully and independently verified the real-slice level-2 KAR archive through a read-only bind mount, including manifest source hashes, provenance, source records, and payload CRCs. This validates the Linux/arm64 static control-plane/CLI artifact, not the x86_64 release path or a CUDA-enabled inference runtime. Hosted GitHub Actions still has not run because this checkout has no GitHub repository or remote. -- The same reproducible sampler has an `--profile expert` option using the same 28,835,840-byte IQ3_S slice plus a 28,800,000-byte leading slice of the much larger `blk.0.ffn_down_exps.weight` IQ4_NL tensor (absolute GGUF offset 913,711,104). The two minimal GGUF inputs total 57,636,160 bytes. Level 2 produced a verified 36,973,056-byte KAR-2 archive (64.1491% of sampled input), SHA-256 `03a971fc1ff0a50c34a24fb5a29df76116f16fe9dec98ed61c3429a8f322af48`, with maximum tensor relative L2 **0.33925502**. Level 3 produced a verified 51,761,664-byte archive (89.8076%), SHA-256 `1f94757878575541d3a1568e7ba8d9e680ba6afed2c1199ae63d4c342a6203f8`, with maximum tensor relative L2 **0.16425464**. These are rates for selected slices from an incomplete shard, not an estimate with validated uncertainty for the full model, and neither rate is approved for serving. -- The first complete Qwen shard was fetched and matched its manifest SHA-256 `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`. Repeating `scripts/measure-real-sample.py --profile expert --levels 2 --source-sha256 ` on this verified file reproduced the same two slice digests, 36,973,056-byte archive, archive SHA-256 `03a971fc1ff0a50c34a24fb5a29df76116f16fe9dec98ed61c3429a8f322af48`, and maximum relative L2 0.33925502. The second source shard is still downloading. -- Added bounded CPU decode of an arbitrary nested KAR tensor range, reading only the relevant scales and bit-plane words after archive verification. A 96-element synthetic archive test covers ranges crossing group boundaries. On the verified-source level-2 expert sample, `compare-kar-range` independently decoded three one-million-value archive ranges and compared them with pinned ggml source decoding: IQ3_S at starts 0 and 33,000,013 had relative L2 0.32941509 and 0.32867352; IQ4_NL at start 25,000,017 had 0.34136948. The same IQ4_NL range from the level-3 archive had 0.16519821. This checks stored archive reconstruction on selected ranges, not GPU execution or model-level quality. -- Corrected a dispatch error found by comparing the native C bridge with pinned `ggml.h`: GGUF kind 18 is `IQ3_XXS` (98 bytes/block) and kind 22 is `IQ2_S` (82 bytes/block); the initial bridge had these two decoders reversed. Dispatch now uses ggml enum names and `decode_into` rejects any mismatch between the C `sizeof` result and the Rust GGUF block geometry before C reads source bytes. Cargo explicitly watches the bridge C and vendored ggml sources, so a C edit rebuilds the native archive. The streamed builder, provenance schema, and virtual-F32 derivation were bumped to v3 to prevent reuse of v2 archives with potentially incorrect kind-18/22 values. The v3 synthetic streamed archive SHA-256 is `c897a2b5016d5734925269b7dc223c33f944f10bc178a85db4b322cbaf058b5a`; the v3 IQ4_NL fixture archive SHA-256 is `955b626c2c206b272b690b301168d01824563bb88dc9963698035c3acb619ba2`. The old v2 hashes above are historical and cannot pass the current streamed verifier. -- `scan-quant-blocks` decoded the first real block of each of the 13 GGUF kinds in the SHA-256-verified first shard and found only finite F32 values. Its kind-18 IQ3_XXS block F32 SHA-256 was `aaf601ac40a43dc9af448936d6ab439a9837f01d13b835574d94af2eb62a2a1e`; kind-22 IQ2_S was `4c4b80c73da67911a002589646c61aed4fe8e0139b3152cffd0b3e4ac4e540de`. The source-verified expert-slice level-2 archive under v3 is still 36,973,056 bytes with maximum relative L2 0.33925502, but its new archive SHA-256 is `9c8d195c80cb4a04789d8f53847811214d5abc3f8c652185000f0055f435522f`. All 62 Rust tests, Clippy with warnings denied, and the updated static CLI synthetic smoke passed locally. The Linux static image must be rebuilt for this v3 correction. -- Extracted the first verified shard’s 248,320-token/247,587-merge tokenizer to an external directory. The native CLI and pinned upstream `strata_tokenizer.py` agreed on IDs and exact decode/encode roundtrips for 20 real-vocabulary cases spanning Cyrillic, CJK, emoji, combining marks, whitespace, C0 controls, long BPE runs, and control/user-defined special tokens, both with and without special parsing. `scripts/compare-real-tokenizer.py` reproduces this offline check; Python and `regex` are evaluation dependencies only, not serving dependencies. -- The second complete Qwen shard was fetched outside Git and matched its manifest SHA-256 `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`; the first complete shard remains verified at `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`. The total GGUF file size is 83,617,662,656 bytes. These are verified source bytes, not a KAR archive size. -- Streamed KAR policy v4 partitions a tensor whose bit-plane stride would exceed KAR-2's `u32` limit. The real 51,200,245,760-element `per_layer_token_embd.weight` is planned as adjacent 32,000,000,000- and 19,200,245,760-element records with checked GGUF block boundaries and contiguous virtual F32 offsets. The part planner checks physical and derived parent hashes; provenance records parent dimensions and each part's source/F32 hashes and offsets. A small forced split fixture passed end-to-end preparation, independent archive/provenance verification, and CPU reconstruction for both parts. Calibration sampling now seeks to at most 65,536 normalized groups for tensors over 1,048,576 elements; F32 and IQ3_S sparse samples matched the complete-stream sampler exactly in dedicated tests. All 65 Rust tests and Clippy with warnings denied passed locally, and the v4 synthetic static-CLI smoke passed against the macOS binary. The Linux/arm64 v4 static validation is recorded below. -- Both SHA-256-verified source shards supplied a reproducible 57,636,160-byte two-tensor sample: a 28,835,840-byte IQ3_S expert slice plus 28,800,000 bytes from the giant `per_layer_token_embd.weight` IQ4_NL tensor. V4 level 2 produced a verified 36,973,056-byte KAR-2 archive (64.1491% of sampled GGUF size), SHA-256 `b1630baa94d01b52916e2d3fbcf73042542a1d4e2f9108517333497cf677db8d`, with maximum tensor relative L2 error 0.33378769. Level 3 produced 51,761,664 bytes (89.8076%), SHA-256 `91ce9e0c5c804a293f3b03aea8644871ef2981ecb562c5417a3c74afa850caa5`, with maximum tensor relative L2 error 0.16037559. Both archives passed source/provenance/payload verification. These are sampled size and reconstruction errors only; neither is a full-model size, model quality gate, or serving approval. -- The optimized macOS release CLI recreated the same v4 level-2 per-layer sample byte for byte: 36,973,056 bytes, archive SHA-256 `b1630baa94d01b52916e2d3fbcf73042542a1d4e2f9108517333497cf677db8d`, and the same 0.33378769 maximum tensor relative L2 as the debug CLI. The release verifier independently matched source manifests, provenance, source records, and payload CRCs. -- On the verified second-shard `per_layer_token_embd.weight` slice, `compare-kar-range` independently decoded one million archived F32 values starting at 25,000,017 and compared them with pinned ggml IQ4_NL source dequantization. L2 reconstruction had relative L2 0.33396194 and maximum absolute error 0.01647477; L3 had 0.15970538 and 0.00811461. This checks one real range of stored KAR output against source values on CPU, not model-level quality or GPU execution. -- Rebuilt the v4 static CLI in the committed Dockerfile for `aarch64-unknown-linux-musl`. The executable is a 14 MiB statically linked Linux/arm64 ELF, SHA-256 `656fefeb0cf8aa7c2b804a162f264e1d59689beadcdc6eb544dc4fe2fa92fc62`. Its `scratch` image ran `--version` and independently verified the v4 real per-layer L2 sample through a read-only bind mount, including manifest source hashes, provenance, source records, and payload CRCs. This validates the current Linux/arm64 CLI path; Linux/x86_64 and CUDA inference remain untested. - -## 2026-10-03 — complete two-shard KAR-2 size - -- Host: macOS arm64; release CLI at commit `edf0617`; KAR-2 experimental streamed policy v4, group 32, level 2. Both source GGUF shards matched the embedded manifest SHA-256 before conversion and were rehashed by the preparation command. -- Command: `leleka-api model prepare-sharded-streamed qwen-iq3-s --source-dir /Users/para/.local/share/leleka-api/qwen-iq3-s --output /Users/para/.local/share/leleka-api/qwen-iq3-s-l2-v4.kar --levels 2`. -- The complete archive has **55,295,529,472 bytes** (51.49797487 GiB) across 1,225 KAR records; the two GGUF shards have 83,617,662,656 bytes. Archive/source ratio is 0.66129006, saving 28,322,133,184 bytes (33.87099%). Accounted rate is 2.500025 bits per derived F32 weight. Archive SHA-256 is `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; derived F32 SHA-256 is `c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479`. -- The writer's full payload CRC verification passed before atomic publication, and a versioned provenance sidecar was written. The maximum tensor relative L2 error measured during encoding was 0.68008092. This is **not** a model-level quality result or permission to serve with KAR-2. No Linux GPU inference, GPU decode, or paired end-to-end throughput result exists yet. -- A separate `model verify-sharded-streamed /Users/para/.local/share/leleka-api/qwen-iq3-s-l2-v4.kar --manifest qwen-iq3-s --source-dir /Users/para/.local/share/leleka-api/qwen-iq3-s --levels 2` run exited successfully. It recomputed the derived F32 source identity, checked both manifest shards, all 1,225 KAR source records and payload CRCs, the archive SHA-256, and the v4 provenance policy. The provenance sidecar SHA-256 is `3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5`. Temporary section files, old real-data slices, local header fixtures, and superseded local Docker images were removed; both verified GGUF shards, the final KAR, and its provenance remain outside Git. - -## 2026-10-03 — outer block codec and selective precision probes - -- Read 18 independent 1,536,036-byte KAR expert sections from the verified full archive (gate/up/down records at layers 0, 3, 14, 24, 37, and 45 for experts 0, 127, and 511). On the same 18 blocks, mean compressed/raw ratios were 0.988025 for LZ4 HC (`lz4 -9`, 1.10.0), 0.935372 for Deflate (`zlib` level 9), and 0.915421 for xz (`xz -9e`, XZ Utils 5.8.4). Median xz ratio was 0.914897, with a range of 0.904669–0.930424. One block per codec decompressed byte-identically. These are CPU encoding and size observations only, without a CUDA decoder, PCIe measurement, or end-to-end A/B result. -- A separate sparse scan of 26 aligned 32 MiB windows spaced 2 GiB across the archive gave mean xz ratio 0.895215, median 1.000051, and range 0.418332–1.000051. The large spread shows that a full-archive size cannot be inferred reliably from a few windows; no complete outer-compressed archive was produced. -- The streamed Rust preparer now retains relative L2, source kind, and section bytes per KAR record in its result and prints the worst 20 when creating a new archive. A forced-split fixture checked that all records are represented and their maximum equals the summary maximum. The existing full archive was created before this diagnostic and has no per-record report; reusing it will not fabricate one. All 65 Rust tests, Clippy with warnings denied, and `git diff --check` passed locally. - -## 2026-10-03 — sampled distortion of the existing complete archive - -- Added `model analyze-sharded-kar` and a reusable verified CPU range decoder. The strict mode checks complete source derivation, archive payloads, and provenance. Its first full-model run was stopped after about 13 minutes because repeated derivation of the 707,775,598,080-byte virtual F32 stream made it unnecessarily expensive; it had produced no report or intermediate model files. A separate `--assume-verified` mode uses the earlier independent full verification of the immutable archive and source shards, checks current metadata and provenance mapping, and reads only sample windows. Synthetic compressed and RAW archives gave identical sampled relative L2 in strict and fast modes. The fast mode does **not** rehash source or archive payloads and says so in its output. -- The fast real-model run produced `/Users/para/.local/share/leleka-api/qwen-iq3-s-l2-v4.sampled-distortion.json` outside Git: 1,225 records, 12,276,608 sampled values, 546,787 JSON bytes, report SHA-256 `1452b55705b9f723747df7dba47fd0484ae8b4140b0022cacceefb16970b5bbf`, bound to the previously verified archive SHA-256 `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`. Each record uses up to three nonoverlapping GGUF-block-aligned windows of at most 4,096 values (beginning, middle, end). The median sampled relative L2 is 0.363209; 22 records are at least 0.5 and 207 at least 0.4. The largest sampled value is 0.77458222 in `blk.0.ffn_gate_inp.weight`; 0.74248190 and 0.73494266 occur in the same tensor family at blocks 30 and 14. A window's relative L2 can exceed the earlier full-record maximum of 0.68008092 because it measures a different subset, and it is not a full-record bound or model-quality result. -- The 22 records at or above 0.5 contain 43,008,000 values. Adding one KAR bit plane only to these records would nominally add 5.13 MiB of plane bits before alignment and metadata; a serving loader and GPU path still need to apply this mixed-rate overlay. An external proposal list, `/Users/para/.local/share/leleka-api/qwen-iq3-s-l3-candidates.json`, has SHA-256 `6c82c80c8edfb7a8b0e83c8ebd690339843b83a9dce0020967e7146cbcb41120`. It is a diagnostic proposal, not an approved precision policy or proof of improved model quality. The split `per_layer_token_embd.weight` sampled at 0.33714705 and 0.33125633; `token_embd.weight` at 0.33737772 and `output.weight` at 0.37104131. - -## 2026-10-03 — selected L3 overlay and paired tensor comparison - -- `model prepare-kar-overlay` encoded the 22 proposed unsplit records from the original GGUF shards at KAR level 3. Each selected physical GGUF and virtual F32 digest matched the full base provenance during encoding; the KAR writer and an independent pass verified the overlay records and payloads. The overlay is `/Users/para/.local/share/leleka-api/qwen-iq3-s-l3-overlay.kar`, **18,827,008 bytes** (17.955 MiB), SHA-256 `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`, with 22 records. The corresponding base archive sections occupy 13,445,632 bytes, so the standalone overlay file exceeds those sections by 5,381,376 bytes, including its own header/directory/alignment. The overlay provenance is 6,039 bytes, SHA-256 `403eeca17d09bd51b3c5f6bae2587c62c483707e346577ab3df6feed2a2a7958`. Private staging sections were removed. -- `model compare-kar-overlay` decoded every value of the same 22 tensors from the base L2 and overlay L3 archives, compared both to pinned GGUF dequantization, and recomputed each selected source tensor's physical and F32 SHA-256. Its external report `/Users/para/.local/share/leleka-api/qwen-iq3-s-l2-vs-l3-overlay.json` is 4,226 bytes, SHA-256 `6413b353381749c5d0cc0eb91ed5bf93e6b8a9c36fd7f6db9942fd20a7478e97`. All 22 full-record relative L2 errors decreased. The median across selected records was 0.50734744 at L2 and 0.22607999 at L3; the largest selected-record error decreased from 0.62459845 to 0.28435756. For `blk.0.ffn_gate_inp.weight`, the paired full-record values were 0.62459845 and 0.28435756. This is a numerical weight reconstruction result, **not** a model-quality result or a GPU/PCIe performance result. The large base archive's earlier full verification is assumed by this comparison, while the selected source tensors and small overlay were freshly checked. -- All 67 Rust tests, Clippy with warnings denied, and `git diff --check` passed after the overlay work. A current macOS arm64 release CLI was saved outside Git at `/Users/para/.local/share/leleka-api/bin/leleka-api-overlay-probe` (13,691,888 bytes, SHA-256 `df2ce4c26dbf000f5935fe79a31a8ef73aea64ee5e48a1f5a5888d3751c94817`). `cargo clean --profile dev` and `cargo clean --profile release` removed their build outputs; the private overlay section staging directory is gone. Verified GGUF shards, the full base KAR, overlay, and reports remain for reproduction. - -## 2026-10-03 — live text SSE preview - -- The restricted `/v1/responses` text path now forwards worker token events through bounded channels as live SSE deltas. It emits `response.created`, `response.in_progress`, output item/content part events, UTF-8-safe text deltas, and a `response.completed` terminal event with continuous sequence numbers. A worker failure emits `response.failed`; dropping the client stream closes its worker receiver so the supervisor sends `STOP` and drains the current generation. -- A synthetic HTTP test received the first text delta before any `DONE` event, then checked the final text and event ordering. A resident mock worker accepted another request after its streaming receiver was dropped. A UTF-8 test checked tokens that split a multi-byte character. All 70 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. This validates the local protocol path only; no real model, Linux GPU, Codex tool call, or end-to-end throughput was tested. -- Follow-up terminal tests checked that worker errors produce `response.failed` and output-token exhaustion produces `response.incomplete` with `incomplete_details.reason=max_output_tokens`, in both the response trace and live SSE path. A length-limited response is no longer misreported as an HTTP gateway failure. All 73 Rust tests and Clippy with warnings denied passed locally. -- A Rust parser now accepts complete Qwen `` output in the buffered Responses path. It preserves literal closing-tag examples inside string parameter values, converts declared non-string JSON values, rejects unfinished/undeclared calls, and validates finished argument objects against the request's local JSON Schema without remote references. Function declarations with duplicate or unsafe names are rejected before generation. A synthetic HTTP test returned a `function_call` with exact string and integer values. All 78 Rust tests and Clippy with warnings denied passed at that step. Streaming tool calls and real-model validation remain open; the tool prompt is an adaptation of the upstream template rather than an established byte-for-byte parity result. -- The route now accepts a text-only `input` array for stateless continuation: earlier `function_call` items with JSON-object arguments must be paired with matching `function_call_output` text before a new generation. The Rust prompt includes the Qwen function and tool-response blocks; mismatched call IDs or incomplete pairs return a request error. A synthetic HTTP continuation reached the mock worker with the tool response intact and returned the next text answer. All 80 Rust tests, Clippy with warnings denied, and `git diff --check` passed. `previous_response_id` storage, multimodal items, reasoning replay, and real-model parity remain unimplemented. -- The representative upstream `tool call and response` golden prompt now matches the Rust tool renderer byte for byte, including the tool schema JSON, function call block, and tool response turn. This checks one pinned case rather than arbitrary tool schemas or real-model behavior. All 81 Rust tests and Clippy with warnings denied passed after the formatting change. - -- The incremental Qwen tool parser now holds split `` markers, including literal closing-tag examples inside parameter values. The live SSE path emits text deltas and a completed, schema-validated function call before worker `DONE`; unfinished and schema-invalid calls end in `response.failed` without publishing arguments. Synthetic worker tests check sequence order and terminal events. This has not been exercised against a real model or Codex client yet. - -- After commit `122c5f0`, `cargo test --locked` passed 85 Rust tests, Clippy with warnings denied passed, and the Linux/arm64 musl CLI cross-build succeeded. The 15 MiB ELF has no `INTERP` or `DYNAMIC` program header and ran `--version` from an arm64 `scratch` container. Its SHA-256 is `13e25f38445ada0b8f99e8a262580484342bdbfd28da39154957aaf29706054b`. This validates the CLI/control plane, not the CUDA worker or compressed-model serving. The superseded local static CLI copy was removed. - -- The HTTP route now stores terminal responses by default in a bounded, process-local cache and can render a `previous_response_id` chain with a new `function_call_output`. A synthetic two-turn worker test checked that the earlier user request, function call, and tool result reach the second Qwen prompt; unknown IDs return 404. This does not establish compatibility with a real Codex session, and the cache does not survive restart. - -- Commit `5a96652` passed 87 Rust tests, Clippy with warnings denied, and `git diff --check`. The updated Linux/arm64 musl CLI ran `--version` in `scratch`, has no `INTERP` or `DYNAMIC` program header, and hashes to `ffff43a30c75f2009a996079e4a8d45698658b3ba8a91a449a2cf87d9645d20c`. It remains a CLI/control-plane artifact without the CUDA engine. The prior local CLI copy was removed after verifying this one. - -- The new `model resolve-kar-overlay` command recomputes full SHA-256 and payload CRCs for the base and overlay archives, validates their shared virtual-F32 source, and maps every tensor name to a base or replacement record. A synthetic fixture rejected a modified overlay provenance digest. The real release-build run on macOS arm64 completed in 407.7 seconds without staging a model copy: base SHA-256 `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`, overlay SHA-256 `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`, 1,225 base records, and 22 selected replacements. The large `per_layer_token_embd.weight` parent correctly resolves through two adjacent KAR records. This validates archive identity and selection only; it does not test GPU residency, CUDA decode, model quality, or inference speed. - -- The CLI from commit `d62c6ce` cross-built for `aarch64-unknown-linux-musl` and ran `--version` in an arm64 `scratch` container. Its ELF has no interpreter or dynamic program header; SHA-256 is `ae22b63d19c11e1de3c5d5279edbdef8042acee89a3fc1192baab25fa41efa7a`. The superseded local static CLI copy was removed. This binary still excludes the CUDA inference engine. -- `cargo check --locked --target aarch64-unknown-linux-musl` passed for the current Rust code. A first release link on macOS chose the host `cc` and failed on ELF flags; setting `CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-musl-gcc` made `cargo build --locked --release --target aarch64-unknown-linux-musl --bin leleka-api` pass. The 15,141,536-byte Linux/arm64 ELF is statically linked, has no `INTERP` program header or dynamic section, and returned `leleka-api 0.1.0` inside the existing Linux/arm64 `scratch` container. External copy: `/Users/para/.local/share/leleka-api/bin/leleka-api-linux-arm64-musl-8704ef3`, SHA-256 `78723399f292816e5f894ebf64b11ecf369eb68cef6478e363d71539d2b787ac`. This is a control-plane/CLI artifact, not a CUDA inference runtime or x86_64 release validation. - -## 2026-10-03 — precision overlay for one partitioned PLE record - -- Overlay preparation and paired comparison now resolve a selected PLE partition to its exact GGUF byte range and base KAR virtual source record. A synthetic v5 fixture encoded both an unsplit dense record and one of four PLE parts at level 3, verified the two replacement mappings, and compared both full records against the GGUF values. Altering the part's source byte offset caused comparison to fail. This validates record mapping and reconstruction for small synthetic data; no full v5 archive or model-level quality result exists yet. -- All 90 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. The local build directory was cleaned after validation; preserved GGUF shards and v4 KAR artifacts were not changed. - -## 2026-10-03 — one-row CUDA smoke path - -- The isolated CUDA smoke target now accepts `--row ROW_ID` for a compressed record, including a selected PLE part from an overlay. It checks the local row bound, stages the record's compressed prefix, calls `kar_decode_rows` on a CUDA stream, and hashes only the one-row output. This reduces the output allocation for the smoke path; it does not reduce the initial compressed prefix transfer or integrate decoding into Strata's multiply path. -- Local Clang C++20 syntax checking with a temporary CUDA API declaration stub passed. No CUDA toolkit or GPU execution was available on the Mac. A read-only check of the Linux RTX 5090 at this step found 31,867/32,607 MiB VRAM in use by existing processes under driver 595.91.07, so neither the kernel result nor CPU/GPU row parity is claimed yet. -- The Rust `model checksum-kar-row` oracle verifies the complete KAR archive and decodes a bounded row for checksum comparison. On the synthetic 32-value fixture its row-0 values match the existing full-tensor CPU decoder exactly: both CLI paths returned FNV-1a `ff9fd7a827b333a5`; an out-of-range row is rejected. The temporary fixture was removed. All 90 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. - -## 2026-10-03 — verified base plus overlay VRAM accounting - -- `model plan-kar-overlay-memory` verifies complete base and overlay archive SHA-256 values, payload CRCs, provenance, and 22 replacement mappings before calculating selected compressed residency. A synthetic v5 fixture selected six records with two overlay replacements and counted each exactly once. All 90 Rust tests and Clippy with warnings denied passed locally. -- The release CLI ran against the preserved real v4 base and level-3 overlay in 421.0 seconds. Verified archive SHA-256 values were `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5` and `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`. At base level 2, overlay level 3, and a hypothetical 24,576 MiB GPU budget, 1,225 selected records (22 replacements) require **55,300,367,408 bytes** of compressed residency: 55,281,550,704 from selected base records and 18,816,704 from overlay records. That is 5,376,352 bytes more than the earlier base-only compressed plan. The largest full F32 scratch is 128,000,000,000 bytes, and two PLE records exceed the per-record full-decode budget while their one-row output bounds fit. All-selected residency plus one largest scratch is 183,300,367,408 bytes, so a 32 GB card cannot keep all selected records resident. This is verified archive metadata arithmetic, **not** measured GPU allocation, model quality, or inference throughput. -- The external report is `/Users/para/.local/share/leleka-api/qwen-iq3-s-selected-overlay-memory.json`, 3,586 bytes, SHA-256 `488a79973f90937429af1483bafe648441cd6e76ceb3a9f9edf9c16c7fcf376c`. The verified source shards, base archive, overlay, and this report remain outside Git. The local release build output was removed after the run. - -## 2026-10-03 — KAR preparation space guard - -- Streamed sharded preparation now checks the output volume before creating private section files. Its conservative lower bound takes the smaller of the mandatory bit-plane bytes and the F32 RAW fallback for each planned part. For the target virtual F32 size of 707,775,598,080 bytes at level 2, the aggregate bit-plane floor alone is 44,235,974,880 bytes before scales, codebooks, alignment, and provenance. The current Mac volume has about 23 GiB free and the occupied Linux host's root volume about 18 GiB free, so neither can hold a second full archive. This guard avoids starting section writes on a clearly undersized volume; source identity calculation still precedes it, and passing the bound does not guarantee a completed archive. -- All 91 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. The v5 partitioned synthetic archive still prepares and verifies under the space guard. - -## 2026-10-03 — fast rejection before existing-shard rehash - -- `model ensure-sharded-streamed` now uses the GGUF directories of already-present, size-matched shards to reject an impossible new archive before `model fetch` rehashes the source. This metadata is not treated as verified input for acceptance: if the lower bound fits, the existing SHA-256 and preparation checks still run. Missing shards retain the normal download path, and reuse of an existing archive does not require a second archive's free space. -- With both real IQ3_S shards present, a v5 level-2 request at `--ple-part-elements 100000000` failed in **0.495 s** from an already-built debug CLI. The directory-derived minimum was 44,235,975,168 bytes; the output volume had 22,671,552,512 bytes available in that run. The command returned `KAR minimum payload does not fit` before source hashing and created no v5 archive. No model bytes or new archive were written. All 91 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. - -## 2026-10-03 — shared-GPU smoke admission - -- The isolated CUDA smoke path now rejects a compressed record whose staged prefix, F32 output, and optional row ID would cross a free-VRAM reserve of `max(512 MiB, total VRAM / 16)`. It checks the selected record's declared level before estimating memory and performs the admission check before CUDA allocations. Allocation can still fail if another process consumes VRAM after the check. -- Local `clang++ -std=c++20 -Wall -Wextra -Werror -fsyntax-only` passed for the smoke source with a temporary CUDA API declaration stub; `git diff --check` passed. No CUDA execution or CPU/GPU checksum comparison was performed because the Linux RTX 5090 remained occupied. The temporary stub was removed. -- The original full-tensor size cap also rejected split PLE records in `--row` mode despite their bounded output. The smoke input check now caps the actual decoded output at 100 million F32 values, allowing a larger compressed record when only one row is requested. The compressed-prefix VRAM admission check still applies. This change has no GPU runtime result yet. - -## 2026-10-03 — resumable transfer retry - -- `model fetch` now makes at most four attempts per shard for transient transport, timeout, short-body, and HTTP 408/429/5xx failures, with 1/2/4-second waits. Each attempt reopens and rehashes its `.part` file before resume; malformed Content-Range, storage errors, and SHA-256 mismatch remain terminal. Local HTTP tests recovered from a 503 while resuming an existing partial file and from a short 200 response by requesting the newly missing range. Both published only the manifest-matching completed file. -- All 93 Rust tests and Clippy with warnings denied passed on macOS arm64. No real model download was repeated for this policy change; hosted CI and Linux GPU inference remain pending. - -## 2026-10-03 — optional private Hub download credential - -- `model fetch` now reads optional `HF_TOKEN` at runtime and attaches a Bearer header only to the exact HTTPS `huggingface.co` host. The token is not placed in manifests, logs, or model artifacts. Manifest URLs and redirects containing userinfo are rejected; reqwest removes sensitive headers when a redirect changes host, port, or scheme. A request-builder test checks that a lookalike domain and local fixture URLs receive no token. No private model was fetched during this validation. -- All 95 Rust tests, Clippy with warnings denied, rustfmt, and `git diff --check` passed on macOS arm64 before the Linux cross-build. The new tests cover exact-host credential scoping and rejection of URL-embedded credentials. - -## 2026-10-03 — private Linux x86_64 preparation host - -- Cross-built the Rust control-plane/CLI at commit `3a96103` for `x86_64-unknown-linux-musl` on macOS arm64 using the pinned Rust 1.99 toolchain and musl cross compiler. The 16 MiB ELF reports static PIE, has no ELF interpreter or `DT_NEEDED` library, and has SHA-256 `d49e02212537b0290717dd7c0818c8ce1b4569712cba4c1bf5acd394285007de`. A private copy at `/home/para/.local/bin/leleka-api-x86_64-musl-3a96103` on the Linux RTX 5090 host matched that digest, returned `leleka-api 0.1.0`, and passed `doctor` under driver 595.91.07. This validates the CLI and driver check, not GPU inference or a single-file CUDA engine. -- The host's NTFS model volume had both expected-size IQ3_S source shards. An old incomplete Q5_K_XL download and nine unneeded experiment-copy directories containing only Q4_K_XL GGUF duplicates were removed after checking current process use, reclaiming 634,919,717,485 bytes in total. Available space rose from about 91 GiB to 683 GiB. The current Strata process's IQ3_S shards, pack, and MTP files were left intact. Low-priority SHA-256 verification of the remote IQ3_S shards matched the manifest values `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. Only after this check, their 83,617,662,656-byte duplicate copies were removed from the Mac; the v4 KAR archive and overlay remain. The Mac's ten authorized Time Machine local snapshots were then removed, raising reported free space from 17 GiB to 138 GiB. The local cross-build directory was removed after the private Linux copy passed its checks. - -## 2026-10-03 — RTX 5090 KAR CUDA smoke - -- On Linux x86_64, driver 595.91.07 and CUDA toolkit/runtime 13.2, compiled the pinned `libkar.cu` plus the local smoke target for `sm_120`. The current Strata server was idle; one synthetic non-streaming Chat Completions request completed with `finish_reason=stop` and 39 prompt / 4 completion tokens. Its raw response and timings are stored privately at `/mnt/microcrm-flash-preflight/microcrm-flash-next-experiment/leleka-api/baseline-smoke-iq3-s.json`. The server used engine commit `30ec18ec7094550fcc594fd948220d511d80464e` with six dirty paths, engine binary SHA-256 `f631b32495440f1dde716734559e757b76f5436c34ca49164cb97bd80b4b18e7`, and config SHA-256 `ac4eebc189350a6392078f168c71cabb45042221e0f7321006922002c1b2a3e0`. This four-token request is a readiness smoke, not a throughput baseline. -- The server's authorized `/unload` returned `unloaded`; GPU memory use fell from 31,867 to 34 MiB while its HTTP process stayed ready for `/load`. On a 32-element KAR fixture, both full and one-row GPU decoding matched the CPU FNV-1a `ff9fd7a827b333a5`. Thirty warm GPU iterations gave medians 0.002816 ms full and 0.003136 ms row, with compressed residency 64 bytes. These are tiny-kernel timings, not a model speed claim. -- The verified 18,827,008-byte real level-3 overlay was copied privately to the NTFS volume and matched its known SHA-256 `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`. Full GPU decoding of `blk.34.ssm_beta.weight` at level 3 matched the independent CPU byte checksum `7a8bd0b57620bfea` across 122,880 F32 values; one-row GPU decoding of `blk.0.ffn_gate_inp.weight` matched CPU byte checksum `1a84ea920505914` across 2,560 F32 values. Each used 30 warm iterations; GPU medians were about 0.003168 ms on these small outputs. This checks CPU/CUDA reconstruction for two real records, not an end-to-end model-quality or throughput result. -- A private v5 PLE-partitioned level-2 conversion is running on the verified remote GGUF shards with low CPU/I/O priority. The v4 base archive is being copied privately for the larger PLE row and overlay-selection smoke checks. No v5 size, model quality gate, or compressed-model inference result is claimed before those jobs finish and independent verification passes. - -## 2026-10-03 — warm control arm and complete overlay decoder parity - -- `scripts/bench-chat-paired.py` and a public three-case synthetic suite now record per-case quality and paired wall time when two endpoints exist. The current server initially returned HTTP 400 while its `/health` reported `loaded: true` with `max_context: 0`; the harness now optionally waits for nonzero context before sending requests. After the model became ready, 15/15 timed baseline responses passed arithmetic, retrieval, and function-call checks (five repetitions each). Median HTTP wall time was 0.0959 s overall, 0.0959 s arithmetic, 0.0670 s retrieval, and 0.1613 s function call. The private response report and hardware/config metadata are on the remote NTFS experiment volume. Archive transfer and conversion were concurrently active, and no compressed endpoint exists, so this is a functional warm control arm, not a paired A/B speed result. The standard server was unloaded through its API after the run; VRAM use returned to 34 MiB. -- `scripts/check-kar-cuda-records.py` compared Rust CPU and CUDA reconstruction checksums for all 22 records in the private level-3 precision overlay. The checksum matched for **22/22** real records: full output for records up to one million values and row 0 for larger records. Thirty warm CUDA iterations per record gave isolated median decode times from 0.002496 to 0.003200 ms; recorded compressed residency ranged from 53,792 to 13,762,592 bytes. Transfer/setup time, matrix multiplication, and model-level quality are outside this measurement. The independent paired full-record L2 report for those same 22 records has median relative L2 0.50735 at base level 2 and 0.22608 at overlay level 3; this improvement is numerical, not a passed model-quality gate. The model-free temporary GPU fixture was removed after validation. -- A local release CLI independently verified the complete 55,295,529,472-byte v4 archive and decoded row 0 of `per_layer_token_embd.weight#strata-part-001-of-002` at level 2. Its 160 F32 values have FNV-1a `c6f74b955ce5a5ae`. This is the CPU oracle for a later GPU check after the remote v4 transfer finishes and its SHA-256 is verified. The temporary local Cargo build directory was removed after this run. -- The local CI entry point now checks Python syntax for both new offline measurement scripts and runs a mock HTTP A/B test. That test delays readiness until `max_context` becomes nonzero, requires bearer authentication, checks three case results per arm and paired output equality, and confirms the private report has mode 0600 without the token. It passed locally with Python 3; hosted GitHub Actions still cannot run until a repository is created. - -## 2026-10-03 — selective KAR row transfer prototype - -- Added an isolated CUDA prototype that verifies a KAR archive, gathers only the requested rows' scales and plane words into one compact packet, and decodes that packet on GPU. On RTX 5090 (driver 595.91.07, CUDA 13.2), level-3 `blk.0.ffn_gate_inp.weight` rows 0 and 1 each reconstructed to the same FNV-1a values as the independently verified Rust CPU decoder: `1a84ea920505914` and `b9359351c81dc9fb`. One row used a 1,136-byte H2D packet versus a 573,472-byte complete record prefix; two rows used 2,256 bytes versus the same prefix. The first kernel's one-row test had median H2D event time 0.003008 ms and decode event time 0.007328 ms over 30 warm iterations. A later two-row run measured 0.009110 ms to build the packet from the mapped, already-verified archive; its separate payload verification took 42.405 ms. Storage/cache state affects both host measurements. The existing full-prefix smoke on the same record reported `reserve_ms=0.044608` and warm decode median 0.003200 ms, but its reserve includes allocation/synchronization and the two programs have different setup paths, so these timing numbers are not a paired speedup claim. The first instrumented prototype binary SHA-256 was `c4c987a514b1ceb0a620b178ff99f63c1dd75f4f71abc98a7e01267ae8d83c10`; it was built with the server's CUDA 13.2 `nvcc`. The server lacks CMake, so the new CMake target itself has not run there; the direct `nvcc` build and real CUDA execution passed. -- An isolated copy of the imported Strata engine source was configured and built as the `strata` target on the RTX 5090 host with CUDA 13.2, `sm_120`, GCC 15.2, and CMake 4.4.3. Its pinned llama.cpp dependency resolved to `3cf03257f219afbe7334045ff7c6a06ac68c627d`, and the executable SHA-256 is `22542ee4c80a67f8796bd6f03048da29af704a3df44a75bccce6aad9930f41be`. The CLI started and printed usage for `--version` (that flag is unsupported). This checks reproducible compilation of the fork without touching the active server process; no model was loaded with the new executable yet. The isolated source/build occupies about 791 MiB on ext4 and can be cleaned after candidate validation. -- The selective-row kernel was changed to eight neighboring threads per 32-value coded word with compile-time precision specialization. Its current binary SHA-256 is `d5a0343f042c71cbf1dbcaa749c83af387f08174396b046247bf5b87aa982a93`. On the same two real overlay rows, the byte checksums stayed exact and 30 warm GPU decode events had median 0.003200 ms for two rows, versus 0.009344 ms in the earlier single-thread-per-word prototype. This is a kernel-only before/after under separate executions; packet transfer and host work were measured separately, and neither result says anything about model throughput. - - -## 2026-10-04 — native cancellation failure isolation - -- The Rust supervisor previously waited indefinitely for `DONE` after `STOP`. - It now drains for at most 20 seconds, discards post-cancellation events, - revokes readiness before killing/reaping an uncooperative worker, and releases - queued requests without reusing an unaligned wire stream. -- A real HTTP test on Linux x86_64 exposed a second defect: idle text/tool SSE - relay tasks did not observe a disconnected client until another engine event - arrived. Both relays now observe the downstream channel closing immediately. - The regression covers both idle text and idle function-call streams. -- `cargo test --locked` passed **98 tests**, including cooperative cancellation, - unchanged successful mock-worker token output, and uncooperative STOP. - Rust format, Clippy with warnings denied, Python syntax and diff checks passed. -- The static musl CLI ran `scripts/smoke-worker-cancel.py` on the Linux host: - STOP was delivered after HTTP disconnect; termination took **20.002 seconds**; - the queued request received HTTP 503 `worker_not_ready`; readiness was Failed - with no context; the worker was reaped; `/health` still returned 200. - This uses sanitized mock engine/tokenizer assets, no model or GPU inference. -- Verified ELF has no interpreter or dynamic library dependencies. Size: - **16,963,568 bytes**; SHA-256: - `4caa3ec4bf4657dadfa6d008351f493a70c99fcc32479255d30dc1684a62018d`. - One private CLI artifact is retained; remote uploaded test binary/script and - temporary fixtures were removed. The private verification JSON remains. -- The HTTP regression is added to the static CLI GitHub Actions job. Hosted - Actions has not run because the project still has no GitHub repository. - Automatic restart, real-model replay and soak stability remain open; - no production profile switch or throughput improvement is claimed. - - -## 2026-10-04 — bounded native worker recovery - -- Added an outer supervisor recovery loop after a post-READY crash or protocol - failure. Default lifetime budget: three restarts, with 2/4/8-second backoff; - `engine.max_restarts` / `STRATA_MAX_WORKER_RESTARTS` accepts 0 through 3. - Zero disables recovery. Startup failures stop the loop. Successful requests - do not replenish its budget. No failed generation is automatically replayed. -- Active and queued requests fail; commands received during backoff or startup - are rejected. Readiness has no context in `restarting`/`starting` and returns - only after a fresh positive handshake. Shutdown interrupts backoff. -- All **102 Rust tests**, format, Clippy with warnings denied, Python syntax and - diff checks passed. New failure fixtures cover crash-once recovery, active - and queued request isolation, rejected commands during backoff/startup, - perpetual crash budget exhaustion, startup failure and shutdown preventing - respawn. Existing cooperative cancellation and output fixtures remain green. -- The actual static Linux x86_64 CLI passed both HTTP smoke modes. Recovery - took **2.013 seconds** with a one-restart budget. The failed request and a - request during recovery got 503; a fresh post-READY request got 200 with - expected text `A`. Exactly two process starts and two generations were - observed: the failed generation was not replayed. With recovery disabled, - STOP failure isolation again passed at **20.002 seconds**, with queued 503, - Failed readiness, reaped worker and health 200. -- Static ELF: **16,984,160 bytes**, no INTERP/NEEDED; SHA-256: - `eb90708ccce588e16bfab4af2a1346de1c9033a7bd57664c457c746907dfcf76`. - Both HTTP checks use sanitized fixtures; no real model/GPU load or soak is - claimed. CI definitions now include recovery; hosted Actions has not run. - Production console profiles have not been switched. - -## 2026-10-04 — actual-model native Responses qualification - -- A real IQ3_S generation on the RTX 5090 exposed missing `RESUME`/`REUSED` - handling in the Rust wire parser. Both prefix-count metadata lines now parse - without ending a request; invalid counts and unknown tags still fail closed. -- All 102 Rust tests, format and Clippy with warnings denied passed. The static - Linux CLI then passed text JSON/SSE and typed function-call JSON/SSE on the - actual baseline model. Both streams had contiguous event numbers and exactly - one terminal event. A two-turn tool result continuation also passed. -- Real HTTP disconnect released the same worker for a successful next request. - Killing the owned engine child produced a failed terminal event and rejected - requests while unavailable; a new worker reached READY in 25.4056 seconds, - then answered correctly. This is one reload under warm storage caches. -- Static CLI: 16,983,824 bytes, SHA-256 - `ee1dd490c64efb636025da74868dad1a59662eb2f95409513f7b900b01d534be`; - no ELF interpreter or required shared libraries. Serving directly used Rust - and the C++ engine; Python only drove offline tests. -- See [the complete scope, configuration and results](experiments/2026-10-04-native-responses.md). - This is not a paired speed result, full Codex replay, reasoning/structured - output qualification or soak. Production profiles remain unchanged; hosted - Actions has not run. Temporary test assets and remote CLI were removed. - -## 2026-10-04 — live structured output feature - -- Connected native Responses `text.format=json_object/json_schema` to live - generation, prompt guidance, schema validation, JSON and SSE, and tool-result - continuation. Structured SSE holds generated items until DONE and validation; - schema failures publish only a failed terminal. Token limits return an - explicitly incomplete response whose partial text may not be valid JSON. - This is validated generation, not a token-level grammar decoder. -- All **105 Rust tests**, formatting, Clippy with warnings denied and diff - checks passed. New live-route cases cover JSON/SSE parity, wrong JSON/types, - token limits, tool-only turns, history, schema rejection before admission, - no structured deltas before DONE, and cancellation while buffering. Existing - plain-text and tool streaming tests remain green. These run in the existing - Rust CI job; hosted GitHub Actions has not run. -- Actual private IQ3_S model, baseline engine/config/hardware from the - [native Responses report](experiments/2026-10-04-native-responses.md): **8/8** - feature checks passed on RTX 5090, greedy, reasoning none, one slot/256K, - INT8 K+V resident32K, spec4. JSON and schema JSON produced the expected - objects in both nonstreaming and SSE modes; SSE sequences were contiguous - with one terminal. One-token limits returned incomplete in both modes. - A typed `record_value(7)` tool call followed by its result produced the exact - schema-valid object `{"confirmation_code":"RECORDED-731"}` over SSE. -- Single-request HTTP wall times, recorded only as functional diagnostics: - object JSON 0.4943 s; schema JSON 0.6286 s; limited JSON 0.0424 s; - object SSE 0.3174 s; schema SSE 0.3298 s; limited SSE 0.0378 s; - tool call 0.8696 s; structured continuation 0.2837 s. Requests were sequential - with mixed prefix reuse; these are not an A/B speed comparison or statistics. -- Static musl CLI: **17,046,600 bytes**, SHA-256 - `b1276083b9a71ea74a0cdefd66f968d064a6dc430a177dc2cd9509a25294b6dc`. - Private raw evidence and offline driver: - `/home/para/.cache/leleka-api/native-structured-20261004`. - Initial test setup pointed to the extraction parent rather than its tokenizer - child; correcting that private configuration allowed startup. No serving - code workaround or Python serving component was added. -- The isolated runtime, uploaded CLI, extracted tokenizer and temporary config - were removed after checks. Source model shards and production profiles were - unchanged. Native reasoning remains a separate feature; full agent replay - and soak are still required for production qualification. - -## 2026-10-04 — native reasoning feature - -- Added effort selection (`none/low/medium/high/xhigh`, default upstream xhigh), - raw reasoning output items, live `response.reasoning_text.delta` events, - separate final answer/tool items, original-token reasoning usage, and raw - reasoning replay in stored/stateless tool continuation. Closing Qwen markers - split across tokens are handled without leaking them into either text field. - Thinking truncated by the output budget returns incomplete reasoning without - inventing an answer; a normal stop missing the boundary fails explicitly. -- Reasoning deltas stream live; final answer/tool items on this path are - buffered until DONE. Structured answers remain schema-validated. There is no - summarizer: `summary:auto` returns an empty summary plus raw reasoning content; - raw thoughts are never labeled as summaries. Encrypted/summary-only context - replay is unsupported. These limits are documented in `api-contract.md`. -- **110 Rust tests**, formatting, Clippy with warnings denied, and diff checks - passed. New tests cover UTF-8/marker splits at every byte, original special- - token counting, effort validation/template selection, JSON/SSE parity, - structured answers, typed tools, unfinished reasoning, live deltas before - DONE, context replay, and idle cancellation. Existing no-reasoning paths pass. -- **8/8 actual IQ3_S RTX 5090 feature checks passed** on the same baseline - engine/hardware/configuration as the native Responses report. Requests were - greedy, low effort unless marked default, maximum 512 output tokens except - the one-token limit tests. SSE reasoning deltas concatenate exactly to final - reasoning content; event sequences are contiguous with one terminal. - -| Case | Reasoning / total output tokens | First reasoning delta | HTTP wall | Result | -| --- | ---: | ---: | ---: | --- | -| Low text JSON | 23 / 26 | N/A | 0.6743 s | Answer `4` | -| One-token JSON | 1 / 1 | N/A | 0.0382 s | Incomplete reasoning | -| Low text SSE | 23 / 26 | 0.0379 s | 0.2239 s | Answer `4` | -| One-token SSE | 1 / 1 | 0.0337 s | 0.0342 s | Incomplete reasoning | -| Reasoning + schema SSE | 26 / 33 | 0.3309 s | 0.6854 s | `{"answer":4}` | -| Default effort SSE | 35 / 38 | 0.4384 s | 0.7320 s | Answer `4` | -| Reasoning + tool JSON | 26 / 53 | N/A | 1.4660 s | Typed `record_value(7)` | -| Tool result continuation SSE | 27 / 36 | 0.1575 s | 0.4135 s | `RECORDED-731` | - -These are single sequential functional checks with mixed prefix reuse, not a -paired throughput result or full model-quality evaluation. Private evidence: -`/home/para/.cache/leleka-api/native-reasoning-20261004` (includes the driver, -raw responses/events, token usage and logs). Model files were not rehashed. -Static CLI: **17,083,088 bytes**, SHA-256 -`949696b3e915cc662f6622cb284eab46fd8d372bc82233276a0d04a1bb82eb3b`. -The isolated worker and temporary uploaded CLI/tokenizer/config were removed -after measurement; the latest CLI is retained privately on the laptop. -Production profiles remain unchanged. Full console-harness replay and sustained -soak still remain; hosted Actions has not run. - -## Native console compatibility, 2026-10-04 - -- An isolated local capture of the installed Codex CLI confirmed its actual - request fields, function namespaces and optional encrypted-reasoning include. - Capture/configs remain private outside Git. The native route now accepts that - envelope and preserves namespace identities through prompt, output and replay. -- Added optional configured model identity and direct `strata-native` discovery - in the installed qwen launcher. The installer is reproducible in - `scripts/install-qwen-native.py`; it preserves the selected connection and - existing MCP configuration. Native traffic bypasses `responses_bridge.py`. -- A real IQ3_S RTX 5090 console smoke run wrote `answer.txt`, read it through the - console shell tool and completed successfully: 370 output tokens, including - 190 reasoning tokens, across two native requests. The file contains exactly - two bytes, `42`. The console reported 45,944 cumulative input tokens and - 23,045 reused tokens. This is a functional check, not a speed comparison. -- The first full Three.js/MCP qualification attempt exposed an unsupported - array-valued tool result after a successful MCP project search. The runtime - rejected it with `tool output needs text`. Added text-part array replay and - a regression, retaining the failed attempt privately. A fresh agent run is - required after the fix; the failure is not counted as a successful benchmark. -- The next attempt reached native approval review, which failed because the - pinned prompt renderer required developer messages to be at the beginning. - The adapter now stably coalesces instruction messages at the front without - dropping their content or demoting their role. Approval remains enabled. - The incomplete attempt is retained; it produced no game and is not a pass. -- 113 Rust tests, format, and Clippy with warnings denied pass. New regressions - cover the captured envelope shape, namespace collision rejection, live - namespaced item identity, tool text-part replay, and late approval - instructions. A fresh install into a temporary launcher copy matches the - installed integration byte-for-byte; a second install is idempotent. -- The fresh console run after those fixes had no transport/protocol errors and - produced a game that passed 23/23 independent browser checks (all eight win - lines, locked terminal boards, restart, draw, occupied-cell handling, mobile - clicking/layout, and no page errors). However, the agent stopped while - preparing its own browser verification; its MCP task TEST-9 remained - incomplete. Exit code zero and `turn.completed` are not sufficient evidence - of task completion. No assistance or continuation prompt was supplied. -- That incomplete run took 452.02 s. The console reported 21,622 output tokens, - including 9,225 reasoning tokens. The engine recorded 24 requests including - approval reviews, 23,180 generated tokens and weighted decode 102.26 tok/s - (per-request median 103.75; p10–p90 70.0–129.75). These are diagnostic numbers - from an incomplete task, not a paired throughput improvement. -- Further prompt inspection found that commentary and a subsequent tool call - from the same response were replayed as separate assistant turns. They now - remain one turn, with reasoning retained and the pinned Qwen template's exact - spacing. A sanitized golden fixture was generated using the pinned local - template with Jinja2 3.1.6; native rendering matches it byte-for-byte. A fresh - independent run is needed to qualify this revision. -- Follow-up protocol checks preserve parallel result identity even when result - delivery order differs: both histories render identically in call order. - Response metadata now reports the actual greedy default temperature (`0`), - confirmed in the running fork's source (`req_temperature = 0.0f`). This does - not change sampling. The earlier console diagnostics used that greedy default. - All 116 Rust tests, format and Clippy with warnings denied pass after these - two checks. The full console run on the preceding revision is kept separate - from the follow-up protocol fixture results. -- The subsequent unassisted console run on a3770ed completed TEST-10 and its - game: 43:07 wall time, 68 main model responses, 68,403 output tokens and - 116.91 weighted decode tok/s. Agent tests passed 132/132; independent browser - checks passed 23/23. One undeclared tool name was safely rejected and retried - by the harness. These are single-run functional statistics, not a speedup. -- The deployed 93e2a9b follow-up passed ordered/reversed parallel tool result - replay on the real model with identical correct greedy output (tolerance 0) - and completed terminal states. Native launcher status and HTTP readiness - pass. The text console profile is available for a user trial; broader scope - and unverified limits are recorded in - [the full report](experiments/2026-10-04-native-console.md). - -## Native service-unit primitive — 2026-10-04 - -- STRA-15 adds `service-unit` rendering and explicit `serve --config FILE`. - This is an installable user-service primitive; managed console start/stop is - still pending. It neither migrates nor restarts the current trial endpoint. -- All 119 Rust tests passed after adding the module/config flag; the three - focused service tests and Clippy with warnings denied passed again after the - systemd path fixes. Formatting passed. Linux musl release compiled. -- Actual systemd 259 on rnr5090 passed `systemd-analyze --user verify` and the - isolated CPU-only lifecycle smoke. It checked literal spaces/percent/dollar - in the binary path, quote/backslash config and working-directory paths, - explicit config precedence over an intentionally invalid STRATA_CONFIG, - EnvironmentFile model override, HTTP health 200, readiness 503 without a - worker, exact process executable/cwd and disappearance on stop. -- The first real parser check caught that WorkingDirectory/EnvironmentFile are - raw path directives, unlike ExecStart arguments. The second caught systemd's - own executable-name rejection of quotes/backslashes. Rendering now handles - each directive separately and rejects unsupported executable/environment-file - paths explicitly. These rules were checked against the installed manual and - [systemd v259's parser](https://github.com/systemd/systemd/blob/v259/src/core/load-fragment.c). -- The temporary unit, configuration, smoke script and remote executable were - removed; no matching smoke user units remain. Local release cleanup removed - 93.8 MiB. A separate private service-preview binary was retained: 17,149,088 - bytes, SHA-256 - `a4c2430803ef7fa19692f6a3a104e59e8eb3b430743c356ac8b19c2fef5aed9c`. -- The active GPU supervisor remained PID 4031422, start ticks 558428413 before - and after, and still reported ready. No inference or model-loading request - was sent to it. The new binary was not deployed over the trial binary. -- Unit syntax smoke is wired into Linux CI; hosted Actions remain unexecuted. - GPU shutdown under a systemd-managed service and login/boot persistence have - not been qualified by this CPU-only smoke. Instructions are in - [deployment](../deploy/README.md#native-linux-service-lifecycle). - -## Console service control — 2026-10-04 - -- STRA-16 adds explicit `qwen-codex-ctl native-service start/stop/status/logs` - for a named systemd user unit over SSH. It does not select a model, provision - a unit, create a tunnel, or infer model readiness from process state. -- Seven focused Python checks passed: idempotent operations, selector rejection - before SSH, missing/invalid status, bounded unit-specific logs, installer - backup/idempotence/profile preservation and refusal to overwrite an unrelated - helper. The test is included in `scripts/check-local.sh` for future Linux CI. -- The installed real controller completed status/start/start/status/logs/stop/ - stop/status against `leleka-api-controller-smoke-20261004.service` on - rnr5090. This isolated CPU-only native service reported the expected model - identity via HTTP and correctly remained unready without an engine. The - second start and second stop reported `changed: false`. The normal default - `leleka-api.service` was absent and was not created by a status call. -- The laptop integration is installed with a private backup; the normal - connection remains unchanged. This is client-side Python only; inference - still runs directly through Rust and the existing engine. -- Real GPU service migration, managed GPU stop during active generation and - login/boot persistence remain unqualified. The external trial endpoint is - preserved; these commands do not adopt it. Raw smoke results are private in - `~/.cache/leleka-api/native-console-20261004/controller-service-quality.json`. - -## Optional native API auth — 2026-10-04 - -- STRA-17 adds private file-backed bearer authentication. All routes except - `/health` are protected when configured; auth-off remains compatible. Invalid - key files fail before bind/worker startup. Stored credential state is a hash; - fixed-size comparison uses the already locked `subtle` 2.6.1 dependency. -- **122 Rust tests**, formatting and Clippy with warnings denied passed; the - static musl release built. CPU-only real HTTP smoke on rnr5090 passed missing, - wrong and duplicate-header rejection before JSON parsing; correct-key status, - public health, protected readiness, malformed/oversized/insecure/missing key - files, nonblocking FIFO rejection, absence of token echo and auth-off behavior. -- Native launcher upgrade, fresh installation from the prior clean launcher, - repeated installation and coexistence with `native-service` passed. The - installed launcher's exec was intercepted without launching an agent: the - auth command read exactly the private test token while neither argv nor - environment contained it. Insecure key permissions were rejected. The native - unauthenticated trial still passes discovery. Seven service-controller tests - also remain green. This is not a full authenticated model/agent qualification. -- Tests caught and fixed an installer-only indentation error on the fresh path; - existing-install upgrade was unaffected. Temporary credentials and copied - launchers were removed automatically. The remote CPU smoke executable/script - were removed; local release cleanup freed 93.8 MiB. The superseded service-only - preview was removed after retaining the combined feature preview (17,206,032 - bytes, SHA-256 - `1f069d66e4546077e3d2494fc725cde994166769d98e506f2c73ab55d1eea121`). -- The GPU trial remains on its prior qualified binary, PID 4031422/start ticks - 558428413, still ready. It was not restarted or sent inference requests. - Hosted CI and independent security review remain pending. This feature does - not add TLS, multi-user isolation or hot key rotation; loopback plus SSH - remains the console transport boundary. - -## Native generation metrics — 2026-10-04 - -- STRA-18 adds a separate authenticated JSON `/metrics` endpoint. It reports - admitted generation activity, bounded channel occupancy, completion/cancellation/ - failure counters, last DONE telemetry and weighted DONE decode rate. `/status` - stays unchanged for console discovery. No prompts, generated text or token IDs - are captured; metrics update only at generation boundaries. -- **124 Rust library tests** passed, along with formatting, Clippy all-targets - with warnings denied and a static Linux musl release build. Existing mock - worker checks now assert active state, cancellation and subsequent generation, - ERR without restart, context rejection exclusion, shutdown interruption and - counters surviving crash/restart. Token events and terminal ordering remain - identical to the fixtures (tolerance zero); no model parameters changed. -- A real HTTP CPU fixture verifies JSON schema, queue occupancy and stable - discovery. Rate tests cover zero duration, overflow and disconnected DONE. - The existing Linux auth smoke now checks protected and authenticated metrics, - initial null/zero values, and auth-off access. This extended smoke passed on - rnr5090 using a temporary process with no engine/GPU and is already included - by the existing CI smoke step. Hosted GitHub Actions have not run. -- Retained combined feature preview: 17,228,336 bytes, SHA-256 - `389d7784c065f978a8b1d0a064b4f3b619e03c6a65895c64b89d278c383df798`. - It supersedes the previous feature preview only. The GPU trial binary and - SSH tunnel remain untouched; PID 4031422/start ticks 558428413 were confirmed. - The trial does not expose the new metrics until a deliberate future upgrade. -- Remote smoke files were removed, ephemeral test keys/configs were cleaned by - the smoke harness, and release cleanup freed 93.8 MiB. The reusable debug build - and private final preview remain. Independent QA and real-model telemetry - qualification are pending; this change claims no speedup or soak stability. - -## Custom text tool transport — 2026-10-04 - -- STRA-19 implements custom text declarations, namespace restoration, native - custom call/input SSE events and typed call/output replay. Qwen uses its - existing one-string function parameter internally. Grammar formats and - unsupported custom fields fail explicitly; no grammar constraint is claimed. -- **127 Rust library tests** passed, formatting and all-target Clippy with - warnings denied passed, and the static Linux musl release built. New coverage - verifies exact multiline/Unicode/whitespace input, namespace and call identity, - public event fields, invalid envelopes, mismatched output kinds and mixed - parallel output ordering. Existing stored continuation and reasoning tests now - exercise both function and custom calls. An incremental test observes custom - input before engine DONE and verifies one matching terminal response. -- `scripts/smoke-custom-tools.py` passed on rnr5090 with the static binary and - a synthetic CPU shell engine: JSON and SSE, reasoning none/low, exact input, - stored continuation and grammar rejection before admission. The smoke is - added to the Linux workflow; hosted GitHub Actions have not run. These are - protocol checks, not model quality or performance measurements. Existing - function/template regressions passed with exact fixture equality. -- Retained combined preview: 17,244,760 bytes, SHA-256 - `b10a7ce9ec8cc85fa99305ba90a9f2b547c22ab0edc407c719355594c5c0c63d`. - The superseded preview was replaced. Temporary remote smoke files and local - smoke bytecode were removed; release cleanup freed 93.8 MiB. Final preview - remains private, with reusable debug build retained. -- User trial is still the earlier qualified binary, PID 4031422/start ticks - 558428413, with readiness and tunnel intact. No GPU inference or agent task - was started, assisted or interrupted. Custom-tool real-model qualification, - grammar support and independent QA remain pending. - -## Native admission drain — 2026-10-04 - -- STRA-20 adds `/admin/drain`, `/admin/resume` and `/admin/lifecycle`, protected - by the existing optional auth gate. New Responses admissions receive 503 - during drain and readiness is withdrawn; already admitted JSON/SSE requests - continue. No worker stop, reload or model switch is performed by these APIs. -- RAII guards track request/body lifetime separately from generation-command - lifetime. The command guard remains held through STOP drain or failed-worker - cleanup, avoiding a false drained result when an HTTP client disconnects. - Frame and trailer forwarding is unchanged. Direct `http-body` dependency - uses the already locked 1.1.0; no dependency version changed. -- **130 Rust library tests**, formatting, all-target Clippy with warnings denied - and static musl build passed. New checks cover admission before JSON parsing, - idempotence, body/trailer equality, distinct request/command lifetimes, - worker-state gating and a cancelled worker held until its STOP terminal line. - Existing function/custom/reasoning and worker recovery fixtures remain green. -- On rnr5090, `scripts/smoke-native-drain.py` passed with a synthetic CPU engine: - one active SSE and one queued JSON response completed with the exact expected - text and terminal event after drain. New admissions were rejected, readiness - stayed false, drained became true only after completion, and resume accepted - a fresh request. Extended auth smoke passed unauthorized admin rejection and - authorized drain/resume. The new drain smoke is wired into Linux CI; hosted - Actions have not run. These checks do not qualify full-model maintenance. -- Retained combined private preview: 17,304,272 bytes, SHA-256 - `e1e7aa29aec1f7d1aeb157920e76ae3daccff957852adee46cc36e599a7c71a2`. - Previous preview was superseded. Remote temporary files and generated smoke - bytecode were removed; release cleanup freed 93.8 MiB. -- GPU trial remains unchanged and ready at PID 4031422/start ticks 558428413, - with its existing SSH tunnel. No inference request or admin mutation was sent - to that trial. Independent QA, GPU maintenance and soak qualification remain. - Drain has no forced timeout or persistence across control-plane restarts; - exact operator semantics are documented in `deploy/README.md`. - -## Native API console control — 2026-10-04 - -- STRA-21 adds `qwen-codex-ctl native-api` commands for status, metrics, - lifecycle, drain and resume, including optional drain waiting. The installer - backs up the launcher and preserves its selected connection. Explicit URL - overrides require explicit authentication and never inherit another target's - key. API identity is checked before admission mutations. There is no automatic - service stop, resume, model switch or tunnel management. -- Eight new Python behavior tests passed: invalid target rejection before I/O, - native identity before mutation, drain completion/timeout/concurrent resume, - response validation, auth selection, direct HTTP without proxy/redirect, - bounded responses and suppression of literal or escaped credential echoes, - installer idempotence and coexistence with native-service in both orders. - All seven existing native-service tests and the installed launcher auth test - passed. `check-local.sh` includes the new tests for future Linux CI; hosted - GitHub Actions have not run. -- Built the current macOS debug control plane and tested the actual installed - controller against an isolated authenticated CPU-only endpoint: all five - commands, repeated drain/resume, drain wait, selected-profile authentication, - explicit key override, and unauthorized mutation rejection passed. Temporary - server, key, config, profile and logs were removed. The normal user connection - was compared before/after and remained byte-identical. This checks console - integration, not model quality or GPU maintenance. -- Read-only `native-api status` succeeded through the preserved GPU tunnel. - PID 4031422/start ticks 558428413 remained unchanged. No inference or admin - mutation was sent to the user trial. Its older runtime still lacks metrics - and admin routes; the client reports unsupported HTTP responses explicitly. - Linux feature-preview binary remains unchanged from STRA-20. Independent QA - and a deliberate future managed GPU deployment remain pending. - -## Embedded native engine package — 2026-10-04 - -- STRA-22 adds an opt-in Linux engine payload to the Rust executable. Build-time - SHA-256, declared source revision and target ELF header checks precede byte - embedding. Default builds remain payload-free. `engine-info` exposes payload - identity, and `--engine-license` retains the imported MIT notice. Serving uses - the payload only with explicit `engine.executable: "@embedded"`. -- Linux execution uses an executable, sealed memfd retained until supervisor - shutdown, including worker restarts; external engine configuration is unchanged. - No executable is extracted to a persistent path. No weights, CUDA libraries - or NVIDIA driver are bundled. The upstream provenance record is unchanged. -- **132 macOS Rust library tests**, formatting and all-target Clippy passed. - Tests cover payload digest/architecture/revision rejection and explicit - selection. The Linux-specific unit test additionally covers shrink/grow/write - seals and descriptor cleanup; its hosted CI execution remains pending. -- Static Linux build with a synthetic CPU ELF passed on rnr5090: embedded digest - equals the source byte for byte; seals prevent writes; worker READY and HTTP - generation return the expected `A`; forced worker crash restarts from the same - payload; output equals the external-file baseline exactly (zero tolerance); - graceful termination removes both worker PIDs and the parent memfd path. - Smoke code handles transient `/proc` socket descriptors and ETXTBSY for a - running executable. This is a packaging/protocol test, not model quality or - performance evidence. The smoke is wired into Linux CI; Actions have not run. -- A private combined preview also embeds the existing qualified engine binary: - engine size 45,680,928 bytes, SHA-256 - `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. - Declared source revision follows its retained `engine-fork-f80a3e0` build - directory: `f80a3e007354a6137c409b760dc70f8f80a3af2c`; no reproducible engine - rebuild was performed in this step. Its byte identity is verified directly. - Combined executable: 63,007,200 bytes, SHA-256 - `ec21fb36fc0ed665fab063877a575b8376d7e8fd9aacbd43889851ac46fd3f5d`, - retained privately as `leleka-api-linux-x86_64-musl-embedded-preview`. - `engine-info` and license output ran on Linux without loading the GPU engine. - Outer ELF has no INTERP/NEEDED entries. The embedded ELF still requires - libcudart.so.13, libcublas.so.13, libstdc++, libgcc, libc and libm; its existing - CUDA library RUNPATH is host-specific. This is not a fully static GPU package - or clean-node deployment qualification. -- The active user trial remained PID 4031422/start ticks 558428413. No inference, - admission mutation, GPU load or tunnel restart was performed. Independent QA, - clean-node library packaging and real-model embedded startup remain pending. -- The default CLI was also checked to reject `@embedded` before opening its - listener when no payload is present. Temporary remote smokes and local input - copies were removed; release cleanup freed 108.0 MiB. The private final - package and the reusable debug build remain. - -## Static CUDA toolkit engine profile — 2026-10-04 - -- STRA-23 adds `STRATA_CUDA_STATIC`, default OFF, requiring Linux/GNU/CUDA. - CMake selects static runtime/cuBLAS targets, including the explicit KAR and - parity runtime links; the `strata` executable links GNU C++/GCC runtimes - statically and omits build-host RPATH. No engine arithmetic source changed. -- A full isolated SM 120 Release build passed on rnr5090 with GCC 15, - CUDA 13.2.86 and portable GGML AVX2 configuration. Compilation ran at nice 10 - with two jobs. Only `--help` was executed, with empty CUDA_VISIBLE_DEVICES and - LD_LIBRARY_PATH removed; no model or GPU context was initialized by the test. -- ELF audit passed: DT_NEEDED contains only libm.so.6, libc.so.6 and - ld-linux-x86-64.so.2; no RPATH/RUNPATH, libcudart, cuBLAS, libstdc++ or libgcc_s - shared dependency remains. Minimum versioned glibc requirement is **2.43**. - Runtime `dlopen` dependencies and model behavior remain unqualified. -- Engine artifact: **593,942,184 bytes**, SHA-256 - `389b518c3c8afaccd20bab78f538e008ff996d11dacb08abe73e315a853c6b11`. - Retained privately on the Linux host as `strata-cuda-static-preview`. - This exceeds the existing embedded payload cap of 128 MiB; the 63 MB combined - preview from STRA-22 remains unchanged. This candidate is not fully static or - qualified for older glibc distributions. -- Five default Linux CPU tests passed: conversation cache, conversation memory, - cache retention, coupled draft and BF16 conversion. A real-ELF fixture gate - passed accepted libc-only linkage, rejection of a toolkit RUNPATH and rejection - of a fake libcudart DT_NEEDED dependency. Invalid CUDA-off/static-on configuration - failed before CUDA setup. Default CUDA configuration still selects shared - libcudart/cuBLAS. Local macOS CMake was unavailable; these checks ran on Linux. -- The ELF fixture is in local/CI checks, and an opt-in private-runner dispatch - builds/audits the static profile without publishing it. Hosted Actions have not - run. Numerical/model parity, clean-node qualification and performance evidence - are pending; no serving default or active user endpoint was changed. -- The preserved trial still reported ready at PID 4031422/start ticks 558428413; - its SSH tunnel was unchanged. The 1.3 GiB isolated source/build directory was - removed after retaining the private candidate, link command, CMake cache and - build/test logs. No original toolkit archives, baseline binaries or model - files were removed. -# Static CLI OCI acceptance (STRA-66) - -`deploy/Dockerfile.static-cli` builds the Rust CLI/control plane into `scratch`. -Its build context includes the upstream license used by `--engine-license`; -the other engine files remain excluded. Build and verify it with: - -```sh -docker build -f deploy/Dockerfile.static-cli -t strata-cli-check . -python3 scripts/smoke-cli-container.py strata-cli-check -docker image rm strata-cli-check -``` - -On an arm64 Linux Docker host, pass -`--build-arg RUST_TARGET=aarch64-unknown-linux-musl` to the build. The hosted -`linux-cli-container` job builds the actual x86_64 image and checks the exact -upstream license, CLI version, missing embedded engine/model, HTTP health, -not-ready response, and graceful shutdown in an isolated non-root read-only -container. CLI prereleases require this check as well as the static binary job. -This is a CLI-only image: full CUDA OCI deployment, model startup and GPU -readiness remain separate acceptance gates. No image is pushed to a registry. - -## Isolated hosted CUDA packaging (STRA-69) - -`workflow_dispatch` input `hosted_cuda_package=true` selects a private-repository -Ubuntu 24.04 CPU job. It never targets the private GPU runner. The existing -`static_cuda_package` and `keyless_gpu` inputs remain false unless explicitly -selected. This build does not load a model or install a driver. - -The build-only `scripts/bootstrap-cuda-toolkit.py` assembles seven components -from NVIDIA's [CUDA 13.0.1 redistrib manifest](https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.1.json), -using its committed manifest/component SHA256 and size pins in -`deploy/cuda-toolkit.lock.json`. Download size is 872,943,748 bytes. A fresh private -prefix, bounded downloads/expansion, safe tar extraction, collision/link checks -and retained component licenses avoid a system CUDA installation. This is a -build dependency bootstrap, not an end-user runtime installer. NVIDIA documents -[component assembly and supported host compilers](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-installation-guide-linux/index.html). -The job explicitly uses GCC 13, one engine compile job, two Rust build jobs and a -150-minute job limit; it refuses acquisition below 6 GiB RAM or 12 GiB free disk. -Actual host/compiler versions and initial resources are recorded. Toolkit bytes -are pinned; hosted OS/compiler patch updates mean byte-identical rebuilds are -not asserted. - -Nonempty Linux engine payloads use a target-assembler `.incbin` in a read-only -ELF section after the existing bounded SHA/ELF verification. Rust references -that immutable section through an exact-length external static; it does not -parse a 600+ MB engine as a Rust byte-array constant. Empty/nonembedded builds -remain unchanged. The hosted packaging step records memory/disk counters and -`time -v` resource usage. Two initial hosted attempts received runner shutdown -signals during the previous Rust embedding path; those logs do not establish -an OOM diagnosis. Exact memfd bytes, seals, restart and external-worker output -equality remain mandatory checks for this build-path change. - -Existing static-engine, combined-package and OCI builders supply the actual -compile/link, dependency/ABI, embedded identity and GPU-hidden help gates. -The private `leleka-api-hosted-cuda-preview` artifact retains package checksums, -source provenance, image archive/receipt, exact toolkit manifest/toolchain data -and component license archive. Retention is seven days. Successful upload is -required; an ephemeral hosted runner is not durable fallback storage if upload -fails. Owned build directories and image are cleaned. Tests use deliberately -invalid archives/receipts and do not require CUDA; only a successful manual -actual-CUDA job qualifies compilation and packaging. GPU driver loading, -full-model/MTP inference, quality and clean-node rollback remain separate gates. - -PLE-only packaging is selected with Gitea input `hosted_cuda_ple=true`; its job -uses the CPU runner and hides all GPU devices inside the pinned build container. -The workflow reads Gitea's raw dispatch inputs as strings and explicitly -compares each opt-in to `true`, so a false string cannot enqueue GPU jobs. - -The Rust installer is pinned separately from the compiler toolchain: - -| Dependency | Pin | -| --- | --- | -| rustup-init | 1.29.0, SHA-256 `4acc9acc76d5079515b46346a485974457b5a79893cfb01112423c89aeb5aa10` | -| rustc / cargo | 1.99.0 from `rust-toolchain.toml` | -| CUDA toolkit | 13.0.1 manifest; NVCC 13.0.88, component hashes in `deploy/cuda-toolkit.lock.json` | -| CUDA build image | Ubuntu base digest `f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b`; GCC/G++ 13 | - -The runner's `ubuntu-latest` label and job container image are runner -configuration, not immutable pins; actual OS and apt package versions are -recorded in artifact provenance. Trigger a private build on a committed branch -with the Gitea API (input values are strings): - -```sh -tea api --repo para/leleka --login git.vezha.io --method POST \ - -d '{"ref":"refs/heads/BRANCH","inputs":{"hosted_cuda_ple":"true"}}' \ - /repos/para/leleka/actions/workflows/linux.yml/dispatches -``` - -## Native per-user installation (STRA-72) - -On Linux with a running systemd user manager: - -```sh -/opt/leleka-api service-install --config /srv/strata/config.json \ - --working-dir /srv/strata --env-file /srv/strata/runtime.env \ - --unit leleka-api-preview.service --start -``` - -`--env-file` and `--start` are optional. The command reuses `service-unit`'s -literal-path renderer and installs a private regular file under -`$XDG_CONFIG_HOME/systemd/user` (default `$HOME/.config/systemd/user`). It -atomically publishes without replacing an existing file. An identical owned -private file is reused; differing content, symlinks and special files fail. -Use a new unit name for a different deployment. Config, binary, working directory -and optional environment file must already exist at absolute paths; keep them -at stable locations. Configuration/model validation still occurs in `serve`. - -Before start, it checks that the manager resolves this unit file without existing -drop-ins; a different XDG search path or overriding runtime unit fails closed. -The command runs user `daemon-reload`, then optional `start`, each with a -30-second client deadline. It never uses sudo, enables login startup or configures -lingering. Failure retains the installed unit for explicit retry. A timed-out -systemctl client is killed/reaped, but a job already accepted by the manager may -still be pending: inspect `systemctl --user status UNIT` before retrying. -Successful start is process activation, not model readiness; use `wait-ready` below. -The JSON `enable_requested: false` records that this command did not enable the -unit; it does not query or undo an existing enablement. - -The existing `smoke-service-unit.py --lifecycle` now exercises native installation, -exact reuse, conflict preservation and actual user-manager start/health/stop on -an isolated hosted Linux runner, with a control-only service. Offline manager -failure/retry and symlink checks also run. This does not qualify GPU/model loading, -boot persistence, runtime upgrades or automatic rollback of a live GPU service. - -## Native readiness waiter (STRA-78) - -After activation, or through an existing SSH loopback tunnel: - -```sh -/opt/leleka-api wait-ready --url http://127.0.0.1:18082 \ - --model strata-native-iq3-s --key-file /srv/strata/api.key --timeout-s 300 -``` - -Only `GET /status` is sent. Success emits JSON with `ready`, `service`, `model` -and `attempts`; it requires the exact model ID, `service: leleka-control-plane`, -`worker: ready` and `ready: true`. This is a readiness snapshot, not an inference -or quality probe, and availability may change immediately afterward. - -The timeout defaults to 300 seconds (range 1..3600) and bounds the entire network -wait, including slow headers, body chunks and retry delays. Parameter/key-file -validation precedes that budget. Each HTTP attempt is also capped at 3 seconds; -network failures, HTTP 429/5xx and loading/unready states retry every 250 ms. -Authentication failures, redirects, wrong identity and malformed or oversized -responses fail immediately. The body limit is 64 KiB. Errors do not print peer -bodies, credentials or transport URLs. - -The URL must be an HTTP origin with a literal loopback IP, no credentials, -non-root path, query or fragment. IPv4 and IPv6 loopback are supported; remote -servers require an existing SSH tunnel. Environment proxies and redirects are -disabled. Optional `--key-file` uses the same bounded regular-file/private-mode -and token-format checks as server authentication; omit it for an unkeyed service. -No model, engine or config is loaded by this command, and no service/tunnel is -created, restarted or modified. It does not upgrade the installed Python switch -controller or alter its existing readiness logic. - -The hosted CPU HTTP gate checks exact identity, loading/retry, auth, redirect -refusal, proxy bypass, oversized/chunked responses, slow header/body deadlines, -private key validation and an actual native service's worker-ready/worker-exit -states. No generation command is sent; real GPU/model qualification remains open. diff --git a/docs/chain-kernels.md b/docs/chain-kernels.md deleted file mode 100644 index eb9930c0..00000000 --- a/docs/chain-kernels.md +++ /dev/null @@ -1,116 +0,0 @@ -# Chain kernels: the GPU chain of the decode verify window and of the MTP draft step (`claude/chain-kernels`) - -Status: tables of section 2 are measured (ledger CUPTI traces, jobs 9062/9004). Sections 4-6 are filled as the model-free probe and A/B jobs -(`tools/chain-probe/`, jobs `9c*`) report; a number without a job name is not measured. - -## 0. Summary - -* In the hit-heavy regime of real agent sessions the verify window is the GPU chain plus the host/PCIe waits. The port's chain is **the Original's chain**: kernel for kernel the - same launch shapes and the same durations (12,561 us per 4-row window for both, section 2). Nothing in the window is slower than the Original's equivalent, and nothing is faster, - so "the port must be faster than the Original" needs kernels that the Original does not have. -* The chain is **latency-bound, not bandwidth-bound**: 2,418 kernels per 4-row window, 25 to 60 per layer, HBM busy about a quarter of the time. The biggest losses against the - bandwidth floor are small-grid kernels with serial dependent loads: the hyper-connection read (3.4 ms, 27 % of the chain, about 4x its floor), the CPU-leg row copy and the plan - copy from mapped host memory, the GDN alpha/beta gates, the QSA decode attention chunk, the hyper-connection up projection. -* `chain_window.cu` holds bit-identical variants of those kernels (same operations, same order, loads issued ahead), plus a few fusions; all behind `LELEKA_CHAIN` (off by default). -* Draft vocabulary: section 7. -* Second pass on the hyper-connection read (section 8, `claude/perf3`): the down projection is re-tiled over rows and tokens, 16.8 -> 9.7 us per read at 4 rows (bit-identical, byte-compared against the Original's kernels), 29.3 -> 22.0 us for the whole read; the window-level A/B is queued (job p36). - -## 1. Tools - -| tool | what | -| --- | --- | -| `tools/chain-probe/window_table.py` | per-role kernel table of the verify windows of two CUPTI traces (`claude/ledger`'s `tools/cupti-trace`, `scripts/profile/lct.py`) | -| `tools/chain-probe/chain_probe.cpp` | model-free probe: loads the sealed Original PTX and `chain_window.ptx`, runs both on real-size random inputs, compares **every output byte**, times both inside a CUDA graph with cold weights | -| `tools/chain-probe/mb_pdl.cu` | graph kernel-to-kernel latency with and without programmatic dependent launch, and prefetch-ahead | -| `tools/chain-probe/jobs/` | holder jobs: `9c5` paired A/B (chain off / on), `9c6` CUPTI traces of both arms, `9c7` draft vocabulary on the CRM replay | -| `scripts/chain/{build_rt,test_driver,seal_chain}.sh` | WSL builds, driver unit tests, compile+seal of `chain_window.ptx` with `compile_assets.py` / `seal_pins.py` | - -## 2. The window, kernel by kernel (port against Original, hit regime) - -Traces: ledger job 9062, `port-corpus-hit` (rt-base, no draft vocabulary bound) and `orig-corpus-hit` (unmodified Original, `--dump-routing` profile of the corpus's own routing, -static 2048 slots, ledger tracer). Windows of 4 rows (49 port / 115 Original windows) and 6 rows (6 / 22). "chain" = every kernel that is not a host or PCIe wait. - -### 2.1 Four-row window - -TABLE4 - -### 2.2 Six-row window - -TABLE6 - -### 2.3 Gaps inside the graph - -Every window is one stream and one graph; consecutive kernels start 64 to 128 ns after the previous one ends (98 % of 112,000 gaps in the 64-128 ns bin): 218 us per port window -(1.7 % of the chain), 239 us for the Original. There are no event gaps (no cross-stream edges) in the window. The graph kernel gap is therefore not where the chain is lost; the loss -is the 0.7 to 1.0 us a tiny kernel takes between its first and last thread, and the serial dependent loads of the small-grid kernels. The only exception in the Original's trace is -an 0.9 us hole after the QSA K projection (`native_mmvq_multi -> norm`, 11 us per window) which the port does not have. - -### 2.4 Ranking against the floor (4 rows, HBM 1.69 TB/s) - -| rank | family | port us/window | floor us | gap us | what limits it | -| --- | --- | ---: | ---: | ---: | --- | -| 1 | hyper-connection read: norm + staged down + up (96 calls, 13.1 MB each) | 3,391 | 910 (7.7 us HBM + 1.5 norm per call) | 2,480 | 41-block down projection 13 us (8 serial cp.async tiles), up 7.5 us (8 rows per warp loaded one behind the other) | -| 2 | routed experts gate/up + down (hits + staged) | 2,434 | 950 (1.6 GB) | ~1,500 | grouped MMQ at 12.5 us per call; ramp and tail of many small groups; not touched here | -| 3 | dense projections (qkv, z, out, q, k, v, shared) | 2,250 | ~2,000 | ~250 | at the HBM floor already | -| 4 | CPU-leg rows copy + plan copy + doorbell + their waits' PCIe reads | 1,040 | ~250 | ~790 | serial volatile loads from mapped host memory: 5 and 6 PCIe round trips | -| 5 | QSA decode attention chunk | 470 | ~60 | ~410 | 64 cells walked one dependent load at a time | -| 6 | GDN alpha/beta | 368 | ~100 | ~270 | 12 blocks, 10 dependent weight/activation rounds | -| 7 | greedy argmax (248,320 logits, one block per token) | 79 | 10 | ~70 | 243 dependent loads per thread | -| 8 | ~25 tiny kernels per layer (quantize, swiglu, scale, sigmoid, ...) | ~900 | | ~450 | launch + ramp (0.7-1.0 us each) | - -Which families are slower than the Original's equivalents: none beyond noise; routed experts gate/up and down are +100 us each in the port because the 4-row set contains more groups -(the port's hit regime differs by about 2 experts per layer between the two runs); `doorbell` is 142 us faster in the port. Extra kernels the port has: the split QSA scores/topk/resolve -(`qsa_decode_scores`, `qsa_topk_ref`, `leleka_qsa_resolve`, `leleka_qsa_miss_copy`) replace the Original's `block_scores_multi`, `block_topk_reg` (+60 us), and the PLE history snapshot copies; -no port-only guard kernels exist in the verify window (they are in the MTP step, section 5). - -## 7. The MTP draft vocabulary (coordinator request) - -DRAFTVOCAB - -## Agreement at long context and decode gain (jobs 9c5, 9d6) - -* Speed (9c5, paired by corpus prompt, 5 prompts x 3 repeats, short prompts, static tier): `LELEKA_CHAIN=all` 74.13 tok/s against 72.53 without it - (+2.2 %); all 15 pairs are positive and the number of verify rounds is the same in both arms. -* Agreement (9d6): the 40 requests of the live CRM session 9e3 teacher-forced along their recorded tokens (about 64k rows at 30-70k tokens of - context), top-16 log-probabilities of every row, against the same run without the chain kernels (arm G of 9d4, same chunk cut, static tier). - The kernels are NOT bit-identical at this length (the fusions change rounding): 5,993 of 64,355 rows are identical, d_top1 p99 0.327, max 4.31, - dmax16 p99 3.48, argmax flips 697 (1.08 %). The control for rounding noise is a chunk-cut change of the exact path (job 9d5): p99 0.394, max 4.64, - flips 1.45 %. The chain kernels deviate less than that, so they are within the rounding noise of any change in the order of the arithmetic - (the rule of `scripts/quality/q_tail_gate.py`: each of p99, max and flip rate at most 1.25 x the control's). They are enabled by the - `rtx5090-32g` profile (`engine_env`). - -## 8. Hyper-connection read, second pass (`claude/perf3`, probe jobs run model-free on the 5090, A/B job p36 queued) - -The 3.4 ms (96 reads of 33.8 us, `old_chain`) were split 2.5 + staged down 18.6 + up 8.9 us; the first chain pass (section 0) took the split to 2.2 and the up to 5.7 us and the down to 16.8 us -(`chain_gr_down_w8_nb3`): 29.3 us for the whole read in the chain. The down projection is the long pole and it was a placement problem, not a bandwidth one. - -**Where the 16.9 us went** (`tools/chain-probe` `grdiag`, T = 4, cold weights, one kernel at a time, graph timing): full 16.9; without the weight loads (constant weights) 13.0; without the activation -staging and shared reads (constant activations) 11.5; neither 5.5 us. Both halves cost and even the bare instruction stream is 5.5 us, because the kernel ran 41 blocks of 8 warps (one weight row per -warp, every warp walking all T tokens): 41 of 170 SMs, 2 warps per scheduler, each SM ingesting 320 KB (160 KB of weights, 160 KB of activations through `cp.async`). - -**Fix: tile the work over rows AND tokens** (`chain_gr_down_t2w8_nb4`): a block is 8 rows x 2 tokens, grid `(41, ceil(T/2))`, the same whole-row weight preload, four tile buffers of two tokens (40 KB of shared -memory at any T). Per (row, token) the arithmetic is the one of `gr_down_staged_kernel` (lane l accumulates chunks `h*160 + l + 32q` ascending with `dot8`, then the xor warp reduction), so every output -is bit-identical: `chain_probe gr` compares **every output byte** (`lo`, `rs`, `R`, `inject`, `mixed`, `xn`) against the Original's split / staged / up kernels at every T from 1 to 8 with and without the -injection (`gr_down_exact`: 16 comparisons of the tiled kernel plus 48 of the other variants, `gr_exact`: 12 of split / up8; 0 mismatches, model-free run `p33-final3`). - -| per call, cold weights (us) | T = 4 | T = 6 | T = 8 | -| --- | ---: | ---: | ---: | -| Original staged down (`old_staged`) | 18.4 | 23.3 | 30.6 | -| first chain pass `w8_nb3` | 16.8 | 20.0 | - (`w8_nb2` 28.9) | -| **tiled `t2w8_nb4`** | **9.2-9.7** | **11.3-12.0** | **15.0-15.3** | -| whole read, Original (split + staged + up) | 33.8 | 40.3 | - | -| whole read, first chain pass (split + `w8_nb3` + up8) | 29.3 | 34.3 | - | -| **whole read, now (split + `t2w8_nb4` + up8)** | **22.0** | **25.2** | - | - -Per window (96 reads): 3.25 -> 2.11 ms of GR at 4 rows against the Original's kernels (-1.14 ms; 6 rows -1.45 ms), -0.70 ms against the first chain pass at 4 rows (-0.87 ms at 6 rows); of a ~12.6 ms -window that is -5.6 % (synthetic, kernel level: the end-to-end number is job p36). `LELEKA_CHAIN_DOWN=w8` selects the previous shape (the window graph records per request, so the A/B arms can live in one process: -replay arm flag `!w8`); default on inside `LELEKA_CHAIN`'s `gr` group. Sealed with the other chain kernels (`chain_window.ptx` re-sealed, 17 entries); the launch geometry is the pure function -`tiled_down_geometry` (unit tested), and `chain_probe` launches with the same formulas. - -Sweep (T = 4 / 6 / 8, us): rows x tokens per block: 8 x 2 with 3 / **4** / 5 / 6 tile buffers 10.1 / **9.74** / 9.68 / 9.85 (T = 4), 12.3 / **11.3** / 11.7 / 12.4 (T = 6); 8 x 1: 11.4 / 16.8 / 20.5; 8 x 3: 11.4-11.6 / -11.7-11.9 / 15.1; 8 x 4: 13.3 / 14.2 / 16.9; 4 rows x 2 tokens (164 blocks of 4 warps): 15.9 / 20.0 / 24.9 (the SM spread alone is not enough: the per-block pipeline needs the 8 warps' weight preload). - -**Rejected, measured**: (1) R rows per warp (the activation tile read once for 2 or 4 rows, weights streamed tile by tile through registers): exact, but 23.7-28.8 us at T = 4 (slower than the 16.8 it was -meant to beat: the just-in-time weight tiles expose the L2/HBM latency 8 times); (2) bulk L2 prefetch (`cp.async.bulk.prefetch.L2`) of the down and up weights from extra blocks of the split kernel: -the split alone grew from 2.2 to 20.7 us (chain 35.6 us); (3) deeper tile buffers than 4 (no gain). What remains of the read at T = 4 (22 us in the chain against 17.6 us summed in isolation, floor -~9 us for the 13.1 MB at 1.69 TB/s) is the dependent launches (split -> down -> up, ~1 us each) and the cold first touch of the activations; fusing split into the previous kernel is the next step. diff --git a/docs/ci-audit.md b/docs/ci-audit.md deleted file mode 100644 index bf0ef39b..00000000 --- a/docs/ci-audit.md +++ /dev/null @@ -1,356 +0,0 @@ -# CI and build audit (2026-11-02) - -Measured on local `main` at `f9003b7ce` (sections 3.1 and 3.2), then rebased onto `main` at `44fb442f5` (observability, unattended -and expert-profile merges) and re-verified (section 3.3). Branch `claude/ci-audit` (worktree `.git/wt/ci-audit`). Question from the owner: do the CI -files and scripts prove that the code builds and that the checks pass? Every CI step was run one at a time on the laptop -(x86_64, Windows 11 and WSL2 Ubuntu 24.04, Rust 1.99.0 on both, 16 cores, 39 GiB in WSL). Nothing here used a GPU, a model, the -5090 server or a system change (no apt, no Docker start, no settings). Raw logs and `results.tsv` (command, exit code, seconds -per step) are in the worktree under `artifacts/ci-audit/` (ignored by Git, as the logs rule requires). - -**Verdict.** Before this branch the answer was no, for three independent reasons: - -1. the shipped product was not built or tested by any CI step (the gap, section 2); -2. the existing gates were red on `main`: `check-local.sh --fast`, `check-local.sh --full` (control-plane format and Clippy), - `desktop.yml` (format, Clippy, hardware smoke), and nothing in the repository shows that any of them ran since 2026-10-14 - (section 1); -3. several tests depend on the machine they run on instead of the code (section 4, findings 6 to 8). - -After this branch `check-local.sh --fast`, `--port` and the new `--product` pass on Linux (WSL in a real-filesystem namespace, -section 3) and `--fast` on Windows, with the remaining debt reported by name. `--full` passes up to the steps that need tools -this laptop does not have (numpy, Docker, cmake, musl-gcc); those are listed as SKIPPED with what to install. A green run proves the product compiles, links, and passes its CPU-side tests; it does not prove -any GPU kernel, model quality or speed (section 6). - -**Follow-up (branch `claude/ci-audit2`, section 3.4).** The steps skipped for lack of Docker or tools were then run inside containers on the -laptop (Docker Desktop started for the purpose and stopped afterwards). That found what the first pass could not see: on a real Linux checkout -**every workflow job died at its first step** (`scripts/install-pinned-rustup.sh: Permission denied`, the executable bit was lost in the 2026-10-14 -import), and the **static musl CLI did not compile** (`MADV_COLLAPSE`). Both are fixed on that branch. - -## 1. Can the workflows run for this repository? - -| Question | Answer and evidence | -| --- | --- | -| Which CI system | Gitea Actions. `linux.yml` uses `gitea.event_name`, `gitea.event.inputs.*`, `gitea.event.repository.private`, posts releases to `https://git.vezha.io/api/v1`, and `docs/build-validation.md` documents triggering it with `tea api ... /repos/para/leleka/actions/workflows/linux.yml/dispatches`. `.github/workflows/` is a directory Gitea Actions reads. `origin` is `git@vezha.io:para/leleka.git`. | -| Runners the workflows need | `ubuntu-latest` (a label the Gitea runner maps to an image, "runner configuration, not an immutable pin": `docs/build-validation.md`), root inside the job (they call `apt-get` without `sudo`), a reachable Docker daemon (`docker.io` is installed inside jobs; `check-local.sh --full` runs `test-cuda-driver-bootstrap.sh`, `test-cuda-fixed-ptx.sh` and the container smoke tests), network to `static.rust-lang.org`, `developer.download.nvidia.com`, Docker Hub and Hugging Face, and a self-hosted GPU runner labelled `[self-hosted, linux, x64, strata-gpu]` for the three manual GPU jobs. | -| Is there evidence that they ran | Only for the older Strata-Next jobs: fix commits "fix(ci): ..." (2026-10-05 to 2026-10-08) and the note in `docs/build-validation.md` that two hosted attempts "received runner shutdown". Nothing in the repository records a green or red run of `port.yml` (added 2026-10-14) or of any workflow after the Rust port (2026-10-15 onward). `docs/roadmap.md` still says "Hosted Actions still needs a GitHub repository and runner". The last edit of `.github/` before this branch was 2026-10-14, while default-members, the deploy tool, the memory governor and the runtime client all came later. I did not query the Gitea instance (private, and out of scope: no network call to it was made), so whether a runner is registered is **unverified**. The owner can see it in the repository's Actions tab. | -| Would they pass today | No. See section 3: on `f9003b7ce` the first step of `verify` (`check-local.sh`) fails at rustfmt, and `desktop.yml` fails at three steps. | - -## 2. The gap: what the CI did and did not build (confirmed) - -`default-members` has 30 crates, including `crates/deploy` (package `leleka-deploy`, the `leleka` binary). `grep` over -`.github/workflows/*.yml` and `scripts/check-local.sh` found no mention of `leleka-deploy`, `leleka-memory` or -`leleka-runtime-client` before this branch. - -| Shipped artifact (docs/deploy.md section 8) | Built by CI before | Tested by CI before | Now | -| --- | --- | --- | --- | -| `leleka` (leleka-deploy: 126 unit, 18 end-to-end, 6 recipe tests) | no | no | release build and tests in `check-local.sh --product` / `product.yml` | -| `leleka-api` (leleka-control-plane) | musl release build (`linux-static-cli`, `release-cli`), debug in `verify` | `cargo test` via `--manifest-path control-plane` (416 tests) and 29 smoke scripts | unchanged, plus release glibc build and `-p leleka-control-plane` tests in the product job | -| `leleka-inference`, `leleka-daemon`, `leleka-cli`, `leleka-seal-exec` (leleka-engine-host, `--features sm86`) | debug build inside `desktop.yml` only (not `sm86`, not release) | desktop-core tests (161) | release build with `--features sm86` of exactly those four binaries | -| leleka-runtime (the engine) | `cargo check` only | no (631 tests, 60 ignored) | `cargo check --all-targets` and `cargo test` | -| leleka-cuda-driver | `cargo check --features cuda-driver`; **`cargo test` without the feature, which does not compile** | no | tests with `--features cuda-driver` | -| leleka-memory, leleka-runtime-client | built as dependencies only | no | tests, Clippy and (runtime-client) rustfmt as hard gates | -| leleka-native-cpu-expert | rustfmt report only | no | tests | -| 17 CPU/iGPU/NPU default-members (`cpu-kernels`, `cpu-sys`, `cpu-worker`, `gguf`, `gptoss*`, `harmony`, `igpu*`, `kar-codec`, `shm`, `openvino`, `npu-*`, `gpu-npu-worker`) | no | no | built by `cargo build --locked`, tested | -| A new crate added to the workspace | silently uncovered | silently untested | `scripts/check-ci-coverage.py` fails the job unless `scripts/ci-coverage.json` lists it (negative test done: removing `leleka-deploy` from the list fails with `UNCOVERED`) | - -So the green CI of `linux.yml` + `port.yml` + `desktop.yml` could never have shown that the product builds. - -## 3. Results (every step, in order) - -Legend: PASS, FAIL (real defect), FAIL-ENV (the host, not the code), SKIPPED (why). "WSL" means the worktree on `/mnt/c` -(9p: no `chmod`, FIFO, symlink or ownership semantics, ports shared with other agents' services). "WSL-ns" means the same -commands run in a private user, mount and network namespace (`unshare -rmn`) with `tmpfs` on `/tmp` and on the two fixture -directories the tests write to, capabilities dropped after mounting, loopback up and nothing else: a real Linux filesystem and -free ports, and nothing written outside the worktree (the mounts vanish with the namespace). Seconds are wall time, warm cache, -two builds sharing the CPU. - -### 3.1 Baseline on `f9003b7ce` (before any change) - -| Step | Platform | Result | Why | -| --- | --- | --- | --- | -| `cargo metadata --locked` | Win | PASS 1 s | lock file consistent | -| `cargo build --locked` (all 30 default-members) | Win | PASS 198 s | | -| `cargo build --locked` | WSL | PASS 835 s (crate download + `/mnt/c`) | | -| `cargo build --locked --release -p leleka-deploy` (`leleka`) | Win / WSL | PASS 39 s / 45 s | `target/release/leleka(.exe)` produced | -| release set of `docs/deploy.md` §8 (`leleka-api` + 4 desktop-core binaries, `--features sm86`) | Win / WSL | PASS 287 s / 330 s | all six binaries present | -| `check-local.sh --fast` | Win / WSL | **FAIL** 1 s / 3 s | rustfmt diff in "strict" crates `leleka-backend-api` (3 hunks) and `leleka-context` (5); behind it, Clippy `type_complexity` in `leleka-tokenizer`, and `literal_port` in `leleka-experimental-ref` | -| `check-local.sh --port`, `--full` (also with `STRICT_DEBT=1`) | WSL | **FAIL** 2 to 3 s | stop at the same fast-path failure (`set -e`) | -| `cargo test -p leleka-cuda-driver` (the `--full` line) | Win / WSL | **FAIL** 8 s / 17 s | 32 compile errors: modules such as `original_expert_stager` and `native_head` exist only with feature `cuda-driver`; `leleka-runtime` always enables it, so nothing noticed | -| `cargo test -p leleka-cuda-driver --features cuda-driver` | Win / WSL | PASS 71 s / 86 s | | -| `cargo test -p leleka-memory` / `-p leleka-runtime-client` | Win, WSL | PASS | 80 / 84 and 12 tests | -| `cargo test -p leleka-control-plane` | Win / WSL | PASS 189 s / 475 s | 359 / 416 tests | -| `cargo test -p leleka-engine-host` | Win / WSL | PASS 148 s / 341 s | 152 / 161 tests | -| `cargo test -p leleka-runtime` | Win | PASS 113 s | 592 tests | -| `cargo test -p leleka-runtime` | WSL | FAIL-ENV 143 s | 2 tests (`failed_cleanup_or_replaced_inode_never_deletes_unowned_file`, `frozen_same_fd_hash_owner_and_source_independence`): fixtures under `../../target/` on 9p. PASS in WSL-ns, 631 tests | -| `cargo test -p leleka-native-cpu-expert` | WSL | PASS 122 s | | -| `cargo test -p leleka-deploy --features test-fakes` | Win | FAIL-ENV 40 s | `the_supervisor_starts_serves_status_and_reconfigure_...` refuses a 12 GiB budget: the laptop's real GPU has 1769 MiB free (another agent's engine holds VRAM) | -| `cargo test -p leleka-deploy --features test-fakes` | WSL | FAIL 53 s, 6 tests | 1 real (stale `8192` context assertion; the laptop profile is 262144), 4 FAIL-ENV (read the real GPU's free VRAM), 1 host-dependent (`dry_run_...`, section 4 finding 7) | -| tests of the other 25 default-members, `--no-fail-fast` | Win / WSL | FAIL 254 s / 322 s | Win: only `leleka-experimental-ref` `literal_port` (4 tests, real). WSL adds 3 `leleka-model-format` tests (FAIL-ENV, 9p; PASS on Windows and in WSL-ns, 143 tests) | -| `cargo clippy -D warnings --no-deps` per product crate | Win / WSL | FAIL except `leleka-runtime-client` | counts in section 4 finding 9 | -| `cargo fmt --check` on the shipped crates | Win | FAIL | per-crate hunks in finding 9 | -| `control-plane` format (`--full`) | WSL | FAIL | 290 hunks | -| `control-plane` Clippy (`--full`, no `--no-deps`) | WSL | FAIL | it lints path dependency `leleka-model-format` (known debt) | -| `desktop.yml`: Format / Lints / Hardware smoke | Win, WSL | FAIL / FAIL / FAIL | 22 hunks; same path-dependency Clippy failure; `cargo run` "could not determine which binary" (six binaries, no `default-run`) | -| `desktop.yml`: Tests | WSL | PASS | 161 tests | -| `smoke-*.py` of `linux-static-cli` against the glibc `leleka-api` | WSL | mostly FAIL-ENV | 9p lacks `chmod` (key-file mode checks), numpy missing, one script hangs without a timeout (`smoke-wait-ready`, killed after 21 min) | -| python `test-*.py` of `--full` | WSL | 8 FAIL-ENV, 1 numpy | `chmod`, FIFO, symlink on 9p; `numpy` missing for `test-keyless-routing`; all PASS in WSL-ns except numpy | - -### 3.2 After this branch, on the `f9003b7ce` base - -| Step | Platform | Result | Notes | -| --- | --- | --- | --- | -| `check-local.sh --fast` | Win | PASS 173 s | the debt lines print `WARNING: known debt` (section 4 finding 9) | -| `check-local.sh --fast` | WSL-ns | PASS 183 s | | -| `check-local.sh --port` (type-check `x86_64-unknown-linux-gnu`, sampler host shim) | WSL-ns | PASS 168 s | live Python differentials SKIPPED (need a venv with numpy, PyYAML, tqdm, Jinja2, regex and a network fetch of llama.cpp `gguf-py`) | -| sampler host shim alone | Win | PASS 9 s | needed a `cygpath` line for Git Bash | -| `check-local.sh --product` | WSL-ns | **PASS** 541 s | coverage gate, PTX LF check, build, six release binaries, `cargo check` of the CUDA crates, 2250 tests passed / 0 failed / 170 ignored, fmt and Clippy hard gates; 4 debt warnings (the two host-dependent deploy tests, rustfmt of 5 crates, Clippy of `leleka-cuda-driver` and `leleka-runtime`) | -| `check-local.sh --full` (`STRICT_DEBT=0`) | WSL-ns | PASS up to the Python tests, then FAIL-ENV 227 s | stops at `test-keyless-routing.py`: `python3-numpy` is not installed in this WSL (the workflow installs it). Everything before it passed: fast path, type-check, shim, `py_compile`, 12 of 13 Python test scripts | -| the rest of `--full`: control-plane format / Clippy `--no-deps` / tests (416) / replay | WSL-ns | PASS | 4 s / 9 s / 278 s / 81 s | -| the rest of `--full`: `test-cuda-driver-bootstrap.sh`, `test-cuda-fixed-ptx.sh` | WSL | SKIPPED (run in section 3.4) | the Docker daemon is not running (Docker Desktop stopped); starting it is a system change. `test-cuda-fixed-ptx.sh` also downloads ptxas (26.7 MB) and nvdisasm (4.1 MB) from `developer.download.nvidia.com`, which I did not do without the owner's go-ahead. Its offline half (source dataflow assertions on `matvec.ptx`) PASS | -| the rest of `--full`: `cuda-stubs/check-cu.py` | | SKIPPED | `clang++` not installed (the script skips itself) | -| the rest of `--full`: `build-cpu.sh` | WSL | FAIL-ENV | "CMake 3.24 or newer is required"; `cmake` is not installed on either side | -| `STRICT_DEBT=1 check-local.sh --fast` | WSL-ns | FAIL 131 s, as designed | first debt: rustfmt of `leleka-model-format` | -| `desktop.yml`: Format / Tests / Lints (`--no-deps`) / Hardware smoke (`--bin strata-desktop`) | WSL-ns | PASS / PASS (161) / PASS / PASS | | -| `desktop.yml`: `dotnet restore/build`, `--self-check`, `reconnect.py`, `lifecycle.py` | | SKIPPED | .NET SDK 9.0.320 only; the project targets `net10.0` and the tests drive the dotnet app | -| `linux-static-cli`: musl build | WSL | SKIPPED | `aws-lc-sys` needs a musl C compiler (`x86_64-linux-musl-gcc`, package `musl-tools`); the musl target itself was added in a worktree-local copy of the toolchain and works. Everything else in the job was run against the glibc build, next row | -| `linux-static-cli`: 29 `smoke-*.py` against the glibc `leleka-api` | WSL-ns | 23 PASS, 5 FAIL-ENV, **1 FAIL** | FAIL-ENV: `smoke-native-pack`, `smoke-native-bootstrap`, `smoke-mtp-pack`, `smoke-runtime-profile` (numpy), `smoke-systemd-manager` (builds a Docker image). FAIL: `smoke-messages.py` (finding 3) | -| `linux-static-cli`: combined-package fixture, runtime image, `linux-cli-container` | | SKIPPED | need `musl-gcc` and Docker | -| `keyless-cuda`, `static-cuda-package`, `hosted-cuda-package` (manual dispatch) | | SKIPPED | self-hosted GPU runner / CUDA toolkit download / Docker | -| `port.yml`: port-fast, port-typecheck, port-oracles (shim), port-linux-tests | | PASS / PASS / PASS (live differentials SKIPPED) / absent script, stays green | | -| `cargo build --locked` (30 default-members) | Win, after | PASS 28 s | | -| `cargo build --locked --release -p leleka-deploy` | Win, after | PASS | `leleka.exe` produced | -| YAML parse of the four workflows, `test-gitea-release.py` | WSL-ns | PASS | the contract test only reads `linux.yml`; adding `product.yml` does not touch it | - -### 3.3 After the rebase onto `44fb442f5` (the tree that would be merged; final commits) - -The rebase brought a new workspace member and new code, and the gates found problems in it at once. - -| Step | Platform | Result | Notes | -| --- | --- | --- | --- | -| `scripts/check-ci-coverage.py` | Win / WSL | **FAIL, then PASS** | `leleka-obs: workspace default-member with no CI coverage entry`: the gate did its job; one line in `scripts/ci-coverage.json` and `-p leleka-obs` in the product test list | -| `check-local.sh --product` (first run) | WSL-ns | FAIL 1468 s, 2 steps | (a) `control-plane/tests/log_failure_sse.rs` `no_panicking_log_macros_in_the_serving_crate` is red on `main` itself: the observability merge added two test-only `eprintln!` samples (`prometheus.rs`, `request_log.rs`) that this source-scanning test forbids; (b) Clippy `items_after_test_module` in `crates/deploy/src/facts.rs` (`lab_holder_running` sits after `mod tests`) | -| the same two fixed (a non-panicking `write_fmt` to stderr with the same output; the function moved above `mod tests`) | | | no behaviour change | -| `check-local.sh --product` | WSL-ns | **PASS** 1106 s | 2337 tests passed, 0 failed, 172 ignored; the same 4 debt warnings as 3.2 | -| `check-local.sh --fast` / `--port` | WSL-ns | **PASS** 160 s / 193 s | | -| `desktop.yml` Lints (`--no-deps`) / control-plane format and Clippy | WSL-ns | **PASS** 12 s / 10 s | | -| `cargo test` control-plane (425) / desktop-core (161) | WSL-ns | **PASS** 267 s / 46 s | | -| `cargo build --locked`, release `leleka`, `check-local.sh --fast`, coverage gate, format hard gates | Win | **PASS** 102 s / 25 s / 204 s / 0 s / 1 s | | - -### 3.4 The Docker- and tool-dependent steps, run in containers (branch `claude/ci-audit2`, base `main` at `55562fff7`) - -How: Docker Desktop 4.42.1 (engine 28.2.2) on the laptop; a builder image `leleka-ci-audit2-builder` made from the CI's own pinned Ubuntu base -(`ubuntu@sha256:f610ab94...`) with the packages the workflows `apt-get install` (build-essential, cmake, ninja, clang, musl-tools, python3-numpy, -docker CLI and buildx, systemd), rustup 1.29.0 and Rust 1.99.0 with the musl target. The source was a `git -c core.autocrlf=false archive` of the -branch in a Docker volume (a real Linux filesystem with the git modes of the index, which is what a runner checkout is; the Windows and `/mnt/c` -runs of section 3.1 show every file as executable and could not see the mode problem). The host's Docker socket was mounted so the scripts that -call `docker` ran as they do on a runner. The musl build used a bind-mounted `CARGO_TARGET_DIR` inside the worktree (`target/musl-ci`). -Nothing was installed on Windows or in the Ubuntu WSL distro. Logs: `artifacts/ci-audit2/` in the worktree (ignored by Git). - -| Step | Result | Notes | -| --- | --- | --- | -| any workflow job's first step, `scripts/install-pinned-rustup.sh`, and `scripts/test-cuda-fixed-ptx.sh` / `test-cuda-driver-bootstrap.sh` / `build-cpu.sh`, run by path from a git checkout | **FAIL, fixed** | `Permission denied`: the 2026-10-14 import commit `7f896a8bb` changed 100755 to 100644 on 16 scripts. Modes restored (`engine/strata` untouched) | -| `scripts/test-cuda-fixed-ptx.sh` (verify job; pinned ptxas/nvdisasm in a GPU-less container) | **FAIL, fixed, PASS** 24 s | asserted the CUDA 13.0 pins; the lock moved to 13.2.2 on 2026-10-14. Pins updated to 13.2.86 from the official manifest (checked against the lock's `manifest_sha256`); the SASS dataflow assertions hold for the new ptxas | -| `scripts/test-cuda-driver-bootstrap.sh` | **FAIL** (stale), now debt in `--full` | builds a synthetic workspace of `crates/cuda-driver` alone; the crate gained path dependencies (`leleka-context`, `-model-format`, `-experimental-ref`) so `cargo metadata` fails, and the script also runs `cargo fmt --check` and Clippy `-D warnings` on the crate (finding 9). The same mock-ELF gates run on the real tree in the next row | -| `scripts/linux-tests/run.sh` (the `port-linux-tests` job) | **PASS** 441 s | `leleka-cuda-driver` 437 passed / 104 ignored, `leleka-runtime` 631 / 60, `leleka-native-cpu-expert` 30 / 4; 0 failed | -| `scripts/linux-tests/run.sh --mocks` (fake `libcuda.so.1` protocol gates) | **FAIL, fixed, PASS** | the fake lacked `cuStreamSynchronize`, which `Driver::load` now resolves eagerly (load-only stub added to `mock_cuda.c`); `port.yml` now runs the gates | -| musl static CLI build (`control-plane`, `--release --target x86_64-unknown-linux-musl`) | **FAIL, fixed, PASS** 353 s | `leleka-model-format` used `libc::MADV_COLLAPSE`, which libc 0.2.190 does not define for musl; spelled out locally (25, glibc's value). ELF: no `INTERP`, no `NEEDED`; `leleka-api 0.1.0`, sha256 `f6d6cb85ad1a26d8cec804e3dd8eb1ad0b20f8c4b1d422bc366b7583c838d875` | -| `linux-static-cli`: 29 `smoke-*.py` against that binary | 26 PASS, **3 FAIL** | `smoke-messages` (finding 3, now confirmed on a clean filesystem); `smoke-mtp-pack` (finding 14); `smoke-systemd-manager` (finding 15). `smoke-service-unit` needs `systemd-analyze`, added to that job's apt list | -| `linux-static-cli`: embedded CPU worker packaging, controller deployment, runtime image build and probe | **PASS** | `build-linux-package.py --cpu-fixture`, `smoke-embedded-engine`, `smoke-controller-deployment`, `build-runtime-image.py --cpu-fixture`, `smoke-runtime-image`; the owned fixture image is removed. Needs BuildKit: Ubuntu's `docker.io` has no `buildx`, and `COPY --chmod` fails on the legacy builder, so `docker-buildx` is added to that job's apt list | -| `linux-cli-container` (`deploy/Dockerfile.static-cli` build, `smoke-cli-container.py`) | **FAIL, fixed, PASS** 118 s | the Dockerfile added the musl target before copying `rust-toolchain.toml`; the floating `rust:1.99` tag is 1.99.1 and the pin is 1.99.0, so the target went to the wrong toolchain ("can't find crate for `core`"). Now after the COPY. "CLI OCI passed: actual image, exact upstream license, no embedded engine/model, non-root read-only health200/ready503, graceful stop" | -| `build-cpu.sh` (cmake, 16 ctest targets) | **PASS** 150 s | 16/16 | -| `scripts/cuda-stubs/check-cu.py` (clang) | **FAIL (advisory), partly fixed** | on glibc/libstdc++ all 104 files failed on name clashes with libm (1236 errors); stub definitions skipped under `__GLIBC__`, a missing include directory for `s26_tsum.cuh` added, and `check-local.sh` now runs the C++-only `--plain` pass off macOS: 101/104 pass. The 3 failures are `static_assert(sizeof(FusedGrArgs)==112)` / `GrMulti==912` in `chain_window.cu`, `mtp_original_full_fused_gr.cu`, `mtp_original_scalar_gr.cu`: the stub types give 168 / 1360, so either the stub types differ from the CUDA ones or the ABI drifted; not resolved here. Clang's CUDA frontend mode passes 22/104 on Linux (it needs macOS-only stub overloads) | -| `check-local.sh --full` (CI `verify` job environment, includes `test-keyless-routing.py` with numpy) | **PASS** 437 s | exit 0: fast path, type-check, shim, 13 Python test scripts (146 unittest cases), Linux-only block, control-plane gates, replay, `build-cpu.sh`; 1402 Rust tests passed, 104 ignored; reported debt: `literal_port` (4), rustfmt/Clippy debt, `test-cuda-driver-bootstrap.sh`, the 3 stub files | -| `port.yml` port-oracles: live differentials against the unmodified Python (numpy 2.5.4, PyYAML 6.0.3, tqdm 4.70.1, Jinja2 3.1.6, regex 2026.9.10; llama.cpp `gguf-py` at the pinned commit) | **4 PASS, 3 FAIL** | PASS: `tokenizer` (14,456,832 pre-tokenizer strings, 0 real mismatches), `dequant` (69 fixtures, 23 types, bit-exact), `tools` (5 tools byte-identical), `mtp_fetch` (10 scenarios). **FAIL**: `native_pack` 60 of 2755 cases, `gguf_header` 188 of 400, `chat_template` 136 of 3000 (finding 16); fixed on `claude/offline-diff`) | -| `desktop.yml` with .NET 10.0.403 | **PASS** 91 s | `dotnet restore --locked-mode`, build (0 warnings, 0 errors), `--self-check` (C# to gRPC to the Rust node), `reconnect.py`, `lifecycle.py`; the two macOS-only SSH tests do not apply | -| workflow YAML parse, `test-gitea-release.py` (26 tests) after the edits | **PASS** | | -| `hosted-cuda-package` (manual dispatch) | SKIPPED | builds the Original engine with a downloaded CUDA 13 toolkit (several GB, hours of compile) on an isolated CPU runner; no model or GPU is needed but it is a release build, not a check | -| `keyless-cuda`, `static-cuda-package` (manual dispatch) | SKIPPED | need the self-hosted GPU runner | -| `release-cli` publish, `linux-static-cli` publish | SKIPPED | publish through the Gitea API with a token; the build and verify steps before them are the rows above | - -## 4. Findings, ranked - -1. **The product was not built or tested by CI** (section 2). Fixed by `product.yml` + `check-local.sh --product` + - the coverage gate. -2. **`main` was red in the gates that exist**: rustfmt in two "strict" crates, a Clippy lint in `leleka-tokenizer`, the - `cargo test -p leleka-cuda-driver` line that cannot compile, control-plane and desktop-core format, the Clippy lines that - lint dependencies' debt, the desktop hardware smoke, a stale `8192` assertion. Fixed (section 5), except the debt below. -3. **`smoke-messages.py` fails against the current `leleka-api`, and the cause may be a prompt change.** For a Messages - `tool_result` with `is_error: true`, the control plane builds `json!({"is_error":true,"content":text})` (`control-plane/src/messages.rs:268`). - Since 2026-10-27 `leleka-harmony` enables `serde_json/preserve_order` (commit `3bedec610`), which feature unification applies to the - `leleka-api` build, so the object is now serialized `is_error` first; before, `serde_json` sorted the keys (`content` first). The - Rust unit test (`messages.rs:643`) expects the new order, the Python smoke expects the old one and also expects the Messages - path to match the Responses path byte for byte. Either the smoke is stale or the prompt text of error results changed for - Claude Code clients. This is an owner decision (tool-call integrity, AGENTS.md priority 2); I did not change it. -4. **The Oct-25 upstream sync left the experimental CUDA ports behind**: `leleka-experimental-ref` `literal_port` failed 4 of 6 - tests (`kv_stream`, `kv_q4`, `kv_q8`, `qsa_attn`: 1, 5, 20 and 197 Original kernel-body lines missing from - `crates/cuda-driver/src/experimental_*.cu`). **Closed** on `claude/experimental-resync` (2026-11-03): the four `.cu` were re-synced, - `literal_port` passes and is a hard gate again; what drifted and what still needs a server-side PTX reseal is in - `docs/experiments/2026-10-14-experimental-modes-port.md` ("Re-sync"). -5. **`main` itself has red tests the CI would have shown**: `log_failure_sse::no_panicking_log_macros_in_the_serving_crate` since the - observability merge, and `literal_port` (finding 4). The first is fixed here; the second is fixed on `claude/experimental-resync`. -6. **Tests that depend on the host instead of the code.** The `leleka-deploy` end-to-end tests read the real GPU through - `nvidia-smi` (free VRAM) and the default loopback ports 18766/18080. On this laptop, with another agent's engine running, - 5 of 6 failures were of this kind; `docs/deploy.md` ("all passing in WSL") was true only on an idle GPU. A CI host has no - GPU at all. `scripts/ci/nvidia-smi` is a stand-in that makes all but two of the 18 pass anywhere. -7. **Two deploy tests cannot both pass on one machine**: `dry_run_prints_the_plan_and_changes_nothing` needs a 5090-class host - with at least 141.7 GiB free disk and free default ports; `a_failing_preflight_stops_before_any_change_and_says_how_to_fix_it` - needs a host that cannot hold the 5090 profile. They are reported as debt in the product job. Fix: each test writes its own - stand-in `nvidia-smi` into its fixture and passes it through `PATH` (the facts reader already honours `PATH` first). -8. **Filesystem-dependent tests**: 2 `leleka-runtime`, 3 `leleka-model-format` and 8 Python test scripts need chmod, FIFO, - symlink or ownership semantics. They fail on `/mnt/c` and pass on a real Linux filesystem. Run Linux checks from ext4 - (`~/work/leleka` on the server), never from `/mnt/c`. -9. **Format and Clippy debt, by crate** (reported by `debt`; `STRICT_DEBT=1` makes it fatal). rustfmt hunks before this branch: - `leleka-runtime` 2833, `leleka-cuda-driver` 1970, `leleka-native-cpu-expert` 396, `leleka-deploy` 281, - `leleka-experimental-ref` 226, `leleka-memory` 224, `leleka-model-format` 143, `leleka-libc-shim` 34; now clean: - `leleka-control-plane` (290), `leleka-engine-host` (22), `leleka-runtime-client` (8), `leleka-backend-api`, `leleka-context`. - Clippy errors on Linux (`-D warnings`, lib target): `leleka-cuda-driver` 372, `leleka-runtime` 196, `leleka-model-format` 4. - `leleka-memory` also has 3 Windows-only Clippy errors (unused imports, dead code) and `leleka-deploy` 2 (`layout.rs`, `winsys.rs`); - the Linux gate does not see them. Other agents own those sources, so they were not mass-reformatted. -10. **Stale lock files.** `control-plane/Cargo.lock` and `desktop-core/Cargo.lock` (2026-10-05) are ignored by Cargo because both - crates are workspace members; `--locked` uses the root `Cargo.lock`. They disagree with it (tokio 1.53.1 vs 1.53.2) and give a false - impression of what is locked. Recommend `git rm` (not done: no deletes). -11. **`smoke-wait-ready.py` has no timeout** and hung for 21 minutes when the engine mock could not start (9p run). A runner would - wait until its job timeout. -12. **Worktree pitfall.** The owner's global `core.autocrlf=true` makes `git worktree add` write CRLF into all 4434 text files - including the sealed `.ptx`, which makes the binary refuse to start. `scripts/dev/worktree.sh` now passes `-c core.autocrlf=false` (the same hazard was found independently on the release branch, - whose `*.ptx -text` line in `.gitattributes` is on `main`; the first commit of this branch also carried one and lost it in the rebase), and the product - job fails if a CR is found in a sealed PTX. -13. **No timing or stability data**: nothing here is flaky-tested; each step was run once (twice for the fixed ones). - -14. **`smoke-mtp-pack.py` is stale after the upstream sync.** It discovers the MTP tensor names with a regex over - `engine/strata/src/core/mtp.cpp`; in engine 0.1.50 that file lists them in a `required[]` array and reads them through `wq(...)`, so - `self_attn.q_proj.weight` is not generated and `assert bad_index != good_index` fails. **Fixed on `claude/offline-diff`**: the nine Q8_0 - names are now read from `required[]` and `wq("...")` (all 26 names resolve in the pinned manifest; an assertion fails if the count changes). - Not run end to end there (the smoke needs a Linux `leleka-api`, a POSIX shell worker and Python 3.11). -15. **`deploy/Dockerfile.systemd-smoke` pins apt package versions that no longer exist** (`systemd=255.4-1ubuntu8.17`, - `ca-certificates=20260601~24.04.1`; apt answers "Version ... was not found"), so `smoke-systemd-manager.py` cannot build its image. Version pins - rot against a rolling archive. **Fixed on `claude/offline-diff`**: the version pins are gone, the base-image digest stays. The image build was - not re-run (Docker Desktop could not start again, see 18). -16. **The offline-port differentials against the updated Original fail in three places** (found in 3.4; root causes and fixes on - `claude/offline-diff`, 2026-11-03): - * `chat_template` (136 of 3000): a **real port drift in the prompt bytes**. The sync to Strata 41cf05a0 (2026-10-25) brought `ChatTemplate.render` - a filter (#843) that removes completed empty assistant turns before the template runs (assistant message, no text after `str.strip()`, no - picture, no tool calls; the final message is always kept; `STRATA_KEEP_EMPTY_TURNS=1` turns it off; a reasoning content does not keep a turn; - a content Python cannot iterate, such as a number, fails the render). `control-plane/src/prompt.rs` did not have it, so an assistant message with - `content: null`, `""` or a reasoning-only turn rendered as `<|im_start|>assistant - - - - -<|im_end|> -` in Rust and not at all in - Python. Ported literally in `Renderer::render` and in the typed `render_with_images` path (native renderer included); 0 failures in - 3000, 2 x 12000 further cases. Real sessions: only a conversation that carries such a turn is affected, i.e. an empty assistant output item or a - replayed `reasoning` item followed by a user turn (an interrupted or cancelled turn); turns with tool calls and any turn with text render as - before (no captured session was replayed for this: the captures are not in Git). Since 2026-10-25 the Rust prompt differed from the Original for - those conversations. `responses.rs` had one test that asserted the old behaviour (unfinished reasoning kept before the next user turn); it now asserts the Original's. - `chat_template_oracle.json` was regenerated from the Original (it encoded the old behaviour: 11 of 112 shared requests changed). - * `gguf_header` (188 of 400): the Original's `gguf_reader.py/.hpp` gained the APR trellis types 143 to 146 (`PTQ1_0`, `TQ2_T`, `TQK6`, `TQK7`, - 128-value blocks of 28/34/26/30 bytes); `leleka_model_format::gguf::block_geometry` did not know them. Added; `gguf_headers.json` regenerated (it now covers them); 0 failures in 400. - * `native_pack` (60 of 2755): (a) `iq_pack.py` `NATIVE_PLE_KEY` gained IQ3_XXS and IQ4_XS (#381, the runtime side `native_dense_plan.rs` already had them), so - `native_pack.rs` converted such a PLE key to BF16 or refused it: fixed (`native_ple_key`). (b) the `f16_nan` cases used the signaling NaN - 0x7D55, whose numpy widening to F32 differs between numpy builds (2.0.2 keeps it, the 2.5.4 run of 3.4 did not); that is the oracle disagreeing with itself, - not the port, so the case now uses a quiet NaN (0x7F55). (c) **Not ported, now refused**: the Original's NVFP4 expert tail (16 bytes of scales per blob, forced - `experts.bin`) and `prism.hadamard.*` experts (`hadamard.txt`, `native_experts.txt` v5, resumable `experts.bin`); the runtime here reads neither, so a pack - without them would be silently wrong. The Rust packer returns an error naming the feature. The live `native_pack` differential could not be re-run on the laptop - (on Windows the Rust packer ends in "Access is denied" after verifying the input, probably its directory fsync, and Docker Desktop did not start): its unit tests and the (a) and (c) paths are covered by - `native_pack` unit tests; the 2755-case run needs one pass in a container. - The other four differentials (tokenizer, dequant, tools, mtp_fetch) were re-run against the fixed binary and still match. - Also found, not fixed (stale goldens, not differentials): regenerating `reasoning_budget_oracle.json` from the Original changes 59 of 400 `Service.run` cases - (every pre-cancelled run, and 25 thinking runs whose completion token count differs; `server.py` gained the answer-room and `#984` budget clamp), and - `setup_policy_oracle.json` changes in 1204 places (a new 204800 context step in `setup.py`). Both ports (`reasoning_budget.rs`, `leleka-context` setup policy) - are behind 41cf05a0; the committed goldens still pass because they are the old Original's. -17. **Every workflow job failed at the first script on a real Linux checkout** (mode loss, see section 3.4) and **the static musl CLI did not - compile** since the huge-page work (2026-11-01), so `linux-static-cli`, `release-cli` and `linux-cli-container` were red as well. Fixed. -18. **Docker Desktop on this laptop could not start**: `%LOCALAPPDATA%\Docker\run\dockerInference` was a stale 0-byte socket file from 2025-06-20 that - nothing (Docker, `del`, `icacls`) could remove ("The file cannot be accessed by the system", error 1920). The directory `run` was renamed to - `run.stale-before-ci-audit-20260625`, Docker created a fresh one; the renamed directory can be deleted. It happened again on 2026-11-03: the - `dockerInference` socket file the audit run left behind (the app was not quit cleanly) blocked the next start with the same error. Docker Desktop - stays unusable until `run` is renamed again, and each unclean quit recreates the problem; nothing outside the repository folder was touched to work around it. - -## 5. What changed on this branch - -Commit "ci: build and test what ships ..." (CI and repairs): - -* `.github/workflows/product.yml` (new, Gitea conventions of `linux.yml`): runs `scripts/check-local.sh --product` on `ubuntu-latest`. -* `scripts/check-local.sh --product`: coverage gate; PTX LF check; `cargo build --locked`; release build of `leleka`, `leleka-api` - and the four desktop-core binaries with `--features sm86`, and a check that all six exist; `cargo check --all-targets` of - `leleka-cuda-driver --features cuda-driver` and `leleka-runtime`; tests of all the crates that ship (and of the 17 CPU/iGPU/NPU - default-members); rustfmt and Clippy as hard gates where clean, `debt` where not. A failing step is recorded and the rest still - runs, so one red run lists everything. -* `scripts/check-ci-coverage.py` + `scripts/ci-coverage.json`: fails when a workspace member is not listed, when a default-member is - exempt, when an entry is stale, or when no workflow or `check-local.sh` step names a "tested" crate. -* `scripts/ci/nvidia-smi`: stand-in used by the product job for the deploy tests. -* `check-local.sh`: `-p leleka-cuda-driver --features cuda-driver`; `literal_port` split out as debt (re-synced and made a hard gate again by `claude/experimental-resync`); control-plane Clippy `--no-deps`. -* `desktop.yml`: hardware smoke with `--bin strata-desktop` (first commit); Lints with `--no-deps` (the "docs: ci-audit" commit). -* Formatting of `leleka-backend-api` and `leleka-context`; a local type alias in `leleka-tokenizer` (`fast.rs`); four one-line - Clippy fixes (`leleka-memory` `governor.rs` redundant cast, `leleka-deploy` `app.rs`, `wsl.rs`, `reconfigure.rs` test); - the stale context assertion in `crates/deploy/tests/e2e.rs`. -* `run_port_host_tests.sh` under Git Bash; `worktree.sh` against the autocrlf pitfall; `.gitattributes` keeps the CI scripts and workflows LF. - -Commit "ci: cover leleka-obs": `leleka-obs` added to `scripts/ci-coverage.json` and the product test list. - -Commit "style: cargo fmt on leleka-control-plane ..." (separable): `cargo fmt` on `leleka-control-plane`, `leleka-engine-host`, `leleka-runtime-client` (37 files), the -four Clippy lints in them (`tool_output.rs`, a test `mut`, a collapsible `if` in `leleka-inference.rs`, `allow(dead_code)` on -`observer_adaptive_slots`), the `log_failure_sse` fix and the `facts.rs` reorder of section 3.3. An earlier version of this commit -conflicted with the observability merge, which is why it was redone on top of it; if more branches land in these crates first, drop it -and re-run `cargo fmt -p leleka-control-plane -p leleka-engine-host -p leleka-runtime-client`. - -Nothing in this branch touches a kernel, `.cu`/`.ptx`, an engine numeric path, or runtime behaviour. The edits to compiled code -are formatting, a type alias, a function moved above a test module, a test-only `eprintln!` replaced by `write_fmt`, `then` to `then_some` of a struct holding borrows, `% 2 == 0` to `is_multiple_of(2)`, a removed -identity cast, `chunks_exact(2)` to `as_chunks::<2>()` in a console-text decoder, and a removed unused `mut`. Release builds were -re-run after them; bitwise identity of engine output is unaffected because no engine code path changed semantically. - -Branch `claude/ci-audit2` (follow-up, on `main` at `55562fff7`): - -* "scripts: restore the executable bit ..." (16 scripts, modes only). -* "ci: repairs found by running the Docker- and tool-dependent steps in containers": `scripts/test-cuda-fixed-ptx.sh` pins (13.2.86), - `MADV_COLLAPSE` spelled out in `crates/model-format/src/huge_pages.rs` (value 25, as in glibc's libc; musl has none), the - `deploy/Dockerfile.static-cli` toolchain order, `mock_cuda.c` load-only `cuStreamSynchronize`, `port.yml` runs `run.sh --mocks`, the - `scripts/cuda-stubs` glibc fixes with `check-local.sh` using `--plain` off macOS, and `test-cuda-driver-bootstrap.sh` as debt in `--full`. -* The documentation commit: this section, 3.4, findings 14 to 18, and `docker-buildx systemd` in the apt list of `linux-static-cli`. - -No kernel, `.cu`/`.ptx` content or engine numerics changed. The only edit to compiled engine-side code is the local `MADV_COLLAPSE` constant. - -## 6. What CI cannot prove (and where the evidence is) - -| Not proved by any CI step | Evidence that exists, and where | -| --- | --- | -| GPU kernels compute the right values (sm_120 / sm_86 PTX, MMQ, attention, GDN, MTP) | The PTX is only assembled by `test-cuda-fixed-ptx.sh` (two toy kernels) or compiled in as bytes. Kernel identity vs the Original: `docs/ledger.md`, `docs/quality-gate.md`, `docs/sm86-assets.md`, per-feature docs in `docs/` | -| Model quality and tool-call integrity at 256k | `docs/quality-gate.md`, `docs/e2e-run.md` (real Codex CLI sessions on the 5090) | -| Speed: decode/prefill/agent throughput, prefix cache | `docs/e2e-run.md`, `docs/ledger.md`, `docs/prefix-cache.md`, `docs/roofline.md`, `docs/experiments/draft-round-5090.md` | -| Memory fit on a real card (VRAM budget, pinned RAM, WSL2 limits), driver >= 595, `libcublas.so.12` | `docs/deploy.md` §10, `docs/laptop-profile.md`, `docs/windows.md` | -| `leleka up` acceptance on a clean GPU node (charter G2) | `docs/deploy.md` §1 states it has not been run | -| The packaged tarball installs and starts | `scripts/package-release.py` is not run by any workflow; `docs/deploy.md` §8 | -| The CPU/iGPU/NPU runtime on real hardware | `docs/cpu-runtime.md`, `docs/worker-pool.md` (CI only runs the host-testable parts) | -| Windows native behaviour | not in CI; `docs/windows.md`, this audit's Win rows | -| The desktop app (Avalonia, dotnet) | `desktop.yml` can only run it with .NET 10 | -| That the workflows run on the Gitea instance at all | section 1 | -| Concurrency, soak, crash recovery under load | `scripts/soak` on branch `claude/unattended`, `docs/port-remaining.md` | - -## 7. What the owner has to install or decide - -* **Check the Actions tab on the Gitea repository** (section 1) and register a runner with the `ubuntu-latest` label that has Docker, - root in the job and network access if none exists; the three GPU jobs need the `strata-gpu` runner. -* Local runs of everything no longer need host installs: the container recipe of section 3.4 reproduces the CI environment (the Dockerfile is - not committed; it is `ubuntu@sha256:f610ab94...` plus the apt lists of the workflows, `scripts/install-pinned-rustup.sh`, `docker-buildx`, - `systemd`). On the server, `scripts/check-local.sh` runs natively with those packages and Docker. -* Decide on findings 14, 15 and 16 (stale MTP smoke, rotting apt pins, the three live differentials) and on the three - `static_assert` ABI failures of the stub check (section 3.4). -* Decide on finding 3 (error `tool_result` key order in Messages prompts), finding 4 (re-sync of the experimental CUDA ports), finding 7 - (per-test `nvidia-smi` stand-ins), and whether to `git rm` the two stale lock files. -* Merge: `claude/ci-audit` (5 commits on top of `44fb442f5`) merges cleanly into `main` at `1cebffd58` (`git merge-tree`); it adds a new - workflow, which runs on the next push once a runner exists. Expect the first hosted run to find host differences this laptop could not (disk space, runner - image, Docker access). - -## 8. Reproduce - -```sh -git -c core.autocrlf=false worktree add .git/wt/x claude/ci-audit # or scripts/dev/worktree.sh new x claude/ci-audit -scripts/check-local.sh --product # ~10 min warm; Linux on a real filesystem (not /mnt/c), no GPU -scripts/check-local.sh --fast # also Windows (Git Bash); the Linux type-check needs the target or SKIP_LINUX_TYPECHECK=1 -scripts/check-local.sh # the full legacy gate; needs python3-numpy, cmake, Docker -``` - -WSL-ns wrapper used here (nothing outside the worktree is written): `unshare -rmn sh -c 'ip link set lo up && mount -t tmpfs -tmpfs /tmp && mount -t tmpfs tmpfs /target/stra157-sdet && mount -t tmpfs tmpfs /target/stra169-mtp-binder && -exec setpriv --inh-caps=-all --bounding-set=-all --ambient-caps=-all "$@"' sh `. diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md deleted file mode 100644 index 8a2680a0..00000000 --- a/docs/compressed-runtime.md +++ /dev/null @@ -1,193 +0,0 @@ -# Compressed model runtime contract - -## Experimental model quality arm - -The imported Strata engine has an optional Linux CUDA build flag, -`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, with `STRATA_NEXT_KAR_DIR` pointing at -`gpu/kar`. It adds `--ple-kar ARCHIVE --ple-kar-level 2` to `strata generate`. -With those flags, the PLE lookup table is decoded from KAR on the CPU, while -the native pack and GGUF shards still supply every other weight. The archive -is checked by `libkar` including all payload CRCs, and its PLE parts must have -the expected F32 geometry and complete row count. Check the known archive -SHA-256 and sidecar for a validated run. A supervised smoke run may skip the -separate full-file SHA pass while recording that it was skipped; the engine -still checks payload CRCs. The feature is off in ordinary builds. -`strata_next_kar_ple_probe ARCHIVE 2 ROW...` prints FNV-1a checksums for -comparison with `leleka-api model checksum-kar-row` on the matching part. - -### Static CUDA PLE package profile - -`scripts/build-static-cuda.sh` accepts only `STRATA_KAR_PLE=0|1`; it defaults -to `0`. The script always resets the cached PLE, expert-KAR, and PLE-trace -CMake options explicitly, so reusing a build directory cannot accidentally -retain those experimental arms. `STRATA_KAR_PLE=1` compiles the existing PLE -implementation from `gpu/kar`; it does not select a model, archive, PLE level, -or runtime profile. The private Gitea `hosted_cuda_package` workflow exposes -this build capability as a separate boolean, defaulting off, and binds the -selected flags and CUDA architecture into the checksummed package provenance. - -The CUDA runtime and C++ runtime are statically linked for the engine build. -The NVIDIA driver and host glibc remain system dependencies; this is not a -fully static CUDA executable and does not eliminate driver compatibility. -The combined outer CLI is separately built for musl. Neither static linking -nor a PLE-enabled package proves GPU inference, model quality, or a speedup; -the serving profile must still explicitly select the model's PLE archive, -level, and cache budget after the separate GPU gates pass. - -This arm measures whether PLE transcoding changes whole-model output and task -quality. It does not load the full compressed model, stage sparse PLE packets -to CUDA, or establish a model throughput gain. Use the same engine source, -model pack, sampling, workload, and server wrapper for control and candidate; -load the arms sequentially on a 32 GB GPU. The private -`scripts/compare-chat-reports.py` pairs two single-arm benchmark reports by -case and repetition and records quality and HTTP wall-time ratios. The times -remain descriptive until run order, disk/cache state, and interference are -controlled. -When Strata reports its `timings`, the comparison also records paired prompt -and decode token rates by case and category; those rates must be interpreted -with their token counts and cache state. - -`scripts/bench-chat-sequential-server.py` can run those arms one after the -other against the same private Strata server configuration. It verifies the -expected KAR SHA-256 first by default; `--skip-kar-sha256-check` skips only -that separate pass for an experimental smoke and marks it unverified in the -metadata. It writes temporary config files in tmpfs with mode -0600, starts only its own server process, unloads each model after the arm, -and keeps response reports outside Git. The candidate adds the experimental -PLE flags only; the original server configuration is never edited. -The frozen public `quality-v1.json` suite has eight deterministic cases across -reasoning, retrieval, instruction following, and function calls. One retrieval -case expands 4,400 filler rows around a single code before sending the prompt. -Passing this smoke suite is only an initial check; perplexity, real agent task -completion, 256K/512K context, and the full compressed-weight arm still need -their separate gates. - -The first paired Linux RTX 5090 measurement is recorded in -[`docs/experiments/2026-10-03-kar-ple-ab.md`](experiments/2026-10-03-kar-ple-ab.md). -Its CPU PLE arm preserved the tested outputs but did not improve prefill or -end-to-end latency. It does not test compressed VRAM expert residency. - -For offline cache sizing, an isolated Linux build can set -`STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON` and provide a new private file path in -`STRATA_PLE_ROW_TRACE_PATH`. The engine writes one line of 16 global PLE row -IDs per token passed to `ngram_rows`, with mode `0600`. The compile flag is off by -default; without the environment variable even that experimental build does -not create a trace. The file can reveal request structure, so keep it outside -Git and remove it after aggregate analysis. The trace includes speculative -row calculations and does not label prefill versus decode. Use -`scripts/ple-cache-reuse.py --rows-trace TRACE` for an ideal cache screen and -`scripts/split-ple-row-trace.py` to map global IDs into a KAR part's local -range before the isolated CUDA cache smoke. Neither script runs in serving. -The [batch-capacity probe](experiments/2026-10-03-ple-cache-batch-capacity.md) -checks that a CUDA decode batch cannot name more distinct rows than the -bounded cache can hold, and records the three engine PLE handoff sites. - -An experimental engine build with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON` -accepts `--ple-kar ARCHIVE --ple-kar-level 2 --ple-kar-gpu-cache-mib N`. -The opt-in cache keeps selected 50-byte KAR PLE rows in 64-byte VRAM slots -and decodes prefill and normal token rows on CUDA. It divides a prefill -request into cache-sized batches when needed. Speculative verification still -uses the same archive's CPU gather because its captured graph reads mapped -host memory. This serves only the PLE tensor from KAR; other model weights -remain in the native pack. Keep it experimental until full-model quality, -GPU memory pressure, and paired agent throughput pass their gates. - -## Artifact pipeline - -`leleka-api model fetch` downloads the pinned source shards to an external volume. `model verify` checks their size and SHA-256 before any conversion. The current experimental `model prepare-sharded-streamed` builds a KAR-2 archive and a provenance sidecar with source and archive digests, codec policy, and tensor mapping; it writes to a staging path and publishes the finished archive without replacing an existing file. A production `model prepare --format kar2` still needs a per-class rate policy, tokenizer identity, and full-model quality approval. The final one-command `serve` flow should run missing fetch/verify/prepare stages automatically, reuse a verified prepared archive on subsequent starts, and never treat an incomplete stage as usable. Neither source shards nor the archive belong in Git or CI artifacts. - -The first source profile is Qwen3.8-Flash-Next IQ3_S, which is already quantized. KAR transcoding of it is a **lossy experiment** until full-model quality is measured. A higher-fidelity source may be needed if the IQ3_S → KAR path exceeds the error budget. Keep the verified native IQ3_S pack as the control arm and recovery path; never infer model quality from archive size or isolated tensor error alone. - -The tokenizer vocabulary, merge rules, and token-ID-to-text decoder belong in host RAM and run in Rust; they need no VRAM residency. Model embedding and output matrices are weights, even when their dimensions include the vocabulary size. Their placement and precision must be planned separately from tokenizer metadata. CPU placement of those matrices is possible but adds transfer or compute cost that must be measured on the target workload. - -KAR-2, as specified by the local koference project at commit `806d2398ae1daaceb2917242911e5680cbfb3608` (`r08/docs/format-kar-v2.md`, `r08/code/libkar.h`), is one archive per model with a source digest, directory digest, payload checks, and per-tensor precision levels. The Rust command should call a validated native encoder or a stable `libkar` API; Python may be used for offline research, calibration, and differential tests, but not by production serving. The decoder must reject an archive whose identity, bounds, checksums, or tensor layout do not match the expected model. - -The current `model inspect-kar` command performs bounded structural checks, header CRC-32, directory SHA-256, source identity reporting, and tensor section checks. `model verify-kar` additionally scans every tensor section and checks its payload CRC-32 with bounded memory. With `--manifest SPEC --source-dir DIR`, it verifies each source shard's size and SHA-256, then hashes the shards in filename order and compares the concatenated digest and byte count with the archive header. The sharded derived-F32 archives below require their dedicated verifier because the physical GGUF shard digest differs from the virtual F32 source digest. These checks do not constitute a model-quality or GPU execution result. - -The Rust `kar_writer` module emits a KAR-2 container from already coded RAW/NESTED tensor slices. A synthetic two-tensor output matches the pinned koference reference writer byte for byte, including header, directory, aligned payload, CRCs, and digest. The writer verifies its temporary file before atomic no-replace publication and rejects non-finite f16 scales/books. It does not choose a compression rate or approve a serving configuration. - -`leleka-api model index FILE.gguf [--hash]` prints one JSON record per tensor with checked absolute offset, exact source byte count, type, and dimensions. `--hash` adds a SHA-256 computed with a fixed 1 MiB buffer. The index uses Strata's pinned GGUF block geometry, including IQ3_S, and rejects unknown types, overlapping spans, truncated payloads, and rows that do not align to quantization blocks. The KAR writer can stream both RAW tensor bytes and pre-encoded NESTED sections from files through a 1 MiB buffer. It checks the RAW source digest or NESTED section digest; the latter also checks finite f16 scales/books and zero alignment padding. The experimental native encoder supplies these sections for all GGUF types found in the target model. - -An experimental native `kar_codec::encode_with_boundaries` converts one in-memory f32 tensor to group scales and MSB-first bit planes using nested boundaries. `kar_codec::fit_topdown` fits those boundaries and f16 books to an already selected normalized sample; pinned synthetic fixtures match koference's Python reference. It rounds scales to IEEE f16 before assigning cells and uses the same bit-within-u32 order as koference's CUDA decoder. `kar_codec::decode_range` reconstructs a selected prefix into a caller-sized CPU buffer, giving a small numerical oracle for later CUDA checks. The streamed pipeline separately handles source decoding, bounded calibration and encoding, while model rate selection and lossy serving approval remain open. - -`leleka-api model prepare-f32-preview FILE.gguf --output FILE.kar --levels N` connects the GGUF index, native calibration, encoder, CPU reconstruction check, and verified KAR writer. It accepts only a single F32 GGUF no larger than 64 MiB, at most 1000 tensors, with at most 1 million elements per tensor. Each encoded tensor is written to a private staging section and released from memory before the next tensor; the archive writer reads those sections with a 1 MiB buffer. Staging is cleaned after success or failure. It fits each tensor from all normalized values, records the rate in the KAR builder identity, and prints source/archive SHA-256 plus the maximum tensor relative L2. This command is an explicitly lossy integration preview. IQ3_S input is rejected, and no output from this command is eligible for serving until the full-model quality gate passes. - -The Rust `iq3_s` module now decodes one GGUF IQ3_S block (110 bytes, 256 F32 outputs) or a caller-sized sequence of complete blocks. Its 512-entry grid is copied from the pinned Strata/ggml tree, checked by SHA-256, and carries the ggml MIT notice in the binary through `--ggml-license`. Synthetic block output matches an independent Python calculation. A real-data slice of 262,144 IQ3_S blocks also produced 67,108,864 bit-identical F32 values against the pinned ggml CPU decoder. Both complete source shards have since passed their manifest SHA-256 checks. - -KAR-2 records `source_dtype` only as F32, F16, or BF16. An IQ3_S GGUF cannot be identified directly as a KAR-2 tensor source without violating that field. `model derive-iq3-identity FILE.gguf` computes a versioned **virtual F32 source identity** for a single GGUF whose tensors are all IQ3_S. It streams dequantized little-endian F32 values in GGUF tensor-directory order, reports the derived stream and per-tensor digests/offsets alongside the original GGUF and IQ3 tensor digests, and does not materialize the expanded data. The original GGUF digest belongs in a separate provenance manifest; the existing `verify-kar --manifest` checks physical source files and must not be used as proof of this virtual stream. - -`model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N` uses that identity to create a small, explicitly experimental KAR archive with F32 source dtype, virtual F32 tensor offsets/digests, and the derived stream digest. The original GGUF and IQ3 digests go into `FILE.kar.provenance.json`, published after the archive and bound to its SHA-256. If provenance publication fails, the new archive is removed. `model verify-iq3-preview FILE.kar --source FILE.gguf` recomputes the virtual source, checks every KAR tensor's F32 source record, scans payload CRCs, and compares the sidecar to the source and archive. It shares the F32 preview's 64 MiB source, 1000 tensor, and 1 million elements per tensor limits; source types must all be IQ3_S. Mixed-type shards, multi-shard identity, real tensor parity, and the full-model quality gate remain open. Neither preview archive is eligible for serving. - -`model derive-mixed-identity FILE.gguf` extends the virtual F32 identity to a single GGUF containing IQ3_S plus other supported types. It preserves F32 bit patterns, expands F16 and BF16 to F32, and uses the pinned Rust IQ3_S decoder or statically linked ggml C CPU dequantizers for other quantized types. The virtual stream digest covers values in tensor-directory order and excludes GGUF headers and padding. The command reports original type and source digest per tensor. `model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N` encodes a small bounded source and verifies its sidecar; that preview still uses the original four source kinds and is not eligible for serving. - -`model derive-sharded-identity MANIFEST --source-dir DIR` computes a virtual F32 identity across two or more GGUF shards. It sorts shards by byte-wise filename, checks each shard size and SHA-256 against the pinned manifest, rejects symlinks and duplicate tensor names, then concatenates decoded tensor values in each shard's directory order. The output includes per-shard identities and global derived tensor offsets. `model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` uses that identity to assemble a small experimental KAR from file-backed encoded sections, with a sidecar that binds every shard, tensor, and the archive digest. `model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR` recomputes and checks those links and the KAR payload CRCs. The 64 MiB preview cap, real-model quality gate, other tensor formats, and GPU path remain open. - -The native `gguf_f32_stream` visitor yields source bytes and derived little-endian F32 bytes in bounded chunks. Besides F32, F16, BF16 and the independent Rust IQ3_S path, it uses the pinned ggml CPU dequantizers for actual target kinds Q8_0, Q4_K, Q5_K, Q6_K, IQ2_S, IQ4_NL, IQ3_XXS, IQ4_XS and Q2_0. The ggml C source at llama.cpp commit `3cf03257f219afbe7334045ff7c6a06ac68c627d` is vendored with hashes and linked statically into the Rust executable. A pinned synthetic IQ3_S block matches the independent Rust decoder exactly; one block of each real target quant type passes the bounded visitor. Both source shards are SHA-256 verified; real-model quality remains open. - -The C bridge dispatches by named ggml type constants and checks its native block size against the Rust GGUF index before reading. This corrected an early kind-18/kind-22 swap (`IQ3_XXS` versus `IQ2_S`). Streamed archives now use v4 builder/provenance/derivation identifiers because giant GGUF tensors require multiple KAR-2 records; earlier streamed archives are rejected by the current verifier. Both target shards are SHA-256 verified, and one real block of every type in the first shard decoded to finite F32 values. The complete model-quality gate remains open. - -The experimental `kar_sample` primitive normalizes these streamed values in reusable groups of 32 with the same rounded f16 scale logic as the existing codec. It takes at most 65,536 values from deterministic, digest-seeded positions spread across the padded tensor. For tensors over 1,048,576 elements it seeks directly to the selected GGUF blocks; F32 and IQ3_S sparse samples matched full-stream samples in tests. This sample is not a validated rate policy; per-class policy and the real-model quality gate remain open. - -The `kar_stream_encode` primitive writes one canonical nested section directly from bounded GGUF chunks using the supplied calibration. It keeps only a group, source chunk, and buffered file writers in memory, hashes both physical and virtual sources, and computes tensor relative L2. A synthetic section matches the existing in-memory writer byte for byte and passes KAR-2 archive verification; an IQ3_S stream crossing a chunk boundary preserves source and derived digests. - -`model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` now connects the bounded visitor, deterministic 65,536-value calibration sample, file-backed section encoder, and KAR-2 archive writer across manifest-pinned GGUF shards. It has no 64 MiB preview cap or per-tensor allocation. If a tensor cannot supply a valid nested calibration, it is copied as virtual F32 into a RAW section instead of being discarded. Every streamed tensor's physical and virtual digest is checked against an independently derived identity, every shard is hashed again after preparation, and the archive and separate preparation-policy provenance are published without replacing existing files. Oversized tensors are split into adjacent records with checked source and virtual offsets and part hashes. `model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N` independently verifies the shards, virtual tensor source records, archive payload CRCs, and sidecar binding. A small forced-split test reconstructs both records on CPU. Both real target shards and selected KAR slices are verified; full-model rate choice, quality, and Linux GPU loader still need validation. This command is experimental and its output is not eligible for serving. - -The streamed preparer tracks relative L2 and encoded bytes per KAR record and prints the twenty records with the largest relative L2 on a newly created archive. The existing 51.50 GiB archive predates that recording and has only its full-record maximum of 0.68008092. `model analyze-sharded-kar` can now compare small source/archive windows for every record in that existing archive; its `--assume-verified` mode uses the earlier full source/archive verification and marks that assumption in the report. This ranks candidates for more precision but is not a full-record error bound or a model-quality score; a split parent tensor appears as multiple records. A selective precision policy can encode sensitive records at more KAR levels, retain an exact representation, or add independently addressable residual blocks. Residuals need archive integrity checks and must be included in transfer, VRAM, and CUDA decode budgets. Choose the policy after per-class distortion measurements and the separate model-quality gate; a lossless outer codec cannot repair KAR quantization error. - -An experimental KAR overlay now carries higher-precision replacement records for a selected subset without rebuilding the full archive. Its provenance binds the base archive and candidate policy digests; selected physical and virtual source digests are checked during encoding. The overlay is independently verified, and the CPU comparison command measures paired full-record error against both archives. A serving loader must still select overlay records by name, verify both artifacts together, and account for their VRAM residency and transfer before this can affect inference. An overlay is not an additive residual: it replaces the selected base record when enabled. - -If selective higher precision does not pass the model-quality gate, an exact -correction tier can be evaluated separately. Its contract is bitwise equality -to a named GGUF dequantization baseline, including values such as signed zero; -ordinary floating-point addition of a residual is not sufficient to promise -that. One candidate is an XOR of the base F32 bit pattern with the reference -F32 bit pattern, packed in independently addressable blocks and decoded on -CUDA. Another is to retain exact original GGUF quantized blocks for selected -tensors. In both cases, record the bytes of the base plus correction, PCIe -traffic, CUDA decode cost, and full-model quality. If exact data removes the -size or transfer advantage, the exact tier is a correctness fallback rather -than a performance win. - -`model resolve-kar-overlay --base BASE.kar --overlay OVERLAY.kar` now emits a verified tensor-to-archive mapping for a future loader. It recomputes both archive SHA-256 values, validates every payload CRC, checks the shared virtual-F32 source identity, and rejects a replacement with a different source digest, offset, or dimensions. The command does not load weights or enable overlay serving. Keep both archives immutable after resolution; a GPU loader must validate their identities again before using this mapping. - -The isolated Linux CUDA smoke target accepts an optional overlay path and routes a requested tensor to the selected archive after payload, common source identity, name, shape, dtype, per-record source digest, and source-offset checks. `--row ROW_ID` selects one local row of a compressed record and decodes it into a one-row GPU output buffer after staging that record's complete compressed level prefix. Run the full Rust resolver first for complete archive hashes and provenance. This exercises compressed VRAM residency and CUDA decoding for one selected record when the GPU is available; it does not integrate with Strata's matrix multiplication, schedule a model, or pass the quality gate. - -For sparse PLE lookups, a small decoded output alone is insufficient: the full-record `kar_reserve` transfer can dominate PCIe traffic. Even a 100-million-element partition remains too coarse to stage afresh for a 160-value row. The isolated `strata-kar-sparse-row-smoke` therefore assembles a compact packet of only each requested row's codebook, group scales, and bit-plane words, transfers the packet, and decodes it on CUDA. This keeps the KAR-2 archive unchanged and does not require millions of tiny directory records. It is a prototype, not a serving source: production integration must verify immutable archive identity once, keep a bounded row or packet cache, account for host page faults and packet assembly, and pass full-model quality and paired latency gates. The original GGUF PLE row is 90 bytes on disk; the current engine expands it to 640 F32 bytes for GPU upload. Compare complete storage, host, PCIe, and GPU costs before selecting a policy. - -The CPU quality oracle can decode up to one million values from an arbitrary nested tensor offset with bounded memory, reading only the needed scales and plane words after archive verification. `cargo run --release --example compare-kar-range -- FILE.gguf FILE.kar LEVEL START COUNT` compares this archived output against pinned ggml dequantization of a one-tensor GGUF sample. On source-verified real slices, independent level-2 archive reconstruction gave relative L2 around 0.33–0.34 for sampled IQ3_S and IQ4_NL ranges; level 3 reduced one IQ4_NL range to 0.165. This is a numerical roundtrip check on selected ranges, not an agent-quality gate. - -`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` adds the opt-in fetch → source verify → streamed prepare → archive verify sequence. On rerun it only reuses an archive after fresh shard, payload, and provenance checks; a damaged archive or changed level fails closed. The measured level-2 real-model archive is 55,295,529,472 bytes (51.50 GiB); its model quality remains unmeasured. Use an external model volume or the Linux GPU host for preparation. - -`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally. - -The streamed assembly now consumes private staged sections as it copies them into the archive, then independently verifies the finished archive before publication. This keeps peak preparation space close to the larger of staged sections or final archive, plus the source shards, rather than requiring both copies of the encoded payload at once. A later shard may omit `general.architecture`; all shards that declare it must agree, and at least one must supply it. The target model's second shard has this metadata shape. - -## GPU path - -`leleka-api model plan-kar-memory FILE.kar --level 2 --budget-mib 24576` reads validated KAR metadata and reports compressed-prefix residency, full F32 decode scratch, the largest single-record peak, and records whose full decode exceeds the supplied VRAM slice. The budget must be the memory left after the engine, KV cache, and other allocations; it is not the card's advertised capacity. `one_row_peak_bytes` is only a geometric lower bound for records that `kar_decode_rows()` can address. It does not mean the model can compute from one row of an arbitrary expert or projection. This command does not scan payload CRCs or approve the archive for serving. - -`leleka-api model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level 2 --overlay-level 3 --budget-mib 24576` first verifies both complete archive hashes, payload CRCs, provenance, and every replacement mapping. It then counts exactly one selected record per tensor at its chosen precision level, separating base and overlay compressed residency and reporting the largest F32 scratch and one-row lower bound. Keep both archives immutable after this check. This is still a memory calculation, not GPU admission or permission to serve a lossy model. - -On the verified Qwen3.8-Flash-Next IQ3_S level-2 archive, the metadata plan at a hypothetical 24,576 MiB slice reports 55,294,991,056 bytes if all compressed records were resident, so residency must be selective. Two split `per_layer_token_embd.weight` records exceed that slice for full F32 decode: their compressed-prefix-plus-output peaks are 138,000,000,016 and 82,801,059,856 bytes. Their one-row lower bounds are 10,000,000,656 and 6,000,077,456 bytes. `kar_decode_rows()` avoids the huge F32 output but `kar_reserve()` still stages the complete 10.0 GB or 6.0 GB compressed record. Efficient cold row lookup therefore needs smaller addressable PLE parts or a sparse staging kernel. The engine must not allocate the full decoded table on the target card. These are metadata arithmetic, not GPU measurements or quality results. - -For the target compressed runtime, copy the selected KAR data to VRAM in compressed form. Keep at least the working layer and selected experts decoded or decode them into a bounded scratch buffer on a CUDA stream before multiply. Use `kar_decode_rows()` for sparse per-layer embedding lookups. The scheduler must account for archive residency, precision level, transfers, decode, and multiply, and measure cold misses separately from warm expert-cache hits. The archive format and decoded numerical values must be compared with the koference CPU oracle before an end-to-end speed claim. - -The user-facing Linux command checks the installed NVIDIA driver and starts the native engine. It does not carry the driver. The single-file GPU packaging goal still needs a real Linux CUDA build and loader test. - -## Cache profiles - -| Profile | Attention state | Status | -| --- | --- | --- | -| `with-key` | K and V cache, using the selected baseline KV format | Control profile for quality and performance | -| `without-key` | Value-Only cache with a validated `Wq_keyless` transform; separate QSA indexer keys remain | Experimental until the Keyless quality gate passes | - -Record the model digest, archive digest, cache profile, KV format, context length, slot count, and hardware with every comparison. Test `without-key` on held-out activation traces and full 256K/512K agent workloads; report memory savings, quality, and throughput separately. A cache profile cannot silently change when an archive is selected. - -## Test-runtime switch - -The testing runtime can first receive shadow traffic after a real Linux GPU smoke test proves model loading and a complete text response. Replacing the current test endpoint requires live Responses streaming, cancellation and tool-call integrity, sanitized Codex replay, a verified compressed GPU path, both cache profiles labeled accurately, and a one-step rollback to the current runtime. `without-key` can be tested separately before it is eligible as a default. - -## KAR level-decode CUDA port (status) - -The Rust runtime now carries an unbuilt CUDA path for decoding NESTED KAR records at runtime levels 2..=5 (kernel source, a fail-closed unpinned driver wrapper, a macOS-verified CPU model of the kernel's addressing, and a pure level/overlay/scratch selection module). Only the CPU model and pure planning code are verified; the nvcc build, PTX pins and GPU smoke are open and there is no performance or quality result. See `docs/experiments/2026-10-14-kar-levels-gpu-port.md`. - diff --git a/docs/cp-latency.md b/docs/cp-latency.md deleted file mode 100644 index 4bb66ee3..00000000 --- a/docs/cp-latency.md +++ /dev/null @@ -1,192 +0,0 @@ -# Host-side request latency: control plane, tokenizer, gRPC (`claude/cp-latency`) - -Status: measured and fixed on the host side of a request (everything before the engine starts the prefill and after tokens -leave it). The numbers below are a paired A/B of the code before and after, on the same workload, with an *instant* engine -(it answers the moment it has the prompt), so they are the cost of the host path only and say nothing about the engine, the -model or its quality. Token ids and prompt text are bit-identical to the old path on all the data checked (section 4). The -real-engine run (section 6) is queued as job `9f1-cp-live-ab` and is not part of the numbers until it ran. - -Branch `claude/cp-latency`, cut from `claude/port-gpu-bringup` at `cfe0a02`. The baseline for every "before" is `dbf487b` -(the original request path plus the env-gated stage spans and the replay driver, nothing else); the "after" is the branch head. - -## 1. What was measured and how - -**Workload.** The engine side capture of two real Codex sessions (`capture/943b-codex-ttt`, `capture/945-codex-crm`: the -rendered prompt token ids of every request) was inverted into the Responses requests Codex sends: `scripts/cp/synth_session.py` -decodes the prompt with the pinned vocabulary and turns the system block into `instructions` and `tools`, the user turns into -messages, the assistant turns into `reasoning` / `message` / `function_call` items and the `` turns into -`function_call_output` items. The history of the CRM session (123,239 tokens) is extended with the second session (call ids and -text tagged so no two items are identical) to reach 196k tokens. Check: rendering and tokenizing the synthesized request for the -last captured round gives **exactly the 123,239 captured prompt ids** (and 82,315 for the other session), through the real HTTP -layer. The captures and the synthesized sessions stay outside Git. - -**Driver.** `control-plane/examples/cp_replay/main.rs`: real axum router, real `backend_worker`, real tokenizer, real loopback HTTP -(keep-alive, SSE), request bodies exactly as Codex sends them (`reasoning.effort` medium, `store: false`, 12 tools, `stream`). -For each history size (20k, 60k, 120k, 180k tokens, picked by the server's own `/v1/responses/input_tokens`) it replays 16 -consecutive rounds of the session on a fresh stack: turn 0 is **cold** (nothing cached), turns 1.. are the **steady state** of a -real session (each request is the previous history plus a few new items). Two engines behind it: - -* `proc`: an in-process engine implementing `leleka_backend_api::Backend` (answers at once with a 420-token reasoning + tool-call - reply, 24-byte deltas 1 ms apart after a 20 ms wait, so the response's opening events have left before the first token); -* `grpc`: the same engine behind the real `RuntimeServer` and the control plane's `GrpcBackend` - (`desktop-core/examples/cp_replay_grpc.rs`): snapshot RPC, a 640 KB prompt string over HTTP/2 on loopback, the event stream back. - -**Metrics** (ms per request, warm turns, p50 / p95): `pre_engine` = the client finished sending -> the engine has the prompt (body -read, JSON parse, validation, chat template, tokenization, queue, prompt text for the engine, the engine call); `first_event` = the -engine's first text delta -> its SSE event at the client; `tail` = the engine's terminal event -> `response.completed` at the client. -The stage table comes from the spans (`STRATA_STAGE_TRACE=1`, off by default: one relaxed atomic load per span; -`STRATA_STAGE_TRACE=log` writes `stage t_unix_ms=` lines to stderr, which `scripts/cp/live_report.py` joins with a -client's timings). - -**Noise.** The laptop (WSL2 Ubuntu 24.04, i9-11900H 8C/16T, rustc 1.99.0, other agents building and running jobs on it) is shared. -Base and new runs alternate (`scripts/cp/run-ab.sh`), five repeats, and each cell is the *minimum over the repeats* of that -repeat's p50 (resp. p95): the least disturbed estimate of each build. Raw per-turn rows are in the result JSONs the driver writes. - -## 2. What was found and what changed (largest first) - -At a 180k-token history, warm turn, `grpc` engine, per request, before -> after: - -| # | finding | before -> after | -| --- | --- | --- | -| 1 | **The whole history was tokenized twice before the engine saw it.** The HTTP layer encoded the rendered prompt (`tokenize`), and the text-level worker then decoded those ids back to text and encoded that again to prove the round trip (`worker_prompt_text`), because the engine contract carries text. The tokenizer (regex pre-tokenizer + string BPE) ran at 1.0-1.3 Mtok/s. | `tokenize` 177 -> 1.0 ms, `worker_prompt_text` 187 -> 0.95 ms | -| 2 | **A new tokenizer fast path with a segment cache** (`crates/tokenizer`): a hand-written scanner for the pinned pre-tokenizer pattern (Unicode classes read out of `regex-syntax`, the crate the regex engine uses), byte-level BPE over token ids with a rank table instead of re-built strings, and a bounded cache of the ids of text between special tokens, keyed by the exact text (a hit is verified byte for byte). Uncached 11.5 Mtok/s (9x); a repeated history costs a hash and a memcpy: 123k tokens in 0.24 ms against 100 ms. The agent resends its whole history every turn, so every turn after the first only tokenizes its new tail. The same crate runs in the engine process (`prepare_prompt` encodes the prompt string again, on every request, before the prefill), so that request-path copy of the cost goes away there too. | cold 123k tokens 100 -> 11 ms (the whole cold `pre_engine` at 180k: 340 -> 24 ms), warm 0.24 ms | -| 3 | **The runtime gRPC server had Nagle on.** `serve_with_incoming_shutdown` ignores the builder's `tcp_nodelay` and `TcpListenerStream` does not set it, so every small response frame (the accept of a generation, the first delta, the terminal) waited for the client's delayed ACK. `TcpIncoming::with_nodelay(true)` in `desktop-core/src/runtime_rpc.rs`. | `engine_start` 42 -> 2.2, first token to the client 19.2 -> 0.4, completion 36.7 -> 1.4 | -| 4 | **Chat template over the whole history**: three copies of every message (`Owned`, `Json`, minijinja `Value`) and the Jinja loop. For this template every message after the leading system messages renders to text that depends on that message alone (`preserve_thinking` is never set), so only the head (tools, reasoning instruction, merged system text) goes through Jinja and the messages are written directly (`prompt::render_native`; `STRATA_REFERENCE_RENDER=1` goes back to the template). | `render` 2.4 -> 0.98 | -| 5 | Tool-schema validation compiled a JSON-schema validator per tool, three times per request (parse, initial envelope, final response). Memoized by the schema text. | `request_validate` 0.26 -> 0.07 | -| 6 | The two per-generation log lines were written before the engine call / before the terminal event reached the client, under the stderr lock. Their timestamps are unchanged; the write now follows. | off the response path | -| 7 | `TCP_NODELAY` on the HTTP listener (SSE events and small responses must not wait for an ACK). | not measurable on loopback; correct for a LAN | - -Not changed, measured: body read + JSON parse 1.4 ms (a borrowed/typed parse would save about 1 ms and needs the validation error -texts re-proved), the snapshot RPC before every generation 0.7 ms (it is a deliberate identity check), the 640 KB prompt over HTTP/2 -about 1.6 ms (frame size and window settings made no difference), `response.created` is sent after tokenization (Codex does not wait -for it). Per streamed token the host spends about 12 us (decode, event JSON, SSE), 0.08 % of one core at 65 tok/s: flush batching per -engine round would change the event contract for nothing. - -## 3. Results - -Headline, 180k-token history, warm turn (steady state of a session), p50 (p95), ms, minimum over 5 interleaved repeats: - -| | before (`dbf487b`) | after | -| --- | --- | --- | -| `pre_engine`, engine behind the real gRPC hop | 376 (398) | **6.5 (6.8)** | -| `pre_engine`, in-process engine | 347 (371) | 5.2 (5.6) | -| `first_event` (engine's first delta -> client), gRPC | 19.2 (20.0) | 0.39 (0.47) | -| `tail` (engine's terminal -> `response.completed`), gRPC | 36.7 (41.6) | 1.44 (1.53) | -| `pre_engine`, first request of a session (cold), gRPC | 340 | 24 | - -The same at the other sizes (`pre_engine`, gRPC, warm p50): 20k 90 -> 2.9, 60k 149 -> 3.8, 120k 270 -> 5.3. The cost used to grow -with the history (about 2 ms per 1k tokens); it now grows by about 0.02 ms per 1k tokens. Per request that is roughly 370 ms -before the engine plus about 55 ms of gRPC stalls around the first token and the completion, at 180k. - -Full tables as printed by `scripts/cp/summarize.py` (p50 / p95 per cell; stage names as in section 1): - -#### in-process instant engine - -| metric (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | -|---|---|---|---|---|---|---|---|---| -| pre_engine_ms | 76.32 / 94.96 | 2.36 / 2.65 | 137.11 / 155.63 | 3.06 / 3.32 | 264.87 / 287.44 | 4.40 / 4.92 | 346.77 / 370.86 | 5.18 / 5.64 | -| first_event_ms | 0.30 / 0.38 | 0.24 / 0.34 | 0.31 / 0.38 | 0.28 / 0.36 | 0.38 / 0.47 | 0.23 / 0.33 | 0.44 / 0.49 | 0.29 / 0.39 | -| tail_ms | 1.32 / 1.37 | 1.08 / 1.17 | 1.44 / 1.51 | 1.10 / 1.24 | 1.53 / 1.65 | 1.24 / 1.35 | 1.60 / 1.75 | 1.31 / 1.37 | - -| stage (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | -|---|---|---|---|---|---|---|---|---| -| http_body_json | 0.30 / 0.36 | 0.35 / 0.43 | 0.56 / 0.71 | 0.59 / 0.69 | 1.14 / 1.22 | 1.08 / 1.15 | 1.35 / 1.43 | 1.32 / 1.53 | -| request_decode | 0.03 / 0.04 | 0.03 / 0.04 | 0.05 / 0.06 | 0.05 / 0.06 | 0.09 / 0.11 | 0.09 / 0.10 | 0.12 / 0.15 | 0.12 / 0.15 | -| request_validate | 0.22 / 0.24 | 0.07 / 0.08 | 0.23 / 0.24 | 0.07 / 0.07 | 0.24 / 0.27 | 0.06 / 0.07 | 0.25 / 0.28 | 0.07 / 0.07 | -| render | 0.64 / 0.71 | 0.44 / 0.47 | 1.09 / 1.21 | 0.55 / 0.61 | 1.81 / 1.91 | 0.82 / 0.90 | 2.31 / 2.53 | 0.99 / 1.02 | -| tokenize | 36.75 / 42.84 | 0.46 / 0.61 | 65.94 / 73.67 | 0.62 / 0.73 | 125.56 / 137.45 | 0.91 / 1.31 | 163.90 / 175.74 | 1.05 / 1.23 | -| worker_prompt_text | 37.86 / 47.49 | 0.35 / 0.40 | 67.95 / 78.76 | 0.48 / 0.54 | 133.91 / 142.57 | 0.74 / 0.85 | 176.74 / 188.26 | 0.97 / 1.07 | -| engine_start | 0.38 / 0.43 | 0.28 / 0.31 | 0.49 / 0.53 | 0.39 / 0.42 | 0.71 / 0.77 | 0.65 / 0.67 | 0.90 / 0.97 | 0.80 / 0.86 | -| post_decode | 0.16 / 0.19 | 0.08 / 0.10 | 0.17 / 0.20 | 0.08 / 0.10 | 0.18 / 0.19 | 0.09 / 0.10 | 0.18 / 0.20 | 0.09 / 0.10 | -| post_assemble | 0.67 / 0.72 | 0.53 / 0.57 | 0.70 / 0.74 | 0.54 / 0.59 | 0.70 / 0.76 | 0.55 / 0.60 | 0.70 / 0.75 | 0.56 / 0.63 | -| post_store | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | -| delta_retokenize | 1.92 / 2.29 | 0.50 / 0.59 | 2.00 / 2.25 | 0.44 / 0.55 | 2.11 / 2.29 | 0.47 / 0.54 | 1.97 / 2.33 | 0.49 / 0.61 | - -cold first request (ms, min over repeats): - base pre_engine cold: 20k=57.0, 60k=120.6, 120k=235.5, 180k=317.4 - new pre_engine cold: 20k=5.6, 60k=9.2, 120k=16.5, 180k=22.8 - -#### instant engine behind the real gRPC runtime server - -| metric (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | -|---|---|---|---|---|---|---|---|---| -| pre_engine_ms | 89.96 / 100.84 | 2.93 / 3.38 | 148.72 / 166.45 | 3.81 / 4.16 | 269.81 / 296.34 | 5.34 / 6.01 | 376.19 / 398.10 | 6.50 / 6.84 | -| first_event_ms | 19.30 / 20.18 | 0.36 / 0.44 | 18.73 / 19.91 | 0.32 / 0.40 | 18.92 / 20.25 | 0.34 / 0.41 | 19.18 / 20.01 | 0.39 / 0.47 | -| tail_ms | 37.11 / 41.51 | 1.18 / 1.34 | 34.79 / 40.25 | 1.21 / 1.30 | 35.73 / 42.66 | 1.31 / 1.40 | 36.65 / 41.56 | 1.44 / 1.53 | - -| stage (ms, warm turns) | 20k base p50 / p95 | 20k new p50 / p95 | 60k base p50 / p95 | 60k new p50 / p95 | 120k base p50 / p95 | 120k new p50 / p95 | 180k base p50 / p95 | 180k new p50 / p95 | -|---|---|---|---|---|---|---|---|---| -| http_body_json | 0.31 / 0.38 | 0.32 / 0.43 | 0.58 / 0.71 | 0.58 / 0.66 | 1.07 / 1.23 | 1.00 / 1.17 | 1.39 / 1.67 | 1.35 / 1.52 | -| request_decode | 0.03 / 0.04 | 0.03 / 0.04 | 0.05 / 0.06 | 0.05 / 0.05 | 0.09 / 0.11 | 0.09 / 0.10 | 0.13 / 0.16 | 0.12 / 0.15 | -| request_validate | 0.22 / 0.26 | 0.07 / 0.07 | 0.22 / 0.24 | 0.06 / 0.07 | 0.23 / 0.28 | 0.07 / 0.07 | 0.26 / 0.29 | 0.07 / 0.08 | -| render | 0.68 / 0.78 | 0.42 / 0.47 | 1.06 / 1.16 | 0.56 / 0.64 | 1.85 / 1.99 | 0.84 / 0.88 | 2.37 / 2.50 | 0.98 / 1.04 | -| tokenize | 40.90 / 45.94 | 0.46 / 0.65 | 70.57 / 79.79 | 0.63 / 0.76 | 127.94 / 148.69 | 0.90 / 1.29 | 176.81 / 202.94 | 1.03 / 1.32 | -| worker_prompt_text | 43.00 / 50.17 | 0.34 / 0.43 | 75.03 / 84.18 | 0.47 / 0.53 | 135.32 / 149.33 | 0.76 / 0.84 | 186.68 / 203.86 | 0.95 / 1.06 | -| engine_start | 1.74 / 40.88 | 1.08 / 1.22 | 39.36 / 41.22 | 1.34 / 1.57 | 40.51 / 42.04 | 1.77 / 1.95 | 41.66 / 42.40 | 2.15 / 2.47 | -| post_decode | 0.16 / 0.19 | 0.08 / 0.09 | 0.17 / 0.21 | 0.08 / 0.09 | 0.15 / 0.18 | 0.08 / 0.10 | 0.16 / 0.20 | 0.09 / 0.11 | -| post_assemble | 0.67 / 0.78 | 0.56 / 0.59 | 0.69 / 0.83 | 0.54 / 0.57 | 0.70 / 0.83 | 0.55 / 0.58 | 0.73 / 0.78 | 0.56 / 0.59 | -| post_store | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.02 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | 0.03 / 0.03 | -| delta_retokenize | 1.97 / 2.17 | 0.53 / 0.58 | 2.07 / 2.33 | 0.45 / 0.49 | 1.94 / 2.12 | 0.49 / 0.54 | 1.99 / 2.24 | 0.54 / 0.57 | - -cold first request (ms, min over repeats): - base pre_engine cold: 20k=61.6, 60k=127.0, 120k=253.7, 180k=340.2 - new pre_engine cold: 20k=6.5, 60k=10.1, 120k=17.6, 180k=23.9 - - -## 4. Equivalence - -* `cp_replay --verify` replays **every round** of the synthesized sessions (135 rounds, 9k-196k tokens, and 52 rounds of the other - session) through the real HTTP layer and checks: the ids of the production path equal `Tokenizer::encode_reference` (the original - implementation) on the prompt the engine received; the ids decode back to that prompt; `/v1/responses/input_tokens` counts them; - the round whose history is the captured request reproduces the **captured prompt ids** (123,239 and 82,315 tokens) exactly. - The per-round `PROMPT round tokens prompt_fnv ids_fnv` lines of the baseline build, of the new build and of the new build with - `STRATA_REFERENCE_RENDER=1` (Jinja for every prompt) are byte-identical (md5 of the 135 lines equal in all three). -* `crates/tokenizer/tests/fast_path.rs`: the scanner splits every Unicode scalar value in 13 contexts and 400,000 fuzzed texts - like the regex; `encode` equals `encode_reference` for ~3,000 fuzzed texts and the oracle cases on a cold cache, a warm cache and - a cache too small to hold anything; real prompts (`LELEKA_TOKENIZER_DIR` / `LELEKA_TOKENIZER_TEXTS`) encode like the reference - cold and warm; the existing Python-oracle test (`oracle_differential.rs`) still passes. -* `prompt::native_render_equals_the_template`: 4,000 random conversations (whitespace of every kind at the edges, empty contents, - template-looking and special-token text, with and without system messages and tools, every effort) render to the same bytes (or - the same error) both ways; the ten golden chat cases pass. -* `leleka-control-plane`: all 282 unit tests and every integration test, including the golden HTTP surface and the full-chain - `backend_worker_http` suite (a new test covers the prompt-text pass-through: the text is sent only if the ids decode to it, else - the old check runs); `leleka-engine-host` (the full chain with the real `RuntimeServer`), `leleka-runtime-client`, - `leleka-backend-api`, `leleka-serving-policy`, and `leleka-runtime --lib` (510) pass. -* Kill switches: `LELEKA_TOKENIZER_REFERENCE=1` (original tokenizer only), `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB=n` (0 = no cache; default - 64, both engine and control plane), `STRATA_REFERENCE_RENDER=1`. - -## 5. How to reproduce - -```text -python3 scripts/cp/synth_session.py TOKENIZER_DIR CAPTURE_DIR LAST_REQ OUT.json [--extend CAPTURE2 LAST2] -cargo run --release -p leleka-control-plane --example cp_replay -- TOKENIZER_DIR OUT.json [--sizes 20000,60000] [--turns 16] [--out r.json] -cargo run --release -p leleka-engine-host --example cp_replay_grpc -- TOKENIZER_DIR OUT.json # real gRPC hop -cp_replay TOKENIZER_DIR OUT.json --verify [--verify-step 1] # equivalence -scripts/cp/run-ab.sh BASE_TREE NEW_TREE TOKENIZER_DIR OUT.json OUT_DIR 5 --turns 16; python3 scripts/cp/summarize.py OUT_DIR -LELEKA_TOKENIZER_DIR=... LELEKA_TOKENIZER_TEXTS=... cargo test --release -p leleka-tokenizer -``` - -## 6. Real engine - -Job `scripts/e2e/codex/jobs/9f1-cp-live-ab.sh` (queue name `9f1-cp-live-ab`): one model load, the current `leleka-api` on :8081 and the -baseline `leleka-api` on :8082 in front of the same engine (the new `leleka-inference`), one synthesized Codex session of about -100k tokens, 20 consecutive requests (`max_output_tokens` 64) sent alternately through the two so the engine sees the same prompt -sequence either way. `scripts/cp/live_report.py` joins the client's timings with both servers' stage logs and the engine's -`generation done` lines: client time to first token = pre-engine host time + engine time + post time. Queued behind the other jobs of `holder2/jobs` (23 pending when submitted); the result is appended here when it ran. - -## 7. What remains - -* The engine contract carries the prompt as text, so the engine still tokenizes it (now a cache hit for a repeated history). Carrying - the ids, or just the new tail plus a prefix digest, would remove the 640 KB string and the text/ids round trip; it is a contract change - (proto, `RuntimeServer`, the engine), not made here. `runtime_rpc.rs` refuses a prompt above 1 MiB: at 3.76 bytes per token that is - about 280k tokens, close to the 262k context for code-heavy text. -* Body read and parse (1.4 ms at 180k), the snapshot RPC (0.7 ms), the prompt over HTTP/2 (1.6 ms) are the remaining 6.6 ms of - `pre_engine`; the first two need semantics decisions (typed parse with identical errors; trusting the server-side epoch fence). -* Clients that send `store: true` or `previous_response_id` (Codex sends neither) pay the history store before the terminal event: - in memory it measured 1.2 ms at 180k (`post_store`, `cp_replay --store`); with persistence on it re-serializes and checksums *all* - stored entries (up to 128 MiB) on every response, which was not measured; `previous_response_id` deep-copies the saved transcript. - Not on the Codex path, not changed. -* With `reasoning.effort` other than `none` the answer text (and tool calls) are withheld until the engine's terminal event (reasoning - deltas stream live); the host cost of that is the 1.5 ms `tail`, the wait itself is the design. -* The engine side of the prefix cache (block hash chain over 180k tokens, about 0.3 ms: one multiply-xor per token, sequential) and - the cache resume grid belong to `claude/ttft`. diff --git a/docs/cpu-runtime.md b/docs/cpu-runtime.md deleted file mode 100644 index 3551dfe4..00000000 --- a/docs/cpu-runtime.md +++ /dev/null @@ -1,273 +0,0 @@ -# Leleka CPU runtime (AVX2 / AVX-VNNI) - -Status on 2026-10-14: runs gpt-oss-20b (MXFP4 GGUF, the lmstudio-community file with SHA-256 -`65d06d31a3977d553cb3af137b5c26b5f1e9297a6aaa29ae7caa98788cde53ab`) end to end through the control plane's -worker protocol. Not wired into the control plane's request path yet (see "Not done"). - -## Crates (a separate runtime; shares only `crates/backend-api` with others) - -| Crate | Role | -| --- | --- | -| `leleka-cpu-sys` | The only `unsafe` code of this runtime: SIMD kernels (`std::arch`, AVX2 and AVX-VNNI plus a portable level), read-only file mapping, core topology. Every public function is safe and checks lengths and CPU support. Optional test features: `c-reference` (the first, C implementation, compared bit for bit) and `ggml-oracle` (llama.cpp's quantizers). | -| `leleka-cpu-kernels` | Runtime dispatch by CPUID (`LELEKA_CPU_ISA` overrides and fails rather than silently switching). | -| `leleka-gguf` | Bounded GGUF reader and per-token byte inventory. | -| `leleka-gptoss` | The decoder: persistent thread pool, chunked prefill, prefix reuse, f32 KV cache, sampling. | -| `leleka-tokenizer` | `gguf_bpe`: gpt-oss tokenizer from the GGUF vocabulary. | -| `leleka-harmony` | Prompt rendering and output parsing of the Harmony chat format. | -| `leleka-cpu-worker` | The executable: `leleka-cpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N]`. | - -## Worker protocol - -Same lines as Strata's `--serve` mode (`control-plane/src/wire.rs`). The worker prints `READY stop` -after loading (and, unless `--no-warm`, reading every page of the model once), then per request: -`PP ` after every prefill chunk, `REUSED `, `T ` per generated token, and one -`DONE stop|length|cancel 0 0 0 0` (or `ERR`). -Input: `GEN [temperature=] [top_p=] [seed=] `, `STOP`, `QUIT`. The end-of-generation marker -(`<|return|>`, `<|call|>` or `<|endoftext|>`) is emitted as the last `T` so the caller can tell an answer -from a tool call. A `STOP` while no request runs is ignored. Tokenization and Harmony rendering/parsing -belong to the caller (the crates above are the pieces for it). - -## What was measured (Core Ultra 7 265U, 15 W, 32 GB class laptop; one noisy machine, no quiet gate for -every number; see the work results on STRA-214 and STRA-217 for the paired runs) - -* Decode, 10 threads, warm pages: 85-100 ms per token (10-11.7 tokens/s). Bionic's llama.cpp measured - 7.6-8.7 tokens/s on the same prompt on this machine (STRA-209, partial baseline). -* Decode at 2,000 tokens of context: 95 ms per token (10.5 tokens/s); attention costs 7.7 ms of it (27.4 ms with scalar attention loops). Attention reads each KV head's keys and values once for its 8 query heads (blocked in L1) with AVX2/FMA kernels and a vector exp. -* Prefill, 10 threads, chunk 64: about 51 ms per token (19.6 tokens/s) on 256 random-id tokens. Bionic's - iGPU engine measured about 90 tokens/s; its CPU engine about 14.8 tokens/s. Prefix reuse makes the - second and later requests of a conversation cheap. -* Correctness: first 16 greedy tokens equal llama.cpp's for "The capital of France is"; chunked prefill and - prefix reuse are bit-identical to feeding tokens one at a time; kernels at every instruction-set level - are tested against exact integer references and against llama.cpp's quantizers. - -## Serving through the control plane - -The control plane (`leleka-api serve`) serves `/v1/responses` for gpt-oss with this worker. Configuration -(JSON file, or `STRATA_GPTOSS_GGUF`): - -```json -{ - "bind": "127.0.0.1:8081", - "model": "gpt-oss-20b", - "engine": { - "executable": "target\\release\\leleka-cpu-worker.exe", - "args": ["--model", "", "--ctx", "8192", "--threads", "10"], - "gptoss_gguf": "", - "startup_timeout_s": 300 - } -} -``` - -`gptoss_gguf` selects the gpt-oss family and takes the tokenizer from that file. The control plane renders -the Harmony prompt from the Responses request (instructions, input items, tools, tool_choice, reasoning -effort), sends the token ids to the worker, and turns the generated Harmony stream into reasoning, -message and function_call items (buffered and streaming). The special markers of the template are written -as private-use sentinel characters and only those become special tokens, so text from a client cannot -forge a marker. Run `benchmarks/tools/Smoke-GptOssStack.ps1 -Model ` to check the whole stack: -plain question, function call, tool-result round trip with prefix reuse (about 130 of 180 prompt tokens -were cached on the second turn), and a streaming request. Not supported for this family: custom tools. -Tool-call arguments arrive in one piece when the call ends (the stream decoder buffers them). -## Known limits / not done - -* The first-step log-probabilities differ slightly from llama.cpp's (0.4 vs 0.45 for the top token); the - teacher-forced logit comparison that would explain it is still to be done. Greedy tokens agreed on the - prompts tried, but near-ties can flip. -* The KV cache holds half-precision keys and values (about 49 KB per token, as llama.cpp's default): the worker's default context is 32,768 tokens (1.6 GB). A 131,072-token context would take 6.4 GB; RAM planning for it with the 12 GB model (STRA-204/205/210) and cold-expert streaming (KAR) are not done. -* One decode at a time per worker (several conversations can share it through `--cache-slots`); sampling is temperature and top-p over the 1,024 best logits. -* iGPU and NPU prefill helpers exist as opt-in workers (`docs/igpu-prefill.md`, `docs/npu-service.md`); the packaged Windows runtime is described in `docs/windows-runtime.md`. - -## Decode speed limit on the reference laptop (2026-10-15) - -The reference laptop has one 32 GB DDR5-5600 module (single channel, 44.8 GB/s peak). One decoded token of gpt-oss-20b -reads about 2.56 GB (experts 1.27, attention Q8_0 0.68, output layer 0.62), so decode is capped near 14-15 tokens/s at -the measured 36-40 GB/s, for this runtime and for llama.cpp alike. The CPU and the integrated GPU share that channel: -streaming from both at once gave about 37 GB/s in total (GPU 28 GB/s alone, about 21 GB/s while the CPU decoded), so -splitting decode across them does not add bandwidth. Verifying several tokens in one CPU pass is compute-bound (about -0.42 single steps per token since the multi-activation kernels, 0.65 before), which caps CPU-side speculative decoding -near 2x; see the `--speculate` section below. -Prompt-lookup drafting accepted only 1.03-1.2 tokens per step on the four set2 texts. A second memory module (dual -channel) is the lossless way past the cap. - -### Experimental lossy mode: fewer experts per token - -`LELEKA_EXPERIMENTAL_EXPERTS_USED=N` routes each token to N experts instead of 4 (off unless set; logs a warning; no quality -gate allows it). Decode and teacher-forced quality against llama.cpp on `table-igpu` / `docs-cpu` (set2), one noisy run: - -| experts | decode tok/s | best-token agreement | mean KL | -| --- | --- | --- | --- | -| 4 (model) | 8.7 | 93.4% / 92.7% | 0.016 / 0.023 | -| 3 | 10.2 | 70.4% / 72.8% | 0.161 / 0.185 | -| 2 | 12.8 | 51.0% / 52.4% | 0.460 / 0.477 | - -Removing expert bytes costs far more quality than it buys speed; not recommended. - -### Experimental quality probe: attention and output weights at fewer bits - -`LELEKA_EXPERIMENTAL_FAKE_BITS=N` re-rounds the attention and output Q8_0 weights to an N-bit symmetric grid per block of -32 (absmax scale in half precision), stored in Q8_0 so there is no speed change; it only measures what an N-bit format -would cost. Teacher-forced against llama.cpp on `table-igpu` (set2; baseline 8-bit: mean KL 0.016, 93.4% agreement): - -| bits per weight (scale not counted) | best-token agreement | mean KL | -| --- | --- | --- | -| 7 | 84.9% | 0.053 | -| 6 | 81.4% | 0.071 | -| 5 | 76.4% | 0.112 | -| 4 | 63.5% | 0.270 | - -Plain block rounding of the attention and output layers is not usable below 8 bits on this model. (An earlier version of -this note called a KAR layout "the same rounding"; it is not: KAR fits a non-uniform codebook per tensor. The real -codec was measured afterwards, see the next section.) The first run of this probe had a half-precision -conversion bug (small scales flushed to zero); the numbers above are from the fixed code. - -### Experimental quality probe: the real KAR codec on attention, output and expert weights (2026-10-16) - -The KAR codec of the control plane (koference KAR-2: f16 absmax scale per group of 32, then an N-level nested codebook -fitted to each tensor by optimal top-down splits) moved unchanged into `crates/kar-codec`, which both the control plane -and the CPU runtime use. `LELEKA_EXPERIMENTAL_KAR_LEVELS=N` encodes and decodes the attention and output Q8_0 weights -with it (codebook fitted to 65,536 values sampled evenly per tensor) and stores the reconstruction in Q8_0 -(`LELEKA_EXPERIMENTAL_KAR_TENSORS` selects tensors by name); `LELEKA_EXPERIMENTAL_KAR_EXPERT_LEVELS=N` with -`LELEKA_EXPERIMENTAL_KAR_EXPERT_LAYERS=a-b` does the same for the MXFP4 experts of those layers and stores them in Q8_0. -Both are probes only: no speed-up, no serving use. Teacher-forced against llama.cpp on `table-igpu` (set2, 770 -positions; baseline 8-bit: 93.4% best-token agreement, mean KL 0.016): - -| KAR levels (bits per weight with scale) | attention + output: agreement / mean KL | uniform rounding at the same bits | -| --- | --- | --- | -| 6 (6.5) | 83.9% / 0.063 | 81.4% / 0.071 | -| 5 (5.5) | 79.4% / 0.095 | 76.4% / 0.112 | -| 4 (4.5) | 68.1% / 0.213 | 63.5% / 0.270 | -| 3 (3.5) | 39.9% / 0.557 | | - -At 4 levels, one group at a time: output layer alone 79.9% / 0.062, `attn_q`+`attn_k` 75.6% / 0.120, `attn_v`+`attn_output` -72.6% / 0.172. KAR's codebook is worth about half a bit over uniform rounding, but every group is sensitive on its own, -so no mixed-precision split brings attention or the output layer below 8 bits within the gate. (A rebuild in a clean -worktree reproduced the 4-level all-tensor run exactly.) - -Experts (already MXFP4, 4.25 bits), layers 0-5 only (a quarter of the model; all 24 in Q8_0 would need about 21 GB): - -| expert format in layers 0-5 | agreement / mean KL | -| --- | --- | -| Q8_0 copy of the MXFP4 values (control) | 92.5% / 0.018 | -| KAR 3 levels (3.5 bits) | 85.8% / 0.081 | -| KAR 2 levels (2.5 bits) | 72.9% / 0.166 | - -Four levels cannot be fitted (MXFP4 blocks hold too few distinct values for 16 cells), and they would not save bytes. -Even a quarter of the experts at 3.5 bits costs five times the baseline KL, so KAR below MXFP4 is not usable either. With -these results no KAR rate saves bytes on gpt-oss-20b within the quality gate; decode stays at 2.56 GB per token. - -### iGPU and NPU prefill at the same time (2026-10-16) - -The two accelerators are separate compute units, and prefill is compute-bound, so running them together adds -throughput where decode cannot (`benchmarks/results/igpu-npu-concurrent-prefill-2026-10-16.txt`; `gpu_prefill` and -`npu_prefill` examples in separate processes, 2048 synthetic tokens each, two rounds, otherwise idle machine): - -| | iGPU tok/s | NPU tok/s | -| --- | --- | --- | -| alone | 72.7, 76.5 | 69.8, 74.6 | -| both at once | 59.4, 59.0 | 49.3, 46.7 | - -Together they prefilled 4096 tokens in 41.6 and 43.9 s (98 and 93 tok/s), 1.25-1.3x the faster device alone; each slows -by a fifth to a third (shared memory and the 15 W power budget). Two requests prefilling at once (one per device) could -use this directly; one prompt would need its batches or its expert products split between the devices, which is not -built. The figures are an upper bound for such a split: no synchronization between the devices was needed here. - -### Prompt-lookup speculation: measured acceptance on agent-style output (2026-10-15) - -The model (greedy, `run_real`) generated 320 tokens for four agent-style prompts over about 800 tokens of context (a Rust -file, or the first 2,200 characters of this document); the draft is the continuation of the latest earlier match of the -last N tokens in prompt plus output, up to K tokens, and a step accepts the longest prefix equal to what the model produced. - -| task | tokens per step (N=2..4, K=4 / K=8) | -| --- | --- | -| rewrite the code with renamed functions (copies the input) | 3.3-3.7 / 5.4-5.8 | -| list function names as JSON and repeat the first function | 1.7-2.0 / 1.8-2.1 | -| reproduce a section of the notes as bullets | 1.4-1.6 / 1.4-1.7 | -| explain what the code does (new text) | 1.05-1.2 / 1.05-1.2 | - -Four prompts, one run each: an indication of the spread, not a workload estimate. Verification cost decides whether this -pays: on the CPU a chunk of 4-8 tokens costs 65-78 ms per token on the noisy machine (about 50 ms quiet), against about -110 ms for a decode step, so with 3.5-5.7 tokens per step the CPU gain is at most about 1.3x; the integrated GPU -(compute about 3-4x the CPU, but expert reads grow with the number of distinct experts in the batch) could reach about -20 tokens/s on copy-heavy output by the estimate in STRA-220, and about nothing on free-form text. - -### Exact speculative decoding in the worker (`--speculate`, experimental, off by default; 2026-10-16) - -`leleka-cpu-worker`, `leleka-igpu-worker` and `leleka-npu-worker` accept `--speculate`. Decoding then drafts from -prompt lookup (`leleka_gptoss::speculate`), feeds the sampled token plus the draft as one batch -(`Model::logits_after_each`, bit-identical to feeding the tokens one at a time; `tests/synthetic_model.rs`), samples -every emitted token from the real logits in order, and cuts rejected positions out of the cache. The output is -therefore exactly that of plain decoding for any sampling settings (`tests/serve_loop.rs`; greedy outputs identical in -all 96 real-model runs below). Drafts never run past the output budget, so a batch stays inside the context margin. -`LELEKA_SPECULATION_LOG=1` prints drafted and accepted counts per request and where the decode time went (passes by size, -sampling, output, drafting, cache cuts), with or without `--speculate`. - -On the CPU a verifying batch is compute-bound, so it is not free (`examples/batch_cost.rs`, position 900, medians). -The batch pass first ran the one-token kernel once per (weight row, token), redoing the MXFP4 decode and scale work for -every token: profiled, the extra cost was compute, not expert bytes (distinct experts per layer rise only from 4 to -9.5 at 9 tokens, while the Q8_0 projections, whose weights every token shares, cost 3.6-4x a single step). The -multi-activation kernels (`leleka-cpu-sys`, portable, AVX2 and AVX-VNNI) decode a weight row once per 64-block segment -and run up to 16 activations over it with exactly the one-token kernel's accumulators, so every value is bit for bit -the one-token kernel's (`tests/multi.rs`; on the real model all 90 paired passes below gave identical logits). Pass -times with them divided by without them, paired back to back in one process (`batch_cost ... 14 ab`, 9 rounds, median -ratio; the machine was busier than for the first row, single step 108 ms): - -| tokens in the pass | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| ms before (quiet run, 93 ms single step) | 93 | 145 | 201 | 264 | 313 | 373 | 443 | 485 | 556 | -| cost in single steps before | 1.00 | 1.56 | 2.16 | 2.84 | 3.37 | 4.01 | 4.76 | 5.22 | 5.98 | -| paired time ratio, after / before | 1.01 | 0.98 | 0.92 | 0.90 | 0.83 | 0.81 | 0.77 | 0.79 | 0.76 | -| cost in single steps after (line used by the drafter) | 1.00 | 1.58 | 2.00 | 2.42 | 2.84 | 3.27 | 3.69 | 4.11 | 4.53 | - -The gain grows with the batch because a token shares a weight row with more others: the Q8_0 projections see every -token, an expert only the tokens routed to it (about 2 at 4 tokens, 4 at 9). Plain decode (one token) is unchanged. A -rerun on a quiet machine (single step 87-92 ms, identical logits in all 90 passes) gave ratios 1.02, 1.05, 0.94, 0.87, -0.83, 0.81, 0.80, 0.76, 0.76 for 1-9 tokens, and passes of 1.52, 1.99, 2.31, 2.65, 3.01, 3.47, 3.92, 4.33 single steps -for 2-9 tokens, slightly below the drafter's line. -A pass over n tokens now costs about 0.74 + 0.42 n single steps, so even a perfect 8-token draft gains at most about 2x, -and a draft accepted 60% of the time still gains almost nothing. The drafter therefore estimates the acceptance of a drafted position -separately by matched-context length (3, 4-7, 8-15, 16+ tokens; decaying counts), drafts the length whose expected -tokens per pass (1 + p + ... + p^k) divided by its cost is largest, and only if that ratio is at least 1.03; the costs -start from the line fitted to the table and then follow the pass times the loop observes. After 16 tokens without a -draft worth making it probes with one token. The defaults were picked by replaying a policy grid over the recorded -outputs (`ab_speculation` with `LELEKA_AB_REPLAY`). - -Paired A/B in one worker process (`crates/cpu-worker/examples/ab_speculation.rs`, raw lines and machine state in -`benchmarks/results/speculation-ab-2026-10-16.txt`): four agent-style Harmony prompts (856-878 tokens) over a Rust -source file, greedy, 320 output tokens at most, 3 alternating pairs per prompt, warm model, decode time only. Paired -speed-up of decode (mean of the three pair ratios): - -| task (output tokens) | inherited fixed-length drafter | cost-aware, noisy machine | same, quieter machine | default policy, noisy | with multi-activation kernels | -| --- | --- | --- | --- | --- | --- | -| rewrite the file with two names changed (320) | 1.36 | 1.26 | 1.34 | 1.25 | 1.54 (1.49, 1.61, 1.52) | -| unified diff adding an attribute (303) | 0.94 | 1.00 | 1.15 | 1.10 | 1.06 (1.11, 1.06, 1.00) | -| functions as JSON (195) | 0.97 | 0.98 | 1.04 | 0.97 | 0.97 (0.97, 1.02, 0.92) | -| explain the file (162) | 0.96 | 0.96 | 1.01 | 0.98 | 0.97 (0.99, 0.97, 0.97) | - -Plain decode ran at 8-9 tok/s on the noisy machine and 11-12 on the quieter one; pair-to-pair spread is about 5%, so -the last two rows are within noise of 1.0. Copying output (rewrites, patches) gains 1.1-1.35x; new text neither gains -nor clearly loses. Three pairs per prompt are not enough for percent-level claims, and these are four prompts, not an -agent trace: the switch stays experimental and off by default. - -The last column was run after the multi-activation kernels on a quiet machine (no other model or compiler process; -`benchmarks/results/batch-pass-multi-2026-10-16.txt`; plain decode 8.9-11.6 tok/s, outputs identical in all 24 runs). The -rewrite now reaches 16-17 tok/s against 10.5-11.6 plain (1.54x, every pair above the 1.23-1.28 of the run before the -change); it drafts longer runs, 222-224 of 227-230 drafted tokens accepted in 39-41 verified batches (43-56 -before). The other prompts are unchanged within the spread. Replaying the recorded outputs through the drafter -predicts 1.59, 1.15, 1.00 and 0.99, close to what was measured. An earlier run of the same binary overlapped another -session's GPU prefill probe and gave 1.34, 1.04, 0.97 and 0.94; it is kept in the results file as disturbed. - -Where the decode time goes (`LELEKA_SPECULATION_LOG=1`, 2 pairs on a quiet machine, outputs identical in all 16 runs; -paired speed-ups 1.55, 1.12, 1.01 and 0.97): everything outside the model passes, that is sampling (40-64 ms per -request), output lines, drafting and cache cuts, is under 0.5% of decode time, and single steps in the speculating arm -cost the same as in the plain arm (81-93 ms). The serving loop has no hidden cost; the gain is set by acceptance and -pass cost. Verifying passes in the worker cost 1.57, 2.04, 2.50, 2.99, 3.66, 4.04, 4.32 and 4.80 single steps for 2-9 -tokens: 3% above `batch_cost`'s random-id passes at 2-3 tokens and 8-22% above from 4 tokens on (real drafts, -positions 900-1200; only 10-11 passes each of 6 and 7 tokens), which is why the rewrite measured 1.55 against the 1.59 -the replay predicts. The drafter follows these observed times after three passes of a size. - -Verifying drafts on the integrated GPU or the NPU does not pay: both run a pass layer by layer with weights uploaded -(GPU) or expanded and prefetched (NPU) every time, a fixed cost of seconds. One 9-token pass from position 0 took 7.3 s -on the GPU (upload 1.2, attention 2.0, experts 3.0, readback 0.7) and 6.3 s through the NPU service, against 0.75-0.93 s -on the CPU; neither is bit-identical to the CPU decoder (KL 1e-4 and 3e-4), so exactness would be lost as well. Keeping -the weights resident on the GPU would need a second ~12 GB copy, which does not fit beside the CPU's mapping on this -32 GB machine (13-15 GB available during these runs). With this, CPU speculation can lift copy-heavy decode from about -10-12 to 13-17 tok/s; the 20+ tok/s goal of STRA-220 is not reachable this way on the single-channel laptop. diff --git a/docs/cross-platform-application.md b/docs/cross-platform-application.md deleted file mode 100644 index 995ee28e..00000000 --- a/docs/cross-platform-application.md +++ /dev/null @@ -1,598 +0,0 @@ -# Strata: застосунок для локальних і віддалених моделей - -**Статус:** архітектура продукту; початкова реалізація desktop, 2026-10-04. -**MCP:** STRA-36, епік STRA-37; desktop STRA-48/49, remote STRA-50–53. - -Цей документ описує запит користувача на macOS, Windows і Linux застосунок із -автоматичною підготовкою моделей. Він доповнює [PROJECT_CHARTER](../PROJECT_CHARTER.md), -але не оголошує завершеними Linux milestones або реалізованими нові платформи. -Порядок пріоритетів незмінний: коректність, якість, швидкість виконання задачі. -Активне користувацьке випробування продовжується без змін runtime. - -## 1. Що отримує користувач - -Основний сценарій: **вибрати модель → підготувати для цього комп'ютера → запустити**. -Застосунок сам визначає сумісні рушії, завантажує потрібні компоненти й модель, -оцінює пам'ять, створює придатне представлення та перевіряє його. Показує прогрес, -можливість продовжити перерване завантаження і конкретну причину несумісності. - -Основні розділи: - -- **Моделі:** каталог, локальний імпорт, версії, розміри оригіналу й підготовлених - варіантів, ліцензія, сумісність, результати перевірки якості. -- **Запуск:** модель, контекст, паралельні запити, режим швидкості/енергії, - фактичний пристрій виконання та оцінка пам'яті. -- **Діалог і API:** простий playground та endpoint для зовнішнього harness. -- **Підготовка:** відновлювані download/conversion/compression/validation jobs. -- **Стан:** TTFT, prefill/decode, токени, RAM/VRAM, черга, помилки. Тексти запитів - не потрібні для стандартної телеметрії. -- **Комп'ютери:** локальний пристрій або явно підключений приватний сервер. - -CLI має ті самі можливості на всіх трьох ОС. GUI можна закрити, залишивши -сервер працювати; команда зупинки явна. Автозапуск вмикається користувачем. -Запропоновані команди, ще не поточний контракт CLI: - -```text -strata model add -strata model prepare --quality preserve -strata run --device auto -strata jobs watch -strata status --json -strata stop -``` - -## 2. Спільне ядро й інтерфейси ОС - -```mermaid -flowchart TD - M[macOS: Avalonia + OS integration] --> C[Спільний protobuf / gRPC API] - W[Windows: Avalonia + OS integration] --> C - L[Linux: Avalonia + OS integration] --> C - CLI[Спільний Rust CLI] --> C - C --> D[Rust service: моделі, jobs, lifecycle, planner] - API[Responses HTTP / SSE] --> D - D --> A[Node agent: local loopback або SSH tunnel, gRPC] - A --> S[Strata worker] - A --> G[Загальний worker: llama.cpp] - A --> N[Платформні workers: Core ML / Windows ML / OpenVINO] - S --> H[CPU / GPU / NPU відповідно до можливостей worker] - G --> H - N --> H -``` - -| Платформа | Пропонований UI | Інтеграція | -| --- | --- | --- | -| macOS | Avalonia, C#/.NET | системні меню й діалоги, shortcuts, Keychain, accessibility, power/sleep | -| Windows | Avalonia, C#/.NET | системні діалоги, credentials, notifications, signed installer | -| Linux | Avalonia, C#/.NET | portals, desktop integration, Secret Service; CLI/headless незалежний від desktop | - -**Рішення реалізації 2026-10-04:** спільний Avalonia UI замінює початкову -пропозицію трьох окремих SwiftUI/WinUI/GTK оболонок. Rust містить portable -контракти й планувальник; UI містить представлення та платформні інтеграції. -Контроли Avalonia не означають автоматичної нативної інтеграції кожної ОС: -меню, accessibility, сховища секретів, power/sleep перевіряються окремо. -Поточний desktop використовує дочірній Rust node і спільний gRPC/HTTP2 контракт; -JSON schema v1 для inventory/planner передається всередині protobuf envelopes. Див. [desktop README](../desktop/README.md). - -**Уточнення користувача 2026-10-04:** management та application-to-worker -transport — спільний версійований protobuf/gRPC контракт для локальних і -віддалених вузлів. Це замінює попередню пропозицію окремого локального JSON-RPC. -Локальний agent є звичайним вузлом пулу: authenticated loopback без SSH; -віддалений — той самий API через SSH tunnel. C# UI та Rust CLI/service -використовують клієнти, згенеровані зі спільної схеми. Desktop уже використовує цей контракт для inventory/planner. Самостійні CLI -команди з JSON збережені для користувачів консолі. -Job events мають sequence number; після reconnect клієнт отримує snapshot і -подальші події. Ваги, tensors і виклики окремих шарів не проходять через gRPC -під час inference: обчислення залишаються всередині worker. - -Inference HTTP/SSE — окремий стабільний контракт: tool calls, reasoning, -cancellation, terminal events та usage. Backend adapter повинен реально -підтримати кожну заявлену capability. Простий chat endpoint не є доказом повної -сумісності Responses або harness. - -## 3. Автовибір прискорення, включно з офісним ноутбуком - -**NPU — повноцінна ціль планувальника.** Для ноутбука без дискретної GPU -порівнюємо сумісні NPU-only, iGPU, CPU SIMD та hybrid plans. Мета — найкращий -виміряний результат для вибраної моделі за заданих обмежень, включно з батареєю -й температурою. Не вимагаємо одночасно завантажити всі пристрої до 100%. - -Визначаємо фактичне обладнання та доступність runtime: - -- CPU ISA, OS-enabled registers, ядра, RAM, bandwidth, NUMA; AVX2/AVX-512/VNNI - або ARM SIMD лише за наявності відповідних можливостей. Portable binary - вибирає спеціалізовані kernels під час запуску. -- GPU, backend, driver, device features, доступна пам'ять, unified/discrete - memory, підтримувані quant formats і kernels. -- NPU, runtime/provider, підтримувані operators, shapes, precision, context, - compilation/cache constraints; фактичний розподіл graph між пристроями. -- Живлення, memory pressure, температурний режим і резерв для ОС та інших програм. - -AVX не закінчується з появою NPU: Core Ultra також має AVX2. -Перевіряємо capabilities конкретного SKU, а не правило «покоління 14/15». -[Intel AVX2](https://edc.intel.com/content/www/us/en/design/products/platforms/details/meteor-lake-u-p/core-ultra-processor-datasheet-volume-1-of-2/002/intel-advanced-vector-extensions-2-intel-avx2/). - -| Обладнання | Початковий шлях | Наступні кандидати | -| --- | --- | --- | -| Apple Silicon | Metal GPU + ARM CPU через загальний engine | Core ML/ANE для сумісного graph та precision | -| Windows/Linux + NVIDIA | CUDA | CPU/GPU offload за memory plan | -| Windows офісний ноутбук з NPU | доступні CPU/iGPU та NPU providers | NPU-only і hybrid prefill/decode, за підтримки моделі | -| AMD/Intel GPU | кваліфікований backend загального engine | HIP/SYCL/Vulkan за відповідною support matrix | -| CPU-only | спеціалізований SIMD backend | threads/batch/cache tuning під RAM bandwidth | - -Windows сам по собі не обмежує модель CPU: CUDA доступна й на Windows. -Metal, CUDA та CPU шляхи вже існують у -[llama.cpp](https://github.com/ggml-org/llama.cpp), але їхня інтеграція й перевірка -в нашому застосунку — окрема робота. -[Core ML](https://developer.apple.com/documentation/coreml/mlcomputeunits) -дозволяє системі використовувати CPU/GPU/Neural Engine. Це не означає, що -довільний graph повністю виконається на ANE. -[Windows ML](https://learn.microsoft.com/en-us/windows/ai/new-windows-ml/overview) -надає execution providers для CPU/GPU/NPU; вимоги ОС/драйверів і підтримка -моделі перевіряються для конкретного provider. - -Hybrid execution практично існує: AMD описує LLM режими з NPU prefill і GPU -decode. Однак список моделей, quantization і допустимий контекст обмежені -конкретним пакетом; їх не переносимо на наш 256K Qwen автоматично. -[Ryzen AI model list](https://ryzenai.docs.amd.com/en/main/llm_list.html). - -### Рекомендації за обсягом пам'яті та конкретним обладнанням - -Каталог пропонує кілька придатних конфігурацій для фактичного комп'ютера, -включно з GPU класів 8, 12, 16, 24, 32 GiB та іншими значеннями. Ці класи — -групування для UI, не жорстка таблиця «стільки VRAM = така модель». -Окремо враховуємо total/free VRAM, доступну RAM, unified memory, GPU architecture, -bandwidth, CPU, driver/backend і вартість передач/offload. В unified memory -не додаємо один і той самий фізичний pool двічі як RAM плюс VRAM. - -Memory plan включає resident weights/experts, KV за заданим контекстом і -паралельністю, activations, scratch/decoder workspace, runtime overhead, -пік завантаження та резерв для desktop/ОС/інших процесів. Невеликий архів -сам по собі не означає, що модель поміститься під час виконання. - -Картки рекомендованих варіантів показують: - -- модель і quant, точний device/backend, контекст і кількість запитів; -- повне розміщення на GPU або частковий offload у RAM/CPU; -- оцінку steady/peak RAM і VRAM та запас, статус якості; -- швидкість лише з релевантних вимірів або явну позначку «ще не виміряно»; -- дії «Запустити» та «Перевірити бенчмарком на моєму комп'ютері». - -Приклад вибору для 8/16 GiB: перевірити компактну модель повністю на GPU та -більшу з частковим offload, якщо вистачає RAM і backend це підтримує. Це -кандидати для порівняння, а не гарантія конкретного розміру моделі/контексту. -Коротший контекст, інша модель або агресивніша quantization пропонуються як -окрема альтернатива зі зміненими умовами, без прихованої заміни вибору. -Якщо придатного плану немає, пояснити дефіцит ресурсу й запропонувати меншу -модель або явно налаштований remote endpoint. - -Результати RTX 5090 не переносяться як виміряна швидкість на інші карти. -Обмеження allocation до 8/16 GiB на 5090 перевіряє лише частину memory planner; -воно не імітує bandwidth/compute/driver поведінку реальної карти цього класу. -Qualification matrix має включати справжні 8 і 16 GiB конфігурації, а також -shared-memory notebook; до перевірки рекомендації мають статус estimated. -Безпосередньо перед load повторно перевірити доступний memory budget. - -**Уточнення користувача:** 8 GiB laptop GPU — пріоритетний масовий сценарій. -Користувач має для майбутніх тестів ноутбук з RTX 3080 16 ГБ; це доступний -кандидат qualification hardware, ще не перевірений нами. Перед запуском -зафіксувати ОС, driver, GPU identity/фактичну VRAM, RAM, TGP/power mode й thermal -state. Порівняти cold/warm та sustained runs від мережі з однаковими задачами. -Кваліфікація 3080 16 ГБ не замінює реального 8 ГБ ноутбука. Адреса/доступ та -вільний час пристрою мають бути визначені до експериментів; надання цієї -інформації про обладнання саме по собі не запускає тест. - -### Алгоритм вибору - -1. Відсіяти несумісні model/backend/device combinations. -2. Побудувати плани розміщення ваг, activation buffers і KV з резервом пам'яті. -3. Відсіяти варіанти, що порушують політику якості або потрібні tool surfaces. -4. На вільному пристрої виміряти cold/warm TTFT, prefill, decode, task throughput, - peak memory та, якщо є достовірні counters, energy. Врахувати copies/sync і - тривалу роботу після прогрівання, а не лише короткий burst. -5. Обрати профіль: «Швидкість», «Тихо/батарея», «Мінімум пам'яті» або Auto. - Політика якості задається окремо; економія батареї не дозволяє приховані втрати. -6. Зберегти recipe за model/engine/driver/hardware/quality/power identities. - Зміна значущих компонентів робить попередню кваліфікацію неактуальною. - -Ділити graph довільно між NPU/GPU не плануємо: використовуємо підтримані -provider-ом розбиття або окремо кваліфіковані межі. KV має залишатися сумісним -між prefill і decode. Надлишкові передачі можуть перекрити виграш прискорювача. -Непідтриманий NPU план пояснюється в UI; fallback не змінює модель чи precision -без згоди. Автокалібрування не запускається під час активної роботи користувача. - -### Автоматичні бенчмарки за вибором користувача - -На картці моделі є дія **«Підібрати найкращі налаштування для мого комп'ютера»**. -Це окремий відновлюваний job. Перед запуском користувач бачить кількість -кандидатів, оцінку часу/тимчасового диска та вибирає сценарій: діалог, довгий -контекст, coding agent або паралельні запити. Контекст і кількість одночасних -запитів є умовами задачі: менше вікно не може непомітно виграти порівняння. - -Два режими пошуку: - -- **Швидкий:** обмежений бюджет часу, попередній відбір і детальна перевірка - найкращих кандидатів. Звіт явно показує неперевірені комбінації. -- **Повний:** усі сумісні комбінації в оголошеній скінченній матриці параметрів, - із pause/resume. Перебір може тривати довго; до запуску показуємо оцінку. - Досягнення ліміту часу залишає результат частковим, а не «все перевірено». - -Матриця включає backend/device, CPU threads, offload, розміщення й місткість -кешів, compression recipe/block size, device decode, batch/microbatch та -speculation там, де їх підтримують модель і engine. KV quantization, V-only та -інші lossy варіанти потрапляють в окремий явно дозволений експериментальний -набір. Вхідна модель, tokenizer, задача й політика якості зафіксовані; -порівняння іншої квантизації моделі показується окремо. - -Порядок виконання: - -1. Зафіксувати модель/digest, software/hardware identities, живлення, параметри - сценарію та визначений baseline. Відсіяти несумісні або небезпечні для - memory budget кандидати із поясненням. -2. Перевірити output/tensor parity для non-lossy змін; для lossy — окремі - quality gates charter. Невдалий або незавершений прогін не може перемогти - завдяки меншій кількості токенів. -3. Виконати парні повтори baseline/candidate з однаковим workload, sampling - policy та cold/warm cache умовами; чергувати порядок для зменшення thermal - drift. За шумного стороннього навантаження позначити результат забрудненим. -4. Для фіналістів повторити незалежні перевірочні задачі, які не використовувалися - для підбору; не перетворювати tuning score на доказ збереження якості. -5. Надати таблицю: quality status, TTFT, prefill/decode, input/output/reused - tokens, час завершеної задачі, RAM/VRAM, доступні energy дані, кількість - повторів і діапазон невизначеності. Для agent workload окремо рахувати - model requests, tool calls та очікування інструментів/компіляції. -6. Рекомендувати найкращий перевірений профіль для вибраного сценарію. Якщо - різниця в межах шуму, не оголошувати прискорення; залишити baseline або - запропонувати еквівалентний дешевший за пам'яттю/енергією варіант. Для заяв - про малі прирости дотримуватися повторів і статистики charter. - -Глобального «найшвидшого для всіх задач» профілю не обіцяємо. Зберігаємо recipe -разом із workload fingerprint, покриттям пошуку, quality evidence та версіями. -Користувач може застосувати переможця, залишити попередній профіль або окремо -вибрати «застосувати найкращий після завершення» перед запуском job. -Автоматичне застосування проходить звичайну switch transaction із rollback. - -Benchmark job отримує exclusive lease на керований worker: активна користувацька -сесія не переривається. Скасування/помилка/OOM завершують лише власний candidate, -зберігають уже отримані результати й відновлюють попередній профіль за можливості; -помилка відновлення показується явно. Нові engine/driver/model versions позначають -результат як застарілий і пропонують повторити перевірку. Приватні задачі -користувача використовуються лише за його вибором; стандартний набір — локальний, -версійований і без передачі prompts назовні. Поточне випробування користувача -не є дозволом запускати цей підбір зараз. - -## 4. Що переноситься на інші моделі - -Наявний engine спеціалізований під `qwen4exp`; це видно в -`engine/strata/src/program/generate.cpp`, model geometry та CUDA kernels. -Загальний формат tensors не робить execution graph універсальним. -Підтримка нової моделі має три окремі рівні: **прочитати → коректно виконати → -виконати з конкретною оптимізацією**. - -| Підхід | Залежність від моделі | Необхідна адаптація | -| --- | --- | --- | -| Download, manifests, resume, lifecycle, telemetry | низька | формат, metadata, ліцензія | -| Блокове lossless-стиснення ваг | принцип загальний | codec, tensor layout, entropy; виграш не гарантований | -| Стиснені ваги на GPU, decode потрібного блока | загальна ідея | decoder для пристрою, integration із matmul, memory scheduling | -| KAR progressive/lossy представлення | tensor codec можна адаптувати | діапазони/геометрія tensors, allocation точності, quality gate кожної моделі | -| Поточний KAR PLE row cache | висока | потрібна відповідна PLE lookup table; у моделі без PLE ця оптимізація відсутня | -| Кеш активних експертів | MoE | router, expert layout, activation distribution; dense-модель не має такого router | -| KV paging/reuse/quantization | середня/висока | attention layout, позиції, state identity; квантований KV має окрему перевірку якості | -| V-only | дуже висока | attention math, norms, RoPE, indexer; можливе навчання/адаптація моделі | -| Speculative decoding | метод загальний | сумісний draft/tokenizer, точний verifier; MTP потребує відповідного шляху моделі | - -Отже, **продукт не прив'язуємо до одного Qwen, але не обіцяємо всі трюки кожній -моделі**. Model adapter описує graph, tokenizer, chat template, tool/reasoning -serialization і capabilities. Optimization recipe окремо задає сумісність -із model architecture, quant, backend та hardware і посилається на validation. - -Поточний користувацький профіль — KAR для PLE з додатковою втратою точності; -це не доказ повного KAR-resident engine для довільної моделі. -[Реальний GPU PLE експеримент](experiments/2026-10-03-agent-gpu-kar-threejs.md). -V-only retrofit нашої Qwen не пройшов агентну перевірку якості, хоча kernel -тести пройшли. Це не заборона методу для інших моделей і не підстава вмикати -його для них автоматично. -[Звіт V-only](experiments/2026-10-04-keyless-runtime.md). - -Перенесення decoder на Metal є окремою kernel-роботою. Для NPU довільний CUDA -decoder непридатний: потрібний підтриманий graph/operator або інше представлення. -Розпакування на CPU перед NPU може економити диск, але не дає автоматично -compressed residency чи меншого device traffic. Розрізняємо ці можливості в UI. - -## 5. Модель, стиснення та збереження якості - -Durable pipeline: - -```text -resolve pinned source → download/resume → verify → inspect -→ estimate temporary disk/RAM → prepare candidate → validate -→ measure eligible plan → atomically publish artifact → load -``` - -SQLite WAL зберігає registry, jobs, checkpoints і recipes; service — один writer. -Ваги зберігаються immutable файлами поза DB. Manifest містить source revision, -digests, tokenizer/template, tensor representation, encoder/engine versions, -точність, dependencies (включно з correction layer), результати перевірок. -Після аварії продовжуємо з перевіреного checkpoint; незавершений artifact не -стає доступним для serving. Cancel прибирає лише job-owned temporary files. - -Типова політика — **без додаткових втрат відносно вибраної вхідної моделі**. -IQ3/IQ4 уже квантовані: точне відновлення їхніх bytes не повертає FP16 оригінал. -Lossless recipe визначає, що саме відновлюється точно: bytes quantized blocks -або canonical tensor values. Correction layer мусить забезпечити цей контракт; -його розмір може прибрати всю користь стискання. Інші kernels можуть мати -відмінне FP округлення навіть із точними вагами: числові tolerances та greedy -output порівнюємо з визначеним baseline. - -Lossy recipes позначаються явно й мають незалежні perplexity, retrieval, -tool-call та task-completion gates за charter. Вдалий короткий діалог не є -quality gate. Наявний свідомо вибраний користувачем experimental profile не -переписує цю політику типових налаштувань. - -Окремі capability flags: - -- `compressed_storage`: економія диска; -- `compressed_transfer`: передавання стиснених blocks; -- `compressed_residency`: blocks залишаються стисненими на device; -- `decode_on_device`: decoder виконується на device; -- `fused_decode_compute`: computation споживає blocks без повної materialization. - -Жоден flag не випливає автоматично з попереднього. Якщо стискання не допомогло, -зберігаємо придатний вихідний варіант і показуємо результат. Після верифікації -повного runnable bundle можна прибрати відтворювані source/intermediate copies -відповідно до політики користувача; не видаляємо потрібні correction dependencies. - -## 6. Lifecycle, ізоляція й безпека - -Workers — окремі процеси з versioned handshake і контрактом -`probe/prepare/load/generate/cancel/drain/unload/stats`. Capability negotiation -включає model architectures, quant, context/slots, tools/reasoning/structured -output, compressed flags, ОС і driver constraints. Failure одного worker -не повинен втратити durable registry або лишити незавершений API stream. - -Switch transaction: підготувати target → перевірити ресурси й dependencies → -дочекатись завершення активних запитів за вибраною користувачем політикою → -вивантажити керований worker → завантажити target → readiness → опублікувати endpoint. -При невдачі спробувати відновити попередній recipe й явно показати результат. -Сторонні GPU процеси не зупиняти. За невідомої або неповної власності ресурсів -перемикання відмовляє з діагностикою. Наявний switch controller — відправна точка: -[STRA-35](experiments/2026-10-04-model-switch.md). - -Model code з репозиторіїв не виконуємо автоматично. Download/extraction обмежують -розмір і paths; engine packages мають pinned versions і перевірені підписи. -API типово loopback з authentication; management доступний власнику через IPC. -Remote — явно налаштований SSH/TLS endpoint. Credentials: Keychain, Windows -credential storage, Linux Secret Service; для headless — захищений локальний -secret file як явна альтернатива. Логи й telemetry без prompts/secrets за замовчуванням. - -## 7. Доставка та CI/CD - -Один встановлений продукт із CLI; пакети окремі для ОС/architecture. -Немає одного executable, спільного для Windows/macOS/Linux. Rust control plane -залишається без Python у production serving. Native preparation — ціль продукту; -offline Python experiments не стають прихованою runtime dependency. -Engine packs завантажуються за потреби; драйвери ОС/GPU не вшиваємо. - -macOS: signed/notarized app і CLI; Windows: signed installer/пакет та CLI; -Linux: CLI archive спочатку, desktop package далі. Background service per-user: -launch agent, Windows user process або systemd user; foreground mode не -потребує системного service manager. Updates завантажуються окремо, перевіряються -і застосовуються між сесіями з rollback, без зупинки активної генерації. - -CI матриця першого розширення: Linux x86_64, Windows x86_64, macOS arm64. -Інші CPU architectures і мінімальні версії ОС — після кваліфікації dependencies. -На всіх ОС: Rust checks, IPC/API contract fixtures, fake-worker crash/reconnect, -job recovery, installer/CLI smokes, path/permission checks. На реальному залізі: -NVIDIA Linux, Metal Mac, Windows CPU/GPU і окремі Intel/AMD NPU SKU. Для NPU -перевіряємо фактичний execution placement, не лише успішне відкриття provider. -Приватні weights і captures не потрапляють у Git або публічні CI artifacts. - -Linux workflow уже є в репозиторії; hosted GitHub Actions run та видачу signed -desktop packages цей документ не підтверджує. Сертифікати, signing і release -infrastructure — окремі delivery dependencies. - -## 8. Послідовність реалізації - -1. **Спільний контракт і CLI:** винести registry/jobs/capabilities/lifecycle із - поточної Linux реалізації. Gate: existing Responses/harness поведінка збережена, - recovery та explicit unsupported responses перевірені. -2. **Mac UI + remote/local:** native shell керує перевіреним Linux endpoint; - додати local Metal worker і одну реально перевірену невелику модель іншої - архітектури. Gate: самостійна агентна задача, tools, cancellation, memory bounds. -3. **Офісний NPU ноутбук:** один конкретний AMD або Intel SKU, одна підтримана - модель; CPU/iGPU/NPU/hybrid порівняння якості, швидкості й енергії. Gate: - відомий execution placement і збереження якості; потім розширення matrix. -4. **Windows UI та Linux UI:** підключити до того самого контракту, package/update - recovery й OS integration. Linux CLI залишається повноцінним server продуктом. -5. **Автоматичні compression recipes:** спочатку точне відновлення + чесні - memory/speed результати; потім Metal/device decoders, інші tensors/архітектури - та явно експериментальні lossy recipes з окремими gates. - -UI, engine portability і нові model optimizations мають окремі implementation -задачі. Цей етап завершується дизайном; він не запускає нові експерименти й не -змінює активну сесію користувача. - -## Remote inference через SSH — STRA-50 - -Ціль виконання є явною: `Local` або `Remote`. Вибір remote зберігає той самий -сценарій «модель → підготовка → запуск», але ресурси, модельні файли та jobs -належать серверу. Ноутбук зберігає налаштування підключення, UI й локальний endpoint. -Параметри SSH: host/alias, port, user, посилання на ключ або системний SSH agent. -Приватні ключі й паролі не зберігаються у профілі/логах/репозиторії. - -Послідовність майстра: - -1. Перевірка SSH і host identity. Невідомий ключ показується користувачу для - довіри; змінений ключ зупиняє підключення. Перевірка host key не вимикається. -2. Read-only preflight сервера: ОС, архітектура, CPU ISA, RAM/VRAM, драйвер, - прискорювачі, доступне місце. План використовує серверні ресурси. -3. Підбір сумісного перевіреного runtime-артефакта. Встановлення у власну - користувацьку теку через staging і атомарну активацію, без автоматичного sudo - або заміни драйвера. Manifest фіксує версію, digest, capabilities та ownership. -4. Завантаження моделі прямо на сервер; підготовка/стискання та quality gate - згідно політики. Можна імпортувати вже наявний файл без повторної передачі. -5. Запуск керованого worker на серверному loopback. Заміна активної моделі - відбувається лише через явну дію перемикання, з перевіркою запитів і rollback. -6. Власний SSH-тунель до `127.0.0.1:`. Перевірка зайнятого порту; - endpoint для harness показується лише після готовності моделі й тунелю. - -Стани `disconnected → verifying → inspecting → preparing → starting → ready` -доповнюються `reconnecting`, `failed`, `stopping`. UI окремо показує SSH, -підготовку моделі та inference readiness. Зникнення тунелю не означає аварії -worker. Після sleep/network interruption відновлюємо transport і читаємо стан; -частково виданий inference-запит автоматично не повторюємо. Закриття UI, -зупинка тунелю та зупинка remote runtime — різні дії. Зупиняємо лише власний -процес з перевіреним instance id/PID/start time, не стороннє GPU навантаження. - -Перший remote worker target — Linux. Mac/Windows/Linux є клієнтами; підтримка -remote worker на інших ОС додається за фактичною підтримкою engine, не лише UI. -Автопідбір зберігає серверний hardware/driver fingerprint, конфігурацію моделі, -cache state й network latency окремо від decode/prefill. - -Реалізація декомпозована в MCP: STRA-51 (профіль/preflight), STRA-52 -(provisioning), STRA-53 (tunnel/UI). На цьому етапі це специфікація; готового -SSH deployment у новому desktop ще немає. Інтеграційний gate — окремий чистий -Linux host: install/resume/rollback, Responses tool calls через тунель, -перепідключення й cancellation. Поточний користувацький сервер не є стендом -для руйнівних перевірок. - -## Пул локальних і SSH-вузлів — STRA-54 - -Користувач може додати **кілька** цілей виконання одночасно. Local/Remote — -властивість вузла, а не глобальний перемикач застосунку. Один Rust gateway на -ноутбуці представляє їх harness як каталог моделей і явно налаштовані пули. -Це desktop-сценарій горизонтального масштабування з G9/M6 charter. - -```mermaid -flowchart LR - H[Harness: паралельні запити] --> G[Локальний Responses gateway] - G --> Q[Планувальник: модель, capabilities, вільні слоти] - Q --> L[Mac: локальна модель] - Q --> T1[SSH tunnel A] - Q --> T2[SSH tunnel B] - T1 --> A[Сервер A: модель і власний KV state] - T2 --> B[Сервер B: модель і власний KV state] -``` - -### Контракт і вибір моделі - -- `Node`: стабільний id, local/SSH transport, hardware fingerprint, ownership, - trust scope, окремі connection/readiness стани й доступні ресурси. -- `Deployment`: node id, модель/digest, quantization/recipe, quality status, - engine version, capabilities, max context, слоти й resource group. -- `Pool`: явний список deployments і правила маршрутизації. Точний model id - направляється тільки до відповідного deployment або еквівалентних replicas. - Пул різних моделей вмикається явно, з дозволеними задачами, capabilities, - quality/privacy constraints; вибір конкретної моделі не підміняється мовчки. -- Gateway надає `/v1/models` з доступними model/deployment IDs та pool aliases, - `/v1/responses` для виконання і окремий management API для стану пулу. - Відповідь/метрики зберігають фактично вибрану модель, вузол та recipe. - Віддалений вузол отримує дані лише для призначеного йому запиту; telemetry - за замовчуванням не містить prompts, коду або секретів. - -### Паралельність і стан - -Один вільний сумісний слот на кожному з трьох незалежних вузлів дозволяє -виконати три незалежні запити одночасно. Harness має сам надсилати їх -паралельно; gateway не розбиває послідовну агентну задачу автоматично. -Наявність трьох моделей у каталозі не означає три вільні слоти: перевіряємо -фактичну готовність, RAM/VRAM і спільні GPU resource groups. Два SSH aliases -до одного worker не подвоюють його місткість. - -Admission атомарно резервує слот і memory budget. Далі кожен запит має власні -stream, cancellation, usage і terminal state; загального inference lock немає. -Усі terminal/error/cancel шляхи звільняють reservation. Черга обмежена й -справедлива, з timeout/backpressure. Метрики розділяють queue, network, prefill, -decode та end-to-end час; додавання вузлів не є гарантією трикратного прискорення. - -Conversation/`previous_response_id` прив'язується до власника стану, моделі та -версії. Окремі незалежні сесії можна розподіляти; продовження сесії не мігрує -мовчки. За втрати її вузла gateway повертає визначену помилку або пропонує явне -відновлення з повної історії, коли воно підтримане. Перерваний SSE і неоднозначну -відправку автоматично не повторюємо без worker-side deduplication. Втрата одного -вузла не скасовує запити на інших. SSH reconnect і retries не можуть повторити -tool calls або створити другий terminal event. - -### UI та gate - -Розділ «Комп'ютери» містить кілька локальних/remote вузлів. Картки показують -модель, слоти, запити, чергу, ресурси, tunnel/readiness та помилки. Редактор пулу -дозволяє включити вузли, вибрати дозволені моделі й routing policy; endpoint -для harness залишається один. GUI і gateway мають незалежний lifecycle. - -MCP: STRA-55 — registry/deployments/pools; STRA-56 — scheduler/admission/stream -isolation; STRA-57 — UI і інтеграційний gate. Автотести з fake workers доводять -маршрутизацію, races, overload, cancellation і failure isolation. Приймання на -реальному local + 2 SSH стенді вимагає трьох перекритих у часі harness-запитів, -коректних незалежних tool calls/terminal events, фактичного model attribution -та виміряної concurrency. Цей розділ фіксує дизайн; pool gateway ще не реалізований. - -**Оновлення реалізації:** експериментальний Rust gateway і bounded queue вже є -у `desktop-core` (STRA-56); три паралельні fake workers та черга перевірені через -реальний loopback HTTP. Це ще не інтеграція з GUI/керованими SSH agents і не -real-model gate. Контракт і поточні обмеження: [POOL.md](../desktop-core/POOL.md). - -## Постійний node agent і gRPC — STRA-58/59 - -Рішення користувача: невеликий Rust agent працює на локальному комп'ютері та -кожному віддаленому сервері й керує власними workers/jobs через однаковий API. -SSH потрібний для першого віддаленого встановлення, перевірки -ідентичності й тунелю. Після bootstrap основний management transport — -версійований gRPC канал між локальним Rust service та node agent. Harness -продовжує використовувати локальний Responses HTTP/SSE endpoint. - -Один логічний канал на вузол містить окремі RPC-потоки: - -- handshake/version/capabilities та snapshot; -- типізовані команди lifecycle/job/admission/cancel і acknowledgement; -- підписку на state/job events і числові метрики; -- окремий потік inference для кожного запиту, з власним backpressure. - -Повідомлення різних запитів не складаються в одну необмежену чергу. Окремі -HTTP/2 streams і bounded application queues запобігають блокуванню control -великим потоком метрик; низькопріоритетні метрики можна об'єднувати до останнього -значення. Загальні transport limits і bandwidth залишаються спільними. -gRPC має transport flow control, але політику черг визначає застосунок. -[gRPC flow control](https://grpc.io/docs/guides/flow-control/). - -Відновлення після обриву: - -1. Клієнт позначає вузол disconnected і тимчасово припиняє новий admission. - Сам disconnect спостерігача не звільняє зайняті слоти на сервері. -2. Відновлює tunnel/channel з exponential backoff, jitter та узгодженим - keepalive; reconnect до інших вузлів незалежний. Auth/schema mismatch - має окремий стан, не нескінченний швидкий retry. -3. Передає `agent_epoch` і останній застосований `event_seq`. Сервер віддає - збережені події; за gap/нового epoch клієнт отримує узгоджений snapshot - із cursor, потім нові події. UI дедуплікує вже застосовані sequence numbers. -4. Команди мають `operation_id`, digest параметрів і збережений стан виконання. - Повтор тієї самої команди повертає її результат, інші параметри з тим самим - id відхиляються. Після втрати ack спочатку звіряється статус операції. - Для рестарту агента потрібний стійкий журнал/reconciliation процесів; - один gRPC retry не гарантує exactly-once execution. -5. Inference із неоднозначним прийманням або вже виданими токенами автоматично - не запускається заново. Resume потоку дозволяється лише за окремого - bounded replay-контракту; інакше повертається явний interrupted стан. - -Автоматичні gRPC retries не замінюють application-level reconciliation, -а keepalive лише виявляє transport failure, не доводить готовність моделі. -[gRPC retry](https://grpc.io/docs/guides/retry/), -[gRPC keepalive](https://grpc.io/docs/guides/keepalive/). - -Локальний transport — gRPC на loopback; віддалений — такий самий gRPC через SSH. -Обидва потребують per-install автентифікації та захищеного зберігання/отримання -credential; localhost не є винятком для auth. Прямий network gRPC потребує mTLS -і явного enrollment. Local та remote проходять однаковий contract suite: -capabilities, lifecycle/jobs, inference/tool calls/terminal events, cancel ack, -bounded queues, reconnect та reconciliation. Закриття локального UI саме по -собі не зупиняє worker чи запит; явна зупинка — окрема команда lifecycle. -Agent має перелік дозволених команд; RPC «виконай довільний shell» відсутній. -Ваги завантажуються сервером або окремим bounded transfer, не event bus. -UI можна закрити, не зупиняючи remote agent чи inference за замовчуванням. - -MCP: STRA-58 — agent/protobuf/control/event service; STRA-59 — reconnect, -resume і reconciliation клієнта. STRA-52/53 використовують цей контракт для -provisioning/tunnel. Початковий gRPC node реалізований локально: handshake/auth, -inventory/planner, snapshot subscription та Responses adapter; див. -[GRPC.md](../desktop-core/GRPC.md). Durable lifecycle/jobs та автоматичне -відновлення ще не завершені. На користувацькому сервері node не встановлено. diff --git a/docs/cuda-driver-bootstrap.md b/docs/cuda-driver-bootstrap.md deleted file mode 100644 index 75a9e0f1..00000000 --- a/docs/cuda-driver-bootstrap.md +++ /dev/null @@ -1,168 +0,0 @@ -# Independent CUDA driver bootstrap contract - -Requirements of record for bounded STRA-102 plan -`d20f1568-5b7b-477d-8eab-a32219af7fd7`, before implementation. -This foundation does not implement inference, model loading or GPU kernels and -must not change production serving or advertise any supported model. - -## Platform and ABI - -- Explicit `cuda-driver` Cargo feature, disabled by default, plus an explicit - `Driver::load()` call; Linux with 64-bit pointers. Unsupported platforms or - disabled capability must return a clear error without touching a CUDA driver. -- Load only the installed NVIDIA Driver ABI soname `libcuda.so.1` at runtime. - No CUDA Toolkit, Strata, Python, C compiler or native build script is a - production build/runtime dependency of this Rust crate. -- Resolve the fixed documented legacy ABI symbols, with `_v2` context, device - allocation/free and synchronous copy symbols where required. Missing symbols - fail before CUDA initialization or resource mutation. No symbol-version - fallback or API reinterpretation. -- Isolate all unsafe FFI and dynamic loader code in the driver crate. Public - callers get owned typed resources and errors, never raw host/device pointers - or mutable CUDA context handles. - -## Fixed ABI and source evidence - -The exact symbol set is `cuInit`, `cuDriverGetVersion`, `cuDeviceGet`, -`cuCtxCreate_v2`, `cuCtxDestroy_v2`, `cuCtxPushCurrent_v2`, -`cuCtxPopCurrent_v2`, `cuCtxSynchronize`, `cuMemAlloc_v2`, `cuMemFree_v2`, -`cuMemcpyHtoD_v2`, `cuMemcpyDtoH_v2`. The legacy create binding has three -arguments: `CUcontext*`, `unsigned int`, `CUdevice`; the current unversioned -CUDA 13 header macro points to the four-argument v4 entry instead and must -not be rebound to this function type. Device pointers are 64-bit for this -64-bit-only surface; byte counts use `size_t`. - -Independent TL verification read the official -[NVIDIA cudart 13.0.88 archive](https://developer.download.nvidia.com/compute/cuda/redist/cuda_cudart/linux-x86_64/cuda_cudart-linux-x86_64-13.0.88-archive.tar.xz) -in memory, without installing headers or a toolkit. Archive size 1,491,604 bytes, -SHA256 `bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`; -`cuda.h` SHA256 `64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`. -Header lines 25633/90 prove the legacy declaration/current alias respectively; -line 274 defines the 64-bit device pointer. Runtime behavior still requires -separate installed-driver qualification. See NVIDIA's -[synchronization behavior](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/api-sync-behavior.html) -for why calling a synchronous-named copy alone does not prove completion of -all host memory references. - -## Ownership and context discipline - -- Driver, context and device-buffer lifetimes keep the dynamic library alive - until every dependent operation and cleanup finishes. Resources cannot be - sent or shared between threads (`!Send`, `!Sync`). -- Create a private context and pop it immediately, restoring the caller's - previous context. Do not use or mutate an external primary context. -- Push the owned context for every operation that needs it, and restore the - previous context on both success and failure. Pop failures must surface as - errors; never claim restoration after the driver rejects restoration. -- Buffers cannot outlive their owner context; allocation/copy operations are - bounded, checked before driver mutation and reject empty/oversized shapes. -- Copies use exact-sized byte slices with bounded owned staging memory and the - synchronous Driver API. DtoH publishes staging only after completion; ambiguous - completion errors retain staging and poison the context to prevent dangling - host DMA pointers. Synchronize - before returning host borrows. Failed copy/synchronization paths must preserve - context cleanup, while reporting the original driver failure accurately. -- Cleanup is best-effort on drop, does not panic and must not free resources in - an unrelated context. Explicit fallible cleanup should expose failure when - the API supports it; permanently failed driver cleanup cannot be guaranteed. - -## Independent CPU qualification - -Only synthetic owned fixtures may be used. The test library is compiled to an -ELF named `libcuda.so.1`, injected through a private subprocess loader environment -inside a disposable Linux CPU Docker container. No installed driver is called, -no NVIDIA device is exposed, and no GPU/model/request probe is performed. -The fake library records synthetic ABI operations, context stack, allocated bytes, -copy/sync actions and cleanup. Independent assertions cover missing symbols, -init/device/create/push/pop/alloc/copy/sync/free/destroy errors, bounds before -mutation, byte-copy round trips and prior-context restoration. Lifetime and -thread-safety compile-fail gates are required as well as runtime tests. - -All existing local gates remain; focused checks add crate format/Clippy/unit and -the Linux ELF mock gate. Results below must report the actual environment, -counts and cleanup, never infer GPU success from a mock or compile pass. - -## Qualification state - -Actual local CPU result on 2026-10-07: - -- Linux **aarch64**, native CPU Docker Desktop execution; Rust 1.99.0 - (`b940084d7 2026-09-28`), GNU C compiler Debian 12.2.0-14+deb12u1. -- Pinned Rust base OCI index: - `sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6`. - Independently inspected index contains Linux amd64 manifest - `sha256:b36c246742b4d323472588f789601be34eb4af053255e2af53969078ee8dcec7` - and arm64 manifest - `sha256:e393e07b3c3c39f238de676b0eb60c03dc7aefe5d6e37be6d29c686bf4d7e256`. - The final owned fixture image after installing matching rustfmt/Clippy was - `sha256:a7fd4951f84b368826117e60c93f1e067ade2e39b2b69329108e70b052dd136d`. -- Actual test container: nonroot UID/GID 65532, default runc, network `none`, - all effective/permitted/bounding capabilities zero, no privileges, no host - binds or device requests/devices; raw NVIDIA/DRI device guard passed. - Build tools were provisioned in an earlier disposable setup container; - all tests and compilation then ran offline with network disabled. -- Minimal synthetic workspace contained only exact driver crate source/tests, - matching workspace package/lint declarations, and approved pinned libc - 0.2.190. Engine, control-plane, CUDA Toolkit/headers/nvcc and installed - `libcuda` were physically absent. The existing registry archive SHA256 - `ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78` - was checked before extraction, then Cargo verified every vendored source - checksum. Normal dependency tree was driver crate → libc only. -- Default denial/unit tests: **2 passed**. Actual enabled-FFI all-target, - all-feature Clippy with warnings denied and formatting passed. -- **33 isolated subprocess scenarios passed**: round trip, pre-mutation - shape/budget refusal, each of the twelve missing symbols, init/version/device, - create/pop cleanup, push/pop errors, mismatched popped context and poisoned - future work, allocation, both copy directions, explicit synchronization, - copy-plus-sync dual errors in original/cleanup order, free and destroy faults. - The fixture matrix is explicitly ignored by ordinary `cargo test`; the harness - selects it with `--ignored` and requires its marker, so an absent harness - cannot appear as a vacuous integration pass. -- Delayed synthetic HtoD at destruction read the exact original eight owned - staging bytes after the caller source was changed to zeros. Delayed DtoH at - destruction wrote retained staging while the still-live caller destination - remained unchanged after failed synchronization. These independently - witness the declared staging/completion behavior, alongside source review; - they are not a proof of all possible memory safety or vendor behavior. -- **10 independent compile refusals passed**: Send and Sync for Driver, Device, - Context and DeviceBuffer; context outliving Driver; buffer outliving Context. - Assertions checked the expected auto-trait/borrow compiler diagnostics. -- Final fake full/missing-DtoH ELF SHA256 values: - `551878f9b518b200f8ac3dbf3570ec7494f1a2226917530c84ea30b418c1d41f` / - `a95af6e51e678a5e3fc5f937b4232393493497161195391e256138a5d2009991`. - Source hashes inside the container matched the working-tree bytes. -- All owned setup/test containers, derived fixture images, private source - staging, synthetic libraries, trace files and target directories were - removed. The shared pinned base image and existing registry cache were retained. - Cleanup attempts each resource independently, preserves test failure, and - fails a successful test run if any cleanup fails. - -Two initial fixture provisioning failures occurred before Rust integration: -missing optional rustfmt/Clippy, then Docker tmpfs execution denial for libc's -Rust build script. The final fixture installs verified toolchain components and -uses an explicitly executable owned `/tmp`; product behavior and assertions -were not weakened. - -Production source receipts: `src/lib.rs` -`7ce58fcf033b5e9704b2d134fc4c16cd2d5c57c5c45a867d2399c310dec3c4d4`; -`src/ffi.rs` `5f00400fab73d98578ca53bfedcb86b4163133d2956a88ac3d2cd156455800c8`. - -## Remaining integration limits - -These outcomes qualify a GNU/Linux CPU mock contract. They do not execute an -installed NVIDIA driver, GPU allocation/copy or a kernel, and they do not prove -vendor cleanup succeeds after a driver failure. A sync fault deliberately -retains bounded staging and poisons that context; failed destruction can retain -the library/context instead of pretending release occurred. Repeated poisoned -contexts can accumulate retained resources; there is no process-wide recovery -or memory-bounded serving guarantee in this bootstrap. - -The existing statically linked musl executable is also **unqualified** for this -loader. [musl's static dlopen stub](https://git.musl-libc.org/cgit/musl/plain/src/ldso/dlopen.c) -refuses dynamic loading; the GNU/Linux ELF mock pass does not make static musl -capable of loading `libcuda.so.1`. A separate executable/loader integration gate -is required. The OCI index admits amd64 builds, but this actual local mock run -was arm64; hosted amd64/compiler qualification is separately pending. - -Installed-driver GPU allocation/copy, kernel execution, model inference, -model quality and paired performance remain separate unqualified gates. diff --git a/docs/cuda-fixed-matvec.md b/docs/cuda-fixed-matvec.md deleted file mode 100644 index eef9e027..00000000 --- a/docs/cuda-fixed-matvec.md +++ /dev/null @@ -1,501 +0,0 @@ -# Fixed CUDA f32 matrix-vector requirements - -Bounded requirements delta for served item **STRA-140**, parent **STRA-102**, -read fresh on 2026-10-08. Written against source revision -`b9519f967af43514331e29e778bd2605d8e4b98b` before implementation. The active MCP -item and [project charter](../PROJECT_CHARTER.md) are the business/specification -authority; this file is the task's reviewable requirements artifact, not a second -project backlog or an assertion that implementation has passed qualification. - -The [bootstrap contract](cuda-driver-bootstrap.md) owns driver loading, platform, -copy staging and resource ownership. The [vector-add contract](cuda-fixed-vector-add.md) -owns the existing fixed operation. STRA-140 adds one bounded fixed matvec action -without changing either historical qualification receipt. Production remains -independent of Python, Strata and a CUDA Toolkit runtime dependency. - -## Scope, actor and outcome - -An internal engine developer explicitly enables `cuda-driver`, loads the driver, -creates a private context and supplies three owned device buffers and dimensions -to `Context::matvec_f32`. The matrix is contiguous row-major f32, the vector has -one value per column, and the output has one value per row. Success means the -attempted kernel completed and the caller's previous context was restored. - -Using `Context::matvec_f32`, the developer can compute the recurrence below over -valid owned buffers, yielding a completed output or structured failure. Invalid -inputs must yield failure before any CUDA mutation. After uncertain completion -or restoration, future work on the context must yield refusal without native work. - -This unit is an application/library deliverable with executable automated -verification. It introduces no serving endpoint, deployment integration, model -loader, inference, tensor view/stride, transposition, batching, quantization, -arbitrary executable, caller stream or caller launch geometry. Default feature -admission stays off. It establishes neither model compatibility nor a speed/SLO -claim; the serial column recurrence is a correctness baseline. - -## FR-MATVEC-1 — exact shapes, bounds and ownership - -The public interface takes an immutable matrix buffer, immutable vector buffer, -exclusive mutable output buffer, and host `usize` row/column dimensions. Dimensions -are checked before conversion to the private ABI; no truncating cast is allowed. - -| Quantity | Required admission bound / meaning | -| --- | --- | -| Rows `M` | `1 <= M <= u32::MAX` (4,294,967,295) | -| Columns `N` | `1 <= N <= u32::MAX` (4,294,967,295) | -| Matrix elements | Checked `M * N`; product need not fit u32 | -| Matrix bytes | Checked `4 * M * N`, exactly the matrix buffer length | -| Vector bytes | Checked `4 * N`, exactly the vector buffer length | -| Output bytes | Checked `4 * M`, exactly the output buffer length | -| Every byte length | Nonzero, fits host `usize`, and `<= isize::MAX` | -| Allocation capacity | Existing context byte budget bounds actual live allocations; matvec allocates no device buffer implicitly | -| Launch | Fixed block `(128, 1, 1)`; checked `grid.x = ceil(M / 128)`, `1 <= grid.x <= i32::MAX`; grid y/z one | -| Addressing | 64-bit row/index/byte offsets; checked allocation address ranges cannot wrap | - -These are representation and ownership limits, not a promise that the GPU has -enough memory or will admit the fixed launch. On Linux64 the matrix constraint -is `M * N <= floor(isize::MAX / 4) = 2,305,843,009,213,693,951` elements, -further restricted by actual owned allocation sizes and the caller's context -budget. The three buffers normally require `4 * (M*N + N + M)` live bytes, -alongside other context allocations. When the two inputs share one allocation, -charge that allocation once, as the existing allocation accounting does. - -The safe API currently exposes only whole owned allocations: `DeviceBuffer::len` -is an exact byte length, with no distinct logical length, spare capacity, -subslice, offset view, cloned handle or raw/imported pointer API. Consequently an -oversized buffer is invalid even if it could contain the requested tensor. -Check each expected byte length for exact equality; do not accept a prefix. -Also reject odd/nonmultiple-four lengths. Shape and overflow refusal must be -possible without allocating a giant test buffer or executing CUDA. - -Both inputs and output must belong to this exact `Context` instance. Equal device -ordinals or separate contexts on the same device do not suffice. Reject poisoned -contexts and absent/released resource handles before push/load/lookup/launch. -No validation refusal changes output bytes, allocation accounting or cache state. - -### Output alias contract - -Inputs may share the same immutable allocation when exact shape checks permit -it; for whole buffers that means `M = 1`. A caller may reuse an output allocation -between completed calls, but output must be a distinct allocation from both -inputs during each call. Rust's immutable input and exclusive mutable output -borrows prevent a safe caller from passing the same buffer as input and output. -Defensively reject equality of output/input device allocation identities before -native mutation, matching the existing vector-add check. Do not create a public -unsafe bypass to test that defense. - -Distinct valid live whole allocations from the same CUDA allocator do not -overlap. The present API therefore needs no tensor-view overlap semantics. A -future imported pointer or view API would require a separately specified range -overlap contract before it could consume this operation. Validate non-wrapping -address extents in the private boundary so arithmetic does not rely on silent -u64 wrapping; invalid synthetic address extents must never be launched. Private -alias tests exercise allocation-identity refusal; they do not invent a public -view/import facility. - -## FR-MATVEC-2 — deterministic arithmetic and access - -For every row `r = 0 .. M-1`, define binary32 recurrence: - -```text -s = +0.0_f32 -for c = 0 .. N-1 in ascending order: - p = round_nearest_even_f32(matrix[r*N + c] * vector[c]) - s = round_nearest_even_f32(s + p) -output[r] = s -``` - -Use a separate `mul.rn.f32` followed by `add.rn.f32` for every column. No FMA, -floating-point MAD, reassociation, parallel/warp/tree reduction, approximate -operation, saturation, `.ftz`, or f64 accumulator may replace this recurrence. -The accumulator starts at positive zero, including for `N = 1`; it does not -initialize from the first product. All f32 bit patterns are valid inputs. -Signed zeros, subnormals, overflow and infinities follow these operations. NaN -results are compared by classification; NaN payload and sign are not guaranteed. - -The arithmetic follows NVIDIA's archived PTX definitions for -[multiply](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-mul) -and [add](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-add). -Explicit rounding modifiers preserve the required separate operation semantics; -assembler acceptance alone does not demonstrate installed-driver execution. - -One thread owns one row, checks `r < M` before any memory access, loops columns -in order and stores output once after the last addition. Other threads may -process other rows independently. Compute `r`, `r*N+c` and scaled offsets with -64-bit arithmetic, including threads in the last partial block. The loop must -terminate correctly at `N = u32::MAX`; increments and comparisons may not wrap -into another iteration. Matrix/vector are never written. Threads beyond `M` -perform no read or write. No atomics, shared-memory reductions, external symbols -or indirect calls participate. - -## FR-MATVEC-3 — trusted executable and fixed launch ABI - -Embed one bounded NUL-terminated matvec PTX image containing exactly the fixed -matvec entry `leleka_matvec_f32`. Preserve the existing image's PTX 7.0, -`sm_75`, and `.address_size 64` baseline; incompatible driver/target combinations -return explicit failures. No fallback or external PTX lookup is allowed. - -The private `kernelParams` table has five entries, in this order: - -| Position | Value stored in owned host argument storage | ABI width | -| --- | --- | --- | -| 0 | Matrix device allocation address | u64 | -| 1 | Vector device allocation address | u64 | -| 2 | Output device allocation address | u64 | -| 3 | Rows `M` | u32 | -| 4 | Columns `N` | u32 | - -Each table entry points to its typed host scalar, not directly to a device -address interpreted as a host pointer. Shared bytes are zero; stream and -`extra` are null. Geometry comes only from FR-MATVEC-1. The existing fixed -16-symbol loader suffices; no new driver symbol, caller executable/name, -function/module handle, callback or launch option enters the public API. - -Cache only a fully loaded/validated matvec module and non-null function under -its owner context. Repeated successful calls reuse that cache; separate contexts -never share it. The matvec cache adds at most one usable module/function per -context. It must coexist with the existing vector-add cache without replacing, -misidentifying or invalidating vector-add's function. Cache topology and shared -cleanup integration require the ARCH decision below before implementation. - -## FR-MATVEC-4 — completion, argument lifetime and faults - -Create and stabilize all scalar storage and its five-entry pointer table before -CUDA mutation. Maintain the existing raw-owned stable allocation discipline: -moving the argument owner must not move or retag referenced storage. No caller -host pointer is retained. Scalars/table stay live through mandatory completion. - -Push the owned context, check load/lookup and non-null success handles, attempt -the launch once, then synchronize after **every attempted launch**, even a -launch returning failure. Preserve primary and subsequent sync/pop errors in -operation order. Load/lookup failure does not count as an attempted launch. -After every successful push, attempt pop and verify it popped the owned handle. - -Return success only when launch, synchronization and restoration all succeed. -After native execution failure, output is unspecified and cannot be presented -as a successfully computed result. A launch failure followed by successful sync -and restoration follows existing policy; it does not by itself imply poisoning. -Never retry a failed launch automatically. - -Failed sync makes completion uncertain: poison the context, permanently retain -all potentially referenced host argument storage, keep buffers/module contained -by the context, and refuse future allocate/copy/sync/kernel work without native -calls. Do not reclaim retained argument storage merely because a later destroy -succeeds. A failed or mismatched pop likewise poisons the context; successful -sync alone cannot justify a success result after restoration failure. Existing -copy staging and thread/borrow safety remain part of the contract. - -## FR-MATVEC-5 — cache cleanup and teardown - -On lookup failure after load, consume the local usable module handle before its -single unload attempt in the owned current context. Preserve lookup, unload and -pop failures in order. Failed unload poisons the context; no retry, cache -publication, handle reuse or healthy cache reinitialization is allowed. - -Healthy teardown unloads each usable owned fixed module at most once after work -completed, before context destruction. Pending/uncertain work or a poisoned -context must never be followed by explicit module unload or buffer free. -Any unload/restoration failure must suppress further unsafe cleanup mutations; -context destruction remains the final containment attempt. Explicit fallible -close reports errors; drop stays best effort and nonpanicking. Failed destroy -retains the loaded library. Permanently failed driver cleanup is not a cleanup -success; repeated poisoned contexts may accumulate resources, so this unit -cannot claim process-wide recovery or bounded serving memory. - -## Security and non-functional acceptance - -| Dimension | Metric / threshold | Verification | -| --- | --- | --- | -| Critical usability | One typed synchronous operation, structured failure, no public raw launch surface | API/source review and synthetic caller | -| Reliability / performance | Success requires launch+sync+restoration; zero automatic retries; one mandatory completion sync per attempted launch; no latency/throughput assertion | ABI and fault traces | -| Capacity / concurrency | Checked bounds above; whole allocations within context budget; creating thread only; at most one additional usable matvec cache/context | Boundary, accounting, cache and compile gates | -| Security / tenancy | In-process context isolation; no network/tenant admission is introduced; zero foreign-context/aliased-output launches; only private fixed executable | Ownership, adversarial alias and ABI review | -| Audit / retention | Only synthetic fixtures; generated traces/artifacts outside Git; record exact source/tool identities and cleanup | Artifact and tracked-file inspection | -| Observability | Fixed operation names and driver codes; preserve primary/cleanup order; errors disclose no pointer/PTX dumps | Error assertions/review | -| Accessibility / i18n | No UI surface or new locale; structured errors remain available to the existing caller | Public-surface review | -| Rate / admission | Synchronous operation on one owning thread with the existing byte budget; no process recovery/rate SLA | API, budget and poison checks | -| Deploy / rollback | Existing opt-in default off; no production consumer or new runtime dependency; caller can omit the new operation | Feature/dependency/consumer inspection | -| Support | Load/lookup/launch/sync/cleanup failures diagnosable; no new production SLA | Fault matrix and documented residuals | -| AI dependence | Zero model/LLM calls in this operation | Consumer/source inspection | -| Integrity / consistency | Inputs unchanged; exact recurrence; no success for partial/uncertain output; only bounded fixed cache persists | Oracle, canary and trace checks | -| Backup / recovery | No durable data created; uncertain teardown retained/reported, never claimed recovered | Fault/source review | -| Privacy | No PII/model/request data in committed fixtures or gate evidence | Fixture/artifact review | -| Maintainability | Existing 16-symbol ABI; bounded fixed matvec module; no new normal dependency | Source/ABI/dependency review | -| Compatibility | Linux64 explicit opt-in; preserve bootstrap/vector-add and ownership behavior; static-musl loader stays unqualified | Existing regression and platform gates | -| Cost / efficiency | CPU-only fixture and offline assembly for this unit; no GPU/device/driver/model access | Recorded container guards and commands | - -## Acceptance mapping and planned verification - -Expected values come from this recurrence, independently recorded fixtures and -the official ABI, not from wrapper code or PTX parsing. The fake driver witnesses -host argument/dataflow and cleanup; it does not execute PTX. The mock's arithmetic -and oracle must have contraction/reassociation disabled and establish binary32 -rounding at each multiply and add; a tolerant f64 dot product is not the oracle. -Declare **zero finite-bit tolerance** against this reference before verification; -compare signed zero bits and non-finite classifications, excluding NaN payloads. - -| Served acceptance criterion | Requirement(s) | Required positive and adversarial evidence | -| --- | --- | --- | -| AC-1: checked typed operation | FR-MATVEC-1 | Exact shapes, rectangular matrix and whole-allocation ownership; zero M/N; each dimension u32 max/max+1; checked product/scaling/isize/address/grid bounds; one-byte short/long and nonmultiple4 lengths for each buffer; foreign context on same device; output aliases each input; accepted immutable same-input case M=1; poisoned/refused handles. Refusals produce zero new CUDA trace entries and unchanged accounting/output/cache. Giant limits use pure/private admission instruments, not giant allocations. | -| AC-2: trusted executable | FR-MATVEC-3, FR-MATVEC-5 | Exact PTX bytes/hash and entry; five argument widths/order/values; fixed grid/block/shared/stream/extra; cache reuse and separate contexts; interleave matvec/vector-add; missing fixed symbols fail pre-init; no public arbitrary PTX/name/geometry API. | -| AC-3: column order and separate rounding | FR-MATVEC-2 | Distinct rows/columns detect transpose/stride errors; M=1 and N=1; M=127/128/129 and larger partial block; varying N; input/canary preservation; independent order/FMA-sensitive fixtures; PTX instruction/control-flow inspection plus pinned offline assembly and inspectable emitted instruction evidence. | -| AC-4: lifetime and poison/cleanup | FR-MATVEC-4, FR-MATVEC-5 | Delayed mock reads retained five-argument table/scalars at sync and containment after failed sync, with allocator churn; push/load/lookup/null-success/launch/sync/pop/wrong-pop/unload/destroy faults; launch+sync+pop and lookup+unload combinations; no unload/free while pending; no retry/reuse; preserved error order; healthy unload before destroy and one unload attempt per module. | -| AC-5: CPU and GPU-hidden gates | All | Preserve existing bootstrap/vector-add mock, default/platform, thread/lifetime compile, format and enabled-FFI lint gates; run new ABI/oracle/boundary/fault checks in disposable Linux CPU fixture; pinned offline PTX assembly with no installed driver calls or exposed GPU/device. Report actual counts and receipts; no GPU/model/quality/speed inference. | - -Arithmetic adversaries must include the row `[2^24, 1, -2^24]` with all-one -vector (ascending recurrence yields positive zero; a reordered sum can yield -one), and row `[-1, 1+2^-23]` with vector `[1, 1-2^-23]` (separate rounding yields -positive zero; fusing the second multiply/add yields `-2^-46`). Add signed-zero, -subnormal, ties, overflow, infinity and NaN-classification fixtures. These are -fixture expectations, not measured GPU results. - -The offline gate must record exact PTX (including its embedded NUL) and assembler -output hashes, pinned image/tool version, target/flags, full argv, source/commit, -host/container architecture, environment/device guards, test counts, exit codes, -and cleanup. Inspect executable instructions/control flow, not comments or the -mere presence of opcode substrings. Establish the ascending loop and separate -multiply/add/no FMA in the recorded offline artifact; its claim is limited to -that tool/target. Installed-driver JIT/numerical execution remains separate. -Keep generated artifacts out of Git and remove only owned disposable resources. - -```mermaid -sequenceDiagram - participant Caller as Internal caller - participant Context as Owned Rust context - participant Driver as Fixed Driver ABI - Caller->>Context: matvec_f32(matrix, vector, output, M, N) - Context->>Context: Validate shape, ownership, alias, poison and bounds - alt Validation refusal - Context-->>Caller: Structured error, no CUDA mutation - else Valid - Context->>Context: Own stable five-argument storage - Context->>Driver: Push owned context - Driver-->>Context: Push result - alt Push failure - Context-->>Caller: Structured push error, no launch - else Owned context entered - opt Cache absent - Context->>Driver: Load trusted matvec, look up fixed entry - Driver-->>Context: Handles or load/lookup failure - end - alt Kernel available - Context->>Driver: Attempt fixed launch once - Driver-->>Context: Launch result - Context->>Driver: Mandatory synchronize, including launch error - Driver-->>Context: Completion result - opt Completion uncertain - Context->>Context: Poison and retain referenced storage/resources - end - else No kernel - Context->>Driver: Single safe partial-module cleanup if needed - end - Context->>Driver: Pop, verify owned handle - Driver-->>Context: Restoration result - Context-->>Caller: Success only if launch, sync and restoration succeeded - end - end -``` - -## Lifecycle and architecture inputs - -**Design need: architectural.** The new public buffer operation crosses the safe -Rust ownership/validation boundary into private FFI and fixed executable code, -and adds a second fixed-kernel lifetime under the existing context poison and -teardown state. This classification comes from served AC-2/AC-4 and the existing -`Context::kernel`, `fixed_kernel`, `unload_kernel`, `LaunchArguments` and -`DeviceBuffer` source at the pinned revision. It requires an ARCH pass before DEV. -This BA artifact does not select cache topology or author an architecture option -matrix. - -ARCH must confirm the single-thread-per-row, ascending-column mapping and checked -u64 addresses meet the caps; five stable host arguments preserve raw ownership; -matvec and vector-add retain distinct function identities; the additional cache -stays bounded; and an unload/pop fault while tearing down either operation -prevents unsafe subsequent unload/free while preserving final destruction/error -reporting. Return any incompatible requirement for refinement before code changes. - -BA has resolved the served row/column and output-alias questions from the fixed -u32 launch convention and exact whole-buffer ownership surface, with overflow -checks above. No user clarification remains for those routine constraints. -Architecture confirmation remains outstanding. No new business-rule conflict was -found with the referenced bootstrap/vector-add/charter invariants. - -Lifecycle inputs for root coordination: clarification deliverable is this -contract; design needs the ARCH decision; backend deliverable is the bounded -typed operation and private PTX/FFI integration; testing deliverable is executable -automated CPU and offline assembly evidence. No frontend, visual-composition, -marketing or deployment/runtime-operation artifact is requested. Those scope -observations are not lifecycle waivers or stage closures; root records applicable -stages and gate evidence through the active served process. Existing task -estimates are not re-estimated by this BA unit. - -No active host-local `.leasevibe.yaml` pointer was supplied and none is present in -this worktree; host settings are unavailable, never inferred or copied. Root -owns coordination records. This BA unit writes only this file, performs no build, -test suite, assembly, GPU, inference, server, commit or publication operation, -and reports no implementation gate as passed. Static-musl loading, installed -driver/JIT execution, whole-model quality/protocol and paired performance remain -the separate qualification boundaries named in the foundation contracts. - -Standing Defaults (§0.10): report honestly, do not cut corners, follow applicable -rules, continue the authorized backlog through root coordination, and be concise. - -## Architecture decision - -**Status: selected for implementation.** This decision is bounded to STRA-140 at -`b9519f967af43514331e29e778bd2605d8e4b98b`. The user authorized completion and -autonomous routine implementation choices; root confirmed that authorization for -these reversible local seams. It selects no new technology, serving topology or -model scope. FR-MATVEC-1 through FR-MATVEC-5 remain the governing contract. - -### Drivers and alternatives - -Workload archetype: synchronous, explicitly enabled, single-thread-owned numerical -library operation. RPS, latency SLO and production recovery are unspecified because -this unit has no serving consumer or throughput claim. - -| Driver | Evidence / constraint | Design consequence | -| --- | --- | --- | -| Correctness and completion | Charter priorities; FR-MATVEC-2/-4 | Serial ascending recurrence and mandatory completion before success | -| Capacity / concurrency | FR-MATVEC-1/-3; existing `Context` and `Rc` ownership | Two bounded fixed caches per context, creating thread only | -| Isolation and operability | Existing `enter`, `CurrentGuard`, `combine`, `destroy` | One context poison state; ordered fallible cleanup and final containment | -| Cost / deployment | Existing `cuda-driver` opt-in, fixed16 ABI and libc dependency | No new runtime dependency or installed Toolkit requirement | -| Data / organization | Three transient owned buffers; existing Rust/FFI boundary | Data Model: N/A for this operation; no durable state, UI or new team/process boundary | - -| Option | Workload / scale | Latency / cold load | Operations / cost | Debugging / readiness | Isolation | Portability / lock-in | -| --- | --- | --- | --- | --- | --- | --- | -| **A: two named cache slots, closed private operation selector** | Exact two-operation bound | Each image loads once on first valid use | Two modules maximum; existing cleanup machinery | Distinct identities, localized source changes | Context owns both; shared poison | Existing Driver/PTX limits only | -| B: one combined image and two functions | Bounded, but couples existing operation to new image | One module load; matvec bytes load for vector-add callers | One unload, broader regression surface | Changes historical vector-add image identity | Same owner and poison | Same Driver/PTX limits | -| C: replaceable single cache or generic kernel registry | Replacement causes reload; registry adds unnecessary growth policy | Reloads or generalized lookup | More invalidation/ownership policy | More state and generic dispatch to audit | Requires extra eviction/lifetime rules | Encourages a future arbitrary executable surface | - -- A pros: preserves vector-add executable identity, isolates lazy initialization, - and makes the two-module bound explicit. Cons: cleanup must sequence two slots. -- B pros: one module lifecycle. Cons: changes the already qualified image and - couples vector-add admission to matvec loading; rejected for this bounded delta. -- C pros: replacement can cap one module, and a registry can accommodate future - operations. Cons: adds reloads or speculative generality; rejected because the - requirements need coexistence of exactly two trusted operations. - -**Architecture Decision: A.** **Architecture Alternatives Considered: B and C** -with the rejection reasons above. The architecture-strategy user-decision step -is satisfied by the existing implementation authorization confirmed by root; -there is no new unresolved external architecture choice to request. - -### Selected source seams and invariants - -In `crates/cuda-driver/src/lib.rs`, retain `FixedKernel` and introduce two named -`Cell>` slots for vector-add and matvec. A private closed -`FixedOperation` enum selects only those slots and their trusted FFI bindings. -It carries no caller bytes, names, handles or launch options. Publish a slot only -after module load and non-null function lookup both succeed. Cache reuse is -per-operation and per-context; no process/global map or eviction is introduced. - -Keep safe validation and orchestration in `lib.rs`; all raw pointer handling -stays in `ffi.rs`. Add a pure checked matvec shape helper producing three expected -byte lengths, ABI rows/columns and row grid. Require exact buffer lengths and -exact context identity, live context/buffer handles, and output allocation -inequality before native calls. Use checked dimensions/product/scaling and -`valid_size`; compute ceil(M/128) in u64 before bounded conversion. Add a private -FFI extent check using checked u64 base-plus-byte-length for each live buffer; -synthetic wraparound refuses before `enter`. Inputs sharing the same whole -allocation remain valid when M=1. A structured matvec shape/range error may be -added; ownership, alias and poison errors retain their existing meanings and -driver errors retain operation/code and `combine` ordering. - -In `ffi.rs`, embed `matvec.ptx` with a final NUL alongside the unchanged vector-add -image. The closed selector matches each image and fixed C entry name explicitly. -Extend both enabled and unsupported API implementations consistently; keep the -existing sixteen symbol resolutions and their pre-init missing-symbol behavior. -Keep vector-add's four-argument launch unchanged; add a private matvec launch -with the same fixed geometry/shared/stream/extra policy and five-argument owner. -Do not introduce a public or crate-generic raw parameter launch interface. - -Matvec argument storage contains three u64 addresses, two separate u32 scalars -(rows, columns), and five host parameter pointers. Convert its allocation with -`Box::into_raw` before forming field pointers using raw projections; its moving -owner contains only `NonNull` and never recreates a reference to the whole -allocation while the pointers are live. Populate every scalar/table entry before -`enter`. Reconstruct the Box exactly once before any launch or after successful -sync; on failed sync permanently forget the owner, including its pointer table. -Moving the owner or borrowing the owner for launch must not move/retag the -storage. A later successful destroy never reclaims forgotten arguments. - -`matvec.ptx` uses the fixed five-entry ABI and PTX7.0/sm_75/address64 baseline. -Compute row as wide block-index times 128 plus widened thread-index, guard row -against widened M before memory access, and use u64 for N, column counter, -row*N+column and byte offsets. A u64 counter allows N=u32::MAX to terminate -without wrap. Begin with positive-zero bits, issue separate `mul.rn.f32` then -`add.rn.f32` for each ascending column, and store once. This is a correctness -baseline; neither source shape nor offline assembler acceptance proves installed -driver execution or performance. - -Both operations use the same `poisoned` cell and `CurrentGuard`. After an attempted -launch, synchronize exactly once even on launch error, then attempt and verify -pop after every successful push. Compose launch, sync and pop errors in that -order. Lookup failure consumes its local module before one unload attempt; -unload failure poisons the shared context, and no partial cache is published. -Load/lookup failure has no launch sync. No automatic launch or unload retry occurs. - -Refactor `unload_kernel` into a bounded slot-cleanup helper and sequential -`unload_kernels`: vector-add slot first, then matvec slot. Each helper consumes -its usable slot before an unload attempt, checks shared poison before push, -unloads only with the owned context current, then finishes the guard. A push, -unload, failed pop or wrong-pop failure poisons the context before another slot -can mutate CUDA. Thus failure in the first cleanup suppresses second unload; -failure in the second still suppresses later explicit frees. A poisoned slot is -only discarded as a usable Rust handle; its native resource remains contained -by the context. `destroy` always performs the final owned non-current context -destruction attempt and preserves earlier cleanup errors; failed destroy retains -the library. Existing buffer free admission through `enter` supplies the shared -poison defense. Drop stays nonpanicking. This is containment, not recovery. - -The level above this change comprises typed owned resources in `lib.rs`, private -Driver bindings and argument ownership in `ffi.rs`, and trusted executable bytes -in PTX; `Context` orchestrates those boundaries. This change belongs inside those -existing units because they own shape admission, module lifetime and completion. -A serving/model layer or public general kernel executor would be appropriate -only if separately authorized consumer/launch contracts existed; neither does. -No durable-state capability or persistence-layer change is introduced. - -### Handoff and revisit conditions - -Required DEV paths are `crates/cuda-driver/src/lib.rs` (API, checked admission, -cache and teardown, inline pure boundary tests), `crates/cuda-driver/src/ffi.rs` -(closed fixed bindings, extent validation and argument ownership, inline private -tests), new `crates/cuda-driver/src/matvec.ptx`, and -`scripts/test-cuda-fixed-ptx.sh` (extend existing pinned offline gate, including -inspectable instruction/control-flow evidence). Automated fixture integration -belongs to the separately routed test owner in existing -`crates/cuda-driver/tests/mock_cuda.c`, -`crates/cuda-driver/tests/mock_driver.rs` and -`scripts/test-cuda-driver-bootstrap.sh`; this decision does not transfer its claim. -No DevOps/IaC work, dependency, CI topology or new child task is implied. - -FR-MATVEC acceptance cases remain mandatory. In addition to shape/rounding cases, -the cross-operation witnesses must interleave add/matvec/add and matvec/add/matvec, -prove distinct function/module identity and one lazy load per slot, and inject -each slot's unload/pop failure with both caches populated. After any poison, -attempt the other operation, allocation, copy, sync and releases: none may call -CUDA. Delayed mock reads must dereference all five arguments at sync and pending -containment after owner movement/allocator churn; no unload/free may precede -uncertain completion. Pure boundary tests cover address wrap and giant geometry -without allocating giant buffers. The independent oracle retains zero finite-bit -tolerance, signed-zero bits and non-finite classification limits declared above. - -The safe Rust to private native execution crossing merits §809 review; root -records the canonical served threat-model artifact before DESIGN closes, using -the trust-boundary input returned with this decision. No committed threat-model -copy substitutes for that served carrier. LIGHT/FULL, implementation and GPU -gates remain root-coordinated; this section reports no such gate as passed. - -Revisit only when a separately specified third fixed operation needs generalized -reuse, asynchronous completion is introduced, or views/imported pointers create -range overlap. First specify its admission/ownership/cleanup contract, then -extend or replace these seams under a new decision and qualification gates. -Rollback for this unit is omission of the new API/image changes and restoration -of the existing vector-add cache path; no stored data migration is needed. -Screened companion decisions (argument layout, u64 counter, fixed teardown order) -are reversible local choices or directly required by FR-MATVEC, so none satisfies -all three grounds for an additional durable ADR. No BA correction is required; -installed-driver/JIT, static-musl loading, model quality and paired performance -remain separately qualified boundaries. No implementation ambiguity remains. diff --git a/docs/cuda-fixed-vector-add.md b/docs/cuda-fixed-vector-add.md deleted file mode 100644 index a3982ed2..00000000 --- a/docs/cuda-fixed-vector-add.md +++ /dev/null @@ -1,238 +0,0 @@ -# Fixed CUDA f32 vector-add requirements - -Bounded STRA-102 requirements for plan -`05e21fde-510e-4d63-8aa1-442e67339961`, written before implementation on -base `0383253c6011ec795aa395b613405263f63378ee`. - -This unit supplies one opt-in, typed operation over owned CUDA buffers: -`out[i] = add.rn.f32(a[i], b[i])`. A successful return must mean the attempted -launch completed and the caller's previous context was restored. Validation -errs toward refusal before native mutation; uncertain completion or restoration -errs toward poisoning and retaining resources. These properties can support -bounded wrapper/ABI claims after their respective gates; they cannot establish -model support or numerical execution merely from a mock or compilation. - -The historical [bootstrap contract](cuda-driver-bootstrap.md) and its actual -12-symbol qualification receipts remain unchanged. This document owns only the -extension below. The charter remains the project goal and quality authority; -this unit advances the independent Rust NVIDIA execution foundation without -changing production serving or the imported Strata engine. - -## Scope and caller outcome - -An internal engine developer can explicitly enable the `cuda-driver` feature, -load the driver, create a private context, allocate/upload two input buffers and -an output buffer, invoke the fixed add operation and read the completed output. -The safe interface accepts owned buffer references and returns structured errors; -it accepts no PTX, module image, entry name, stream, launch geometry, raw pointer, -foreign context or callback from a caller. - -The existing default feature remains off. No new HTTP endpoint, worker switch, -backend/model admission, scheduler, tensor loader, inference implementation or -production deployment integration is included. Deployment of this foundation -must continue to require only the installed NVIDIA driver rather than Strata, -Python, a C compiler or CUDA Toolkit; offline verification tools are separate. - -## Requirements and acceptance conditions - -### FR-VADD-1 — validate owned shapes before mutation - -- Accept two immutable input buffers and one mutable output buffer belonging to - the exact same owned `Context` instance. Equal device ordinals or separate - contexts on the same GPU do not establish ownership equality. -- All three byte lengths must be equal, nonzero and divisible by four; interpret - them as f32 elements. The element count must fit `u32`, byte bounds must retain - the bootstrap's checked budget/`isize` constraints, and grid arithmetic must be - checked without truncation or overflow. -- Preserve safe aliasing: inputs may refer to the same immutable allocation; - output must not alias an input. The public borrow contract must enforce this, - with defensive identity refusal wherever implementation structure permits - otherwise. No unsafe bypass is exposed publicly. -- Reject invalid ownership, shape/count/geometry, unavailable capability and - poisoned contexts before push, module load, lookup or launch. Do not mutate - output or allocation accounting on validation refusal. Do not allocate new - device buffers implicitly for this operation. - -### FR-VADD-2 — one trusted module and function - -- Embed a bounded, NUL-terminated PTX byte sequence in the crate. It contains - exactly the fixed entry `leleka_vector_add_f32` with parameters in this order: - input A u64 device address, input B u64 device address, output u64 device - address, element count u32. Treat pointers as private ABI values, never public - Rust handles. Record the exact embedded bytes' SHA256 for verification. -- The entry checks `i < n` before any element access; address arithmetic must - not wrap. Every in-range thread reads the corresponding A/B elements and - writes exactly one output element. No input writes, external symbols, - indirect calls, atomics, shared-memory state or out-of-range writes. -- Use explicit `add.rn.f32` without `.ftz`, saturation, approximate arithmetic - or floating-point contraction. No `fma`/`mad` substitutes for the add. The - selected fixed image uses PTX 7.0, `sm_75`, and `.address_size 64`; unsupported - driver/target combinations fail explicitly, not by selecting another kernel. -- Cache at most one successfully loaded module/function per context, lazily - after validation. Repeated successful calls reuse it. Publish a cache entry - only after both load and function lookup succeeded with valid non-null - handles. Failed initialization must not create a usable partial cache. - -The arithmetic spelling is grounded in NVIDIA's archived -[PTX floating-point add specification](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-add). -This is the required arithmetic, not evidence that real hardware has executed -it. Signed zeros, subnormal handling, overflow, infinities, NaNs and NaN payload -behavior still require explicit installed-driver numerical qualification. - -### FR-VADD-3 — fixed 16-symbol loader and launch ABI - -Extend the bootstrap's fixed twelve symbols by precisely these four: - -| Symbol | Private C ABI parameters | Return | -| --- | --- | --- | -| `cuModuleLoadData` | `CUmodule*`, `const void*` | `CUresult` | -| `cuModuleGetFunction` | `CUfunction*`, `CUmodule`, `const char*` | `CUresult` | -| `cuModuleUnload` | `CUmodule` | `CUresult` | -| `cuLaunchKernel` | `CUfunction`, six `unsigned int` grid/block dimensions, `unsigned int` shared bytes, `CUstream`, `void** kernelParams`, `void** extra` | `CUresult` | - -All sixteen resolve before `cuInit`; each missing extension symbol must fail -before initialization. Keep the legacy bootstrap `_v2` signatures, soname, -library lifetime and platform guards. Opaque module/function/stream pointers -remain inside audited private FFI. The ABI references are NVIDIA's archived -[module management](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__MODULE.html) -and [execution control](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__EXEC.html) -documentation. Independent advisory verification checked the official pinned -cudart 13.0.88 archive (1,491,604 bytes, SHA256 -`bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`) -and `cuda.h` SHA256 -`64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`. -Header lines 7365/7476/7532 identify load/unload/function lookup; lines -17537–17547 identify launch with seven unsigned-int arguments including shared -bytes. This is header evidence, not an execution result. - -Launch one dimension with fixed block size 128, `grid.x = ceil(n / 128)`; -grid/block y and z are one, shared memory is zero, stream is null, `extra` is -null. `kernelParams` is a private four-entry array of pointers to the typed -argument values above. Own the scalar/device-address parameter storage and -pointer table, keeping their addresses stable through launch and synchronization. -If the table references fields of its own storage object, establish those pointers -only after stable heap placement; moving an inline self-referential object must -not invalidate them. NVIDIA's documentation describes copying parameter values -from the supplied regions, but this contract does not infer a stronger -before-return timing guarantee from that wording; -if completion is uncertain, retain any storage the driver could still reference -and poison future work. No caller host pointer or arbitrary argument escapes -into this interface. Compute the grid in a wider -integer and require `grid.x <= i32::MAX`. Kernel index/address arithmetic must -cover the final partial block without u32 overflow or reading beyond `n`. -No caller can alter this launch shape. The driver may still reject this fixed -shape on unsupported hardware; that is a reported operation failure. - -### FR-VADD-4 — completion and context restoration - -- Push the owned context for module/launch operations and pop it on all paths - after a successful push, checking that the popped handle is the owned one. - Successful operations and handled failures restore the prior caller context; - a failed or mismatched pop reports the failure and poisons this context. -- After **every attempted `cuLaunchKernel`**, synchronize even when launch - returns an error. Retain the launch error and subsequent synchronization/pop - errors in their operation order; cleanup must not replace the original error. - A lookup/load failure before launch is not a launch attempt. -- Return success only after launch, synchronization and restoration all succeed. - Inputs stay immutable; output contents after a native execution failure are - unspecified and must not be reported as a successfully computed vector. -- Synchronization failure means completion is uncertain: poison the context, - reject future allocation/copy/sync/kernel work without further native work, - and keep possibly referenced buffers/module alive until safe context teardown. - Do not free or unload them merely because a failed launch was observed. -- Continue the bootstrap's staged-copy rule, including keeping ambiguous host - DMA staging alive. A fixed kernel must not weaken existing copy/borrow safety. - -### FR-VADD-5 — module ownership and failure cleanup - -- Module/function cache lifetime is inside its owner context and dynamic-library - lifetime. No public module or function can outlive that context or cross a - thread; retain the existing `!Send`/`!Sync` resource guarantees. -- On function lookup failure after module load, attempt unload in the owned - current context. Consume the module's usable-handle slot before calling unload, - regardless of its return value; unload at most once per handle. A failed - unload poisons the context. Retain only context-owned residual/accounting for - final destruction: never retry unload, reuse the handle or reinitialize a - healthy cache after that failure. If restoration is uncertain, likewise - report all relevant errors and forbid treating the module as a valid kernel. -- Healthy teardown unloads the cached module after completed work, in the owned - context, before destroying the context. Pending/uncertain work must not be - followed by explicit module unload or buffer free. Context destruction is the - final containment attempt; permanent driver failures cannot be called cleaned. -- Explicit fallible close reports unload/restoration/destruction failures; - destruction should still be attempted when safe. Drop remains best effort - and nonpanicking. Failed destroy retains the library as required by the - bootstrap rather than permitting calls through an unloaded library. -- No automatic retries of a failed launch. Repeated poisoned contexts can - retain resources; this unit supplies no process-wide recovery or cumulative - resource bound and must not advertise a leak-free serving guarantee. - -## Security and non-functional contract - -| Dimension | Metric / threshold | Planned verification | -| --- | --- | --- | -| Critical usability | One typed add action; structured errors, no raw pointer/module interface | Public API review and synthetic caller | -| Reliability | Success requires launch + completion + restoration; zero silent launch retries | Fault matrix and trace order | -| Performance | No speed/SLO assertion; one launch and one mandatory completion sync per valid call | ABI trace, separate future paired benchmark | -| Capacity | One cached module/context; fixed block128; checked count/grid and existing byte budget | Boundary/refusal and repeated-call tests | -| Security / isolation | Exact context ownership, private fixed PTX/entry, no safe arbitrary execution surface | Cross-context/alias/ABI review and compile refusals | -| Audit / retention | Only owned synthetic traces; no model/request/credentials in Git; private evidence outside source | Harness output and cleanup review | -| Observability | Fixed operation names, driver codes, ordered primary/cleanup errors; no pointers or PTX dumps in error text | Fault assertions and error-text inspection | -| Accessibility / i18n | No UI is introduced; existing user interfaces/locales remain unchanged | Changed-surface review | -| Rate / admission | One synchronous call on the creating thread; existing per-context memory budget; no new network/tenant admission | Thread/lifetime gates and budget refusals | -| Deploy / rollback | Default feature off, no serving consumer, no deployment-tool dependency added; disable opt-in to return to existing path | Feature/default/dependency/consumer review | -| Support | Load/lookup/launch/completion/cleanup failures remain diagnosable; no production support SLA is claimed | Error matrix and documented residuals | -| AI dependence | This fixed arithmetic operation performs no model call; no AI output or quality gate substituted by it | Consumer/source review | -| Integrity | Inputs unchanged; output published as success only for completed add; no hidden persistent state except bounded cache | Synthetic data/canaries and cache traces | -| Backup / recovery | No durable data introduced; failed driver teardown is reported/retained, not treated as recovery | Fault/ownership review | -| Privacy | Only sanitized synthetic vectors permitted in this unit's verification | Fixture and artifact review | -| Maintainability | Four additional exact symbols, one embedded module/entry, no new normal dependency | Source/ABI/dependency review | -| Compatibility | Linux 64-bit opt-in only; legacy12 bindings and existing33 mock/10 compile guards preserved | Default/platform and regression gates | -| Cost / efficiency | CPU mock/tooling work only for this delivery; no GPU/probe/model access, no duplicated CI | Recorded commands and container guards | - -## Verification plan — outcomes not yet measured - -The planned instruments derive from the requirements and official ABI, rather -than obtaining expected outputs from the wrapper implementation. A synthetic -mock can witness argument/context/cleanup behavior and expected fixture data; -it does not execute or establish correctness of the embedded PTX instructions. - -| Gate | Required checks / predicted refusal | Claim licensed by a pass | -| --- | --- | --- | -| Existing regression | Retain all 33 bootstrap mock cases and 10 compile refusals, default-denial units, enabled FFI format/Clippy | Existing contract still holds against changed source | -| Missing extension symbols | Independently omit each of four new symbols; zero `cuInit` and resource mutation | Fixed16 pre-initialization admission | -| Typed validation | Different contexts on same device; unequal/nonmultiple4/empty shapes; count/grid overflow; invalid output alias; poisoned context. All refuse before push/load/launch | Bounded safe wrapper admission | -| ABI and synthetic data | Verify exact trusted PTX/entry identity, parameter order/width/value and live owned device allocations, fixed dimensions/null stream/null extra, context sentinel, input immutability/output/canaries | Mocked host ABI/dataflow only | -| Launch bounds | Counts 1,127,128,129 and a bounded larger nonmultiple128 vector; checked maximum/count-overflow tests without giant allocations | Shape/tail guard contract, not real GPU memory safety | -| Cache/lifetime | First valid call loads/looks up once; next call reuses; independent contexts own separate caches; zero unload with pending work; healthy unload before destroy | Bounded cache and resource ordering | -| Faults | Load/lookup/null-success handles/push/launch/sync/pop/wrong-pop/unload/destroy, plus launch+sync and lookup+unload errors; failed unload consumed once, no retry/reuse/cache reinitialization | Original errors retained, cleanup attempts, poison/refusal behavior | -| Delayed completion | Mock defers add completion to sync, including dereferencing retained parameter storage; failed sync leaves work pending until containment; no early argument release/buffer free/module unload; caller output never presented as successful after failure | Declared containment behavior alongside source review | -| Ownership compile gates | Existing driver/context/buffer borrow and thread refusals remain; no safe arbitrary module/function/pointer escape | Rust safe API lifetime/thread surface | -| Offline PTX assembly | GPU-hidden Linux CPU Docker with pinned `ptxas`; exact PTX SHA, tool/version/container target and flags; no devices, installed driver calls or user data | PTX assembler acceptance for the recorded target only | -| Installed-driver numerical execution | Separate authorized real-GPU gate: independent f32 reference; declare finite tolerance before execution (target exact finite bits), signed zeros/subnormal/overflow/Inf/NaN cases with NaN classification/payload limits | Only the executed hardware/driver numerical scope | -| Model / protocol / throughput | Separate Qwen and two named MoE integration, real quality/protocol gates, same-workload paired distributions/provenance | Whole-engine claims only after their own evidence | - -Record actual argv, source/commit and embedded PTX hashes, toolchain, architecture, -image/ELF identity, environment/guards, exact test counts, failures and exit codes. -Keep generated evidence private outside Git, remove owned disposable resources, -and report cleanup failures. No number in the planned matrix is a measured pass. - -## Remaining platform and qualification boundaries - -GNU/Linux 64-bit CPU mock/assembly results do not qualify the existing static -musl executable for `dlopen(libcuda.so.1)`. Its loader integration remains open, -as described in the historical bootstrap contract. PTX loading may require the -installed driver to JIT the fixed image; driver/JIT compatibility is unqualified -until a separate real-driver gate. No Toolkit becomes a deployment prerequisite -merely because offline assembly is used for validation. - -No real GPU allocation, kernel execution, model support, quality, protocol -completion, rollback or performance is established by this requirements unit. -The autonomous engine parent and its dependent intake/delivery items remain -open under root coordination. No admission/closure flags are changed here. - -No active host-local `.leasevibe.yaml` pointer was supplied; it was absent in -the worktree and canonical repository. Task-relevant host settings are therefore -unavailable, not inferred. The explicit session restrictions remain binding: -Gitea only for future publication/CI, no merge, no active Qwen/runtime changes, -no GPU/model/user-data probes. This BA unit changes only this requirements file. diff --git a/docs/cuda-seal-plan-additions-experimental.json b/docs/cuda-seal-plan-additions-experimental.json deleted file mode 100644 index 2a9107ca..00000000 --- a/docs/cuda-seal-plan-additions-experimental.json +++ /dev/null @@ -1,222 +0,0 @@ -{ - "schema": 1, - "note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.", - "assets": [ - { - "cu": "crates/cuda-driver/src/experimental_kv_q4.cu", - "cu_pin": { - "sha256": "378058e82084b697e13e8ac3cd25520372d2848ed3ebec78ac5e369ee9a91720", - "bytes": 17507 - }, - "ptx": "crates/cuda-driver/src/experimental_kv_q4.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). FWHT-256 + Q4_0 append (step/batched) + gather; Original kv_q4.cu precise (default flags, not in the fast-math list); K8V4's Q4_0 V half and rotated INT8's FWHT", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/kv_q4.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[0].source_sha256", - "PINS[0].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "74665b016fde9dc4f50a36e62cbf2e578c735e48e3be51b70734e9e53942cde7", - "seal_length": 36319 - }, - { - "cu": "crates/cuda-driver/src/experimental_kv_q8.cu", - "cu_pin": { - "sha256": "007f00692c702313a79dee0f1aa433c3412f6b4d73de620b02e136d960203c9f", - "bytes": 13448 - }, - "ptx": "crates/cuda-driver/src/experimental_kv_q8.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). INT8 append (K+V, K8V4 K half, V-only) + gather; Original kv_q8.cu precise", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/kv_q8.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[1].source_sha256", - "PINS[1].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "43c308960830833e29329907e27be5203ef3bc89cc7d0a9176270dc18732d600", - "seal_length": 32973 - }, - { - "cu": "crates/cuda-driver/src/experimental_kv_stream.cu", - "cu_pin": { - "sha256": "8c9fe1c0e4164ac2b40304a389710615829842a2ac47ab4b4ef92b3ace5d5a4f", - "bytes": 12456 - }, - "ptx": "crates/cuda-driver/src/experimental_kv_stream.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). CLOCK residency resolver, block copy, ring table, u4 copy; Original kv_stream.cu precise; integer only", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/kv_stream.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[2].source_sha256", - "PINS[2].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "4f71e720e0ca950d321ba3cbb20082ca473e9839b76d08898e95b6623bfffe50", - "seal_length": 34329 - }, - { - "cu": "crates/cuda-driver/src/experimental_keyless.cu", - "cu_pin": { - "sha256": "77c50e5baff842e31f0d71624a5706f46ed74a56cdfc5e4211086d2ef08671c5", - "bytes": 1987 - }, - "ptx": "crates/cuda-driver/src/experimental_keyless.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). per-head query routing (fmaf-ordered 256x256); Original keyless.cu precise", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/keyless.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[3].source_sha256", - "PINS[3].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "1ab8b8156e8c824131c00cecda177fe57d74b286a02b7e5afdfa39acadaa33e6", - "seal_length": 3760 - }, - { - "cu": "crates/cuda-driver/src/experimental_qsa_attn.cu", - "cu_pin": { - "sha256": "907ffc8f7504efd0655d2311ac4787fb131dfd1ef7cbf1aebfdddf1b9d31c505", - "bytes": 23119 - }, - "ptx": "crates/cuda-driver/src/experimental_qsa_attn.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). experimental attention modes 2/3/4 + merge; Original qsa_decode_attn.cu precise (expf/exp2f exact, not in the fast-math list)", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/qsa_decode_attn.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[4].source_sha256", - "PINS[4].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "5623a5ae9b2ebd2fa010c334367ffc54879ac6df76aef08381dbd32b0f7ef311", - "seal_length": 128247 - }, - { - "cu": "crates/cuda-driver/src/experimental_cvec.cu", - "cu_pin": { - "sha256": "d4fe221b11569db73247644bb79118b34d040b49c14897e0bac158dcd4ca356e", - "bytes": 4783 - }, - "ptx": "crates/cuda-driver/src/experimental_cvec.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). control-vector apply; Original cvec.cu default flags (its own __expf in sigmoidf_ is explicit in the source)", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/cvec.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[5].source_sha256", - "PINS[5].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "193add5cb448f5e193f20ff248ca4459abb962b472663c00d18941313bfa3ebc", - "seal_length": 28943 - } - ] -} diff --git a/docs/cuda-seal-plan-additions-window.json b/docs/cuda-seal-plan-additions-window.json deleted file mode 100644 index d6e1ccf8..00000000 --- a/docs/cuda-seal-plan-additions-window.json +++ /dev/null @@ -1,286 +0,0 @@ -{ - "schema": 1, - "purpose": "Assets Root must seal for the literal Verifier window recorder (OriginalVerifyWindowOps). Everything not listed under new_sources is an already sealed asset that the window producers merely bind (SHA-256 pinned in the AssetSpec constants of crates/cuda-driver/src/original_verify_window_*.rs).", - "toolkit": "deploy/cuda-toolkit.lock.json (CUDA 13.0.88), built through scripts/build-original-verify-ptx.sh", - "new_sources": [ - { - "source": "crates/cuda-driver/src/original_verify_window_moe_experts.cu", - "ptx": "crates/cuda-driver/src/original_verify_window_moe_experts.ptx", - "nvcc": [ - "--ptx", - "-std=c++17", - "-O3", - "-arch=sm_120", - "--fmad=true", - "--ftz=false", - "-Iengine/strata/include", - "-Iengine/strata/third_party/ggml", - "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda", - "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include", - "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src" - ], - "exports": [ - "window_moe_gu_16", - "window_moe_gu_17", - "window_moe_gu_18", - "window_moe_gu_21", - "window_moe_gu_22", - "window_moe_gu_23", - "window_moe_gu_29", - "window_moe_gu_42", - "window_moe_gu_12", - "window_moe_gu_13", - "window_moe_gu_8", - "window_moe_down_20", - "window_moe_down_23", - "window_moe_down_42", - "window_moe_down_7", - "window_moe_down_8" - ], - "derived_from": "engine/strata/src/kernels/cuda/iq_kernels.cu (native_gu_kernel, native_gu_multi_kernel, native_down_kernel, native_down_multi_kernel via native_expert_grouped / launch_gu / launch_down; textually includes crates/cuda-driver/src/mtp_original_full_head_iq.cu, the sealed copy of iq_kernels.cu; engine/strata/CMakeLists.txt gives iq_kernels.cu no per-source COMPILE_OPTIONS)", - "notes": "NEW source: no sealed PTX instantiates the grouped gate/up and down templates for the target's formats. The rest of native_expert_grouped (swiglu_entries_kernel, quantize_q8_1_kernel) is sealed in mtp_original_full_head_iq.ptx under mangled names. The PTX will also carry the unused head_* / dequant entries of the included file. Update EXPERTS.sha in original_verify_window_moe.rs after sealing; the build script's required-exports check should list the exports above.", - "install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL." - }, - { - "source": "crates/cuda-driver/src/original_verify_window_qsa_gate.cu", - "ptx": "crates/cuda-driver/src/original_verify_window_qsa_gate.ptx", - "nvcc": [ - "--ptx", - "-std=c++17", - "-O3", - "-arch=sm_120", - "--fmad=true", - "--use_fast_math", - "-Iengine/strata/include", - "-Iengine/strata/third_party/ggml", - "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda", - "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include", - "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src" - ], - "exports": [ - "verify_window_qsa_gate" - ], - "derived_from": "engine/strata/src/kernels/cuda/native_qsa.cu (kernel `gate`; CMakeLists.txt compiles native_qsa.cu with --use_fast_math)", - "nvcc_note": "--use_fast_math (as engine/strata/CMakeLists.txt compiles native_qsa.cu) implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true; --ftz=false is deliberately NOT passed.", - "install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL." - } - ], - "sealed_assets_bound": [ - { - "ptx": "crates/cuda-driver/src/mtp_original_full_attention.ptx", - "sha256": "3fb235ca405d24c3b8d0ec46611d9d640103b71a65859923194f02f06b482f6c" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_bf16.ptx", - "sha256": "a16dfcfc9a49ccab25d8030293d5826f8f75e2868fae1b6c4cef706b6dfc3d08" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_combine.ptx", - "sha256": "2253fe2d641350f4445a0a69c4a0fc22b85c2fffca7cbd536ffe5d2912f81fb7" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_element.ptx", - "sha256": "8fdfdf8ef616698c12301f7df4716fc022bf34b419099e4c972729920bd5f4a7" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_fused_gr.ptx", - "sha256": "ac5400a7972b3f242648c2de71ef4f178466d38b1392a83a9591b3b24e92c59b" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_gr_norm.ptx", - "sha256": "06d6177b482cb67413c6596a0291b4dab1850332164a9212aff67b9efdf21120" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_gr_post.ptx", - "sha256": "9b479c0f412ae00773815c9a6d89d7f4c3f7a9f0f691876de805eb38178d9790" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_head_iq.ptx", - "sha256": "e57452ccac772a8a8a77253bc6c964ebb7bc61fdb2e97527a9775f8ccf3c3b9f" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_head_native.ptx", - "sha256": "f8209e1c9fbf978bc57b60b0b5f6edcab1905e49a4ab3aa982604e3e680fa437" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_router.ptx", - "sha256": "be6e3c91e4f6831464f5993787f0bff969bc5d28395f24226b88676b3069a8cb" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_router_legacy.ptx", - "sha256": "a58412249757cc351eb8332e807e79f1b3da5865574d0fb7179ef558df70af24" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_s2.ptx", - "sha256": "fbb917d590ea80338a7bdf07b2ca6d458fa72763ba279e576bcc1eec8836fd55" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_full_shared.ptx", - "sha256": "b36f432692e43f7948a2538c22cab55ef67c625b8d4461c67ca2a27519b9e0f0" - }, - { - "ptx": "crates/cuda-driver/src/mtp_original_kv.ptx", - "sha256": "e0c1ff10d3d4bcf8fd3369713079b232e62cdb2c3a345faec49d1e66763f911f" - }, - { - "ptx": "crates/cuda-driver/src/ple_native_batch.ptx", - "sha256": "5fa5c930f40cb49d9e79a35e1911c68581f92c097750eff28c245e2870964a40" - }, - { - "ptx": "crates/cuda-driver/src/qsa_decode_postops.ptx", - "sha256": "fd76e6f84557d7f2a62ac56e16d5e4f78862e756ef9852b04d591999213a5119" - }, - { - "ptx": "crates/cuda-driver/src/qsa_prompt_postops.ptx", - "sha256": "486a73b06b3a34f298f57e92c20cc8394dc59d7bd84b5cccf8da53aa5081ac9f" - }, - { - "ptx": "crates/cuda-driver/src/qsa_prompt_resolver.ptx", - "sha256": "8d3ecbaecbf28445ba64485bdff3d91a21d87b85d5939a0152ef2f2414480e22" - }, - { - "ptx": "crates/cuda-driver/src/qsa_prompt_select.ptx", - "sha256": "1e35514744216229b0cffb4f45d2f13f25cb95f377a30c1c012543dbf53a1c2d" - } - ], - "numerics_risk_fast_math": { - "engine_fast_math_sources_cmake": [ - "native_mmvq", - "native_bf16", - "native_gr_norm", - "native_moe", - "native_gdn", - "native_gr_postops", - "native_router", - "native_gdn_preprocess", - "native_qsa", - "native_rope", - "native_ple_postops", - "native_flash_attn", - "native_qsa_indexer", - "native_qsa_score" - ], - "note": "engine/strata/CMakeLists.txt compiles these Original sources with --use_fast_math. The sealed Rust copies below were built with the precise flags of scripts/build-original-verify-ptx.sh (--fmad=true --ftz=false). Some copies reproduce the fast-math operations with explicit intrinsics in the .cu (e.g. mtp_original_full_shared.cu: __fdividef/__expf); the others are a numerics risk for bit-exact parity with the Original window until a per-kernel golden comparison on the GPU (or a re-seal with --use_fast_math) proves otherwise.", - "candidate_resealed_assets": [ - { - "ptx": "mtp_original_full_head_native.ptx / mtp_original_tail.ptx / mtp_original_full_checks.ptx", - "derived_from": "native_mmvq (quantize_q8_1 + MMVQ)" - }, - { - "ptx": "mtp_original_full_bf16.ptx", - "derived_from": "native_bf16" - }, - { - "ptx": "mtp_original_full_router.ptx", - "derived_from": "native_router" - }, - { - "ptx": "mtp_original_full_gr_norm.ptx / mtp_original_full_gr_post.ptx", - "derived_from": "native_gr_norm / native_gr_postops" - }, - { - "ptx": "mtp_original_full_combine.ptx", - "derived_from": "native_moe" - }, - { - "ptx": "mtp_original_full_qnorm.ptx / mtp_original_full_qsa_gate.ptx / qsa_native_gate.ptx", - "derived_from": "native_qsa" - }, - { - "ptx": "qsa_decode_postops.ptx", - "derived_from": "native_qsa norm + native_rope" - }, - { - "ptx": "original_verify_qsa.ptx / qsa_prompt_indexer.ptx", - "derived_from": "native_qsa_indexer" - }, - { - "ptx": "ple_native_batch.ptx / ple_prompt_device.ptx", - "derived_from": "native_ple_postops" - }, - { - "ptx": "mtp_original_prefill_mmq.ptx / mtp_original_prefill_fixup.ptx / mtp_original_prefill_quant.ptx", - "derived_from": "ggml mmq instances + quantize.cu, built by the Original's strata_mmq target with -use_fast_math" - } - ], - "audit": { - "method": "For each Original source in the fast-math list that the window launches, the fast-math-sensitive operations (/ , expf, sqrtf, powf, sinf, cosf, logf) were listed from engine/strata/src/kernels/cuda/*.cu and compared with the instruction mix of the sealed PTX. A precise nvcc compile emits div.rn/rcp.rn/sqrt.rn and the multi-instruction expf sequence (fma.rn + ex2.approx.ftz + mul); --use_fast_math emits div.full, rcp.approx.ftz, sqrt.approx.ftz, ex2.approx.ftz(x*log2e), sin/cos.approx.ftz and .ftz on the arithmetic. Only qsa_decode_postops.ptx carries .ftz on its arithmetic.", - "sealed_precise_but_original_fast_math": [ - { - "ptx": "mtp_original_full_head_native.ptx", - "entry": "head_quant", - "original": "native_mmvq.cu native_quantize_q8_1_kernel", - "operations": "d = amax / 127.0f and q = roundf(xi / d): two div.rn.f32 where the Original emits div.full.f32 (a 1-2 ulp quotient change can flip roundf at a half-integer, i.e. one int8 code); every q8_1 activation of the window (GDN/QSA projections, shared expert, head) goes through it. The MMVQ dot kernels have no division (FTZ-only difference)." - }, - { - "ptx": "original_verify_qsa.ptx", - "entry": "verify_qsa_append_analytic (+ commit re-append)", - "original": "native_qsa_indexer.cu append (the default; STRATA_ROPE_TABLE=1 is opt-in)", - "operations": "powf(theta_scale, pair), cosf(theta), sinf(theta) (and logf for YaRN) are precise here and __powf/cos.approx/sin.approx in the Original; angles reach thousands of radians so the pooled index keys differ well beyond 1 ulp. Matters once the context exceeds the 2051-cell selection width." - }, - { - "ptx": "mtp_original_full_router.ptx", - "entry": "mtp_full_route", - "original": "native_router.cu route", - "operations": "expf(values - max) (precise expf sequence vs ex2.approx(x*log2e)), 1.0f / warp_sum and 1.0f / selected_sum (rcp.rn vs div.full): the routed expert weights differ in the last bits (expert ids do not)." - }, - { - "ptx": "mtp_original_full_gr_post.ptx", - "entry": "mtp_full_down_silu, mtp_full_pre_final, mtp_full_native_write", - "original": "native_gr_postops.cu", - "operations": "sigmoid 1.0f / (1.0f + expf(-x)) and silu x / (1.0f + expf(-x)): precise expf and division; used by final_write and the head mix." - }, - { - "ptx": "mtp_original_full_gr_norm.ptx", - "entry": "mtp_full_gr_norm", - "original": "native_gr_norm.cu weighted_rms_norm", - "operations": "mean = partial / n_cols (div.rn vs div.full) feeding rsqrtf; used by the head mix." - }, - { - "ptx": "ple_native_batch.ptx", - "entry": "native PLE post-ops", - "original": "native_ple_postops.cu", - "operations": "sqrtf, expf, 1.0f / (1.0f + expf(..)), sum / (1.0f + expf(..)) and partial / N: precise vs fast; only with a PLE block." - } - ], - "ftz_only_difference": [ - "mtp_original_full_bf16.ptx (native_bf16.cu)", - "mtp_original_full_combine.ptx (native_moe.cu)", - "the MMVQ kernels of mtp_original_full_head_native.ptx (native_mmvq.cu)", - "qsa_prompt_postops.ptx (q/gate split copy)" - ], - "matches_original": [ - "qsa_decode_postops.ptx (fast math, native_qsa norm / native_rope)", - "original_verify_window_qsa_gate.cu (to be sealed with --use_fast_math)", - "mtp_original_full_shared.ptx (Original shared_expert.cu spells __fdividef/__expf itself)", - "mtp_original_full_attention.ptx (qsa_decode_attn.cu: __expf explicit, precise division)", - "original_verify.ptx, mtp_original_full_fused_gr.ptx, mtp_original_kv.ptx, qsa_prompt_select.ptx, qsa_prompt_resolver.ptx, mtp_original_full_element.ptx, mtp_original_full_s2.ptx, mtp_original_full_head_iq.ptx, mtp_original_full_router_legacy.ptx (all precise in the Original)" - ], - "not_in_verify_window": "native_flash_attn.cu and native_qsa_score.cu are launched only by the single-token layer.cpp path, never by verify.cpp (qsa_decode_attn_batch / qsa_block_scores are precise)", - "action": "Re-seal the six assets above from their existing .cu with --use_fast_math (scripts/build-original-verify-ptx.sh compiles every source with the precise flags) and update their SHA pins; none of those sources contains hand-written intrinsics that a fast-math build would double-apply. The same assets back the MTP path, so the MTP golden comparisons must be redone after the re-seal." - }, - "not_candidates_original_is_precise": [ - { - "ptx": "mtp_original_full_attention.ptx", - "derived_from": "qsa_decode_attn.cu" - }, - { - "ptx": "qsa_prompt_postops.ptx", - "derived_from": "prefill/kernels.cu" - }, - { - "ptx": "qsa_prompt_select.ptx", - "derived_from": "qsa_select.cu (the Original verifier scores with qsa_select, not native_qsa_score)" - }, - { - "ptx": "mtp_original_full_router_legacy.ptx", - "derived_from": "router_top10.cu" - }, - { - "ptx": "mtp_original_full_fused_gr.ptx", - "derived_from": "fused_gr.cu" - } - ], - "correction": "The first version of this list named mtp_original_full_attention, qsa_prompt_postops, qsa_prompt_select, mtp_original_full_router_legacy and mtp_original_full_fused_gr; a function-level comparison against the Original shows those derive from sources that are NOT in the CMake fast-math list, and it missed the assets listed above." - } -} diff --git a/docs/cuda-seal-plan-additions.json b/docs/cuda-seal-plan-additions.json deleted file mode 100644 index c3813da7..00000000 --- a/docs/cuda-seal-plan-additions.json +++ /dev/null @@ -1,325 +0,0 @@ -{ - "schema": 1, - "note": "Additions to CUDA-SEAL-PLAN.json (schema 1, see stra169 plan) for the .cu assets added on claude/port-forward-leaves. Same fields; seal_sha256/seal_length are filled by the sealing session after nvcc. None of these needs -I/work/include (they include only cuda_fp16.h/cuda_runtime.h/libc headers). Verify each compiled entry list with `cuobjdump -sass`/`grep .entry` against `entries` before pinning. Flags follow engine/strata/CMakeLists.txt: --use_fast_math only for files in the native_* fast-math list.", - "assets": [ - { - "cu": "crates/cuda-driver/src/qsa_prompt_attention_variants.cu", - "cu_pin": { - "sha256": "6ee7f0d468a714767f684ebe302cd2e269f68764944dd862ed92a94813c7f1e4", - "bytes": 23880 - }, - "ptx": "crates/cuda-driver/src/qsa_prompt_attention_variants.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120" - ], - "policy": "Original qsa_prompt_attn.cu precise (not in CMake fast-math list); v1 template kernel modes 0 fp16 / 1 int8 / 3 K8V4", - "direct_original_headers": [], - "rust_consumers": { - "qsa_prompt_attention.rs": { - "sha256": "464e6f0ec82736c5337b540e6015e946b1651a278329c9dc19e29e17d17d3a2d", - "bytes": 17896 - } - }, - "rust_fields_to_fill": {}, - "encoding": "include_bytes", - "seal_sha256": "9041e250f6ffca2f849c20605a3f758c54f7856e7cd015c8a1da6625048d6aac", - "seal_length": 216290, - "entries": [ - "leleka_qsa_prompt_attn_v1_i8", - "leleka_qsa_prompt_attn_f16", - "leleka_qsa_prompt_attn_k8v4", - "leleka_qsa_prompt_guard", - "leleka_qsa_prompt_output_guard" - ], - "note": "Wired: qsa_prompt_attention.rs loads it lazily (only for non-default pools / debug switches). Dynamic smem 54288 / 37904 / 46096 B; the v1 launcher opts in via cuFuncSetAttribute (allowlist in qsa_prompt_attention_ffi.rs)." - }, - { - "cu": "crates/cuda-driver/src/native_flash_attn.cu", - "cu_pin": { - "sha256": "5cb73b5892c94238ae3a4470aa71585550c1526983ea0b5655281f294f354734", - "bytes": 8955 - }, - "ptx": "crates/cuda-driver/src/native_flash_attn.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "--use_fast_math" - ], - "policy": "Original native_flash_attn.cu fastmath (CMake fast-math list); short-context Q24x256/KV2x256 F16 only", - "direct_original_headers": [], - "rust_consumers": { - "native_flash_attn.rs": { - "sha256": "db43d4b64692024cc1c3647363c5a1731dca8410f160c8517ce8a1ff665a0132", - "bytes": 10775 - }, - "closed_kernels.rs": { - "sha256": "4fdfaae52112dc60e21ec1aa5eca82baa7916bc706578018f3d941f69fcd3afa", - "bytes": 28979 - }, - "closed_kernels_gpu.rs": { - "sha256": "bf92ce678f4b1bee725771ac238313ea95159c9d124982902ca22069b76888da", - "bytes": 18057 - } - }, - "rust_fields_to_fill": { - "closed_kernels.rs": [ - "PINS[0].source_sha256", - "PINS[0].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "be353e619a15a566e57bae12a0bf30cc1712a281bce6928f3bb76c14e5114bba", - "seal_length": 208590, - "entries": [ - "leleka_native_flash_attn_short" - ], - "note": "Wired by closed_kernels_gpu.rs (ClosedKernels::native_flash_attn_short, grid 24, block (32, 4), no dynamic smem) behind a zero PTX pin; the (32, 4) block goes through the generic KAR launcher (Api::launch_closed). Run the closed_gpu_* ignored smokes before freezing the pin." - }, - { - "cu": "crates/cuda-driver/src/mmq_original_prefill_misc.cu", - "cu_pin": { - "sha256": "da4cc72e19ca1ad694f4be807d6c0c1337ecfd8ca553fe31dd4c5185ed24cf4a", - "bytes": 3072 - }, - "ptx": "crates/cuda-driver/src/mmq_original_prefill_misc.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120" - ], - "policy": "Original prefill/moe_mmq.cu copy1/strata_q2/iota; integer only so precise and -use_fast_math PTX are identical", - "direct_original_headers": [], - "rust_consumers": { - "mmq_original_prefill_misc.rs": { - "sha256": "3dbfa2bb94a8c2adeb231c970ed3726de5fd43dbeaceeb105bb9ff166b79a093", - "bytes": 9943 - } - }, - "rust_fields_to_fill": {}, - "encoding": "include_bytes", - "seal_sha256": "3e57326d0dd6aec8147e6cf837ceca9d779ba06ea67bf4311b3ce0baa6d04d69", - "seal_length": 5267, - "entries": [ - "leleka_original_mmq_copy1", - "leleka_original_mmq_strata_q2", - "leleka_original_mmq_iota" - ], - "note": "Not wired: launched by the prompt composer hooks (executor_original_prompt.rs OriginalPromptHooks) once the MMQ owner loads it. 256 threads, ceil(n/256) blocks." - }, - { - "cu": "crates/cuda-driver/src/device_poison.cu", - "cu_pin": { - "sha256": "6b2ca992ac39d5b6b1820a744ad8bca03f6426302bc178c0d3089e4f767b610e", - "bytes": 914 - }, - "ptx": "crates/cuda-driver/src/device_poison.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120" - ], - "policy": "Original core/device.cu poison_kernel; device.cu is not in the CMake fast-math list", - "direct_original_headers": [], - "rust_consumers": { - "device_arena.rs": { - "sha256": "777a57fe571949e293e781fba254a0dae71ce2be7935ff4ad7435a3829bc23d0", - "bytes": 8773 - }, - "closed_kernels.rs": { - "sha256": "4fdfaae52112dc60e21ec1aa5eca82baa7916bc706578018f3d941f69fcd3afa", - "bytes": 28979 - }, - "closed_kernels_gpu.rs": { - "sha256": "bf92ce678f4b1bee725771ac238313ea95159c9d124982902ca22069b76888da", - "bytes": 18057 - } - }, - "rust_fields_to_fill": { - "closed_kernels.rs": [ - "PINS[2].source_sha256", - "PINS[2].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "587b097a201a6730e8fe5543291987bbf807da72da12b8e0a169f9e5e8f6a658", - "seal_length": 870, - "entries": [ - "leleka_poison_f32" - ], - "note": "Wired by closed_kernels_gpu.rs (ClosedKernels::poison_f32: 256 threads, blocks sliced at 0x7FFFFFFF) behind a zero PTX pin; nothing calls it by default." - }, - { - "cu": "crates/cuda-driver/src/s_gemv_legacy.cu", - "cu_pin": { - "sha256": "0922bb96ca3b2f1110509adab242cf76fa1f910cde859d1e4e4150c607b51952", - "bytes": 51423 - }, - "ptx": "crates/cuda-driver/src/s_gemv_legacy.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120" - ], - "policy": "Original s_gemv.cu / s2_gemv*.cu precise (none is in the CMake fast-math list); legacy S2/S4/S8 canonical-form GEMVs", - "direct_original_headers": [], - "rust_consumers": { - "s_gemv_legacy.rs": { - "sha256": "bf294d7996b76ef62a5307f59ec061eb8eabbd45dd2aa8efc9a28068d354963f", - "bytes": 36529 - }, - "closed_kernels.rs": { - "sha256": "4fdfaae52112dc60e21ec1aa5eca82baa7916bc706578018f3d941f69fcd3afa", - "bytes": 28979 - }, - "closed_kernels_gpu.rs": { - "sha256": "bf92ce678f4b1bee725771ac238313ea95159c9d124982902ca22069b76888da", - "bytes": 18057 - } - }, - "rust_fields_to_fill": { - "closed_kernels.rs": [ - "PINS[1].source_sha256", - "PINS[1].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "3ab4d12a5e97c4e2f4602c6c872372c5c0685d8cf1a20260af6e0f5205ac76d5", - "seal_length": 303521, - "entries": [ - "leleka_s_gemv_2", - "leleka_s_gemv_4", - "leleka_s_gemv_8", - "leleka_s_gemv_split_2", - "leleka_s_gemv_split_4", - "leleka_s_gemv_split_8", - "leleka_s_gemv_q8k_4", - "leleka_s_gemv_q8k_8", - "leleka_s_gemv_q8k_split_4", - "leleka_s_gemv_q8k_split_8", - "leleka_s_gemv_q8_0_split_4", - "leleka_s_gemv_q8_0_split_8", - "leleka_s2_gemv", - "leleka_s2_gemv_quads", - "leleka_s2_gemv_q8", - "leleka_s2_gemv_fast_staged", - "leleka_s2_gemv_fast_unstaged" - ], - "note": "Wired by closed_kernels_gpu.rs (ClosedKernels::s_gemv / s2_gemv over the s_gemv_legacy planners, dynamic shared memory via Api::launch_closed) behind a zero PTX pin; nothing calls it by default." - } - ], - "flags_policy_audit": { - "audited": "2026-10-14 with scripts/cuda-stubs/literal_diff.py (SOURCES=1) over every crates/cuda-driver/src/*.cu, against engine/strata/CMakeLists.txt", - "cmake_policy": { - "per_source_use_fast_math": [ - "native_mmvq", - "native_bf16", - "native_gr_norm", - "native_moe", - "native_gdn", - "native_gr_postops", - "native_router", - "native_gdn_preprocess", - "native_qsa", - "native_rope", - "native_ple_postops", - "native_flash_attn", - "native_qsa_indexer", - "native_qsa_score" - ], - "cmake_lines": "engine/strata/CMakeLists.txt:340-352 (strata_kernels), :965 (strata_mmq)", - "strata_mmq_extended_lambda_use_fast_math": [ - "src/prefill/moe_mmq.cu", - "src/prefill/ggml_cuda_host.cu", - "ggml-cuda/quantize.cu", - "ggml-cuda/template-instances/mmq-instance-*.cu" - ], - "everything_else": "default nvcc flags (no --use_fast_math); strata_next_kar* add CUDA_STANDARD 17 only" - }, - "unsealed_assets_without_an_entry_in_the_three_additions_files": [ - { - "cu": "mmq_original_group_swiglu.cu", - "original": "prefill/moe_mmq.cu swiglu_kernel / copy16_kernel", - "required": "--extended-lambda -use_fast_math (strata_mmq). swiglu_kernel computes g / (1 + __expf(-g)) * u, so the division is rcp.approx under fast math; a precise build is NOT the Original", - "entries": [ - "leleka_original_mmq_swiglu", - "leleka_original_mmq_gather", - "leleka_original_mmq_gu_finite" - ], - "note": "leleka_original_mmq_gu_finite is a port-side integer exponent scan, not an Original kernel" - }, - { - "cu": "mmq_original_group_mul.cu / mmq_original_group_fixup.cu / mmq_original_formats.cu / mmq_original_formats_fixup.cu", - "original": "ggml-cuda mmq.cuh instances (strata_mmq)", - "required": "-use_fast_math (the .cu headers already say so); 66 mul_mat_q + 66 stream-k fixup instantiations are exactly the (type,width) set of ffi.rs mmq_original_group_function" - }, - { - "cu": "mtp_original_scalar_gr.cu", - "original": "kernels/cuda/fused_gr.cu", - "required": "default (precise)" - }, - { - "cu": "mtp_original_scalar_norm.cu", - "original": "native_qsa.cu norm<1024> + native_rope.cu apply", - "required": "--use_fast_math" - }, - { - "cu": "mtp_original_session_native_rope.cu", - "original": "native_rope.cu apply", - "required": "--use_fast_math" - }, - { - "cu": "mtp_original_session_legacy_rope.cu", - "original": "rope.cu rope_neox_kernel", - "required": "default (precise)" - }, - { - "cu": "original_sampler.cu (= mtp_original_full_coupled.cu = native_head_sampler.cu text)", - "original": "kernels/cuda/sampler.cu", - "required": "default (precise)" - }, - { - "cu": "native_parity.cu", - "original": "iq_kernels.cu", - "required": "default (precise); test harness only" - }, - { - "cu": "native_head_native.cu / native_head_iq.cu / native_head_sampler.cu", - "original": "native_mmvq.cu / iq_kernels.cu / sampler.cu", - "required": "native_head_native: --use_fast_math (native_mmvq); the other two precise. These are byte/semantic twins of the sealed mtp_original_full_head_* sources and are not referenced by any Rust asset" - }, - { - "cu": "kar_decode_levels.cu", - "original": "none (gpu/kar/src/kar_expert.cu pairing; spec in crates/model-format/src/kar_kernel_model.rs)", - "required": "precise: --ftz=false --prec-div=true --prec-sqrt=true --fmad=true; the multiply uses explicit __fmul_rn/__fadd_rn" - } - ], - "sealed_assets_built_precise_whose_original_is_fast_math": [ - "mtp_original_tail (native_mmvq)", - "mtp_original_full_checks (native_mmvq)", - "mtp_original_full_head_native (native_mmvq)", - "mtp_original_full_bf16 (native_bf16)", - "mtp_original_full_router (native_router)", - "mtp_original_full_gr_norm (native_gr_norm)", - "mtp_original_full_gr_post (native_gr_postops)", - "mtp_original_full_combine (native_moe)", - "mtp_original_full_qnorm / mtp_original_full_qsa_gate / qsa_native_gate (native_qsa)", - "qsa_decode_postops (native_qsa norm + native_rope)", - "original_verify_qsa / qsa_prompt_indexer (native_qsa_indexer)", - "ple_native_batch / ple_prompt_device (native_ple_postops)", - "moe_route_top10 (native_router)", - "mtp_original_prefill_mmq / _fixup / _quant (strata_mmq -use_fast_math: the q8_1 quantizer divides)" - ], - "sealed_assets_whose_original_is_precise": [ - "mtp_original_full_attention (qsa_decode_attn)", - "qsa_prompt_postops (prefill/kernels.cu)", - "qsa_prompt_select (qsa_select.cu)", - "mtp_original_full_router_legacy (router_top10)", - "mtp_original_full_fused_gr (fused_gr)", - "mtp_original_full_s2 / mtp_original_full_shared / mtp_original_full_verify / mtp_original_full_element / mtp_original_full_gr_write / mtp_original_full_head_iq / mtp_original_full_head_sampler / mtp_original_full_coupled / mtp_original_full_quant80" - ], - "stale_toolkit_comments": "kar_decode_levels.cu, experimental_*.cu, mmq_original_group_*.cu, mmq_original_formats*.cu say nvcc 12.8.93; deploy/cuda-toolkit.lock.json and scripts/build-original-verify-ptx.sh pin 13.0.88" - } -} diff --git a/docs/decode-parity.md b/docs/decode-parity.md deleted file mode 100644 index e855c595..00000000 --- a/docs/decode-parity.md +++ /dev/null @@ -1,114 +0,0 @@ -# Decode parity with the unmodified Original (`claude/decode-parity`) - -RTX 5090 (PCIe 5 x16), Ryzen 9 9950X3D, driver 595.99, CUDA 13.2; 6 prompts x 2 passes x 128 greedy tokens, spec 4 + suffix 3, -`min_p` 0.5, 2048 per-layer slots from the placeholder profile unless stated, int8 KV, KAR PLE L2, adaptive tier on. "Decode -tok/s" = produced tokens / decode phase ms over the requests of 100+ tokens, mean per pass. "Phase" is what the smoke prints -(whole decode phase of the port, including the per-request verifier assembly); "serve" is the verify loop alone (what the -Original's `decode_ms` measures). Jobs 980-985 (`~/work/gpu-runs/holder2/jobs`), scripts and parsers in the report branch's -commit messages; analysis scripts were outside the repository. - -## Findings - -1. **The Original's pass-0 number in job 809 was depressed by a cold file.** The Original read the 52 GB KAR through its own - page cache next to the holder's memfd copy; the two together pushed the memfd into swap (30-40 GB of swap in use, IO pressure - 60 %). Reading the same memfd through `/proc/self/fd/N` removes that. Same configuration, three interleaved repetitions - (job 984): Original 68.8 / 84.0 tok/s (pass 0 / pass 1; repetition ranges 68.7-68.9 and 83.9-84.1), not 52.8 / 74.7. -2. **Window cost, same prompts, static residency (GPU stage stamps, jobs 980/981):** every GPU stage is within 0.1 ms/window - of the Original except the PCIe copy stage (`waitB`, copy kernel): port 32.4 vs Original 25.9 ms/window (prompt 0), 33-45 vs - 27-36 on the others. That is the whole GPU-side gap (+7-10 ms/window). Isolated, the port's copy kernel moves 14 experts at - 48.5 GB/s (microbenchmark job 980-a, 4 KiB pages = THP = cudaHostAlloc, kernel = DMA); inside a window it is slower, so the - loss comes from contention with the CPU pool for host memory, not from the kernel or the page size. -3. **CPU leg:** 37 us per CPU entry in the port vs 35 us in the Original (same code); at the auto-sized cache the port's - pool time is 9.6 ms/window vs 5.0 + 0.5 in the Original (fixed per-group host cost, not yet attributed; spans - `cpu.plan/open/zero/compute/sink` are in the head but their job did not run). -4. **Per round outside the window:** port 2.2 ms (draft + commit) vs Original 1.2 ms. The port's MTP chain-step graph is - GPU-bound at 0.68 ms (events), host overhead per step ~0.02 ms; why the Original's steps are shorter is not known. -5. **Per request:** verifier assembly 63 ms (capture 28-50 + instantiate 17-24 + canonical GDN upload 11) + teardown 10 ms, - not part of the Original's `decode_ms`: 3.6 % (pass 0) to 4.6 % (pass 1) of the port's phase rate at 2048 slots, 6 % with the - auto-sized cache. -6. Residency was not the cause: per-request hit rates agree (VRAM entries over VRAM + CPU entries, the Original's definition, - 52 % / 74 % port vs 50 % / 69 % Original on prompt 0), and the adaptive policy is a literal port. The - adaptation knobs (`LELEKA_ADAPT_*`, swaps) are within noise; only cadence 2 helps. - -## What changed (all flag-gated; defaults noted) - -| change | flag | default | measured (adaptive, 2048 slots, port phase tok/s pass 0 / pass 1) | -| --- | --- | --- | --- | -| PCIe staging by DMA, one driver entry per group, one `cuMemcpyBatchAsync`, flag B by `cuStreamWriteValue32` (falls back to plain calls when the driver refuses; opt-in on WSL) | `--pcie-mode` auto = dma; `LELEKA_PCIE_DMA_MANY/_DMA_BATCH/_FLAGB` | on | 57.9 / 70.2 (copy kernel, head) -> 64.1 / 80.5 (3 interleaved repetitions each, ranges <= 0.5) | -| unrolled copy kernels (`k1u16`, 16 loads in flight) | `LELEKA_PCIE_KERNEL`, `LELEKA_PCIE_GRID` | off (kernel mode only) | static +8 % over the sealed kernel | -| adaptive tier every 2 rounds | `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2` | 4 (the Original's) | 67.3 / 81.9 vs 64.1 / 80.5 | -| PCIe share controller | `LELEKA_PCIE_AUTO=on` | off | no better than the best fixed share | -| opened-expert span cache for the CPU leg | `LELEKA_OPEN_CACHE=on` | off | not measured | -| bank THP, CPU workers, adaptive min/margin/decay | `LELEKA_BANK_THP`, `..._CPU_WORKERS`, `LELEKA_ADAPT_*` | off | THP took no effect; workers > 15 fail at open; adaptation knobs within noise | - -PCIe share sweeps (static, jobs 981): kernel mode 0.55 -> 0.25 / 0.35 / 0.45 = 47.9 -> 52.0 / 53.9 / 54.9 tok/s (pass 0); -DMA 0.45 / 0.55 / 0.65 / 0.75 = 56.9 / 55.4 / 49.0 / 44.6. Adaptive with DMA: 0.35 / 0.45 / 0.55 = 60.9 / 64.8 / 64.2, so the -share default stays 0.55. - -## Paired A/B (jobs 984, 985; three interleaved repetitions, order rotated; mean [min..max] of the per-repetition means) - -2048 slots, decode tok/s pass 0 / pass 1: - -| arm | phase | serve only | -| --- | --- | --- | -| Original, shipped config (pcie 0.55, copy kernel) | 68.8 [68.7-68.9] / 84.0 [83.9-84.1] | same (its `decode_ms`) | -| Original, `--pcie-frac 0.35` | 72.8 [72.6-72.9] / 89.1 [88.6-89.5] | | -| port, previous head (`PCIE_MODE=kernel`) | 57.9 [57.6-58.1] / 70.2 [69.7-70.5] | 60.7 / 74.2 | -| port, new defaults | 64.1 [63.9-64.4] / 80.5 [80.2-80.9] | 66.5 / 84.4 | -| port, new defaults + cadence 2 | 67.3 [67.1-67.4] / 81.9 [81.8-82.0] | 69.8 / 85.9 | - -Auto-sized cache (all free VRAM; Original 9971 slots, port 8820): Original 94.4 [94.0-94.7] / 129.1 [127.8-130.3]; port -84.3 [83.7-84.7] / 110.1 [109.9-110.4] (serve only 88.2 / 117.2). - -The port does not reach the Original on this metric: -7 % / -4 % (defaults), -2 % / -2.5 % (cadence 2) against the shipped -Original, -8 % / -8 % against the tuned Original, -11 % / -15 % with the auto-sized cache. In the loop alone cadence 2 is +1.4 % / +2.3 % -over the shipped Original and -4 % / -3.5 % under the tuned one. - -Tokens: the adaptive placement depends on timing, so outputs differ between arms and between engines (static runs of the same -binary agree 7-12 of 12 requests, depending on window-size timing); the Original and the port also take different numbers of -tokens per window on the same prompt (2.2 vs 2.5), which moves a per-prompt rate by several percent either way. - -## TTFT - -Prompt phase of the port: prefill read 550 ms + lent-slot refill 44 ms (+ 63 ms assembly counted in the decode phase) for -60-100 token prompts; the Original's `prompt_ms` 335-510 ms on repeats, 640 ms mean in job 809 (cold). The prefill agents own it. - -## What remains (ordered by measured size) - -* PCIe copy stage 25-35 % slower than the Original's inside a window although isolated bandwidth is equal: needs a - contention microbenchmark (CPU workers streaming while the GPU fetches; contiguous blobs vs three tensors) - - `pcie_mb2` was written (`dec-mb/pcie_mb2.cu`, not in the repository) but its job was withdrawn. -* Fixed per-group host cost of the CPU leg (4-5 ms/window at the auto cache): spans are in the head; `LELEKA_OPEN_CACHE=on` - is the first candidate. -* Draft + commit 1 ms/round above the Original (GPU-bound MTP step graph). -* Per-request verifier assembly + teardown (about 75 ms): needs a verifier that persists across requests. -* VRAM reserve: the auto-sized cache holds 1151 fewer slots than the Original's. - -# Round 2 (auto-sized cache, contention, controller, draft, assembly) - -Reference (fixed, recorded): Original shipped 68.8 / 84.0, tuned (pcie 0.35) 72.8 / 89.1, auto-sized cache 94.4 / 129.1 tok/s -(pass 0 / pass 1; no Original run was repeated). Since round 1 the integrated head added the prompt-routing seed and -prefix/memory work: the port's own previous head at the auto-sized cache moved from 84.3 / 110.1 to 104.4 / 122.4. - -* **VRAM (jobs 987/988/989, free-VRAM notes, `LELEKA_SERVE_PROFILE=1`):** 32 110 MiB visible; embedding 324, native head 506, dense - 4 640, MoE prompt arena 942, prompt executor + MTP drafter 920-1 068, expert cache, then the per-request verifier assembly takes only - ~450 MiB (also at 180k tokens, capacity 8192). The decode reserve of 1024 MiB left ~550 MiB idle. Default is now 300 MiB: - 8820 -> 9144 slots (+324; 9104 with 450 MiB in the 180k smoke, prefill 3873 -> 3913 tok/s, free after assembly 701 MiB). The - Original's 9971 slots are not reached: the remaining ~800 slots are the port's larger resident set (MoE prompt arena, drafter - buffers, KV window); not shrunk. -* **PCIe stage under contention (job 987-b, microbenchmark, 15 CPU streaming workers):** PCIe drops from 48 to 31.5-34.5 GB/s - while the CPU gets 42 GB/s (one DRAM ceiling); contiguous blobs vs three tensors, 4 KiB vs THP, and kernel vs DMA differ by <= 3 % - (DMA best). The in-window PCIe stage is therefore bounded by the host memory system, not by the port's layout or kernel. - The optimal share is P/(P+C) = 0.45 (schedule agent, job 909): default now 0.45 (auto cache, 3 interleaved repetitions: - 128.2 vs 122.4 tok/s pass 1, +4.7 %; pass 0 104.9 vs 104.4; equal at 2048 slots). -* **Controller `LELEKA_PCIE_AUTO=lag`** (flag-B wait after the CPU leg): no gain (104.2 / 121.5 vs 104.4 / 122.4); the old hill - climber (`=on`) is also no better than the fixed 0.45. Both stay off. -* **Draft + commit (2.2 vs 1.2 ms/round):** the chain-step graph has 113 nodes (round graph 155-186) and is GPU-bound at 0.68 ms - (events). The ledger agent attributes ~0.4-0.5 ms/round to the smokes and the daemon not binding the MTP draft-vocabulary subset - (`--mtp-rt-dir`, 106 299 rows instead of the 248 320-row head): jobs 991/992 carry the arm `R` - (`LELEKA_ORIGINAL_SERVE_RT_DIR`). -* **Verifier persistence: not done.** The prompt executor's QSA layers own the index/KV objects the verifier journal also wraps - (`take_qsa_owners` / `adopt_qsa_owners`, session lineage witnesses, `prepare<'index>` borrows); keeping graphs across requests - needs the executor to use the owners through the journal. Assembly (63 ms) + teardown (10 ms) stay: 7-9 % of a pass-1 - request at the auto-sized cache (serve-only 134 vs phase 123 tok/s). -* **Not helpful:** opened-expert cache (`LELEKA_OPEN_CACHE=on`, no change), `min_p` 0.3 / 0.7 (both below 0.5), KV window 4096. diff --git a/docs/delivery-gap-audit.md b/docs/delivery-gap-audit.md deleted file mode 100644 index 9cd2cccc..00000000 --- a/docs/delivery-gap-audit.md +++ /dev/null @@ -1,182 +0,0 @@ -# Delivery gap audit: control plane and packaging (M2) - -Branch `claude/m2-control-plane` (base `claude/port-gpu-bringup` @ `6cd926d`), audit of 2026-10-16. Host-side only: no model -was loaded, no GPU context was created, and nothing here is a performance or model-quality result. File:line references are -to this branch. The run recipe is [`rust-runtime-run.md`](rust-runtime-run.md). - -## 0. Findings that decide the next work - -> Update 2026-10-16, branch `claude/api-over-rust-engine`: finding 1 and section 7 task 1 are addressed in software by -> [`api-over-rust-engine.md`](api-over-rust-engine.md) (the full `leleka-api` API in front of the runtime, tested with a scripted -> engine; no real engine run). Findings 2-5 and the delivery tasks are unchanged. The lock flakes of section 1 are most likely a test -> artefact (a `flock` kept alive past `drop` by a child another test forked meanwhile); the reopen in those tests now waits, and 12 of 12 -> parallel runs of the `leleka-engine-host` lib suite passed afterwards (the mechanism itself was not isolated). - -> Update 2026-10-17, branch `claude/deploy`: the packaging half of finding 4 and tasks 3-4 of section 7 are addressed in software by -> [`deploy.md`](deploy.md) (`leleka up`: preflight incl. driver/cuBLAS/`/proc`/RAM/disk, asset fetch+verify+archive with stamps, native sealed-memfd supervisor, -> auto-load and readiness, systemd unit, OCI recipe, release tarball with provenance). Still open there: the MTP pack has no automated producer, no clean-VM run on -> Ubuntu 24.04/26.04, the image was not built here (see `deploy.md` section 10), and SIGTERM handling of the daemon/engine is worked around by the supervisor (it sends SIGINT). - -1. **Two serving stacks exist and the full API is wired to the wrong one.** `leleka-api` (`control-plane/`) has the Responses / - Chat / Messages surface, text.format, custom tools, reasoning, drain, history, MCP hub, but it drives an *engine process over - the Original stdio wire protocol* (`READY`/`GEN `/`T `/`DONE`, `control-plane/src/wire.rs`). The Rust engine - (`leleka-inference`) speaks gRPC with a **text prompt in, text deltas out** (`crates/backend-api/src/lib.rs:130-211`) and is - fronted only by `leleka-daemon`, whose `/v1/responses` is a narrow text subset. No adapter joins them. Codex cannot use the - Rust engine directly today (section 4). -2. **The daemon rejects a Codex-shaped request.** A body with `reasoning`, `include`, `tool_choice` or `parallel_tool_calls` - gets 400 `unsupported_request_field` (`desktop-core/src/runtime_gateway.rs:422-431`, observed live, section 2); `max_output_tokens` - defaults to 256 and is capped at 4096 (`:442-443`); tools are off unless `experimental_native_tools` is set (`:642`). -3. **Every Original-path request starts from an empty context** (no conversation or prefix reuse is bound, - `docs/original-serve.md:97-104`); the backend serves one generation at a time (`backend.rs:759`). -4. **Delivery of the Rust pair is absent**: no image, no installer, no health/ready endpoint on the daemon, no SIGTERM - handling, no readiness after restart without a manual `load-mtp`. Existing packaging (`deploy/`) ships `leleka-api` plus the - C++ engine only. -5. **Gate A evidence is synthetic.** Every committed Responses fixture is marked `synthetic` - (`benchmarks/fixtures/responses/*.json`); no recorded Codex session or comparison against the Python server exists - (`docs/roadmap.md` P3 last item, charter backlog item 3). -6. Found and fixed here: a dead log sink killed the worker supervisor and left readiness true (section 6, `e743764`); the static - CLI image could not build (`e5c7c32`); three smoke/test expectations were stale (`203b88f`, `6ca48b8`). - -## 1. Host test suites (no GPU, no model) - -Linux x86_64 (`rnr5090`: Ubuntu 26.04.1, Rust 1.99.0, own tree `~/work/leleka-m2`, `nice -n 15 cargo test --locked -j 8 ---no-fail-fast`, default workspace members): - -| run | passed | failed | ignored | targets | note | -| --- | --- | --- | --- | --- | --- | -| 1, base `6cd926d` | 898 | 6 | 1 | 72 | see failures below | -| 2, HEAD after the fixes | 910 | 0 | 2 | 73 | includes 4 `leleka-seal-exec` and 3 `log_failure_sse` tests | - -Failures of run 1: - -| test | cause | status | -| --- | --- | --- | -| `desktop-core/tests/native_tools_sdet.rs` `declarations_are_bounded_unique_and_closed_before_render` | stale: asserted temperature 0.4 is refused, valid since `cce4333` | fixed `203b88f` | -| `leleka-engine-host --lib` `operation_journal::tests::{append_failure_preserves_existing_evidence, terminal_history_survives_and_incomplete_is_not_replayed}` (and `recovered_uncertainty...` in reruns) | `journal already owned or locking unavailable` under the parallel lib run; pass alone and with `--test-threads=1`; 4 of 5 parallel reruns failed once, run 2 passed. Root cause not isolated (suspected: the `flock` of one test inherited by a concurrent child process until `exec`) | **open, flaky** | -| `leleka-control-plane --lib` `responses::tests::durable_history_roundtrip_delete_eviction_and_faults` | same message from `history.lock`; 3 of 3 reruns passed | **open, flaky** | -| `runtime_gateway_sdet` `daemon_http_disconnect_cancels_one_runtime_generation` | timed out (13 s) in the loaded run; 3 of 3 isolated runs passed | load-sensitive | - -Other checks on Linux: `cargo clippy -p leleka-control-plane --all-targets --no-deps -- -D warnings` clean; with dependencies it stops -at known debt in `leleka-model-format` (`pinned_arena_plan.rs:325` `type_complexity`), so `scripts/check-local.sh` full mode fails -at the control-plane Clippy step. `cargo fmt -p leleka-engine-host --check` also reports existing drift (`leleka-inference.rs`, -untouched here). - -HTTP/SSE smokes against `leleka-api` with scripted engines (Python 3.14 as test driver only), debug binary: pass -`test-live-responses-replay` (21 corrupt streams rejected, JSON+SSE tool continuation), `smoke-tool-policy` (216 cases), -`smoke-custom-tools`, `smoke-sse-keepalive`, `smoke-input-tokens`, `smoke-response-history` (+`--durable`), `smoke-native-drain`, -`smoke-signal-drain`, `smoke-generation-deadline`, `smoke-worker-cancel`, `smoke-native-auth`, `smoke-queue-deadline`, -`smoke-config-check`, `smoke-wait-ready`, `smoke-chat-completions`, `smoke-messages` (the last two after `6ca48b8`; before it -they failed on stale expectations). `replay-responses --sse` on the structured-tool fixture ends in `response.completed`. -Not run: `smoke-static-cli`, `smoke-embedded-engine`, packaging and container smokes, the live Python-oracle differentials. - -Windows 11 (Rust 1.99.0): the 8 portable crates (`leleka-backend-api`, `-tokenizer`, `-quant-core`, `-context`, `-sampler-ref`, -`-experimental-ref`, `-serving-policy`, `-offline-tools`): **341 passed, 0 failed**. The default workspace does not build -here: `desktop-core` pulls `leleka-runtime` -> `leleka-cuda-driver` (Linux-only items, 29 compile errors), `leleka-control-plane` lib tests use -`std::os::unix` (`vision.rs:499,513`), `leleka-model-format` lib tests need the unix-only `RangeSource for KarInspection` -(`kar_levels.rs:582`, used at `tests/kar_ple/mod.rs:693`). Windows is not a delivery target; use Linux. - -## 2. Synthetic verification of the request path - -| layer | what ran | result | -| --- | --- | --- | -| daemon gateway, mock backend, real HTTP/2 + gRPC | `runtime_gateway_sdet` (8 tests): ordered SSE with one terminal, finish reason `stop` -> `completed`, `length` -> `incomplete`, missing terminal / tool reason / accepted fault -> `response.failed` without retry, disconnect cancels one generation | pass | -| daemon process + `leleka-inference` process (real binaries, **no Load**) | `/runtime/status` connected, `model_ready: false`; `/v1/responses` valid body -> 503 `model_not_ready`; unsupported field -> 400; no token -> 401 | as expected; recipe in `rust-runtime-run.md` | -| `leleka-api` over a scripted engine | live SSE: `created, in_progress, output_item.added, content_part.added, output_text.delta*, done events, output_item.done, function_call_arguments.delta*/done, ... completed`; token budget -> `response.incomplete` (`max_output_tokens`); worker error -> `response.failed` (unit tests `responses.rs:5428,5490`) | pass | -| log failure | real binary, stderr consumer gone, protocol failure mid-stream | stream ends `response.failed`; readiness drops (after `e743764`) | - -## 3. Python audit - -Production serving path (what `leleka-api serve`, `leleka-daemon`, `leleka-inference` start at run time): **no Python**. - -| item | where | class | -| --- | --- | --- | -| external processes spawned by `leleka-api` | `nvidia-smi` (`doctor.rs:50`, `cuda_memory.rs:134`), `systemctl` (`service_install.rs:543,627`), operator `engine.executable` / `@embedded` memfd (`worker.rs:441`, `embedded_engine.rs`), operator `strata-vision` (`vision.rs:222`), operator `before_load` argv or `sh` (`worker.rs:235-244`), operator MCP server commands (`mcp.rs:135`), `kill` (`mcp.rs:346,355`) | no Python hard-coded; an MCP server or `before_load` the operator configures may be anything | -| chat template | `include_str!(engine/strata/serve/chat_template.jinja)` rendered by minijinja (`prompt.rs:32`) | data file, not Python | -| `leleka-inference` / `leleka-daemon` / `leleka-cli` / `leleka-seal-exec` | `ldd`: libc, libm, libgcc_s; dlopen `libcuda.so.1`, `libcublas.so.12` | none | -| error text only | `original_mtp_rt.rs:71` says "run tools/mtp_rt.py" (offline conversion; ported to `crates/offline-tools`) | message | -| KAR sealing for the engine | bring-up used operator scripts `seal_exec.py` / `kar_holder.py` (outside the repo) | replaced by `leleka-seal-exec` (`414169b`) | -| offline-only tooling | `scripts/offline/diff_*.py` (oracle differentials), `engine/strata/tools/*.py` (Original converters; Rust ports in `native_pack.rs`, `offline-tools`; `mtp_pack` producer still absent), `scripts/gpu-bringup/*.py` (compile/seal PTX), `scripts/build-linux-package.py`, `build-runtime-image.py`, `bootstrap-cuda-toolkit.py`, `publish-gitea-release.py` | build / offline | -| test-only | `scripts/smoke-*.py`, `scripts/test-*.py` (83 `.py` files in `scripts/`, including benches and installers), `desktop/tests/*.py`, `control-plane/tests/mcp_hub.rs` (spawns `python3` for a fake MCP server) | CI / test | -| client-side launchers | `scripts/install-qwen-native*.py`, `qwen_native_api.py`, `qwen_native_service.py` (`qwen-codex-ctl` on the laptop) | not serving | -| reference only | `engine/strata/serve/server.py` (Original Python server): differential goldens (`tests/fixtures/golden/*`, `http_surface.rs`) | not started by any Rust code | -| images | `Dockerfile.runtime` is `scratch`-like plus the binary; `Dockerfile.systemd-smoke` installs python3 for its fixture | test image only | - -Residual risk: CI itself (`linux.yml`, `desktop.yml`, `port.yml`) needs Python; production does not. - -## 4. Codex-direct audit - -"leleka-api" = `control-plane/`; "daemon" = `desktop-core/src/runtime_gateway.rs`. Wire contract: `docs/api-contract.md`. - -| requirement | leleka-api | daemon (Rust engine) | gap / location | -| --- | --- | --- | --- | -| `POST /v1/responses`, bearer auth, SSE | yes (`responses.rs:1078`, streams `:1951,2122,2423`) | yes | none | -| Codex-shaped body (`include`, `reasoning`, `store:false`, `parallel_tool_calls`, `tool_choice:auto`, `prompt_cache_key`, `client_metadata`) | accepted (`responses.rs:487-521`, `:709-722`) | **400** `unsupported_request_field` (`runtime_gateway.rs:422-431`; tool path `runtime_tools.rs:393-418`) | daemon | -| unknown top-level or `text` fields | **rejected** by `deny_unknown_fields` (`responses.rs:486,524`): `service_tier`, `text.verbosity`, `max_tool_calls`, `user` would 400 | rejected | decide accept-and-ignore for harmless fields | -| `reasoning.effort` / `summary` | effort none..xhigh; summary only `auto`/null (`:1361-1388`); `minimal` and `concise`/`detailed` -> 400 | thinking never enabled (`Effort::None`) | leleka-api: map `minimal`; daemon: absent | -| `text.format` text / json_object / json_schema | prompt guidance + validation of the finished text; buffered until DONE; invalid -> `response.failed` (`:684-707`, render `:1625-1640`, `api-contract.md` "Live structured text") | only `{"format":{"type":"text"}}` (`runtime_tools.rs:432-437`) | **no constrained decoding anywhere**; daemon: absent | -| function tools | yes, schema-validated before publication (`:765-791`); names `[A-Za-z0-9_-]` up to 64 bytes | behind `experimental_native_tools` (default off, `:642`), buffered, one regeneration on invalid output, at most 128 tools (`runtime_tools.rs:14`) | daemon: default-off, no streaming of arguments | -| custom tools (text) and regex format | yes, validation-only (`response_tools.rs:62-101`) | tool adapter covers namespaced custom regex (test `native_tools_sdet`) | no grammar-constrained sampling | -| custom tools with **Lark** grammar | rejected 400 (`response_tools.rs:87-89`) | rejected | a Codex that sends its freeform `apply_patch` as a Lark custom tool gets 400; needs the function variant or Lark support | -| hosted tools (`web_search`, `local_shell`, `image_generation`, `file_search`) | rejected (`response_tools.rs:65-67`) | rejected | acceptable unless Codex config enables them | -| `tool_choice` auto / none / required / forced function or custom / `allowed_tools` | yes (`:589-652`, `:730-763`, `validate_live_subset` `:2684`) | adapter only | forced namespaced selectors -> 501 | -| `parallel_tool_calls:false` enforcement | yes (`:645`) | adapter | none | -| streaming event order, `sequence_number`, one terminal | tested (`responses.rs:4851,5153,5369,5527`) | `Trace` (`runtime_gateway.rs:519-594`) | none | -| terminal event on every failure | worker error, DONE missing, store failure -> `response.failed` (`:2098-2113`, `:2293`, `:2614`); **log-sink failure fixed** `e743764` | stream error -> `interrupted()` `response.failed` | no SIGTERM handler in the daemon: a stop cuts live SSE (`leleka-daemon.rs:38`, SIGINT only) | -| max output tokens | default min(32768, context minus prompt) (`:1135-1140`) | default **256**, max 4096 (`:442-443`) | daemon | -| long-prefill keep-alive | `: keep-alive` after 15 s (`native_events.rs:9-11`) | only in the tool path (`:902-917`) | text path silent while prefilling | -| conversation / prefix reuse across turns | engine-side (`RESUME`/`REUSED` lines) | none: every request resets to position 0 (`original-serve.md:97-104`) | full re-prefill per Codex turn | -| stored responses, `previous_response_id`, input_items, DELETE | yes (`api-contract.md`, in-memory or durable) | no | daemon | -| `/v1/responses/input_tokens`, `/v1/chat/completions`, `/v1/messages` | yes | no | daemon | -| MCP | Codex executes MCP tools itself; the server only sees function tools named `mcp__server__tool` (accepted). Server MCP hub `mcp.rs` is tested (`tests/mcp_hub.rs`, 5 tests) but nothing executes tools for a client (`api-contract.md:208`) | same as function tools | the real Codex+LeaseVibe MCP episode is not recorded | -| approval / review turns | developer messages coalesced into the system section (`api-contract.md` "Approval/review requests") | untested | no real capture | -| reasoning item replay | requires raw `reasoning_text` content; `encrypted_content` or summary-only -> 400 (`responses.rs:1660-1668`) | n/a | unverified against what Codex actually re-sends | -| concurrency | one generation at a time; admission 429 / drain 503 | `max_concurrent_generations: 1` (`backend.rs:759`) | charter G8 later | -| transport | HTTP on loopback, no TLS (use SSH forwarding) | same | rented server needs a tunnel | -| error body | `{"error":{"message","type","param","code"}}` | `{"error":{"message":code,"type":code}}` | differing shapes | -| evidence | all fixtures synthetic | synthetic | **no recorded Codex session, no comparison with the Python server** | - -## 5. Deployment audit (clean Ubuntu 24.04 / 26.04, NVIDIA driver >= 595) - -| item | state | evidence | missing | -| --- | --- | --- | --- | -| driver floor | `doctor` / `gpu_requirement` know only `cuda-13.0-linux` = 580.65.06 | `doctor.rs:27,44` | the sealed PTX contains ISA 9.2 (36 `.ptx` files, nvcc 13.2) and the target floor is 595: a `cuda-13.2-linux` profile; no check for `libcublas.so.12` | -| cuBLAS | the Rust engine dlopens CUDA **12** `libcublas.so.12` by name | `ple_batch_ffi.rs:147` | not packaged, not preflighted; `deploy/README.md` still says `libcublas.so.13` for the C++ engine; version pin undecided (bring-up 12.9.1.4, Ubuntu 26.04 `libcublas12` 12.4.5.8) | -| binaries | `cargo build --release -p leleka-engine-host --bin leleka-inference ...` needs only Rust + a C compiler | `ldd` of the debug build | no release job, no checksum/provenance for the Rust pair; `linux.yml` builds only `leleka-api` + C++ engine; `port.yml` only type-checks | -| one-command install | `leleka-api service-install` (user unit, `--start-ready`) exists for `leleka-api` | `deploy/README.md:77-130` | nothing for `leleka-inference` + `leleka-daemon`; no asset fetch/verify chain for the KAR archive, MTP pack and shards of the Rust path | -| sealed KAR | `leleka-seal-exec` (`414169b`) | tests | 55 GB RAM per engine start; no preflight of free RAM/`/proc`/memfd | -| systemd | templates `deploy/rust-runtime/*.service` pass `systemd-analyze --user verify`; `leleka-api` has a user unit (`service_unit.rs:44-63`, `Restart=no`) | | never run with the real model; no system-wide unit; lingering is never configured (`deploy/README.md:240-246`), so a user unit does not start at boot without admin action | -| signals | `leleka-api` has shutdown grace; the Rust pair handles SIGINT only | `leleka-daemon.rs:38`, `leleka-inference.rs:211` | observed on the daemon: SIGTERM ends the process with status 143, SIGINT exits 0; templates set `KillSignal=SIGINT` as a workaround | -| readiness / health | `leleka-api`: `/health`, `/ready`, `/status`, `wait-ready`; daemon: authenticated `/runtime/status` only | `runtime_gateway.rs:220` | no unauthenticated probe, no `wait-ready` equivalent, no auto-load: after any engine restart the model is not loaded until `leleka-cli load-mtp` | -| OCI image | `Dockerfile.runtime` = `leleka-api` + embedded C++ engine on an Ubuntu 26.04 digest, non-root, `NVIDIA_VISIBLE_DEVICES=void` default | `deploy/Dockerfile.runtime`, `build-runtime-image.py` | no image for the Rust pair; `Dockerfile.static-cli` context was broken (fixed `e5c7c32`) | -| model volume / no re-download | asset manifests with SHA-256, resumable fetch, atomic publish for `leleka-api` | `deploy/README.md:646-770` | not wired to the Rust path's inputs (shards + KAR + provenance + MTP pack) | -| observability | JSON `/metrics` on `leleka-api` (not Prometheus) | `api-contract.md:265` | none on the daemon/engine; `DBG arena` `eprintln!` lines remain on the engine load path (`cache_original_prompt.rs:31-62`) | -| security | loopback only, bearer tokens from env, 0700/0600 checks in `leleka-api`; tokens for the Rust pair read from env | `leleka-inference.rs:112` | systemd `EnvironmentFile` mode not enforced by tooling | -| clean-host test | none for either stack (`docs/roadmap.md` P4 acceptance open) | | | - -## 6. Changes made on this branch - -| commit | change | -| --- | --- | -| `203b88f` | `desktop-core/tests/native_tools_sdet.rs`: stale temperature assertion corrected (accept 0.4, refuse 2.5) | -| `e743764` | `control-plane`: `elog!` replaces every `eprintln!` (it panics when stderr is unwritable); new `tests/log_failure_sse.rs` (control case plus dead-sink case on the real binary, and a source scan) | -| `6ca48b8` | `smoke-chat-completions.py`, `smoke-messages.py`: refusal cases use out-of-range values; picture block is countable | -| `414169b` | `desktop-core`: `leleka-seal-exec` (sealed memfd launcher), `rustix` target dependency | -| `e5c7c32` | `.dockerignore` / `Dockerfile.static-cli`: carry `chat_template.jinja` | -| docs commit | this page, `rust-runtime-run.md`, `desktop-core/examples/daemon.original.json`, `deploy/rust-runtime/` templates | - -Not changed: `engine/strata/`, `crates/cuda-driver`, `crates/leleka-runtime`, the flaky tests, the Windows test portability. - -## 7. Recommended tasks (priority order) - -| # | task | acceptance | -| --- | --- | --- | -| 1 | **One API in front of the Rust engine.** Add token-level generation to `backend-api` (prompt token ids in, `TokenDelta` out, versioned) and a worker trait in `control-plane` with the stdio and the gRPC/in-process implementations; or move the daemon onto the control-plane router | the `control-plane` HTTP fixtures (tools, custom/regex, text.format, reasoning, cancel, drain, history, Chat, Messages) pass unchanged against a fake `Backend`; a Codex-shaped body returns 200 with the section-4 event order; `leleka-daemon` route set equals `leleka-api`'s | -| 2 | **Record and sanitize real Codex sessions** (plain turns, MCP tool turns with LeaseVibe, approval/review, long context) and replay them through `leleka-api` and the Python server, then the Rust path | N sessions, zero protocol errors, zero streams without a terminal event, unchanged tool arguments, a written diff against the Python server; fixtures free of credentials and prompts that are not public | -| 3 | **Rust-pair delivery**: one command that preflights (driver >= 595, `libcublas.so.12`, `/proc`, free RAM >= 56 GB, disk), verifies assets by SHA-256, seals, starts engine and gateway, loads, waits for readiness | on a clean Ubuntu 24.04 and 26.04 VM with a GPU: one command -> authenticated `/ready` true -> one `/v1/responses` completes; a restart reaches ready again without re-download | -| 4 | **OCI image for the Rust pair** (pinned base digest, pinned CUDA 12 cuBLAS with SHA-256, four binaries, non-root) and a CI job building it | loader test without GPU passes (`ldd`, `--help`, dlopen failure messages); `docker run --gpus all` smoke on the GPU runner; provenance file lists binary digests | -| 5 | **Lifecycle of the daemon/engine**: SIGTERM drain with terminal SSE events, unauthenticated `/health` + `/ready`, `--autoload`/`wait-ready`, readiness false after engine restart | kill -TERM during a stream ends it with `response.failed`/`completed`; a killed engine flips `/ready` and returns to ready by itself | -| 6 | Conversation/prefix reuse on the Original path and a per-turn token budget default | second turn of a 50K-token conversation re-prefills only the new suffix (token counts reported, greedy output equal to the full re-prefill) | -| 7 | Constrained decoding for `text.format` and tool arguments (regex first, then JSON schema) | schema-valid output on a fixed adversarial schema set without retries; validation still runs | -| 8 | Compatibility edges: Lark custom tools or the function form of `apply_patch`, harmless-field policy (`service_tier`, `text.verbosity`), `reasoning.effort=minimal` | each Codex request shape from task 2 accepted or refused with a documented reason | -| 9 | Linux CI job for the default workspace (`cargo test`), fix the lock-inheritance flakes (serialize lock-holding tests or isolate them), clear the Clippy debt so `check-local.sh` is green | 10 consecutive green parallel runs; `check-local.sh` full exits 0 | -| 10 | Driver profile `cuda-13.2-linux` (595) and cuBLAS check in `doctor`; remove `DBG` `eprintln!` from the engine load path; telemetry per charter G10 | `doctor` fails on driver 580 and on missing `libcublas.so.12`; no stderr noise on a quiet load | diff --git a/docs/deploy.md b/docs/deploy.md deleted file mode 100644 index 44d30f6d..00000000 --- a/docs/deploy.md +++ /dev/null @@ -1,436 +0,0 @@ -# One-command deployment: `leleka up` - -**Windows 11:** `leleka.exe` (WSL2 bridge and native engine) is described in [`windows.md`](windows.md). - -Written 2026-10-17 on branch `claude/deploy`; sections 1 and 4 re-checked for release 0.1 on 2026-11-03 (the acceptance run on the 5090 is in `docs/release/5090-v0.1-checklist.md` section 7). This page describes the deployment -tool `leleka` (crate `crates/deploy`, no Python at run time), what it does, every flag, and what was and was not run to -check it. Results are in [section 10](#10-what-was-run-and-what-was-not); nothing here is a performance or model-quality -claim. Background: [`rust-runtime-run.md`](rust-runtime-run.md) (the processes), [`model-assets.md`](model-assets.md) (the model -commands `leleka` drives), [`laptop-profile.md`](laptop-profile.md), [`sm86-assets.md`](sm86-assets.md), -[`delivery-gap-audit.md`](delivery-gap-audit.md) section 5 (the packaging gaps this closes in part). - -## 1. Quickstart - -Server (Linux x86_64, NVIDIA driver >= 595, systemd), as root, from the unpacked release: - -```sh -tar -xJf leleka-VERSION-COMMIT12-5090-linux-x86_64.tar.xz && cd leleka-VERSION-COMMIT12-5090-linux-x86_64 -sudo ./install.sh --assets /data/leleka # preflight, fetch+verify, KAR archive, install, start, wait for ready -``` - -WSL2 laptop (RTX 3080 16 GB), as your user, in a terminal (WSL2 usually has no systemd): - -```sh -./install.sh --assets ~/leleka --foreground # keep the terminal open; Ctrl-C drains and stops -``` - -Both do the same thing, idempotently, and print the endpoint, model digest, GPU, the VRAM/RAM budget that was chosen, and the -log directory when the service answers `/ready`. Look first with `--dry-run`: it prints the preflight and the plan and changes nothing. - -```sh -./bin/leleka up --dry-run --assets /data/leleka -``` - -This is charter goal G2 (`PROJECT_CHARTER.md` section 6): one command, GPU and memory plan chosen automatically, external model volume, readiness only after the model is loaded, orderly stop and restart of the worker, no Python at run time. -Its acceptance test (a clean Linux GPU node, driver installed, one command, no re-download after a restart) has **not** been run; section 10 lists what was. - -Container: [section 7](#7-container-image). Build your own release: [section 8](#8-build-a-release-tarball). - -## 2. What `up` does - -| # | step | what happens | idempotency | -| --- | --- | --- | --- | -| 1 | preflight | driver >= 595, GPU architecture, VRAM free vs budget, RAM total/available, disk on each volume, WSL2 mounts, `libcublas.so.12`, `memfd_create`, ports, systemd, the six binaries | read-only; any FAIL stops before anything is changed | -| 2 | layout | state (0700), logs, run, stamps, assets | `mkdir -p` | -| 3 | binaries | copy `bin/*` to `PREFIX/bin`, SHA-256 checked against `MANIFEST.json` | skipped when identical; replaced by rename (safe for a running binary) | -| 3b | expert profile | the ranked VRAM expert tier's table `ASSETS/data/expert-profile.bin` (192 KiB, upstream Strata at the pinned commit): the upstream bytes are embedded in the `leleka` binary (`crates/deploy/data/expert-profile.bin`, MIT notice beside it) and written there on first start, so no network is needed; `--expert-profile-file PATH` installs your copy instead, and an https download from the pinned commit is only the fallback; SHA-256 `8f59b4aa...388975baf` is checked, the file is installed by rename, any other digest fails closed (a wrong file already there is moved aside, never deleted); `--no-expert-tier` is the explicit opt-out. Planned before the large downloads. `status`, `verify`, the ready summary and the supervisor log say `expert tier ON (sha256 ...)` or `WARNING expert tier OFF: reason` | skipped when the file has the pinned digest | -| 4 | cuBLAS 12 | uses what the host has; otherwise downloads the pinned NVIDIA 12.9.1.4 redistributable (SHA-256 pinned, resumable) into `PREFIX/lib/cublas` | skipped when `libcublas.so.12` and `libcublasLt.so.12` are found | -| 5 | secrets | two service tokens into `STATE/runtime.env` (0600), API key through `leleka-api api-key init` | never rotated; only missing/invalid ones are created | -| 6 | model | `leleka-api model fetch qwen-iq3-s` then `model verify` (resumable `.part` files, SHA-256) | stamped with size+mtime: skipped on re-runs unless `--reverify` | -| 7 | KAR archive | `leleka-api model ensure-sharded-streamed qwen-iq3-s --levels 2` (level 2, the pinned 55,295,529,472-byte archive + provenance) | stamped; also checks the length the engine admits | -| 8 | MTP pack | `ASSETS/data/mtp-rt` must exist; `--mtp-pack` imports it from a directory or tarball | skipped when present | -| 9 | tokenizer | `model extract-tokenizer` from shard 1 | skipped when present | -| 10 | config | `leleka.json`, `daemon.json`, `strata.json`, `profile.json`, `runtime.env` | rewritten only when the content changes | -| 11 | service | systemd unit (system or user), `daemon-reload`, `enable`; none in foreground mode | rewritten only when the content changes; a changed unit restarts a running service | -| 12 | start / ready | start the unit (or run the supervisor in this terminal), poll `/ready` with the key, print the summary | an already ready service is left alone | - -The archive step runs `ensure-sharded-streamed`, which fetches and verifies the shards itself, so on a first run step 6 is folded into -step 7 (the plan says so). The strict verification of an *existing* archive re-derives the 708 GB virtual F32 stream and is slow; a -machine that already holds the archive can pass `--trust-archive`: the archive is accepted when it has the pinned length and a -provenance file, and the engine checks its SHA-256 and every CRC against the pinned digest at each load anyway. - -A failed run is resumable: fix the cause and run the same command; finished steps are skipped (downloads continue from `.part`). - -## 3. The processes and files - -```text -leleka run (supervisor, the systemd ExecStart or your terminal) - |- seals the KAR archive into a memfd ONCE (memfd profile) -- or hands the engine a read-only file (file profile) - |- leleka-daemon gateway for the typed lifecycle, 127.0.0.1:18080 - |- leleka-inference engine, gRPC 127.0.0.1:18766 (started through `leleka exec-inherit`, which passes the sealed fd) - |- leleka-cli load-mtp qwen-iq3 qwen4exp-kar-ple-mtp-v1 -> wait for model_ready (the engine verifies shards + archive here) - `- leleka-api serve public API (Responses, Chat, Messages, tools, ...), 127.0.0.1:8081, bearer key -``` - -```text -PREFIX/bin/{leleka,leleka-api,leleka-inference,leleka-daemon,leleka-cli,leleka-seal-exec} PREFIX/lib/cublas/ -STATE/{leleka.json,daemon.json,strata.json,profile.json,runtime.env,api-key} STATE/{logs,run/status.json,stamps,mtp-staging} -ASSETS/model/*.gguf ASSETS/qwen-iq3-s-l2-v4.kar(.provenance.json) ASSETS/data/mtp-rt/ ASSETS/tokenizer-assets/ -``` - -Defaults: root gets `/opt/leleka`, `/var/lib/leleka/state`, `/var/lib/leleka/assets`; a user gets `~/.local/share/leleka`, -`~/.local/state/leleka`, `~/.local/share/leleka/assets`. Environment: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`. -**Put `--assets` on the big volume**: about 140 GB (shards 83.6 GB + archive 55.3 GB); the first run needs that plus slack. - -### The sealed KAR archive is made by the service - -The engine accepts the archive only as a sealed memfd (regular, unlinked, pinned length, `WRITE|GROW|SHRINK|SEAL`). Until now an operator -tool (`kar_holder.py` / `seal_exec.py`, outside the repository) did that. `leleka run` now does it natively: it copies the archive into a -sealed memfd once (the whole 55 GB, or for `rtx5090-32g` only the 16.0 GB extents the serve path reads; large O_DIRECT blocks on many threads, so the copy leaves nothing in the page cache), keeps the descriptor close-on-exec in the supervisor, and hands a duplicate -to each engine start through `leleka exec-inherit` (standard input in, a descriptor number >= 3 out). An engine restart therefore does -**not** copy 55 GB again, and the API, the gateway and the CLI never see the descriptor. `leleka-seal-exec` still ships for manual runs. -`--kar-fd N` (on `up` and `run`) reuses a descriptor inherited from a parent that already holds one (a holder, a test harness): no second copy, and its RAM is not demanded. - -The **file profile** (laptop) cannot afford 55 GB of shmem. `leleka-inference` gained `--kar-archive-file PATH --kar-provenance PATH` -(`InheritedKarArchive::open_read_only_file`, the form `docs/laptop-profile.md` measured in a bench): the archive stays an ordinary file; -it must be regular, single-link, owned by the service user and without write bits (`up` sets mode 0400). It is weaker than the seal (immutability rests on -the file system) and is selected only by that profile. The full SHA-256 and all CRCs are still checked at load. - -## 4. Memory profiles - -`--profile auto` (default) picks by the GPU `nvidia-smi` reports; `--profile NAME` or `--profile FILE.json` overrides it, and -`--gpu-budget-gib` / `--context-tokens` override single values. `leleka profiles` lists them, `leleka profiles show NAME` prints one to copy and edit. -The files live in [`deploy/rust-runtime/profiles/`](../deploy/rust-runtime/profiles/) and are embedded in the binary. - -| profile | selected for | GPU budget | context | KAR archive | routed experts | RAM floor (total / available at start) | other | -| --- | --- | --- | --- | --- | --- | --- | --- | -| `rtx5090-32g` | sm_12x, >= 30 GB VRAM | 32,819,404,800 B = 31,299 MiB (needs that much free at start: 31,299 of the 32,110 MiB an idle card reports; was 30 GiB, see [vram-footprint-5090](experiments/vram-footprint-5090.md)) | 262,144 | sealed **sparse** memfd (`memfd_extents: ple_only`): only the 16.0 GB of the archive the serve path reads (the PLE rows, 2 extents), holes elsewhere; read O_DIRECT, so no page-cache copy | `resident`: page-locked RAM copy (50.3 GB) | 100 GiB / 74 GB (113 GB for `memfd_extents: full`; 58 GB when `--kar-fd` supplies the archive) | one resident copy of every model byte in host RAM (`kar-sparse-memfd.md`) | -| `rtx3080-16g` | sm_80..119, 14-24 GB VRAM | 15 GiB (needs 14,500 MiB free; the `workstation` preset the owner runs lowers it to 13 GiB) | 262,144 (chunk and prefix-cache grid 6144, tail `prompt`) | read-only file | `mapped`: read-only mappings of shard 0 | 22 GiB / 10 GiB; advice `.wslconfig memory=40GB swap=8GB` | VRAM expert tier: `up` fetches `ASSETS/data/expert-profile.bin` (pinned SHA-256 `8f59b4aa...388975baf`; `--no-expert-tier` to run without); one `engine_env` pin (`LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no`); see the laptop paragraph below | -| `rtx5090-32g-file` (experimental, never auto-selected: `--profile rtx5090-32g-file`) | none (explicit name only) | as `rtx5090-32g` | 262,144 | read-only file (`kar_source: file`; no memfd, no holder; start reads about 1 MB of it when its verification stamp is current) | `resident` | 64 GiB / 62 GB (the 55 GB archive is page cache, not a charge) | as `rtx5090-32g` except an explicit `prefix_cache_mib` 6144; [`kar-file-source.md`](kar-file-source.md): what the file form reads, its integrity guarantees, the A/B (`scripts/e2e/decode/kar-file-ab.sh`, not run) | -| `rtx5090-32g-gguf-ple` (experimental A/B arm, never auto-selected: `--profile rtx5090-32g-gguf-ple`) | none (explicit name only) | as `rtx5090-32g` | 262,144 | **no KAR archive** (`kar_source: none`): not required, checked, sealed or passed; the engine loads `qwen4exp-native-mtp-v1` and reads the PLE rows from GGUF shard 1 (page cache, `LELEKA_PLE_DIRECT=0`) | `resident` | 64 GiB / 62 GB (the 28.8 GB PLE table is page cache) | as `rtx5090-32g` except an explicit `prefix_cache_mib` 6144, no memfd lock/heal; `--kar-fd` is refused; [`experiments/kar-off-ab-5090.md`](experiments/kar-off-ab-5090.md): the paired speed and quality A/B against `rtx5090-32g` (no claim before that page says so) | - -**Expert tier layout (owner decision 2026-11-12).** The three 5090 profiles (`rtx5090-32g`, `-file`, `-gguf-ple`) set `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no` (the VRAM tier is filled in global rank order, not with the same quota per layer) and `LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.65` (share of the misses that go over PCIe) as `engine_env` keys; both appear in the `engine environment` line of `leleka up` and in `leleka-serve meta: config` (`expert_per_layer=0`, `pcie_frac=0.65`). Paired 5-pair group A/B on release 02c784249a7e at the 256k configuration: decode +8.2 % (95% CI +6.5..+9.9), ms/round -7.2 %, minimum free VRAM 478 MiB, 0 OOM; it is a placement-class change (the CPU and the GPU round an expert differently), see `docs/experiments/step-ledger.md` H4. `rtx5090-32g-gguf-ple` differs from `rtx5090-32g` only in the PLE source (GGUF shard 1, 28.8 GB, page cache, instead of the KAR table of 16.0 GB): the routed experts (GGUF shard 0, IQ3_S, 2.047 MB each) and the PCIe traffic per round (at most 144 MB on this layout) are the same. The laptop profile `rtx3080-16g` is unchanged. To get the previous layout set `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes` and `LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45` in a copy of the profile (`--profile FILE.json`). - -**Route tail skip, LOSSY, on by default in the 5090 profiles (owner decision 2026-11-13).** The three 5090 profiles (`rtx5090-32g`, `-file`, `-gguf-ple`) set `LELEKA_ROUTE_TAIL_SKIP=7` and `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100` as `engine_env` keys (the only two `LELEKA_ROUTE_` keys the profile allow-list lets through, `crates/deploy/src/profile/profile_limits.rs`). Semantics: a missed expert (not in the VRAM tier) that every token of the verify window routes at rank 7 or lower is neither copied over PCIe nor computed on the CPU, and its weight is not renormalised, so THE OUTPUT CHANGES (the same shipped default as vanilla Strata 0.2.x, rank 7). The skip applies while less than `MAX_CACHED` percent of all experts are in VRAM (100: always, on this card the tier holds about 50 %). The engine says so in `engine.log`: `leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP=7, ...% of the experts in VRAM)`, and both keys are in the `engine environment` line of `leleka up`. Gate evidence (release 83bdd85bb482, real Codex CLI, 3 repetitions per arm, `docs/experiments/codex-compare-speed-gap.md` "Lever 7 gate"): CRM decode 211.0 tok/s against 184.2 (+14.5 %), CRM wall -15 %, CRM rounds -11 %, ttt decode 202.6 against 181.7 (+11.5 %), ttt rounds +39 % (one 49-round session, the median equals the baseline), relaxed CRM acceptance 56/56, 56/56, 55/56, ttt 14/14 x 3; logit gate 3.6 % argmax flips against the Original's own envelope of 2.8 %. The gate was assessed and its open points (the logit envelope 3.6 % against 2.8 %, the ttt round growth, n = 3) were overridden explicitly by the owner on 2026-11-13; this is the one recorded exception to the rule "no lossy default before its quality gate passes" (`AGENTS.md`), logged as row H9 of `docs/experiments/step-ledger.md` and in plan stage 6f. Confirmation on the package built from main 945fc44f32fb with the default profile and no shell exports (3 CRM + 3 ttt): CRM decode 214.2 tok/s, wall 406.8 s, accepted 56/56 x3 under the relaxed and 55/56 x3 under the strict checker; ttt decode 211.2 tok/s, 14/14 x3 (`docs/experiments/codex-compare-speed-gap.md`, "Lever 7 as the 5090 default"). The laptop profile `rtx3080-16g` is unchanged (tail skip off). To turn it off set `LELEKA_ROUTE_TAIL_SKIP=0` (in a copy of the profile, `--profile FILE.json`, or as an operator `engine_env` value) or remove the key. - -**Tier swap bursts, on by default in the 5090 profiles (owner decision 2026-11-13, placement class).** The three 5090 profiles (`rtx5090-32g`, `-file`, `-gguf-ple`) set `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2` and `LELEKA_ORIGINAL_SERVE_ADAPT_SWAPS=48` as `engine_env` keys (both under the allowed `LELEKA_ORIGINAL_SERVE_` prefix); both appear in the `engine environment` line of `leleka up`. What it does: the adaptive expert tier swaps up to 48 experts every 2 rounds instead of up to 96 every 4 rounds (the engine's own defaults, `ADAPT_EVERY` 4 and `ADAPT_SWAPS` 96 when the keys are absent): the same swap throughput per round in bursts of about 1.65 ms that fit under the draft chain, so the host waits less for the copies. Evidence (stage 6c, release 83bdd85bb482, 67k replay, `docs/experiments/host-round.md` sections 5 and 6): swap wait (`round.apply_pending`) 0.351 -> 0.098 ms per round, paired decode +1.53 % (95% CI +0.26..+2.79, 3 blocks). Quality gate: it is a placement-class change (which experts sit in VRAM), judged by the control-relative rule of H4 on the teacher-forced 256k session. Against the worst of three ordinary controls (PCIe share 0.35 / 0.55 / 0.75) it passes: limits p99 0.2745, max 1.027, flips 2.31 %; variant 0.1915 / 0.796 / 1.73 %. It did NOT pass against the single 0.55 control alone (max 0.796 against 0.497); the owner accepted this explicitly (judged against the worst ordinary control, as for the PCIe 0.65 default). The tier cadence allocates no VRAM, so the 256k free-VRAM floor of H4 does not apply. The laptop profile `rtx3080-16g` is unchanged. To turn it off set `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=4` and `LELEKA_ORIGINAL_SERVE_ADAPT_SWAPS=96` (the previous defaults, in a copy of the profile with `--profile FILE.json`, or as operator `engine_env` values) or remove both keys. Row H4 and the 6c paragraph of `docs/experiments/step-ledger.md` record the decision. - -**The laptop profile `rtx3080-16g` and the 5090 defaults (audit 2026-11-13, `docs/laptop-profile.md` "Update 2026-11-13").** None of the 5090 `engine_env` defaults is copied to the 3080 laptop except a pin of the expert tier layout, `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no` (the engine's own default, global rank fill). Not applied: `PCIE_FRAC=0.65` (a pageable mapped bank pays more for PCIe copies than the CPU pool does: measured 25-29 % slower on this laptop with a share set), the swap bursts and `PLE_ON_CHAIN` (their gain is 0.1-0.25 ms of a 18 ms 5090 round; the laptop round is 130-240 ms), and every `LELEKA_SM120_*` / `LELEKA_DRAFT_FUSED_COMMIT` switch (inert below compute capability 12: `Sm120Switches::resolve`). `LELEKA_DRAFT_CHECK_MERGE` and `LELEKA_SM120_ATTN_DAILY_MTP` are not gated by the card and have no sm_86 companion PTX, so `Profile::validate` refuses them in a profile whose card window ends below sm_120. The LOSSY route tail skip is an opt-in for the laptop (copy the profile, add `LELEKA_ROUTE_TAIL_SKIP=7` and `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100`, pass `--profile FILE`); there is no quality gate for the laptop's small tier and it is not in the shipped profile. Under WSL2 the planner now caps the CPU expert workers at the physical cores minus one (7 on the i9-11900H, as on native Windows; it was 12 under `workstation`). - -Both profiles also carry a `memory` section (prefix cache `auto`, soft/hard floors 4096/2048 MiB, reserve, lock and heal of the sealed memfd): the engine sizes its caches from the memory left after the fixed footprint, sheds and refuses under pressure, and refuses to start with numbers when the footprint does not fit ([`memory-safety.md`](memory-safety.md)). The unit sets `LimitMEMLOCK=infinity`, which is what lets the lock keep the 55 GB memfd out of swap. - -Both profiles run `--backend-mode original` and the level-2 archive; the routed-expert bank must be admitted before the Original stack opens, which `leleka-inference` now does from `--expert-source resident|mapped` (see section 10, finding 1). They select documented switches only (budget, context, archive form, the -`LELEKA_ORIGINAL_SERVE_*` environment); they are **not** tuned, not quality-gated and carry no speed claim. A GPU that fits neither -(a 24 GB 4090, say) gets an error that names the way out: write a profile file. Fields: see `crates/deploy/src/profile.rs` -(`gpu_budget_bytes`, `context_tokens`, `prefill_capacity`, `kv`, `kv_resident`, `prompt_cache`, `kar_source`, `min_*`, `engine_env` -restricted to `LELEKA_ORIGINAL_SERVE_*`, `LELEKA_SM120_*` and `LELEKA_CHAIN`, plus the two exact keys `LELEKA_ROUTE_TAIL_SKIP` and `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED`); unknown fields are refused. - -One binary serves both architectures: the sealed sm_120 PTX is used as is on Blackwell, and the build with `--features sm86` -(every release) swaps in the sm_86 companion PTX on 8.6 <= cc < 12.0 cards ([`sm86-assets.md`](sm86-assets.md)). Preflight reads `MANIFEST.json` and refuses a -binary built without `sm86` on such a card. All PTX is embedded in the binaries (the release also ships the files and a `SHA256SUMS` for audit). - -## 4b. Resource presets - -`leleka up` computes what the runtime takes of the host (`crates/deploy/src/resources.rs`, a pure function of the probed host facts and the profile), prints it, and bakes it into `leleka.json` (the profile's budget and floors, and `LELEKA_ORIGINAL_SERVE_CPU_WORKERS`). Two presets: - -| | `dedicated` (default) | `workstation` | -| --- | --- | --- | -| purpose | the host belongs to the runtime | Docker, agents and the IDE share the machine | -| CPU expert workers | `min(cores - 2, 15)` | `min(cores - leave, 15)`, leave 4 cores (8 above 16 cores) | -| host RAM kept free | the profile's governor floors (server: soft 4 GiB, hard 2 GiB) | soft floor 8 / 12 / 16 GiB (hosts under 32 / under 64 / from 64 GiB RAM), hard floor half of it; the profile's floors are only raised. The governor sheds the prefix cache first, then refuses new requests with 503 `memory_pressure` | -| VRAM | the profile budget | `min(profile, free - 2 GiB)` rounded down to GiB; the expert tier is sized from what remains | - -The native expert pool takes at most 15 workers. **Measured cost of the preset on the 5090** (job 9p0, tic-tac-toe replay, 16 requests, 2 repeats, fixed window): default (30 GiB, 15 workers) 139.8 tok/s; 8 workers alone 136.4 (-2.4 %); 8 workers and a 27 GiB budget 119.6 (-14.5 %). **Host RAM of the server profile (live check plat-reconf-live):** the 121 GiB server holds the 51.5 GiB sealed archive and an engine with a fixed footprint of 53.5 GiB (the page-locked copy of the routed experts and the pools), which leaves 12-13 GiB available while it runs. The `workstation` preset asks the governor for 16 GiB plus its 2 GiB reserve, so on that host it is not reachable in the resident form: the planner now says so (and `leleka up` falls back to the mapped form, `leleka reconfigure --preset workstation` refuses and points to `leleka up`). A host with 192 GiB or more has room for it. The VRAM taken from the expert tier is what costs (about 4 % per GiB), so the workstation margin is 2 GiB, not more, and the workers are capped at 15 rather than 8. If the workstation target cannot be met (less than half of the profile's VRAM budget would remain) the preflight fails with the numbers; a RAM shortfall does not fail: when the pinned form (sealed archive plus engine, about 58 GiB on the server) would leave less than the free target, `up` switches the profile to the mapped form of the laptop profile: the archive stays a read-only file and the experts are memory-mapped from SSD/HDD, with `available - target - 8 GiB` of experts page-locked (`resident_budget_gib`, 0 on a small host). It prints a warning, because decode is slower than with everything in RAM. The same fallback applies to `dedicated` when the host cannot hold the pinned form at all. `--gpu-budget-gib` and explicit profile fields win over the preset. - -## 4c. What the runtime reports (`leleka status`) - -The engine samples itself once a second and records every request (`crates/leleka-memory/src/telemetry.rs`). The document travels -gRPC `Snapshot.telemetry_json` -> the gateway -> `GET /v1/status` `machine` -> `leleka status` (also `--json`): - -| block | figures | -| --- | --- | -| `gpu` | utilisation %, memory-bus %, VRAM used/total, power, SM clock, temperature, board name (NVML, loaded with `dlopen`; where `libnvidia-ml` cannot be loaded, WSL2 and containers, the engine polls `nvidia-smi` instead, at most every 2 s; absent when neither exists) | -| `ram` | host total/available, engine resident and pinned, swap in use | -| `cpu` | engine CPU in busy cores (of the cores this process may use), whole-system busy % | -| `throughput` | prefill tok/s (last request, running average, lifetime) and decode tok/s (same, plus the live rate of the request in flight) | -| `cache` | requests and how many reused a checkpoint, prompt tokens reused of all, the last request's reused/prompt tokens | -| `context` | tokens live in the session, the configured maximum, percent used; `phase` idle/prefill/decode; `request` (prompt and generated tokens, seconds) while one runs | - -Prefill rate counts the tokens actually prefilled (prompt minus reused). Rates are `null` until a request has been measured. - -## 4d. Changing the runtime settings (`leleka reconfigure`) - -The engine can be re-initialised while it runs: it closes its serve stack and opens a new one with other settings, **without reloading the -weights, the CUDA context or the sealed archive** (**7 s** on the 5090 instead of the 3-5 minute start, live job 9r1). The call waits for the request in flight; requests that arrive meanwhile wait in the -gateway queue. If the new stack cannot open (for example the VRAM -does not hold a larger context) the previous settings are reopened and the call answers `reconfigure refused: ...; the previous settings are back`. - -```sh -leleka reconfigure --context-tokens 131072 --prefix-cache-mib 20480 --prefix-cache-tail reply --cpu-workers 8 -leleka status # prints "settings in force" with the engine telemetry -``` - -| setting | meaning | note | -| --- | --- | --- | -| `--context-tokens N` | context length (prompt plus output of one request) | 1..262144; bounded by the VRAM left for the K/V window | -| `--prefill-capacity N` | prefill chunk (256 ... 8192) | 8192 prefills a cold 100k prompt about twice as fast as 2048; takes VRAM from the expert cache. The `rtx5090-32g` profile ships 8192 (with `--prefix-cache-block 8192`): 256k session TTFT sum 131 s at 2048 against 55-60 s | -| `--kv-resident N` | K/V cells per layer kept in VRAM | fixed for the life of the process: only the value in force is accepted (a different one needs a restart; 9r1 showed the engine refuses it) | -| `--prefix-cache-mib auto\|off\|N` | host-RAM budget of the cross-session prefix cache | `off` drops the cache | -| `--prefix-cache-tail off\|prompt\|reply` | request-end checkpoints | `docs/prefix-cache.md` | -| `--prefix-cache-block N`, `--prefix-retention-min N` | block / grid size, minutes an idle session is kept | | -| `--cpu-workers N` | CPU expert workers (1..=15, the native pool's limit; the engine default is 15) | the resources the engine takes on the host | -| `--spec-min-p P` | draft-probability floor | | - -The same call is `POST /v1/reconfigure` with the JSON document (`{"context_tokens": 131072, ...}`; same bearer key; the answer carries the -effective settings) and gRPC `Runtime.Reconfigure`. The prefix cache is rebuilt empty (its host images belong to the old stack), so the -next request of every session reads its prompt again once. - -**Keeping a change (`--persist`).** Without it a change lasts until the service restarts. With `--persist` the supervisor also writes the -result into `STATE/leleka.json` (profile fields: `context_tokens`, `prefill_capacity`, `kv_resident`, `spec_min_p`, -`memory.prefix_cache_{mib,tail,block}`, `memory.prefix_retention_min`, and `engine_env.LELEKA_ORIGINAL_SERVE_CPU_WORKERS` for the workers) and -regenerates `strata.json`, so a restart of the service, and a restart of a crashed engine, start with the new numbers. The file written is the -configuration in force, so a change made earlier without `--persist` in the same service life is written with it. With no supervisor running -the file is edited directly. - -**Budget and preset: restart in place.** The VRAM budget and the resource preset are fixed when the CUDA context is created, so the running -engine cannot reopen them. `leleka reconfigure --gpu-budget-gib 24 --preset workstation` (either alone, plus any runtime settings and -`--persist`) hands the request to the supervisor (a small file in `STATE/run/`, answered in `reconfigure-result.json`), which - -1. checks it with the resource planner (`resources.rs`) without disturbing the service, and refuses what cannot work even with the engine gone - (a budget above the card, the workstation preset on a card that is mostly taken, an explicit budget the preset cannot give, an invalid - runtime setting, a host too small to keep the sealed archive and the preset's free memory at once); -2. stops the engine process (SIGINT, then SIGKILL after the grace period) and checks again against what the host really has free; -3. starts the engine again with the new numbers (`--gpu-budget`, the preset's CPU workers and RAM floors, the runtime settings), handing it the - sealed archive descriptor the supervisor still holds (no second 55 GB copy, no second hash: the first engine already verified this memfd), - and loads the model (minutes); -4. keeps the gateway and the API in their processes and on their ports; requests that arrive during the restart see `/ready` 503. With - `--persist` and a new context the API process is restarted too (seconds), because `strata.json` carries the context it advertises. - -If the planner refuses after the stop, or the new engine does not come up, the previous settings are started again and the call answers -`... ; the previous settings are back` with a non-zero exit. A request that equals what is in force is answered at once. A planned restart does -not count against the crash-restart limit. The planner needs the supervisor to hold the archive (`kar_source: memfd`) and refuses a plan that -would switch the installation to the file-backed form: `leleka up` decides that. Going back from `workstation` to `dedicated` restores the -profile as `up` resolved it (`base_profile` in `leleka.json`, written since this feature; an older file can leave `workstation` only through -`leleka up --preset dedicated`). - -## 5. Flags - -`leleka up [OPTIONS]` (also accepted by `preflight`, `status`, `down`): - -| flag | meaning | -| --- | --- | -| `--dry-run` | print preflight and plan (and the exact engine command); change nothing; exit 1 if a check fails or a step is blocked | -| `--json` | machine-readable plan / summary on stdout (logs stay on stderr) | -| `--profile auto\|NAME\|FILE` | memory profile | -| `--gpu N` | CUDA device ordinal (default 0) | -| `--assets DIR` `--state-dir DIR` `--prefix DIR` | the three roots (section 3) | -| `--bin-src DIR` | where the six binaries come from (default: the directory of `leleka`, i.e. the release `bin/`) | -| `--mode auto\|system\|user\|foreground\|none`, `--foreground` | `auto`: root with systemd -> system unit; a user with a systemd user session -> user unit; otherwise foreground. `none` prepares and starts nothing | -| `--service-user NAME` | system unit only: the account the service runs as (default `leleka`, created with `useradd --system`; state and assets are chowned to it) | -| `--api-port` `--engine-port` `--daemon-port` | ports (defaults 8081, 18766, 18080) | -| `--api-bind IP` | API listen address, default `127.0.0.1`; `0.0.0.0` only inside a container whose port is published to the host's loopback or tunnelled (the bearer key is the only protection, no TLS). The engine and gateway are always loopback | -| `--preset dedicated\|workstation` | how much of the host the engine takes (env `LELEKA_PRESET`, section 4b; recorded in `leleka.json`) | -| `--gpu-budget-gib N` `--context-tokens N` | override one profile value | -| `--no-fetch` | never download or build; require verified files to exist | -| `--reverify` | ignore the stamps and hash everything again | -| `--trust-archive` | accept an existing pinned-length archive + provenance without the strict re-derivation (section 2) | -| `--mtp-pack PATH` | import the MTP pack (directory or `.tar/.tar.gz/.tgz/.tar.xz`, sub-directories searched) | -| `--expert-profile-file PATH` / `--no-expert-tier` | install the ranked expert table from this copy of the upstream `data/expert-profile.bin` instead of the embedded one (the pinned digest is still required) / run without the VRAM expert tier (much slower; reported as OFF) | -| `--cublas-dir DIR` / `--no-install-cublas` | use this CUDA 12 cuBLAS / fail instead of downloading it | -| `--kar-fd N` | an already sealed archive descriptor inherited from the parent (foreground or `--mode none` only) | -| `--timeout-s N` | wait this long for `/ready` (default 3600) | - -Other commands: `leleka verify` (full parallel hash of shards and archive, renews the stamps; section 6b), `leleka preflight` (checks only, exit 1 on FAIL), `leleka status` (cheap: no GPU probe; exit 0 only when ready; this is the container health check), -`leleka down` (stop the systemd unit), `leleka run --config STATE/leleka.json [--kar-fd N]` (the supervisor), `leleka profiles [show NAME]`. -`HF_TOKEN` in the environment is used only by `model fetch`, is sent only to `https://huggingface.co`, is removed from every child the supervisor starts, and is never printed or written. - -## 6. Operating it - -* systemd: `systemctl status leleka`, `journalctl -u leleka -f` (user unit: add `--user`; run `loginctl enable-linger USER` to start without a login). The unit has - `Restart=on-failure` with `RestartSec=30` growing to 10 minutes (`RestartSteps`), no start limit, and no restart after exit code 2 (configuration). The unattended - server setup (hardened unit, install script, lab mode) is in [`unattended.md`](unattended.md). -* The supervisor restarts a dead engine with the same sealed descriptor and loads the model again, waiting 5 s, 10 s, 20 s ... (at most 300 s) between attempts; - a start that fails counts as an attempt; after 6 in a row (the counter resets after 10 ready minutes) it exits 1 and systemd starts everything afresh. A hung engine is - found by the health check (`GET /metrics` every 10 s) and killed; see `unattended.md` section 5. The API process stays up and answers not-ready meanwhile. - A dead gateway (3) or API (5) is restarted too. -* `SIGTERM`/`SIGINT` drain: the API first (`shutdown_grace_s` 10), then the gateway and the engine (both handle SIGINT only, so the supervisor sends SIGINT), then SIGKILL after the grace. -* Logs: `STATE/logs/{leleka,engine,gateway,api,install}.log`; the supervisor copy-truncates any log past 16 MiB every 10 s and keeps 3 generations (`logs` in `leleka.json`). - Status: `STATE/run/status.json` (`phase`: sealing, starting_engine, loading, starting_api, ready, engine_restarting, draining, stopped, failed; also uptime, restarts and - their reason, the health judgement, log volume; rewritten every 30 s). `leleka status` renders it, `leleka verify --quick` checks the installation without reading the model. -* Use it: `curl -H "Authorization: Bearer $(cat STATE/api-key)" -H 'content-type: application/json' -d '{"model":"qwen-iq3","input":"hello","max_output_tokens":32}' http://127.0.0.1:8081/v1/responses`. - Remote clients: an SSH tunnel. Known limits of this API-over-engine path (4096 output tokens, 256 generations per engine epoch, no image input) are in [`api-over-rust-engine.md`](api-over-rust-engine.md). - -## 6b. Fast restarts: where a cold start went and what was changed - -A start used to hash 83.6 GB of shards and the 55 GB archive one after the other, each in a single thread that alternated -`read` and `update` (laptop, cold: shard 0 115-134 s, shard 1 64-96 s, archive 95-181 s; 265-400 s in all, 100-215 s of it system time in -`read`). Every engine now prints `leleka-load-time phase=... seconds=... total=...` lines on stderr (`STATE/logs/engine.log`), and -`leleka-inference --verify-only` runs just the source verification (no CUDA) so that phase can be measured anywhere. - -| change | where | effect | -| --- | --- | --- | -| shard 0, shard 1 and the archive are verified at the same time | `backend.rs` `verify_sources_parallel`; refusals consumed in the old order (shard 0, shard 1, binding) | wall = the slowest file, not the sum | -| a reader thread keeps 6 x 8 MiB chunks ahead of the hasher (`pread`, `FADV_SEQUENTIAL`, recycled buffers) | `model-format/src/readahead.rs`, used by `VerifiedGgufFile::open` and the archive scan | I/O and hashing overlap | -| archive scan: SHA-256 on one thread, per-section CRC-32 on another | `kar.rs` `verify_integrity_pipelined`; same verdicts and precedence (SHA mismatch before CRC failure), tested against the stream scan | the 55 GB pass costs the slower of the two | -| **verification stamps**: a file that matched its pinned digest and is unchanged (device, inode, size, mtime, **ctime**) is not hashed again | `model-format/src/verify_stamp.rs`, `leleka-inference --verify-stamps DIR` (the supervisor passes `STATE/stamps/engine`) | a restart hashes nothing that did not change | -| the supervisor copies the archive into the memfd with 32 threads reading 8 MiB `O_DIRECT` blocks (`model-format/src/bulk_read.rs`) and checks that the source did not change while it was copied | `sealed.rs` `seal_file_report` | 55 GB cold in 153 s on the 5090 server instead of 6-33 min (`unattended.md` section 4) | -| a sealed memfd that this supervisor already had verified (an earlier engine) or that was copied from a file whose `kar-source` stamp matched is not hashed again: `--kar-attested-by-stamp` | `supervisor.rs`, `verify_stamp::set_attested_archive` | engine restarts and service restarts skip the 55 GB hash | -| on the first start, a CPU-only `--verify-only` hashes the shards while the supervisor fills the memfd | `supervisor.rs` `spawn_shard_preverify` | the two big reads overlap | -| `leleka verify` | `app.rs` | hashes shards and archive in full, in parallel, renews every stamp | - -Stamp rules (fail closed). A stamp is one line per (kind, pinned digest) in a directory that must be owned by the service account and closed to -group and others; any difference in any field, an unreadable, malformed or extra-long stamp, a symlink, or a stamp directory that is not private means -"hash in full". `ctime` changes on every write, truncate, chmod, chown and rename and cannot be set from user space, so a rewritten file does not match even -when its `mtime` is restored (unit-tested). A stamp is recorded only if the file's identity is the same before and after the full hash, and it is keyed by the pinned -digest, so it never replaces the pin. A changed file is hashed in full and refused if it no longer matches. What a stamp cannot defend against is someone who can write both the stamp -directory and the model file as the service account; that account also owns the archive the engine maps. `--verify-rehash` / `leleka verify` ignore existing stamps; `"verify_stamps": false` in -`STATE/leleka.json` turns the whole mechanism off (every start hashes everything, in parallel). - -Measured so far (CPU-only `--verify-only`, laptop i9-11900H, WSL2 ext4, shards and archive evicted from the guest page cache first; the host may still cache the virtual disk): - -| run | shard 0 | shard 1 | archive | wall | -| --- | --- | --- | --- | --- | -| before: sequential, `read` + `update` in one thread | 115 s | 64 s | 95 s | 265 s (a first run with a colder host cache: 400 s) | -| after: parallel + read-ahead, no stamps | 74 s | 57 s | 74 s | 72 s | -| after: parallel, second sample (warmer host cache) | 47 s | 28 s | 47 s | 45-51 s | -| after: stamps current | 0.02 s | 0.01 s | 0.00 s | 0.02 s | - -The laptop reads at about 1 GB/s at best; the 5090 server numbers are in the holder jobs `9g1`-`9g6` (section 10). - -## 7. Container image - -[`deploy/Containerfile.rust-runtime`](../deploy/Containerfile.rust-runtime): Ubuntu 24.04 (glibc 2.39, the floor of the binaries) + the six binaries + cuBLAS 12.9.1.4 -(downloaded by BuildKit with `ADD --checksum`, only `libcublas.so.12*` and `libcublasLt.so.12*` kept) + the manifest/provenance. The sealed PTX is inside the binaries; `ldd` shows only libc, libm -and libgcc_s, and the engine `dlopen`s `libcuda.so.1` (injected by the NVIDIA Container Toolkit) and `libcublas.so.12`. Not in the image, by design: the model, the driver, any secret. Non-root (uid 10001), volumes `/models` and `/state`, -`HEALTHCHECK` = `leleka status`. - -```sh -tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64 -docker build -f /path/to/repo/deploy/Containerfile.rust-runtime --build-arg VERSION=VERSION -t leleka-runtime:VERSION . -# pin the base for a release: docker buildx imagetools inspect ubuntu:24.04 then --build-arg BASE=ubuntu:24.04@sha256:... - -docker run -d --name leleka --gpus all --restart unless-stopped \ - -v /data/leleka-models:/models -v leleka-state:/state -p 127.0.0.1:8081:8081 \ - leleka-runtime:VERSION # default command: up --foreground --no-install-cublas --api-bind 0.0.0.0 -docker logs -f leleka # first start: hours (download, verification, archive build); later starts: minutes -docker exec leleka cat /state/api-key -``` - -The memfd profile needs the host to give the container ~60 GB of RAM (no `--memory` below that; memfd is shmem charged to the container, not limited by `--shm-size`). Docker's default seccomp -profile allows `memfd_create`. Build is not run in CI; see section 10 for what was checked. - -## 8. Build a release tarball - -On Linux/WSL, from a tree with the toolchain pinned by `rust-toolchain.toml` (no CUDA toolkit is needed; the PTX is checked in): - -```sh -cargo build --release --locked -p leleka-engine-host --features sm86 \ - --bin leleka-inference --bin leleka-daemon --bin leleka-cli --bin leleka-seal-exec -cargo build --release --locked -p leleka-control-plane --bin leleka-api -cargo build --release --locked -p leleka-deploy --bin leleka - -# provenance is made where git exists (an exported tree has no .git); the tree must be clean or --allow-dirty marks it -python3 scripts/package-release.py provenance --repo . --out provenance.json -python3 scripts/package-release.py package --repo . --target-dir target --provenance provenance.json --out dist -``` - -`dist/leleka-VERSION-COMMIT12-linux-x86_64.tar.xz` (+ `.sha256`) contains `bin/` (six binaries), `share/leleka/ptx/{sm_120,sm_86}` (the sealed PTX and `SHA256SUMS`), `share/leleka/{profiles,templates,docs}`, -`MANIFEST.json` (version, commit, `features`, SHA-256 of every binary, rustc/glibc of the builder), `PROVENANCE.json`, `SHA256SUMS` for every file, and `install.sh`. `--no-ptx` omits the PTX files (they are embedded anyway); -`--with-cublas DIR` bundles cuBLAS (NVIDIA's redistribution terms apply). -`PROVENANCE.json` records the git commit, whether the tree was dirty (and a digest of the diff), the `Cargo.lock` digest, and for `engine/strata`: the upstream URL and commit from [`upstream.md`](upstream.md), -the subtree tree id, the import commit, every later commit touching the subtree, and the diff since import (shortstat + digest). The diff against the upstream tree itself is computed only when the upstream commit is present -in the repository (`git fetch strata-upstream`); otherwise the record says so. `engine/strata` is not modified by this work. - -## 9. Troubleshooting - -| message (preflight / run) | cause and fix | -| --- | --- | -| `NVIDIA GPU: nvidia-smi was not found` | no driver. Linux: install the NVIDIA driver >= 595. WSL2: install the Windows driver (never a Linux driver inside WSL), `wsl --shutdown`, retry | -| `driver version: 580.x is older than 595` | the sealed PTX needs ISA 9.2 (CUDA 13.2): update the driver | -| `GPU memory: N MiB free but the engine needs M MiB` | another process holds VRAM (`nvidia-smi`); stop it or lower `--gpu-budget-gib` | -| `architecture: ... built WITHOUT the sm86 feature` | an RTX 30-series card needs a release made with `--features sm86` | -| `memory: ... available is below ...` | the sealed archive copy needs the whole 55 GB in RAM. Free memory, or use the file profile if the GPU fits it. On WSL2 put `[wsl2] memory=32GB swap=8GB` in `%UserProfile%\.wslconfig` and `wsl --shutdown` | -| `WSL2 file system: ... is on a Windows/network mount` | `/mnt/c` is 9p: far too slow for mapped reads. Use a path on the WSL ext4 disk | -| `cuBLAS 12: libcublas.so.12 ... not found` | let `up` download the pinned 12.9.1.4 (needs curl or wget, tar, xz), or `--cublas-dir DIR`, or `apt install libcublas12` | -| `disk space: assets ...: N GiB free, M needed` | nothing was downloaded yet; point `--assets` at a larger volume | -| `loopback ports: already in use` | another listener; `--api-port` / `--engine-port` / `--daemon-port` | -| `permission denied` on `/dev/nvidia*` in the system unit | the device nodes are not world-accessible: add the service user to the `video` (or `render`) group and restart the unit | -| `systemd: not running` | WSL2 without systemd or a container: `--foreground`, or enable systemd in `/etc/wsl.conf` | -| `step mtp-pack is blocked` | the MTP pack has no automated producer yet; copy `data/mtp-rt` from a machine that has it (`--mtp-pack` takes a directory or tarball) | -| `... has N bytes but the engine only admits the pinned 55295529472-byte level-2 archive` | the archive was built with another level or policy; the engine would refuse it. Rebuild with `--levels 2` | -| `step model failed: ... 401/403` | the repository needs a token: `export HF_TOKEN=...` (sent only to huggingface.co) | -| `load-mtp was refused` | read `STATE/logs/engine.log` (the engine prints a fixed code, never a path or a secret) | -| `the model was not ready within 1800 s` | the engine verifies 84 GB of shards and 55 GB of archive at load; a cold disk can need longer: raise `load_timeout_s` in `STATE/leleka.json` | -| a stale `Another supervisor is running for ...` | `leleka down` (systemd) or stop the other process; `STATE/run/status.json` names its pid | - -## 10. What was run and what was not - -All of this is bring-up evidence, not a performance or quality result: no paired A/B, one request, no token statistics beyond what is quoted. - -### Findings that the real run produced - -1. **The production `Load` of the Original path could not succeed.** `leleka-inference ... --backend-mode original` never admitted a routed-expert bank - (the serve smokes call `load_resident_expert_source()` themselves; `backend.rs` did that only for the `--experimental-optimized-*` modes), so the first real `load-mtp` - through the daemon failed in `OriginalServeStack::open` with `MoeWeightCache::new_original_prompt_arena: InputRead` (`leleka-load phase=OriginalStack class=BackendUnavailable` in - `engine.log`) and the engine process stayed up. Fixed here: `OriginalServeOptions.expert_source` and `--expert-source resident|mapped` (default `resident`, the smoke form); - `backend.rs` admits the chosen bank before the driver, as it does for the optimized modes. The profile files select `resident` (server) and `mapped` (laptop). -2. **The supervisor waited out the load timeout for a refused load.** The engine does not exit on a failed load; `leleka` now reads the operation record - (`leleka-cli operation`, state FAILED/INDETERMINATE) and stops with the last lines of `engine.log`. -3. `leleka-inference` had no way to take the archive as a read-only file (only the 55 GB sealed memfd); `--kar-archive-file` is new and was exercised on the laptop. - -### Real runs - -| where | what | result | -| --- | --- | --- | -| WSL2 laptop, RTX 3080 Laptop 16 GB, driver 617.42, Ubuntu 24.04 with systemd, RAM 40 GB (`.wslconfig`) | `leleka up` from the unpacked release (commit `e03d97d`, 30.7 MB tarball, sm86 build), user unit, real shards and archive (copied to the WSL ext4 disk), profile `rtx3080-16g` chosen by `auto` | preflight 13 ok / 1 warning (cuBLAS missing); cuBLAS 12.9.1.4 unpacked from the pinned archive (SHA-256 checked; **the download itself was not exercised**: the archive was placed in `PREFIX/lib` beforehand); fetch + verify of the real shards about 3 min (hash reuse, no download); tokens, configs, tokenizer, `systemctl --user enable/start`; **model loaded in 198 s, `/ready` 200**; one `POST /v1/responses` (59 input tokens, 16 output tokens, 21.4 s wall, stopped by `max_output_tokens`, text is the model's reasoning preamble) | -| same | peak during that request | VRAM 13,971 MiB; engine RSS 26.4 GB (anon 2.6, file-backed 19.9, shmem 4.0); the engine log shows 3,133 VRAM expert slots (the expert tier was on because `expert-profile.bin` had the pinned digest) | -| same | idempotence | a second `up` against the running service: 0.27 s, same systemd `MainPID`, every step `done`; `leleka down`: 1.9 s, no process left, VRAM back to 0 | -| same | engine killed with `kill -9` | phase `engine_restarting`, `/ready` false, the engine restarted and reloaded: ready again 293 s after the kill (load 286 s), restart counter 1, gateway and API processes unchanged, one request served afterwards | -| RTX 5090 server (Ubuntu 26.04, driver 595.99.02, 121 GB RAM) | `leleka up --dry-run` with the real assets and the real preflight | 12 checks ok; the plan names the exact engine command; nothing created. The real-model jobs `930-deploy-prepare.sh` and `931-deploy-serve.sh` are in the holder queue (they inherit the holder's sealed descriptor with `--kar-fd`); see "Server job" below for their state | - -### Tests (no GPU, no model) - -* `cargo test -p leleka-deploy --features test-fakes` (71 unit, 11 end-to-end, 4 recipe tests, all passing in WSL): unit tests (profiles, facts parsers, preflight on synthetic hosts - server, laptop under default WSL2 memory, old driver, busy GPU, - no cuBLAS, full disk, `/mnt/c`, no systemd -, plan, units, CLI, sealed memfd, stamps, HTTP), `tests/e2e.rs` against a test double of the five programs - (supervisor lifecycle with an inherited sealed descriptor and with a read-only file: ready, SIGKILL of the engine -> restart with API/gateway unchanged -> SIGTERM drain with every child gone; - an engine that cannot start; a refused load fails fast; weak tokens are exit code 2; `up` is idempotent, resumable after a deleted archive, never rotates secrets, `--trust-archive`, wrong-size archive refused; - `--dry-run` creates nothing; a failing preflight changes nothing), `tests/recipe.rs` (the Containerfile is non-root, has a health check, copies no model or secret; the cuBLAS pin agrees in three places; `install.sh` verifies before it runs). - `cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` are clean. -* `cargo test -p leleka-engine-host --bin leleka-inference` (14 argument-parsing tests, including `--kar-archive-file` and `--expert-source`). -* Linux only for the process tests; the portable parts also run on Windows (`cargo test -p leleka-deploy`), where the POSIX-path tests are not meaningful. - -### Not done / open - -* **No container image was built.** Docker Desktop on this laptop does not start: its backend aborts on stale `AF_UNIX` socket files (`%LOCALAPPDATA%\Docker -un\dockerInference`, - `userAnalyticsOtlpHttp.sock`, dated 2025-06) that Windows refuses to delete without elevation (`Error 1920`). The recipe is checked statically (`tests/recipe.rs`) and by simulation: the `COPY` layout - rebuilt under `/opt/leleka` in WSL, `env -i`, the container's environment variables: `ldd` resolves every library from the base alone (libc, libm, libgcc_s), `libcublas.so.12` is found in - `PREFIX/lib/cublas`, `leleka status` answers in 2 ms; the content is 167 MB of binaries + 815 MB of cuBLAS = 982 MB before the Ubuntu base layer (no image digest exists). - Build it on a machine with a working engine (section 7) and record the digest and size. -* The **system-scope** unit (`useradd`, chown of state and assets, `/etc/systemd/system`) and the `curl` branch of the cuBLAS download have unit tests / renders but were not run for real. -* No clean Ubuntu 24.04 / 26.04 VM was installed from nothing; the first-ever archive build (`ensure-sharded-streamed` creating 55 GB) was not repeated. -* The MTP pack has no producer in the repository (`mtp_pack`); `up` needs it in `ASSETS/data/mtp-rt` or via `--mtp-pack`. -* Not measured: the load time of the server profile under the supervisor, the RAM peak of 55 GB memfd + 50 GB bank, anything about throughput. -* Native Windows is not a target. TLS and remote access are not part of this: use an SSH tunnel. - -### Server job (RTX 5090) - -Two holder jobs are queued on `rnr5090` (`~/work/gpu-runs/holder2/jobs/`), written to run after each other and to inherit the holder's sealed descriptor, so nothing is copied or downloaded: - -* `930-deploy-prepare.sh`: `up --dry-run`, then `up --mode none --kar-fd $LELEKA_STRA169_KAR_FD --trust-archive` against `/home/para/work/leleka/models/leleka-gates/assets` (real `model fetch`/`verify` of the existing shards by hash reuse, - tokens, configs, tokenizer extraction into `assets/tokenizer-assets`), then a second dry-run and a second `up` to show that nothing is redone. -* `931-deploy-serve.sh`: `up --foreground --kar-fd ...` with the real model (typed load, `/ready`), one request through the API, an unauthenticated request (must be refused), SIGTERM, the logs and a check that no process is left. - -The release is unpacked at `~/work/deploy-run/rel`, state is `~/work/deploy-run/state`. At the time of writing the holder was busy with earlier queue entries (the holder takes a snapshot of the job list per pass, so entries added later run in the next pass), so -**these two jobs had not run**; read `930-deploy-prepare.log` and `931-deploy-serve.log` next to the scripts. The strict re-verification of the existing archive (`ensure-sharded-streamed` without `--trust-archive`) was deliberately not queued: -it re-derives the 708 GB virtual F32 stream (the analysis tool was stopped after 13 minutes at the same step, `build-validation.md`). - -### Startup profile jobs (RTX 5090, queued) - -`~/work/gpu-runs/holder2/jobs/9g1`-`9g6` (templates in `scripts/startup-profile/`) measure the phases of a -supervised start on the real assets with the holder's sealed descriptor: `9g1` verification only, baseline binaries (warm, cold shards, warm); `9g2`/`9g3` a full start with the baseline binaries -(warm / shards evicted); `9g4` verification only, new binaries (without stamps, with stamps first and second run, `--verify-rehash`); `9g5`/`9g6` two consecutive starts with the new binaries -(the second one is the restart that uses the stamps), warm / cold. Each prints the `leleka-load-time` lines, the governor's load ledger of the stack opening, the supervisor's -`start_to_ready` seconds and two requests (the second shows the warm-up cost of the first). They are FIFO behind the other queue entries; at the time of writing none had run. -The baseline binaries are the commit `cceb4b4` build (phase lines and `--verify-only`, sequential verification); the new ones the final build of this branch. - diff --git a/docs/design/memory-single-copy-and-elastic-state.md b/docs/design/memory-single-copy-and-elastic-state.md deleted file mode 100644 index 3ed364f6..00000000 --- a/docs/design/memory-single-copy-and-elastic-state.md +++ /dev/null @@ -1,300 +0,0 @@ -# Host RAM on the 5090: one copy of each table, and elastic session state (design, no implementation) - -Date 2026-10-30. Branch `claude/mem-design`. Analyst: design/analysis agent, CPU-only. No GPU job was run and the server was not touched (its root NVMe is unstable); every -number below comes from the code in this tree or from a document already in the repository, with the path named. - -Evidence labels: **M** measured (a log or document records it), **S** read from source, **E** estimate (derivation given), **U** unverified / needs a run. -Nothing here is a performance claim (AGENTS.md): every speed statement about a future change is an E or U and the tasks in section D carry the paired A/B that would turn it into a result. - -Owner requirements this page answers: (1) "dual use of memory is stupid" on the 5090 profile; (2) session state that moves to RAM must not be reserved at full-window size: -allocate on use, hard cap, evict under pressure, compress when parked. - -## Update 2026-11-02 (claude/single-copy): census, decision, what is built - -* The census was run on the real archive (T1): a sparse copy is **16,000,348,672 B in 2 extents (14.901 GiB, 28.94 %)**; 39,295,180,800 B (36.596 GiB, 71.06 %) are never read. Section 0 and A.4 are confirmed, no longer E. - The 144 routed-expert records of the archive are 262,144,256 B each: 35.16 GiB for all 24,576 experts against 46.84 GiB in the GGUF bank (0.7506; 1.952 MiB -> 1.465 MiB per expert). -* B0 is built on top of the O_DIRECT bulk reader (`bulk_read`): the copy of the extents never enters the page cache, hash passes evict what they read (`readahead.rs`), `rtx5090-32g` has `memfd_extents: ple_only` - and the pinned extents digest `7568b121...af72143` is compiled in. The alternatives measured against it are in `scripts/e2e/decode/single-copy-ab.sh` (main with the full memfd / sparse memfd / `rtx5090-32g-file`). -* Candidate "KAR on the fly" (experts decoded from the compressed archive, no GGUF bank): not built. Reasons recorded in the task report: level-2 experts are lossy (relative L2 about 0.33 against 0.165 at level 3), - the only GPU path (`kar_expert_source`) decodes to an F32 scratch (18.75 MiB per expert against 1.95 MiB read today) and is refused together with the optimized MMQ owners, and the CPU leg consumes GGUF block layouts. - -## 0. Result in ten lines - -1. **The two big host tables are not the same bytes, but the sealed memfd does hold a second copy of the model.** The 55.3 GB memfd is the pinned level-2 KAR archive. The engine reads - exactly one thing from it: the PLE n-gram rows (320,001,536 rows x 50 B = 16.0 GB, S). The other 39.3 GB (71 %, E) is a lossy level-2 re-encoding of the same shard-0 tensors - (routed experts and dense weights) that the resident bank was built from, and the Original serve path never reads it (S, section A.4). It costs 36.6 GiB of unswappable-by-choice shmem for nothing. -2. The resident expert bank (46.84 GiB) is built from GGUF shard 0, not from the memfd, and is read by the VRAM tier fill, the PCIe staging, the CPU expert leg and the prefill ring (S). - It is not removable on this profile, and mapping it instead would save ~0 at 256k (the prefill touches the whole bank every chunk, E) while risking speed (section B). -3. **Recommended single-copy step: a sparse memfd that holds only the PLE extents** (bits identical, same pages read, no speed risk): host RAM at 256k falls from ~109 GiB to ~72 GiB - accounted (E). Everything else in section B is either no gain at 256k or a fallback for smaller hosts. -4. Today's inventory at a 245k session: about 109 GiB accounted of ~121 GiB, matching the measured turn-5 picture (anon 55 + shmem 56.5 + file ~7 GiB, MemAvailable 8.6 GiB; section A). -5. Session state: the prefix cache **budget** is not reserved, it is a ceiling that the governor sizes to be filled on purpose (75 % of what is left, 5.7-6.1 GiB today, ~31 GiB after step 3 if left on - `auto`: a hazard this page flags). The only real reservation is the pinned K/V image (3.094 GiB, allocated whole at open, and it is the live session, not staging). -6. The store keeps a second copy of the live session's K/V (blocks are copied out at every grid chunk) although the pinned image already holds it: ~3.5 GiB at 245k (E from 14,208 B/token). - Parking on overwrite instead of on every chunk removes it in the single-session case and costs about 0.27 s at the moment of a switch (E from the measured 13-14 GB/s restore). -7. Hybrid model: K/V is 12 QSA layers x 1,056 B = 12,672 B/token (14,208 B with the index rows): 3.09 GiB per 256k window; the 36 GDN layers add a constant 112.2 MiB. A parked 256k session is - ~3.6 GiB raw (S/E). -8. CPU compression of parked state is a weak lever: int8 K/V 1.06-1.20x and fp32 GDN ~1.2x by entropy bound on synthetic data (E, section C.5). Cap, lazy parking and idle trimming first; measure - real blocks before building a codec. -9. A restore beats a re-read by two orders of magnitude: ~0.27 s (E) against ~55-60 s for 245k tokens (M: sum of the five-turn TTFT, 57.3 s). The "10-12 s" figure is the per-turn - delta of ~50k tokens, not a full re-read. -10. Tasks (section D): archive census, prefix hard cap, sparse memfd (code), the 5090 A/B with identity, lazy parking, then compression measurement. - -## A. Inventory of host RAM at 256k on the 5090 profile - -Profile `deploy/rust-runtime/profiles/rtx5090-32g.json`: `kar_source: memfd`, `expert_source: resident`, `context_tokens: 262144`, `prefill_capacity: 8192`, prefix cache `auto`, tail `reply`, -block 8192, lock `try`, heal on. Host: 121 GiB visible (decode-tail doc), 9950X3D, 15 pinned CPU expert workers. All sizes GiB unless marked. - -### A.1 The table - -"Class" is the kernel's view: shmem (memfd and `cuMemHostAlloc` mappings, counted in neither `MemAvailable` nor reclaimable), anon (heap, swappable unless locked), file (page cache, reclaimable). -"When": S = at stack open, L = lazy, E = elastic (grows with use). - -| # | consumer | GiB | class | when | source | who reads it | -|---|---|---:|---|---|---|---| -| 1 | sealed KAR memfd, 55,295,529,472 B | **51.50** | shmem | S | M (`docs/memory-safety.md` 3.1: 52,733.9 MiB; `deploy/src/profile.rs` `ARCHIVE_BYTES`) | PLE row reads only (A.4) | -| 1a | of which PLE extents: 320,001,536 rows x (10 B scales + 2 x 20 B planes) | 14.90 | | | S (`model-format/src/kar.rs` `read_rows_chunk`), E for the byte count | `KarPleBinding::read_rows*`, prefill read-ahead `row_reader`, `KarPleCache` misses | -| 1b | of which everything else in the archive | **36.60** | | | E (A.4) | nothing on the serve path | -| 2 | resident routed-expert bank, 144 tensors of shard 0 (50,292,326,400 B) | **46.84** | anon, registered (page-locked) lazily by `cuMemHostRegister` | S | M (`laptop-profile.md`, `memory-safety.md` 8: RssAnon 49,690 MiB at load) | VRAM tier fill, PCIe staging, CPU expert pool, prefill ring, slot refill (A.5) | -| 3 | pinned K/V host image, 12 layers x 276,825,088 B | **3.09** | shmem (device-mapped pinned) | S | M exact (`context/src/geometry.rs`, `memory-safety.md`: plan equals measurement) | QSA layers read pages over PCIe; it is the authoritative copy of the live session | -| 4 | native head + embedding mapped host copy (pinned) | 0.31 | shmem | S | M (322 MiB, `vram-footprint-5090.md`) | decode gather over PCIe | -| 5 | MTP drafter / verifier pins | 0.26 | shmem | S | M (~266 MiB, `memory-safety.md` 3.1) | drafter | -| 6 | dense weights, host side | 1.37 | anon | S | M (+1,403 MiB RSS at the dense stage) | upload source; **may be freeable after upload (U, T12)** | -| 7 | MoE arena host side + CPU pool scratch | 0.10 | anon | S | M (74 + 28 MiB) | prompt MoE, CPU pool | -| 8 | rings, stager buffers, empty-prompt checkpoints, tokenizer, thread stacks (unattributed) | ~1.5 | mixed | S | E: 3,686 MiB (`OTHER_FIXED_ESTIMATE_RESIDENT`, M from job 945) minus rows 4-7 | various | -| 9 | prefix store (blocks 14,208 B/token + node states ~127 MiB each) | 0 -> budget | anon | E | M (`prefix-cache.md`; budget 5.7-6.1 GiB `auto`); use at 245k E: 3.24 blocks + ~0.5 nodes | restore path only | -| 10 | conversation checkpoints, 118 MiB each | 0 | anon | E | S (`memory_governor.rs`: 0 when the prefix cache is on; 6 x 118 MiB = 0.69 GiB when it is off) | Original-style conversation cache | -| 11 | page cache (logs, binaries, PTX, MTP pack, tokenizer; shards dropped after load) | ~7 | file | L | M (owner, turn 5) | reclaimable | -| 12 | gateway, supervisor/holder, kernel structures | ~1-2 | mixed | S | E | | - -Device (VRAM) holds its own, separate inventory (`vram-footprint-5090.md`); the VRAM window of K/V is 251.7 MiB, the rest of the 256k window lives only in row 3. - -### A.2 Totals - -| view | GiB | basis | -|---|---:|---| -| fixed at open: rows 1-8 | **105.0** | 51.50 + 46.84 + 3.09 + 0.31 + 0.26 + 1.37 + 0.10 + 1.5; cross-check: `resources.rs` plans `ARCHIVE_BYTES + 54 GiB` = 105.5 (S) | -| + prefix store at a 245k session (row 9) | ~109 | E | -| + page cache and gateway (rows 11-12) | ~117 | E | -| measured at turn 5 (owner, 247k): anon 55 + shmem 56.5 + file ~7 | 118.5 | M; MemAvailable 8.6; read as GiB it reconciles with the table: shmem = rows 1+3+4+5 = 55.2 (+~1.3), anon = rows 2+6+7+9 = 54-56 | -| vanilla Strata at turn 5 (same card) | anon 54.7, MemAvailable 9 | M (`decode-tail-5090.md` section 4): vanilla also runs near the floor, but its PLE is a file mapping, not a memfd | - -Of the 105.0 GiB fixed, **36.6 GiB (35 %) is never read** (row 1b) and 3.5 GiB more is a duplicate of the live K/V (A.6). That is the real "dual use". - -### A.3 What the planner and governor assume (S) - -* `crates/leleka-memory/src/plan.rs`: `A = MemAvailable` at start; `F` = fixed items still to allocate (resident bank 50.3 GB, pinned K/V, `OTHER_FIXED_ESTIMATE_RESIDENT` 3,686 MiB); - the memfd is **inherited, so it is already out of `MemAvailable`** (`KarForm::MemfdInherited`, K = 0). `R = A - F - K` must stay above `soft_floor 4 GiB + reserve 2 GiB`. The remainder - `elastic = R - floors` is handed out: resident complement (mapped form only), then the prefix cache `auto` = **75 % of the elastic memory, ceiling 96 GiB, off under 1 GiB**. -* `auto_prefix_budget` repeats the rule when the stack opens, from the live `MemAvailable` after the bank is resident; that second value is the one in force (5.7-6.1 GiB on the 5090). -* Pressure monitor: `shed` below the soft floor (prefix cache evicts to 3/4 per second, insertions stop at `soft + reserve` = 6 GiB), `reject` below the hard floor (503 `memory_pressure`). -* Deploy plan: `resources.rs` computes `footprint = ARCHIVE_BYTES + 54 GiB`; if `available - footprint < target + reserve` it **switches the profile to `kar_source=file` + `expert_source=mapped` with - `resident_budget_gib = min(46, (avail - target - reserve - 8 GiB))`** (S: the fallback ladder already exists at plan time, not at run time). `preflight.rs` requires 113 GB available for the profile. - -### A.4 What reads the memfd, and what is in it - -* Reads (S): `InheritedKarArchive` -> `load_pinned_inherited_archive` -> `VerifiedKarPleArtifact` -> `read_rows`/`read_rows_batch`/`row_reader`, whose only I/O is `read_rows_chunk`: three positional reads - per PLE row (10 B of scales at `scales + 10*row`, 20 B at `planes + 20*row`, 20 B at `planes + stride + 20*row`). Consumers: `KarPleCache` (decode rows, prefill batches, read-ahead). The governor maps the - descriptor only to lock it and count swapped pages (`archive_handle` comment). -* Not read (S): the engine args built by `deploy/src/config.rs` contain no KAR expert-source argument, so `kar_expert_source` is `None`; `docs/original-serve.md` states the Original executors - "read the pinned model's own mapped routed experts, not a KAR level decode". `qwen4exp_inherited_kar_gpu.rs` is a seal test fixture. -* Content (E, two independent derivations that agree): - 1. The pinned profile (`qwen4exp_kar_ple.rs` `pinned_profile_spec`) has a virtual F32 stream of 707,775,598,080 B; the first PLE part starts at 502,974,615,040 B, so **71.1 % of the stream precedes the - PLE parts** and is other tensors (shard 0: routed experts and dense weights). PLE is 204,800,983,040 B of it (28.9 %). - 2. Level-2 nested coding costs the same per element everywhere: PLE 16,000,076,800 B over 51.2 G elements = 2.50 bits; the remaining 39,295,452,672 B over 125.7 G elements (502.97 GB / 4) = 2.50 bits. - `build-validation.md` independently measured a level-2 IQ3_S expert slice at 75 % of its GGUF size. - The experiment doc `2026-10-03-kar-ple-ab.md` and `compressed-runtime.md` agree on the purpose: the archive "serves only the PLE tensor from KAR; other model weights remain in the native pack". - `laptop-profile.md` calls the level-2 experts lossy (relative L2 ~0.33, no quality gate), so they are not a usable source either. -* So the memfd's extra 36.6 GiB is dead weight, not a safety net. **U until T1 prints the archive directory** (a CPU-only read of ~1 MB on the server). - -Can the CPU expert kernels read the memfd directly with the same bits? **No.** The kernels consume GGUF block layouts (IQ3_S/IQ4_NL/IQ2 blocks, `native-cpu-expert`); the memfd holds nested bit-plane KAR coding -that is a different, lossy representation. The "mapped" mode of the laptop profile maps **GGUF shard 0** (`load_mapped_expert_source`, `model-format/src/qwen4exp_expert_source_bank.rs`), whose bytes are the verified file's, -so a CPU kernel sees the same bits through the mapping as through the resident copy (S: `mapped.len() == descriptor.bytes`, same descriptor, "every consumer sees exactly what the resident copy would hold"). - -### A.5 Why the resident copy exists, and who reads it - -Built by `Qwen4ExpArtifact::load_resident_expert_source`: for each of 48 x 3 expert tensors, `shards[0].load_resident_tensor` copies the raw bytes into anonymous memory (admission against `MemAvailable`, -cap 52 GiB, no finite scan; the shard page cache is dropped afterwards by `drop_file_cache`). Readers (S): - -| reader | what it reads | frequency | cost of a pageable source | -|---|---|---|---| -| VRAM tier fill and `refill_lent` | expert bytes by profile rank, one blocking copy per slot (11,280 slots = 21.5 GiB) | at open; the lent prompt slots (2,238, ~4.2 GiB) refilled after every prefill, 307-419 ms (M) | page faults and a staged copy | -| prefill ring (`moe.ring`) | every expert the arena cache does not hold, by DMA straight from the registered bank | every chunk: 15,534 ring entries per 8192 chunk (M, `upstream-port-plan.md`), ~34 GB per chunk at the 2048 shape, ~45 GB/s (M, `prefill-throughput.md`) | pageable banks take the `Stager` path (helper threads copy into pinned buffers); measured only on the laptop | -| decode PCIe share | missed experts DMA'd to staging slots (13-60 per window, seed off, M) | every window | pageable DMA is slower; the code refuses PCIe staging for a pageable bank unless `pcie_frac` is set explicitly (laptop: 6.7 vs 10-12 tok/s, M) | -| decode CPU leg | missed experts computed in place by the 15-worker pool (23-79 per window, ~3.9 ms of a ~15 ms round) | every window | the same bytes, read through page cache instead of anon | - -The bank is page-locked (`cuMemHostRegister`) because registered memory is what lets the copy engine DMA from it without a bounce buffer; that, plus the whole-bank prefill sweep, is the reason the 5090 -profile asks for `resident`. - -### A.6 The duplicate of the live K/V - -The pinned K/V image (row 3) is the live session's whole 256k K/V. After every grid chunk the prefix store may copy the new cells into immutable blocks (`PrefixStore::consider`, 14,208 B/token) so that a -different session can later overwrite the positional buffer without losing them. In the single-session case those copies are never read (the live buffer is continued, "copies no K/V at all", -`prefix-cache.md`), yet they occupy 3.24 GiB (245k) of the budget. Nodes (GDN images, 127 MiB each) are the part that cannot be reconstructed from the live buffer. - -## B. Options for a single copy - -Premise correction first: option 3 as phrased ("drop the memfd after building the resident copy") does not apply, because the resident copy is **not** built from the memfd. The real options: - -| option | RAM saved at 256k (E unless noted) | risk | speed risk | changes | test | -|---|---|---|---|---|---| -| **B0 sparse memfd: only the PLE extents are filled, the rest are holes** | **36.6 GiB** (row 1 51.5 -> 14.9); MemAvailable at turn 5 from 8.6 to ~45 | low: same rows, same pages, same bits; the verification model changes (below) | none expected (reads hit the same pages; a hole is never read) | `deploy/src/sealed.rs`: fill a range list instead of `0..total`; `model-format/src/kar.rs`: pinned digest of the extents, refuse reads outside them; `leleka-memory` `guard_archive`: lock and heal **only the extents** (`mlock`/`MADV_POPULATE_READ` on a hole would allocate it); `KarForm` bytes and deploy `ARCHIVE_BYTES`/`min_ram_available` use the extent size | rows through the sparse memfd equal rows through the file (property test over random rows incl. partition seam 200,000,000); greedy-id identity and A/B on the 5090 (T4) | -| B0' PLE-only archive file (new pin, 16 GB) | same RAM; also 39 GB less disk and hashing | medium: new archive digest, provenance, receipts | none | offline repack tool, new constants everywhere the 55.3 GB archive is pinned | CRC and row identity against the old archive | -| B1 `expert_source: mapped`, nothing pinned | ~0 in steady state at 256k: one 180k request already touched ~46 GiB of the mapped bank (M, job 911, `memory-safety.md` 3.1); the bytes only become reclaimable | high | prefill: pageable `Stager` instead of direct DMA (E: material loss of the 34 GB/chunk stream, never measured on the 5090); decode PCIe share off or slow; after a 40 GiB competing reader evicted part of the file-mapped bank, the first two requests decoded at 11 tok/s against 17-19 (M, 5090 job 917, `memory-safety.md` 5.5; old small-tier config, so the ratio, not the rate, is the evidence) | none (exists) | only as a measured negative control | -| B2 hybrid `mapped` + `resident_budget_gib` | up to 21.5 GiB become reclaimable if the pinned budget is the VRAM-complement only (13,296 experts x ~1.95 MiB = 25.4 GiB, E); not a hard saving | medium: the unpinned part is file-backed and the model volume is the unstable disk | PCIe share of unpinned misses and the 4.2 GiB refill read pageable pages; `LELEKA_PCIE_LOCKED_ONLY` and `pcie_frac` exist to bound it | none for the mechanism: `pin_resident_complement` pins by profile rank, clamped to `MemAvailable - 4.25 GiB`; only valid with `mapped` (guards at `original_serve_residency.rs:1144`, `memory_governor.rs`) | T10: arms at 100 %, 60 %, 0 % of the complement pinned | -| B3 drop the memfd after building the resident copy | n/a: the memfd is not a build input and PLE needs it for the life of the process | | | | | -| B4a PLE as an ordinary file (`kar_source: file`, stamps skip the hash) | 14.9 -> page cache of the touched rows; E: 1M distinct rows after ~250k tokens (decode-tail 4) x up to 3 pages = 4-12 GiB | medium: random 4 KiB reads on the model volume; no sealed immutability (weaker form, `qwen4exp_kar_ple.rs` doc) | cold row reads on prefill; `window.ple` today 0.1-0.2 ms | none (laptop form) | T14 | -| B4b native PLE from shard 1 (IQ4_NL, 90 B/row, direct I/O) | 14.9 -> ~0.1 | high: **not ported to the Original serve path** and different numerics than KAR L2 (A/B showed matching outputs only on short suites) | unknown | large | not planned | -| B4c free the host copy of the dense weights after upload | up to 1.4 GiB | low | none | verify first that it is retained for a reason | T12 | - -### Recommendation - -**B0, in that order of care: T1 (census) -> T3 (code) -> T4 (A/B).** It removes the only copy that is never read, keeps every consumer on exactly the bytes it reads today, and needs no model-quality gate because -nothing a kernel reads changes. Keep `resident` for the expert bank on the dedicated profile. Keep the existing plan-time fallback to `mapped` + budget for smaller hosts and treat B2 as the measured -version of that fallback rather than as a default. - -How B0 keeps the fail-closed property. Today the engine hashes the whole archive on a memfd unless the parent "attested" the copy (`verify_stamp::set_attested_archive`, `kar.rs` `attested_memfd`); the -supervisor verifies the file (stamp or full hash) before copying. With holes, the engine cannot hash the archive. Instead: (a) the supervisor copies only the extents of the two PLE parts plus the header, directory -and the book words (a handful of ranges, ~16.0 GB); (b) a **pinned SHA-256 of the extent bytes** (computed once from the pinned archive, T1) is checked by the engine on the memfd, ~16 GB, a few seconds, instead of -55 GB; (c) the reader refuses any offset outside the extents (they are all derived from `VerifiedPart`, so a bug cannot read a hole silently); (d) the provenance digest check stays. - -Interaction hazards found while reading (all in the change list above): `guard_archive` maps the descriptor and `mlock`s it in chunks, and heal uses `MADV_POPULATE_READ`; both would instantiate the holes -(55 GB of zero pages) if pointed at the whole mapping. The deploy preflight and `resources.rs` constants (`ARCHIVE_BYTES`, `min_ram_available_bytes 113e9`) must use the extent size or the profile -will keep refusing hosts that now fit. - -Projected host picture at 256k after B0 (E): PLE 14.9 + bank 46.84 + K/V 3.09 + other 3.6 = **68.4 GiB fixed**, plus a capped prefix store (D, T2: 6 GiB now, 8 later) = ~74-77 GiB of 121; the 8.6 GiB of -MemAvailable at turn 5 becomes ~40-45 GiB. - -**Hazard created by B0 alone:** `auto` would then size the prefix cache from the freed memory (75 % of ~40 GiB = ~30 GiB). Without a cap the freed RAM would be refilled "on purpose" by cached blocks. -T2 (an explicit cap in the profile) must land before or with T3. - -## C. Elastic session state - -### C.1 How it is budgeted today (S unless marked) - -| state | where | sizing | allocated | released | -|---|---|---|---|---| -| live K/V (12 QSA layers) | pinned host image, 3.094 GiB | whole serving context | at open, `cuMemHostAlloc` | process exit | -| VRAM K/V window | 251.7 MiB, `--kv-resident 32768` | fixed | at open | exit | -| GDN state (36 layers) | device, 112.2 MiB (`gdn_state_bytes` 117,669,888, golden from the C++ `conversation_state_sizes`), PLE history 360 KiB | fixed | at open | exit | -| prefix store blocks | pageable heap, 14,208 B/token | ceiling = `auto` budget (A.3) | per insertion, after each grid chunk (and at request end with tail `reply`) | evict by score (expected tokens saved per byte), TTL 60 min, shed on pressure + `malloc_trim` (`heap.rs`) | -| prefix store nodes | ~127 MiB each (GDN/PLE images, draft ring snapshot, index tails) | counted in the same budget | with the node | with the node | -| conversation checkpoints | 118 MiB each, `--prompt-cache 6` | only when no prefix cache | at request boundaries | LRU, root pinned | -| `Policy.prefix_cap` | 96 GiB (24 laptop) | no env knob | | | - -What "plans fullness on purpose" means in the code: `auto_prefix_budget` = 75 % of `available - (soft_floor + reserve)`; `plan()` subtracts the fixed items and then hands the cache the share of what is left, -so the thresholds (shed at 4 GiB, admit stop at 6 GiB) are chosen so that a **full** cache is survivable (`memory-safety.md` section 8: "the plan designed a minimum of 7 GiB available with the cache full"). -The memory is not committed up front; it is committed by use and the plan assumes use will reach the ceiling. Only the pinned K/V (and the fixed items) are true reservations. - -### C.2 Real sizes from the model geometry (S, `crates/context/src/geometry.rs`, `qwen_forward/original_serve_stack.rs`) - -Qwen3.8-Flash-Next here has 48 layers: **12 QSA (attention) + 36 GDN (recurrent)**. Only the QSA layers carry a per-token cache. - -| quantity | per token | at 245k | at 262,144 (256k window) | -|---|---:|---:|---:| -| K/V int8 + scales (K 512 B, V 512 B, K scales 16 B, V scales 16 B per cell per layer = 1,056 B) x 12 layers | 12,672 B | 2.89 GiB | **3.094 GiB** (= 12 x 276,825,088 B, the pinned image, M) | -| pooled index rows (128 B per cell per layer) x 12 | 1,536 B | 0.35 GiB | 0.375 GiB | -| block in the prefix store (K/V + index) | **14,208 B** | **3.24 GiB** | **3.47 GiB** | -| GDN state + PLE history + index tails + draft ring snapshot, per node | constant | ~127 MiB (M) | ~127 MiB | -| **a parked 256k session, one node** | | ~3.4 GiB | **~3.6 GiB** | - -For scale: the same window on a dense 48-attention-layer model of this width would be 4x the K/V (~12 GiB); the hybrid layout is why parking is affordable at all. The GDN state does not grow with context, so -it is paid per node, not per token. A thinned session keeps the frontier, the previous one or two, and a geometric spread of older nodes (`prefix-cache.md`), i.e. ~3-6 nodes: 0.4-0.8 GiB. - -### C.3 Session multiplexing: what exists - -* One generation at a time (`parallel 1` is the vanilla launch shape too, `s0-7-vanilla-arms.md`; the store "needs no locking"). -* Switching conversations already works through the prefix store: a session returning after another one finds its nodes by hash chain, writes back **only the blocks the other session overwrote** - into the pinned image (`import_parked`), installs the GDN/PLE images and re-anchors the draft ring. Measured on the 5090: 98k tokens (1.4 GB) in 101 ms, 172-180k tokens (2.4-2.6 GB) in 175-194 ms (13-14 GB/s, - M, `prefix-cache.md`), against 28-55 s of prefill at that time. -* `NO_PARKING` (`original_serve_conversation.rs`) refers only to the Original's *whole-conversation* snapshot cache (`--conversation-cache-mib`), which the prefix store replaces; the six-checkpoint - conversation cache remains for the no-prefix-cache path. Upstream's batch-slot parking series (`01e404c1`, `cea3ed40`, `c7a0cef1`, rows B2/B3/R16 of `docs/upstream-review/cpu-and-platform.md`) is for batch mode and was - judged "n/a, ours is single-stream"; its parked-K/V-in-VRAM and ready-pool ideas are not wanted here (VRAM is the scarce side). -* Upstream's own numbers for parking are a useful bound: restoring a parked 64K conversation 0.97 s against 49 s (P100, `engine/strata/docs/RESEARCH_RUNS.md`), and its stalls were caused by the OS paging the engine - while it parked (DETAILS.md): parking must never allocate in a way that competes with the pinned banks. - -### C.4 Cost of a parked 256k session, raw and compressed, and restore against re-read - -| | raw | compressed (E) | -|---|---:|---:| -| blocks, 245k tokens | 3.24 GiB | 2.7-3.1 GiB at 1.06-1.2x | -| one node | 127 MiB | ~105-120 MiB at ~1.1-1.2x | -| restore, 245k tokens | **~0.27 s** (E: 3.48 GB at the measured 13-14 GB/s) | + decompress: 3.5 GB raw at ~1-1.5 GB/s per core x 8 cores = 0.3-0.5 s (E, typical zstd -1 speeds; U on this CPU) | -| re-read (prefill) of 245k tokens | **~55-60 s**: M, the five-turn TTFT sum is 57.3 s (`upstream-port-plan.md`, rest-full2) for 247k tokens, per chunk 1.68 s at 139k | | - -The "re-prefill of 245k takes ~10-12 s" in the task brief is the per-turn TTFT (10.5-13.2 s, M) of a ~50k-token delta, not of a 245k read. Either way a restore wins by 25-200x, so the decompression budget is -generous: even a slow codec leaves the switch under a second. The design question is therefore RAM, not latency. - -### C.5 Compression: what to expect - -Measured here on synthetic data only (`scripts/memory/entropy_bound.py`, absmax-int8 quantization of 128-wide vectors, 0-order entropy and zlib-1 as a stand-in for LZ; E, not a measurement of the model): - -| data | entropy bits per byte | ideal entropy coder | zlib-1 | -|---|---:|---:|---:| -| int8 codes of Gaussian vectors | 7.53 | 1.06x | 1.05x | -| int8 codes of Laplace vectors | 7.01 | 1.14x | 1.12x | -| int8 codes of heavy-tailed (Student-t-like) vectors | 6.65 | 1.20x | 1.17x | -| fp32 Gaussian state, raw / byte-plane shuffled | b0..b3: 8.0, 8.0, 7.97, 2.6 | 1.20x | 1.08x / 1.16x | - -Reading: a byte-oriented LZ (lz4) finds almost nothing in quantized K/V; an entropy stage (zstd, level 1-3) gets 5-20 %; fp32 GDN gains only after a byte shuffle. Real K/V has outlier channels (absmax scaling -leaves the other channels on few levels), so the real ratio may be better than the synthetic bound (U): that is exactly one measurement, T8. A lossy shrink (fp16/bf16 GDN state, q4 K/V, which the session -policy has switches for) would halve a part but changes numerics, so it stays an experimental, quality-gated mode (AGENTS.md) and is out of scope. - -CPU contention is real: the 15 expert workers sit on 15 physical cores and the CPU leg is ~3.9 ms of every ~15 ms round, so compression threads must run **only while no request is active** (or at idle priority on -the SMT siblings), never during a window. Compression is therefore a background pass on parked blocks, not part of the request path. - -### C.6 Design: lazy, capped, evicted under pressure, compressed when parked - -1. **Hard cap first.** Replace "fill the elastic share" with `prefix_cache_mib = min(explicit cap, 75 % of elastic)`; the 5090 profile gets an explicit cap (T2: 6,144 MiB = today's `auto`, then sized by sessions, e.g. - two 256k sessions + nodes = 8 GiB). The cap, not free RAM, defines "full". Freed RAM stays free. -2. **Commit on use, per tier.** Blocks and nodes are already built on insertion; keep that. Do not preallocate anything for sessions. The pinned K/V image stays a fixed reservation (it is the live session); - a lazily pinned image (64-256 MiB steps registered over one reserved virtual range) is possible (T13) but saves nothing at 256k and only matters for idle hours. -3. **Park on overwrite, not on every chunk.** Nodes (GDN states, 127 MiB) are still admitted at grid points because they cannot be rebuilt. Blocks are copied out of the pinned image only when the next - prefill is about to overwrite cells that no stored block covers (the request path already tracks `live`, the cells known to hold the current prompt). Single-session continuation then stores no - blocks at all (-3.2 to -3.5 GiB at 245k, E); a switch pays one memcpy of the overwritten tail, <= ~0.27 s (E), instead of nothing on the switch and a permanent copy of every session. Failure behaviour: - the live image stays authoritative until the copy completes; a cancelled request parks nothing it did not finish. -4. **Evict under pressure in this order:** compressed blocks of the oldest sessions -> raw blocks of the oldest sessions -> nodes of the oldest sessions -> everything but the frontier (the existing - `shed` ladder, scoring by tokens saved per byte), with `malloc_trim` after each (existing). Add an idle rule: after N minutes without a request (default 10) compress what is raw; after the retention time - (60 min) drop. Admission keeps the `soft_floor + reserve` stop that exists. -5. **Compress when parked, in the background, only when idle.** Per block, byte-shuffle for GDN images, zstd level 1-3 (or none when T8 measures < 1.15x). Decompress on restore on the restore threads before the - `import_pages` memcpy. A block header carries `{codec, raw_len, crc}` so a corrupt or truncated entry falls back to a re-read (a miss), never to wrong state. -6. **Telemetry:** `prefix.store` keeps raw and compressed bytes, bytes parked on overwrite, restores, restore ms and bytes, evictions by reason; `/v1/status` -> `memory` already carries the inventory. Acceptance - below uses `scripts/e2e/sample_env.sh` series (RssAnon, RssShmem, VmLck, MemAvailable). - -## D. Tasks (small leaves, ordered by value / effort) - -A/B protocol for every GPU row (charter: paired, same workload, quality result, full record): RTX 5090 server, one heavy job at a time under `/data/leleka-e2e/gpu.lock`; frozen corpus -`/data/leleka-e2e/decode/corpus/src/crates` (file-list sha256 `1152f45acaa9a62591e50d8f6807f50ce6fe1249db659cdb9e8e4a041ed119a7`, 14,132,376 chars); `scripts/e2e/long_session.py` five turns -(45.8k / 105k / 153k / 199k / 247k prompt tokens, 300 output tokens, greedy); upstream profile `data/expert-profile.bin` (sha `8f59b4aa...388975baf`); shards `4c1eb2ce...`, `316b46f3...`; archive -`536d612c...`; production env of the profile; chunk 8192; 3 runs per arm, arms interleaved; record binary sha256, driver 595.99, CUDA 13.2, kernel, page-cache state at start (dropped or not), RSS/shmem/anon/ -MemAvailable/swap series every 5 s, TTFT and decode tok/s per turn with the distribution, token counts, and the engine log. Identity row = greedy ids equal and top-16 logprobs bitwise equal where the change is -declared non-numeric. - -| # | task | GPU? | acceptance gate | estimate | -|---|---|---|---|---| -| T1 | **Archive census.** Server, read-only, ~1 MB read: dump the KAR directory (`leleka model inspect-kar` or the `KarInspection` records): name, class, bytes per record. Compute the PLE extents and their SHA-256. | no (server read-only; do when the server is back) | PLE extents total 16.0 GB +- header/books; non-PLE records total 39.3 GB; extent list equals the `VerifiedPart` offsets used by `read_rows_chunk` | 1 h | -| T2 | **Prefix hard cap in the 5090 profile**: `memory.prefix_cache_mib: 6144` (no change today; protects against T3's freed RAM being refilled). Deploy tests updated. | no | deploy tests green; engine log shows the cap; owner confirms the value | 1 h | -| T3 | **Sparse memfd, code**: `ple_extents` from `KarInspection` + `PLE_EXTENTS_SHA256`; `sealed.rs` sparse fill; engine verify-by-extents and refuse outside; governor lock/heal over extents; `KarForm`/`ARCHIVE_BYTES`/`min_ram_available` use the extent size; flag `kar_source: memfd` keeps full copy unless `kar_fill: ple` | no | unit/property tests: random rows (incl. seam at row 200,000,000 and last row) equal through sparse memfd and file; `st_blocks` ~ extents; holes unread; hash mismatch and out-of-extent read fail closed; miri-clean modules stay clean; laptop WSL run on a synthetic archive | 2-3 d | -| T4 | **[GPU] Sparse memfd A/B + identity** (arms: full memfd vs sparse, same binary except the flag) | yes | greedy ids identical on all five turns and top-16 logprobs bitwise equal (a lossless repack must be exactly equal, not "within tolerance"); decode tok/s and TTFT per turn within the run-to-run noise (decode-tail: 3-8 %); RssShmem -36 GiB +- 1; MemAvailable at turn 5 >= +35 GiB; zero swap; `window.ple` unchanged | 0.5 d + runs | -| T5 | **Store use analysis, offline**: from existing logs (`runs/*/inference.log`, CRM job 945, the 5-turn runs) count bytes of blocks admitted vs bytes ever restored, per session shape | no | a table: share of admitted block bytes ever read back in single-session vs alternating runs | 0.5 d | -| T6 | **Park on overwrite** behind `LELEKA_PREFIX_PARK=lazy` (default eager until T7 passes): nodes at grid points, blocks at overwrite; telemetry | no (code/tests) | store unit tests (sharing, refcount, restore of a lazily parked path equals an eager one); `prefix_tail_equivalence.py` equivalence; cancel/failure tests leave no claim over unfinished cells | 3 d | -| T7 | **[GPU] Lazy parking A/B**: (a) single session five turns, (b) two sessions alternating at 100k+ | yes | identity: restored state bit-equal to an eager restore (ids + logprobs); (a) anon -3 GiB or more, TTFT unchanged; (b) switch latency within +0.4 s of eager, restore bytes equal | 0.5 d + runs | -| T8 | **Real compressibility**: one 245k run with a debug dump of parked blocks and nodes (small hook), then offline `zstd -1/-3`, `lz4`, byte-shuffle + zstd, per component (K codes, V codes, scales, index rows, GDN, ring) | one run | ratios per component; **build the codec only if K/V >= 1.3x or GDN >= 1.3x**; decompress MB/s per core on the 9950X3D | 0.5 d | -| T9 | Compressed parking, idle-only background pass, block headers with crc; telemetry | no | round-trip property tests; corrupt block degrades to a miss; no compression thread runs while a window is in flight (log assertion) | 3 d (only if T8 passes) | -| T10 | **[GPU] Hybrid fallback A/B** (`mapped` + `resident_budget_gib`): arms resident, 100 %, 60 % and 0 % of the 25.4 GiB complement pinned, one cold-cache run per arm | yes | table of decode tok/s, CPU-leg ms, PCIe-leg ms, TTFT per turn, page-fault counters, MemAvailable; defines the smaller-host ladder; no default change | 1 d | -| T11 | **Cap-first planner** in `leleka-memory`: cache = `min(cap, 75 % elastic)`, idle shrink schedule, eviction order of C.6; plan output states cap and expected use separately | no | pure unit tests on fixtures (the 5090 numbers of A.1, a 64 GiB host, an unknown-telemetry host) | 2 d | -| T12 | Free the dense host copy after upload if it is retained without a reader (row 6) | GPU for the check | RSS -1.3 GiB, ids identical | 1 d | -| T13 | **[GPU] Lazy pinned K/V spike**: reserve the 3.1 GiB virtual range, `cuMemHostRegister` it in 64-256 MiB steps as the position advances | yes | kernels address the sub-ranges (UVA) unchanged; registration cost per step; ids identical | 2 d, low value at 256k | -| T14 | **[GPU] PLE as a file (`kar_source: file`)** after T4: touched pages of the archive after the five-turn session, NVMe latency tail | yes, only with owner approval (the model volume's unstable disk) | page cache <= 8 GiB and `window.ple` and TTFT within noise; otherwise keep the sparse memfd | 1 d | - -Value order: T1, T2, T3, T4 (largest, 36.6 GiB, no risk), then T5-T7 (3.5 GiB, removes the live-session duplicate), T11, T8/T9, T10, T12, T14, T13. - -## E. Not verified, and what could change the plan - -* **The 39.3 GB being dead weight** is E until T1. If the directory shows PLE parts at more than level 2 (more planes than the two read), the sparse extents grow and the saving shrinks accordingly; the derivation - above (equal 2.50 bits per element in both halves) makes that unlikely. -* All speed statements about mapped, hybrid and pageable banks on the 5090 are E; the only measurements are on the laptop (3080, WSL2) and job 911 (file-mapped bank, small VRAM tier). -* The owner's "anon 55 GB / shmem 56.5 GB" were read as GiB (they reconcile with the table that way); if they are decimal GB the unattributed row 8 grows by ~3 GiB. -* Compression ratios are synthetic bounds; real KV/GDN data was not available on this machine. -* Prefill restore/re-read numbers are from `upstream-port-plan.md` runs on the frozen corpus with chunk 8192; a full 245k cold re-read was not run as one request. -* Lazy pinning, dense-copy freeing and the 5090 behaviour of a pageable prefill ring are untested ideas, listed as tasks, not as claims. diff --git a/docs/design/single-copy-ram-2026-11-09.md b/docs/design/single-copy-ram-2026-11-09.md deleted file mode 100644 index 223d4ddc..00000000 --- a/docs/design/single-copy-ram-2026-11-09.md +++ /dev/null @@ -1,81 +0,0 @@ -# One copy of the model in host RAM (design, 2026-11-09, branch `claude/single-copy-ram`) - -Base `claude/hexagonal-finish-14ee3a` (b686f6ab7). Evidence labels as in `memory-single-copy-and-elastic-state.md`: **M** measured (record named), **S** read from source, **E** estimate, **U** not verified. -No GPU job and no server command were run for this page; the server numbers are the owner's 2026-11-09 reading. Nothing here is a performance claim. - -## 1. Finding - -The product already holds one copy. The lab does not. Everything the single-copy work built is merged (`claude/sparse-memfd`, `claude/kar-file-source`, `claude/single-copy`, `-base`, `-win` are all ancestors of `main` -and of the base; `rtx5090-32g` has `memfd_extents: ple_only`, the extents digest is pinned, the checklist rows Q12/A6 record bitwise identity and MemAvailable 8.5 -> 45.1 GiB). What the owner measured on 2026-11-09 is the -**lab holder's full 55.3 GB memfd**, not the sparse memfd of `leleka up`: - -| measured 2026-11-09 (M, owner) | GiB (from GB) | explained by (S/E) | -|---|---:|---| -| Shmem 58.6 GB | 54.6 | full memfd 51.50 + pinned K/V 3.09 + head/MTP pins 0.57 = 55.2 (a sparse memfd would give 14.90 + 3.09 + 0.57 = 18.6, which is the A6 measurement) | -| engine touches 3.9 GB of the memfd | 3.6 | PLE rows only: ~1M distinct rows after ~250k tokens, one 4 KiB page each (`design` A.4) | -| RssAnon 55.1 GB (one region 46.54 GiB + heap 0.95 GiB) | 51.3 | resident expert bank 46.84 GiB (GGUF shard 0) + dense host copy 1.37 + arena/pool/rings ~2 | -| MemAvailable 7-8 GB, Free ~1 GB, page cache ~2.6 GB | | 121 - 54.6 - 51.3 - 2.6 - ~4 (kernel, gateway, Codex, node) | - -Why the holder: `scripts/e2e/decode/single-copy-holder.sh` ran `leleka seal-exec --file KAR --expect-bytes 55295529472 -- python3 single-copy-holder.py` **without `--sparse-ple`**; `single-copy-window.sh` and -`cmp_window.sh` restart the holder with that script, and the older `run_holder2.sh` / `kar_holder2.py` (outside the repository) copy the whole file too. Every holder job (`spd_ab_job.sh`, `cmp_codex_job.sh`, the Codex replays) -runs `leleka up --foreground --kar-fd FD`; the supervisor then pins the extents digest (profile `ple_only`), the engine hashes only the extents inside the full copy, and starts without complaint. The run is bitwise correct and -wastes 36.6 GiB (S: `supervisor/archive.rs` `open_inherited_archive`, `engine .../inherited_kar_archive.rs` `open_sparse`). U until `holder3.out` (`holder3 ready fd=.. bytes=.. allocated=..`) or -`scripts/e2e/decode/ram-inventory.sh` (memfd block: apparent vs allocated) is read on the server: both are read-only. - -## 2. Where the model bytes live (S) - -| copy | built by | file / function | class | GiB | read by | -|---|---|---|---|---:|---| -| resident expert bank (GGUF shard 0, 144 tensors, native IQ3_S/IQ4_NL blocks) | the engine at stack open | `model-format/src/qwen4exp_expert_source_bank/qwen4_exp_artifact.rs` `load_resident_expert_source` -> `load_banks` -> `gguf_resident/verified_gguf_file.rs` `load_resident_tensor` (heap or huge-page buffer; `bulk_read::read_into`, O_DIRECT by default) | anon, page-locked later | 46.84 | VRAM tier fill, PCIe staging, CPU leg, prefill ring | -| sealed KAR memfd, full | the holder (`seal-exec` without `--sparse-ple`, or `kar_holder2.py`) | `deploy/src/sealed/linux.rs` `seal_file_report` (parallel O_DIRECT fill, `sealed/linux/copy.rs`) | shmem | 51.50 | PLE rows only (3.6 GiB touched) | -| sealed KAR memfd, sparse (product) | `leleka up/run` supervisor | `supervisor/archive.rs` `seal_archive` -> `sealed.rs` `seal_extents_report`; extents from `sealed/exec_arguments.rs` `archive_serve_extents` | shmem | 14.90 | PLE rows (`read_rows_chunk`) | -| VRAM expert tier | engine | `qwen_forward/original_serve_residency/open_tier.rs`, copies bank bytes by profile rank (11,280 slots, 1.95 MiB each, 21.5 GiB) | device | | the MMQ kernels decode a block in registers per multiply; no decoded copy is stored (S) | -| page cache of the shards | the load | `memory_governor/page_cache.rs` `drop_file_cache` (twice: after the bank, after the stack open) | file | ~2.6 (M) | nothing | - -So in the product the bytes are not duplicated: the bank holds the experts, the memfd holds PLE rows (a different tensor family, KAR level 2), and the 1223 other records of the archive (never read) are holes. -The VRAM tier is already "compressed, decoded only where multiplied" in the Original's own format (GGUF quant blocks). What the owner asks beyond that, a KAR-coded bank (35.16 GiB instead of 46.84), is a different -and lossy encoding (relative L2 0.33 at level 2, 0.165 at level 3) and is section 4, step 6. - -## 3. Candidates - -| # | candidate | smallest change | freed (host) | quality / identity | risk | status | -|---|---|---|---:|---|---|---| -| C1 | holder seals sparse (`--sparse-ple`), supervisor refuses a `ple_only` profile on a full memfd | 1 script line + `sealed/single_copy.rs` (40 lines) + 12 lines in `supervisor/archive.rs` | **36.6 GiB** shmem (E; A6 measured 55.2 -> 18.6 GiB Shmem) | bitwise: same rows, same pages (Q12: 2057/2057 top-16 rows, 1036/1036 draft lines) | the live holder must be restarted; old jobs with profile `full` need `HOLDER_MEMFD=full` | **this commit** | -| C2 | bank built from the memfd / KAR | new decoder, GGUF-layout kernels, F32 scratch (18.75 MiB per expert) | 11.7 GiB host, +3.7k VRAM slots (E: 21.5 GiB / 1.465 MiB) | lossy (L2); needs the 245k quality gate | high; refused today with the optimized MMQ owners | step 6, experimental | -| C3 | PLE from the file, O_DIRECT, bounded row cache (`kar_source: file`) | exists (`rtx5090-32g-file`) | 14.9 -> cache size (E: ~4 GiB touched at 256k) | bitwise (per-read identity check) | decode 82.7 vs 153-154 tok/s measured with the page-cache form (A6); O_DIRECT cache never measured; model volume is unstable | step 5, owner approval | -| C4 | bank as `mapped` (B1/B2) | exists | ~0 at 256k (whole bank touched per prefill chunk) | bitwise | prefill/decode loss (job 917) | rejected | -| C5 | drop the dense host copy after upload (T12) | engine | 1.37 GiB | bitwise | low | step 3 | -| C6 | park on overwrite (T6/T7) | store | 3.2 GiB at 245k | bitwise restore | medium | step 4 | - -Files of the speed session (`original_serve_residency*`, `cpu_expert_miss`, `original_verify_gpu_plan*`, `original_expert_stager*/cache*`) are not touched by C1. C2, C5 and C3's engine part would touch -`original_serve_residency/open_tier.rs` only to read the compressed form; that is for the owner of that session. - -## 4. Ordered steps and what each measures - -Common record (charter): server `rnr5090`, RTX 5090, driver 595.99, CUDA 13.2, binary sha256, model digests (shards `4c1eb2ce`, `316b46f3`, archive `536d612c`), cache state at start, token counts and distributions. -Series every 5 s by `scripts/e2e/sample_env.sh` + `scripts/e2e/decode/ram-inventory.sh` at READY, at each turn end and every 60 s: RssAnon, RssShmem, VmLck, Shmem, MemAvailable, Free, Cached, -`/proc/pressure/memory` (some/full total), `/proc/vmstat` `allocstall_*`, `pgscan_direct`, `compact_stall`, swap. Report deltas over the run, not boot totals (the 2026-11-09 totals are since boot). - -| step | change | measurement before -> after | gate | -|---|---|---|---| -| 0 | read-only evidence on the server (no restart) | `holder3.out` allocated bytes; `ram-inventory.sh before`; PSI and vmstat counters | memfd allocated ~55.3 GB confirms section 1 | -| 1 | this commit; then restart the holder with `single-copy-holder.sh` (hex-finish owns the queue) | Shmem 58.6 -> ~20 GB; MemAvailable 7-8 -> ~44 GiB (E); RssAnon unchanged; PSI memory some and allocstall per hour -> ~0 (U, the hypothesis of the host stalls); engine log `sealed memfd` line shows 14.9 GiB | identity: replay `out_sha` of every request equal (`scripts/e2e/codex/speed/replay_hash.py`), top-16 logprob rows and draft trace equal on the replay gate; **paired A/B, n >= 10 blocks**, arms F (`HOLDER_MEMFD=full` + `LELEKA_ALLOW_FULL_MEMFD=1`) and S (sparse), interleaved by holder restart, same recorded cells (`VANL/nestng-crm-r2`, `VANL/ttt-r3`) through `spd_ab_job.sh`, `ab_report.py RUN F S --skip 3`; tok/s within run noise (A6: +0.58 %, se 0.91) and host-stall spans (prefill input) not longer | -| 2 | retire the Python holders: `run_holder2.sh` and `kar_holder2.py` (buffered 16 MiB reads leave a second 50 GB copy in the page cache) replaced by `single-copy-holder.sh` everywhere; `baseline-reboot-series.sh` and `kar-file-ab.sh` still name them | `fincore` of the KAR and shards (`ram-inventory.sh` pagecache block) after the holder is READY: ~0 | page cache of model files < 1 GiB | -| 3 | T12: free the dense host copy after upload | RssAnon -1.4 GiB | ids identical, replay `out_sha` equal | -| 4 | T6/T7: park on overwrite | anon -3 GiB at 245k; switch latency +0.4 s at most | restored state bit-equal | -| 5 | C3: PLE from file, O_DIRECT, bounded cache | Shmem -10 GiB (E) | `window.ple`, tok/s, TTFT within noise on the 245k replay, else keep step 1 | -| 6 | C2: KAR-coded expert bank and slots (experimental, never default) | host -11.7 GiB, slots +33 % (E) | the Original's own quality envelope at 245k (separate gate, charter), then paired A/B n >= 10 | - -## 5. What this commit does (step 1, code) - -* `crates/deploy/src/sealed/single_copy.rs`: `single_copy_verdict(form, allocated_bytes, allow_full_copy)`. A `ple_only` profile accepts an inherited memfd that allocates at most the extents (16,000,348,672 B) + 1 GiB; - anything above is refused with the remedy. `LELEKA_ALLOW_FULL_MEMFD=1` is the explicit, logged override; `memfd_extents: full` profiles are unaffected. -* `sealed/linux.rs` `inherited_archive_allocated_bytes(fd)` (`st_blocks * 512`; a stub on non-Linux). -* `supervisor/archive.rs` `check_single_copy`, called from `open_inherited_archive` (the one path of `up --kar-fd` and `run --kar-fd`). -* `scripts/e2e/decode/single-copy-holder.sh`: `--sparse-ple` by default, `HOLDER_MEMFD=full` for the old form. -* Tests: verdict table, override, `st_blocks` of a real memfd (hole = 0, 4 MiB written = 4 MiB). U: the end-to-end run on the server with a real holder. - -## 6. Not verified - -The cause in section 1 is derived from the byte accounting and the scripts; it is not read from the server. The PSI/allocstall improvement is a hypothesis until step 1 is measured. The end state is -RAM = PLE 14.9 + bank 46.84 + K/V 3.09 + other ~4 = ~69 GiB of 121, not "compressed everywhere": that needs steps 5 and 6. diff --git a/docs/e2e-run.md b/docs/e2e-run.md deleted file mode 100644 index b0b54896..00000000 --- a/docs/e2e-run.md +++ /dev/null @@ -1,310 +0,0 @@ -# End-to-end run of the production stack on the RTX 5090 - -Branch `claude/e2e` (cut from `claude/port-gpu-bringup`, merged with `0b0d128` = integrated head incl. `claude/deploy`), runs of -2026-10-17 on `rnr5090` (Ubuntu 26.04, kernel 7.0.0-38, RTX 5090, driver 595.99.02, 121 GB RAM). Everything below is a functional -and stability result of the **current** code, one sample per cell; it is not a performance or quality claim (charter rules: no paired -A/B, no quality gate). - -Stack under test, all four processes started inside a holder job (sealed KAR memfd inherited, `MODEL.lock` held by the holder): - -```text -python3 e2e_client.py (Codex-shaped Responses requests) -- HTTP, Bearer test key --> leleka-api serve (runtime block) 127.0.0.1:8081 -leleka-api -- gRPC, runtime token ----> leleka-inference --backend-mode original 127.0.0.1:18766 -leleka-cli load-mtp (through leleka-daemon 127.0.0.1:18080) loads the model; leleka-api only attaches. -``` - -## 1. Binaries (built in WSL, never on the server) - -`cargo build --release --locked -p leleka-engine-host --bin leleka-inference --bin leleka-daemon --bin leleka-cli -p leleka-control-plane --bin leleka-api -p leleka-deploy --bin leleka` -(rustc 1.99.0, WSL2 Ubuntu 24.04, `CARGO_TARGET_DIR` outside the tree), sm_120 default and `--features leleka-engine-host/sm86`. Only the first four were copied to -`rnr5090:~/work/leleka-e2e/bin-sm120/` (`scp`, mode 0755). The sm86 binaries were built and started with `--help` in WSL (RTX 3080 Laptop, cc 8.6, `ldd`: libc, libm, libgcc_s), not run against a model here. - -Final build, tree `73e77f8` (= `claude/port-gpu-bringup` head `4f7c461`-era merge + this branch; the Codex jobs 943b / 945 ran the earlier build listed second): - -| binary | sm_120 bytes | sm_120 sha256 | sm86 bytes | sm86 sha256 | -| --- | ---: | --- | ---: | --- | -| leleka-inference | 69,249,120 | `0eb83374e9782ded5c2d8d62d2552b4efd8c37142ea62d3d2309f9fcfe40eb26` | 120,106,704 | `30e08783873e7dc952020a8f93cf9232ef7ccb4c7f07ed5a18fbb8b81e6f0a2d` | -| leleka-daemon | 23,340,736 | `f7908fc6f4d5924bb9b3ebbd1ef7e7158fcc8bdde72d5efe515a896973b17cbb` | 23,340,024 | `a73a1c0e8ecc7241436a81c2da85fa9b8ce6369712a7fbc1ad87a75e2ed1a63d` | -| leleka-cli | 10,462,568 | `19bf908a56e900677b46488a11c1860cc7e524a1d9615b72a1effa712b5f2d3b` | 10,462,472 | `8c44891388e859e8c1525bfa0fc8b8df10e3d24b73950470b0620f3bdb7b7f2c` | -| leleka-api | 28,834,064 | `ce98d23fd4e9efcbd3c46ca322641c1cbec8b3af142762866467143b3533b9b7` | 28,834,048 | `2fa5573f1c2062e50e6e9e8c6e0a4af704906222ba3ef6f92efacc6f9721d0f2` | -| leleka (deploy supervisor, not copied) | 2,938,592 | `b2be6e21e19975387141f314ecc92c681bb8a91e48338b102ca432d96a87d053` | 2,938,592 | same | -| leleka-runtime-tests (replay smoke, server: `leleka-runtime-tests-73e77f8`) | 79,533,344 | `4d0b400d951f0f485a5b31c66c8952669b11a64323dc46896b937b4a1a49a321` | | | - -Binaries of the Codex jobs 943b / 945 and the replay job 947 (the server copies in `bin-sm120/`): `leleka-inference` `484b7622274ec80cab5357dd304de41c5a311163161a5daf7e4771fe8f1c4eae`, -`leleka-daemon` `8d681a3a3a88d5b354481766998fc5a72780e8d0e942c57e3280baaecdd8d0bd`, `leleka-cli` `8615325793196b3740a584916e70b09bedaa5c16a3e1d03ba955cae5749bbd0c`, -`leleka-api` `ac0bfa40215844148785680697c693c01616c7ec0bcb34f65e3623af849c0768`, `leleka-runtime-tests` `a4dfb8530b76a19e7114c64ee0ebf1062d9a52d533cb46310fd31a4d73bbfc2e`. -Cargo unifies features per build, so byte identity of `leleka-api` / `leleka-daemon` between the sm_120 and sm86 builds is not expected. The `leleka` supervisor (native sealed memfd) is not used by these -jobs: inside a holder job a second 55 GB memfd would not fit, so `scripts/e2e/run-e2e.sh` starts the same processes with the holder's descriptor (`--kar-archive-fd $LELEKA_STRA169_KAR_FD`), the flags of -`deploy/rust-runtime/profiles/rtx5090-32g.json` (`--gpu-budget 25769803776`, `--context-tokens 262144`, resident expert source) and the bring-up expert-tier environment of the 98x jobs. - -## 2. How to rerun - -```sh -# on the laptop: build (WSL), copy the four binaries and scripts/e2e to rnr5090:~/work/leleka-e2e/ (see section 1) -# on the server: drop a holder job, e.g. ~/work/gpu-runs/holder2/jobs/942-e2e-full.sh (template: section 8) -E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 E2E_OUT=$HOME/work/leleka-e2e/runs/NAME \ -E2E_CLIENT_ARGS="--soak-n 40 --burst 20 --xlong-tokens 24000" bash ~/work/leleka-e2e/scripts/e2e/run-e2e.sh -``` - -`run-e2e.sh` refuses to start unless it inherited a sealed memfd and `MODEL.lock` exists, nothing else holds the GPU and no stack process is -running; it generates the two service tokens and the API key into mode-0600 files (never printed), extracts the tokenizer assets, starts -`leleka-inference`, `leleka-daemon`, runs `leleka-cli load-mtp` and **fails fast** on a `leleka-load phase=` line, starts `leleka-api`, waits -for `/ready`, runs `scripts/e2e/e2e_client.py` (or `E2E_RUN_CMD`, used by the Codex jobs), samples RSS/VRAM every 30 s (`env.tsv`), then stops -with SIGINT and reports left-over processes and GPU applications. Logs and `results.json` are written under `E2E_OUT` -(`inference.log`, `leleka-api.log`, `daemon.log`, `client.log`, `results.json`, `env.tsv`); they stay out of Git. -`scripts/e2e/run-fake.sh` + `fake_llm_engine.py` run the identical client against a scripted engine without GPU (465 checks pass); that is how -the client's own checks were debugged. - -## 3. Runs - -| job | what | result | -| --- | --- | --- | -| 940 | first stack start | load failed: `new_original_prompt_arena: InputRead` (defect 1); job aborted by me after 10 min (the runner then had no fail-fast) | -| 941 | after fix 1, `LELEKA_BRINGUP_TRACE=1` | load 390 s, all scenarios ran in 2 min, 11 checks failed (tool-call format of the model, test expectations, defects 3-5) | -| 942 | after fixes 3-6, soak 40, burst 20, xlong 24k | load 371 s, 13 scenarios, **459 checks, 9 failed, 0 errors**; all 9 are the model's malformed tool calls (section 5); no leaked process, GPU back to 2 MiB | -| 946 | queued: `long` scenario with tools off | pending in the serial queue when this was written (section 9) | - -## 4. Results (job 942 unless noted; sm_120, `--backend-mode original`, prompt cache on (6), expert tier 2048 slots, adaptive) - -Model load through `leleka-cli load-mtp`: 371 s (942), 390 s (941). After load: `leleka-inference` RSS 53.6 GB (49.6 anon + 3.8 shmem), VRAM -13.2 GB, host MemAvailable 14.3 GB (the sealed memfd holds 52 GB of shmem outside the process RSS). - -| scenario | checks | measured | -| --- | --- | --- | -| endpoints (`/health` unauthenticated, `/ready`, `/status`, `/metrics`, `/v1/models[/id]`, `/api/health`, `/admin/lifecycle`, 401 without or with a wrong key, 404 stored id) | 12/12 | all as specified; `/status` answers in < 2 s while a generation runs | -| simple (Codex-shaped: instructions + developer + environment + user items, 4 function tools, `reasoning`, `include`, `text.verbosity`, `prompt_cache_key`) | 37/37 | 980-token prompt: TTFT 2.95 s first request (cold, graph capture), 0.36 s when repeated (973 reused); `max_output_tokens: 24` -> `response.incomplete`, `max_output_tokens`, `output_tokens == 24`; `/v1/responses/input_tokens` equals `usage.input_tokens` exactly (tokenizer agreement with the engine; no `the engine counted N input tokens, the control plane M` line in any log) | -| tools (3 tools, stream + stateless replay of the output items and `function_call_output`) | 99/102 | all three first calls valid JSON, names declared, arguments schema-valid; continuation after the tool result produced prose (59 tok/s decode); turn 2 re-prefilled 170 / 88 / 108 of 1150 / 1070 / 1100 tokens (980-992 reused); the 3 failures: forced `tool_choice`, `tool_choice: none` (section 5) | -| multiturn (`previous_response_id` and full replay) | 82/82 | turn 2/3 of 329/358 prompt tokens: 294/322 reused, 35/36 re-prefilled, TTFT 0.69/0.72 s; replay path identical numbers; GET, `input_items`, DELETE, 404 after delete, continuing from a deleted id 404 | -| long (8.5k tokens, tools declared) | 28/34 | the model answered with a malformed shell call 3 of 3 times -> `response.failed` (section 5); the cache numbers come from `xlong`, the tools-off rerun is job 946 | -| xlong (23,331-token prompt) | 25/25 | prefill 18.0 s = 1,295 tok/s, **one SSE `: keep-alive` comment** during the prefill; follow-up turn: 23,324 reused, **53 re-prefilled**, TTFT 0.88 s | -| cancel | 42/42 | disconnect mid-decode: engine idle again after **0.05 s**, `metrics.generation.cancelled` +1, next request fine; disconnect during a 6,036-token prefill: idle after **1.6 s** (cancel is polled per prefill chunk); re-sending the cancelled prompt re-prefills all 6,036 tokens (cached 0, TTFT 4.8 s) | -| parallel | 35/35 | the engine serves one generation at a time: B (stream) and C (JSON) sent while A (420 tokens, 5.3 s) ran were **queued** (`/metrics`: `active=true`, `queue_used=2`, `queue_capacity=16`), answered correctly in order, B's first text 1.26 s after A ended; a burst of 20 simultaneous requests gave 17 x 200 and 3 x 429 `runtime_overloaded` with `Retry-After` (`max_in_flight_requests` 17), all admitted ones completed (21.7 s) | -| invalid (24 bad requests) | 52/52 | 400 with `error.{message,type,code,param}` for malformed JSON, missing/empty/mistyped fields, unknown field, zero/negative/above-cap `max_output_tokens`, sampling out of range, bad tool (no name, bad name, duplicate, undeclared `tool_choice`, hosted), image, `reasoning_budget_tokens`, bad effort, `json_schema` without schema, **context overflow**; 404 for unknown model and `previous_response_id`; no half-open SSE for an invalid streaming request | -| compat (Chat Completions, Messages, tool call over Chat) | 3/3 | | -| determinism | 2/2 | greedy x3 identical; the seeded sampled pair matched in 942 and differed in 941 (`C++` vs `C`): documented envelope of the adaptive expert tier (`original-serve.md`), recorded as a note, not a failure | -| reasoning (Codex default `effort: medium`, `summary: auto`) | 26/26 | reasoning item + message, `reasoning_tokens` 14 of 19, replay of the reasoning item accepted (981 of 1027 reused) | -| soak (40 consecutive requests, alternate stream/JSON, every 4th a tool call) | 7/7 | all 40 ok (10 tool calls schema-valid), latency 1.69 / 1.87 / 2.09 s (min/p50/max), decode 60.7 tok/s mean; `leleka-inference` RSS +0 MiB, `leleka-api` +0, daemon +0, **VRAM +0 MiB** after warm-up; `/metrics` delta started 40 = completed 40 | - -Whole job 942: 98 generations seen by `leleka-api` (log line `generation done:`), 145,787 prompt tokens of which 30,878 reused (21 %; the -low share comes from the soak and invalid-input requests, whose ~980-token system prefix is below the cache's `--prompt-cache-root 2048` threshold -and therefore never reused across unrelated prompts), TTFT median 1.63 s (p90 1.68 s, max 18.0 s), decode median 68.4 tok/s per request -(10th-90th percentile 48.9-89.0), sum-weighted 68.5 tok/s over 1,791 tokens. Memory over the job (7 samples): inference VmRSS 53,611 -> 54,347 -MiB (+0.7 GB while the 24k prompt was served, flat in the soak), VRAM 13,192 -> 13,424 MiB, MemAvailable 14.3 -> 13.5 GB, no growth trend. - -Teardown (every job): `SIGINT` to leleka-api, daemon, engine: all exited, `pgrep` empty, no GPU compute applications, `free -m` back to -avail 68.8 GB; the one forced abort (job 940) also left nothing behind. - -## 5. Findings - -### Defects fixed on this branch (each with a test) - -| # | defect | repro | fix | -| --- | --- | --- | --- | -| 1 | `leleka-inference --backend-mode original` could not load: `MoeWeightCache::new_original_prompt_arena: InputRead` (the retained routed-expert bank was never admitted on the Original path; only the serve smoke did it) | job 940 | `9b56aec`; the integrated branch carried an equivalent fix (`--expert-source resident|mapped`), my duplicate was dropped in the merge `98b7cf2`. Covered by the real load of jobs 941/942 (needs a GPU, no unit test possible) | -| 2 | at most **256 generations per runtime epoch**, then every request failed with `generation_capacity` until the engine was restarted and loaded again (`RuntimeServer` request ledger and the engine `Proxy.seen`) | `api_over_runtime::documents_the_256_generations_per_runtime_epoch_limit` (old test) | `b4d12bd`: `leleka_backend_api::RecentIds`, a FIFO window of the 16,384 most recent ids; test `serves_more_than_256_generations_in_one_runtime_epoch` (300 requests) + 4 unit tests + the rewritten RPC test | -| 3 | client errors surfaced as server errors: a context overflow or `max_output_tokens` above the runtime cap was queued and refused by the worker as **502 `generation_failed`** (SSE: `response.failed` after a 200) | `invalid[...]` rows of job 941 | `f5925f3`: 400 `context_length_exceeded` / `invalid_output_limit` before queueing; tests `a_prompt_that_cannot_fit_the_context_is_a_400...`, `the_runtimes_output_cap_...` | -| 4 | the default output budget (`context - prompt`) ignored the engine's 8-token margin, so a prompt close to the context failed at the worker | same | `f5925f3` (default leaves the margin) | -| 5 | `reasoning_budget_tokens`, `strata_tune`, `experimental_speed_projection` and sampling finer than the fixed point were 502 after queueing | `invalid[reasoning_budget_tokens]` = 502 in job 941 | `af3beab`: 400 `unsupported_request_field` / `invalid_sampling_precision` for a text-level engine; test `text_the_contract_cannot_carry_is_refused_not_dropped` | -| 6 | no operator-visible trace of why a generation failed or how a request went | `leleka-api.log` had one line | `af3beab`, `da187a9`: `generation failed: ` and one `generation done: finish= prompt_tokens= reused= generated= prompt_ms= decode_ms=` line per request; `STRATA_DEBUG_FAILED_OUTPUT=1` additionally logs the generated text of a failed tool turn (operator debugging only) | - -All of `cargo test -p leleka-control-plane` (274 lib + integration, 28 in `backend_worker_http`), `-p leleka-engine-host`, `-p leleka-runtime-client`, -`-p leleka-backend-api` and the 10 runtime-stack HTTP smokes (`scripts/test-api-over-runtime.py`) pass on Linux after these changes. - -### Model-origin tool-call failures (not fixed, repro below) - -Every failed generation of job 942 (4 of 98) was a malformed tool call **produced by the model**, correctly refused by the server (the full stream -is `response.failed` with the message; nothing partial is published as a call): - -* `` with `["ls"]` instead of `` -> `tool call has an invalid parameter or is incomplete` (forced-choice test). -* `shell` with `command` a plain string (`ls /workspace/leleka`, `grep -rn "tools" ... | head -50`) where Codex's schema wants an array of strings -> - `function call arguments violate schema: "..." is not of type "array"` (3 of 3 attempts in the 8.5k-token `long` scenario; the same tool with a short - context was called correctly 5 of 5 times in `tools` and the soak). -* forced `tool_choice` to `update_plan`: the model called another tool -> `generated tool does not match forced tool choice`; there is no constrained decoding - anywhere in the stack, so forcing is only validated afterwards. - -This is the quality risk for a real Codex session (the model may emit the string form of `shell.command` once the context grows). The stack has no -repair step: a daemon-side "one regeneration on invalid output" exists only in `leleka-daemon`'s experimental tool adapter. Candidate fixes (not implemented, -need the quality gate of `AGENTS.md`): schema-driven constrained decoding for tool arguments, or a bounded retry in `backend_worker`. - -### Observations for other workstreams - -* Prefix reuse works across turns of one conversation (294/329, 322/358 tokens; 23,324 of 23,377 on the 24k prompt; engine `reused=` agrees) and across a stateless replay. It does - not help unrelated requests that share a ~1k-token system prefix (root checkpoint needs 2048 tokens), nor a re-sent prompt whose first attempt was cancelled in prefill. -* Cancel during prefill takes up to one prefill chunk (1.6 s here, chunk 2048). -* `MemAvailable` stays at 13-14 GB while serving (52 GB sealed memfd + 54 GB engine RSS on a 121 GB host): no headroom for a second large process. -* A job costs 6 min of model load before the first request; the serial holder queue (stale per-pass snapshot) delayed every job of this branch by 1-4 hours. -* The golden fixtures in `control-plane/tests/fixtures/golden` hold Python-server HTTP-surface and `GEN` line goldens produced with a fake - engine, no model-generated tool calls, so model tool-call output could not be compared with the Original server through them; tool-call integrity is checked by - parsing (JSON arguments, declared name, schema validation), by delta == done == item equality in the stream, and by the 216-case tool-policy smoke. - -## 6. Contract checks (what is verified where) - -| requirement | check | result | -| --- | --- | --- | -| tool-call JSON integrity | every call: name in the declared set, `arguments` parses as an object, schema-valid, `call_id` present; streamed argument deltas == `arguments.done` == final item | pass for all successful calls (3 + 1 forced-none excluded + 10 in soak + chat) | -| streaming event order | first `response.created`, strictly increasing consecutive `sequence_number`, `event:` name == `data.type`, every added item done, exactly one terminal event and it is last, text deltas == `output_text.done` == final message | pass for every stream of the runs (about 60 streams) | -| usage counts | `usage.total == input + output`, `input_tokens` == `/input_tokens` endpoint, `output_tokens` == engine count (24 for a 24-token limit), `cached_tokens` == engine `reused=` | pass | -| stop reasons | stop -> `completed`; length -> `incomplete` + `max_output_tokens`; cancelled -> no terminal for the closed client, `cancelled` metric | pass | -| cache reuse across turns | `usage.input_tokens_details.cached_tokens` per turn, table above | pass | -| cancel frees the engine | `/metrics` `active=false` after 0.05 s (decode) / 1.6 s (prefill) | pass | -| no leaked processes | `pgrep`, `nvidia-smi --query-compute-apps` after every job | none | -| memory stable over 40+ requests | `env.tsv`, soak samples | +0 MiB RSS, +0 MiB VRAM | - -## 7. The real Codex CLI (0.163.0) against the stack - -Operator-approved downloads, made by the coordinator and verified: Codex CLI `rust-v0.163.0` `codex-x86_64-unknown-linux-musl` (unpacked binary sha256 -`399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215`, `codex --version` = codex-cli 0.163.0), three.js 0.170.0 (`three.module.min.js`, sha256 -`08fd7545d13d2c7fb65ab691530a802dafefd638596501854f267d0fb13c39e7`), and on the laptop Node 22.16 + Playwright 1.49.1 + Chromium 131 (the server has no node or browser: the -agent verifies with Python only, and the six browser checks run afterwards on the laptop). Config: isolated `CODEX_HOME`, `wire_api = "responses"`, `approval_policy = "never"`, -`sandbox_mode = "workspace-write"` (no network), effort medium, `model_context_window = 262144`, `web_search = "disabled"`, key from a freshly generated test key in `E2E_API_KEY`. -The engine ran with the shipped options (KAR PLE level 2, `--backend-mode original`, spec_min_p 0, expert tier 2048 slots adaptive, INT8 K+V 32768 resident cells), **greedy** -(Codex sends no sampling and the config has no `sampling` block: the Original server's default too), profiling on (`LELEKA_SERVE_PROFILE=1`, `LELEKA_BRINGUP_TRACE=1`), engine capture on. -Prompts: tic-tac-toe `scripts/e2e/codex/prompt-threejs.txt` sha256 `f57248412f69b4a6a76aab00c2ff33ee3ce676849768f847d412c7e9e9d8a074` (own equivalent of the old private prompt, without the -LeaseVibe part); CRM `prompt-crm.txt` sha256 `2ab4d92db393334f1ac953086116cefb9744b522b98bfd4ea6efd7e02e319af9` (phase 1 build, phase 2 seven-item refactor-and-extend to make the agent read and edit many files). - -What Codex needed from the stack, found before spending GPU time (a mock `/v1/responses` server, `scripts/e2e/codex/mock_responses.py`): its default request carries the hosted tool -`{"type":"web_search"}` (refused with 400 by design, so `web_search = "disabled"` is part of the config, as `scripts/install-qwen-native.py` already does), a `namespace` tool -`multi_agent_v1` (10 KB, accepted), `exec_command` (a string `cmd` parameter, **not** the array `command` of the older `shell` tool: the "shell.command as a string" failure of section 5 cannot occur with -this Codex), `write_stdin`, `view_image`, goal tools, `parallel_tool_calls: true`, a 17 KB developer message, `include: [reasoning.encrypted_content]`; about 9.3k tokens before the first user word. -`apply_patch` is a shell command (`apply_patch < 55.0 GB, VRAM 13.2 -> 13.6 GB, MemAvailable 14.4 -> 12.8 GB | RSS 53.7 -> **60.4 GB**, VRAM 13.3 -> 13.7 GB, MemAvailable 14.0 -> **7.4 GB** (flat from about minute 10) | -| tool-call failures | none at the API (0 `generation failed`); 5 of 53 commands exited non-zero (missing `node`, a malformed `apply_patch` heredoc, grep, a probe, `git status`), all handled by the agent | none at the API; 2 of 60 commands exited 1: a malformed `apply_patch` ("must end with *** End Patch") that Codex returned to the model, which re-sent it correctly | - -Reading: a real agent session is dominated by **decode (84-86 % of wall time)**. The engine reuses 96.5 % of the prompt, close to the 98-99 % of the vanilla runs, yet both sessions decode at -72-75 tok/s against 116-150 for the vanilla runs on the same host. Decode speed is flat from 4k to 123k of context, so the gap is not a context effect; what differs is the engine -configuration (shipped spec_min_p 0, tier hits 43-49 % from VRAM) and the accepted drafts per round (2.9-3.4 tokens per verify round); suffix-draft share is not logged. The prefix cache -(CRM) served 83 of 84 prompts from a stored checkpoint (`hits=83 misses=1`, 7.3 of a 7.5 GiB budget used, 23 evictions) but resumes at a 2048-token grid node, so every turn re-reads -the partial block (about 2.2k tokens per turn against a roughly 340-token real suffix); the conversation cache of the tic-tac-toe run re-read about 1.1k per turn. - -MemAvailable dips: the CRM session's 7.4 GB minimum is the prefix cache filling its auto budget (75 % of available minus 4 GiB at open = 7,476 MiB, used 7,330 MiB) plus 6.7 GB of engine RSS -growth over the session; it stayed above the cache's 3 GiB insertion floor (4.4 GiB headroom at the minimum), the cache evicted inside its budget, nothing was shed and nothing failed. -The memory-safety agent was given these numbers. - -**Defect 7 (fixed: output cap 4096 -> 32768).** Job 943: at 14.3k context the model wrote the whole `index.html` in one tool call; the runtime facade cut every generation at 4,096 tokens -(the Original server has no such cap: `max_tokens` 0 = the rest of the context). Codex saw `response.failed` ("tool parameter is incomplete"), reconnected twice with the identical request -(greedy, same cut) and then `turn.failed` ("incomplete: max_output_tokens"), exit 1. The decoded captured tokens show a coherent design monologue followed by an unfinished HTML file, not a -repetition loop. `leleka_backend_api::MAX_OUTPUT_TOKENS = 32768` is now the single cap of `RuntimeServer`, the engine request check, `leleka-api`'s runtime default and the `leleka-deploy` -generated config. Also fixed on the way: `/v1/status` always carried `prefix_cache: null`, which broke the `http_surface` golden after the prefix-cache merge. - -**Does Codex recover by itself?** Tool-level errors: yes (a rejected `apply_patch` came back as a tool result and the model corrected it; failed commands were retried or worked around). A -truncated generation: no (Codex re-sends the identical request twice, which is deterministic under greedy decoding, then fails the turn). The model-side `shell.command`-as-string failure of -section 5 did not occur because this Codex has no such tool. - -**CUPTI hook.** The tracer of `claude/ledger` (`~/work/cupti-trace/libleleka_cupti_trace.so`, trigger file `~/work/codex-e2e/cupti/cupti.trigger`, helper `scripts/e2e/cupti_trigger.sh`) was injected -into the engine of job 945 and stayed armed and idle (nobody fired a window during the 25-minute session); the 943b run had it off. Armed-idle overhead is therefore not measured separately. - -**Per-request data.** `docs/e2e-data/{943b,945}-trace.csv` (one row per generation: prompt / reused / re-prefilled tokens, TTFT, decode tokens and tok/s, rounds, tokens per round, tier -shares, prefix-cache resume, gap before the request and the command time inside it, RSS / VRAM / MemAvailable), `*-analysis.txt` (the session report of `scripts/e2e/analyze_session.py`: time shares, -context growth, prefill cost against context, slowest requests with causes, ideal against actual) and `*-env.tsv` (10 s samples). Captures of the prompt and generated token ids for offline -replay are private: `rnr5090:~/work/codex-e2e/capture/{943b-codex-ttt,945-codex-crm}/`. - -**Replay.** Both sessions were captured by the engine (`LELEKA_CAPTURE_DIR`: prompt ids and generated ids of every completed request, plus sampling fields) and are replayable offline by the ignored test -`original_serve_replay_smoke` (`crates/engine-qwen35-cuda/src/backend/original_serve_replay.rs`; greedy, recorded output length as the budget, one stack, requests in order, so the conversation or prefix cache -behaves as in the live session). Job `947-e2e-replay.sh` (template `scripts/e2e/codex/jobs/`) replays 943b with the conversation cache and 945 with `LELEKA_REPLAY_PREFIX_MIB=auto`; its logs go to -`rnr5090:~/work/leleka-e2e/runs/947-replay/{ttt,crm}.log` (`REPLAY #n ...` per request, `REPLAY SUMMARY weighted_decode_tok_s=...`). **It had not run when this was written**: the serial queue was held by a long -ledger job (9003, running more than three hours), so there is no replay number in this report; the live numbers above are the baseline to compare it with. The adaptive-spec and decode-parity agents were told -where the corpora and the harness are. - -### 7b. Reference-equivalent reruns (943c, 945c) and replay arms (948): queued, not run when this was written - -The sessions above ran the **shipped** options, which are not the configuration of the reference runs (115.7 / ~150 tok/s: the Original with `--spec 4 --spec-min-p 0.5`, INT8 K+V with 32,768 -resident cells, the automatic per-layer expert cache of about 9,971 slots). Differences found: - -| setting | jobs 943b / 945 (shipped) | reference / reruns 943c, 945c | -| --- | --- | --- | -| expert cache | `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048` (run-e2e default, 43-49 % of entries from VRAM) | `auto`, per layer, profile of the 98x/990 jobs, `--gpu-budget` 30 GiB (as the 98x auto-cache jobs) | -| `--spec-min-p` | not passed (engine default 0 = full window) | 0.5 | -| MTP draft vocabulary | **not bound**: `leleka-inference` was started without `--mtp-rt-dir`, so `rt_directory` was None and the MTP chain step drafted over the full 248k-row head (about +0.18 ms per step, 3-4 steps per round; ledger agent) | bound: `--mtp-rt-dir /home/para/work/leleka/models/leleka-gates/assets/data/mtp-rt` (`draft_vocab.bin`, 106,299 rows, the Original's) | -| MTP depth / seed / tier adaptation | depth 4 (Original default), seed and adaptive tier at the head defaults | same | - -Confirmed from the command lines in `run-e2e.sh` at the time: 943b and 945 had no `--mtp-rt-dir`. Changes made: `run-e2e.sh` now always passes `--mtp-rt-dir $A/data/mtp-rt` (`E2E_NO_RT_DIR=1` reproduces the old -behaviour); `leleka-deploy` generates `--mtp-rt-dir ` in the engine command (test `server_engine_command_matches_the_documented_one` updated) so `leleka up` binds the draft vocabulary; the replay test honours -`LELEKA_ORIGINAL_SERVE_RT_DIR`. Jobs (all in `jobs/PRIORITY` below the adaptive-spec and ledger jobs): `943c-e2e-codex-ttt` (conversation cache) and `945c-e2e-codex-crm` (`--prefix-cache-mib auto`), both with -auto slots, `--spec-min-p 0.5`, the draft vocabulary, the head build, CUPTI off; `948-e2e-replay-arms` (first 30 requests of the 943b capture, four arms: 2048 / auto slots x spec_min_p 0 / 0.5, plus auto + 0.5 without the -draft vocabulary, each with weighted decode tok/s, tokens per round and tier shares); `947-e2e-replay` is the baseline replay of the full 943b and 945 captures with the shipped options. Results go to -`rnr5090:~/work/leleka-e2e/runs/{943c-codex-ttt,945c-codex-crm,947-replay,948-replay-arms}/`; if the sessions reach 115+ tok/s the production profile -(`deploy/rust-runtime/profiles/rtx5090-32g.json`) should carry: expert slots `auto` per layer with the shipped profile file, `--spec-min-p 0.5`, `--gpu-budget` as the 98x auto-cache jobs (30 GiB), and the draft vocabulary (done). - -**Result of the first reference-config attempt (jobs 943c / 945c) and the defect it exposed (defect 8, fixed).** Both runs ended with Codex exit 1, but not because of Codex or its sandbox -(the `Rejected(... rm -f ...)` line in `codex.err` of 945c is the Codex exec policy refusing one `rm -f` command; the agent carried on) and not because of model quality: the engine returned -`leleka-serve request failed: class=CudaExecution` for every attempt of one request (Codex re-sent it twice, then failed the turn). 943c died on its very first request (9,358-token prompt), 945c on request -24 (71.7k-token prompt) after 23 good requests. The engine trace shows the same chain both times: `draft ring open` -> `fallback reason: RegionTooSmall` (a prompt whose tail is only a few tokens takes the scalar -draft-KV fallback) -> `scalar draft-kv matrix EmbeddingNorm: buffer is not the retained one` -> `InvalidProjectionShape` -> `CudaExecution`. The fallback verifies that the retained scalar MTP weights are the very -buffers of the pinned pack's MoE cache; with `--mtp-rt-dir` (the Original's draft vocabulary, the newly bound option) the retained weights come from the RT bank and are separate allocations, so the identity check -could never pass. In the earlier runs (no `--mtp-rt-dir`) the same fallback completed (`after scalar fallback -> Completed`). Fix (`fix(runtime): scalar draft-KV fallback checks its weights against the retained -MTP owner`): `record_original_scalar_draft_kv` now compares against `RetainedOriginalMtpWeights::matrix` (the owner the scalar weights were built from, for either source). It needs a GPU to be proven; jobs -`943d` and `945d` (identical to 943c / 945c, new binaries) are at the top of `jobs/PRIORITY`. - -What the 23 good requests of 945c already show (reference config: 8,419 auto-sized slots per layer, `--spec-min-p 0.5`, draft vocabulary, prefix cache, context 18k -> 69k): **weighted decode 138.8 tok/s** -(55,857 tokens / 402.5 s; per-request median 131.6) against 74.8 for the same task with the shipped options, **expert entries from VRAM 83 %** (PCIe 7 %) against 43 %, tokens per verify round 3.21 against 3.36 -(the speed-up comes from the tier and the shorter draft step, not from more accepted drafts), decode by context 110 (4-16k), 140 (16-48k), 125 tok/s (48-96k), ttft 1.2-2.9 s, 90.7 % of the prompt reused. -That is inside the 115.7-150 reference band, so the 72-75 tok/s of the first sessions was a configuration difference: the production profile should carry expert slots `auto` per layer (with the shipped -profile file), `--spec-min-p 0.5`, `--gpu-budget` 30 GiB and the draft vocabulary (already generated by `leleka up`). 943c produced no completed request (0 numbers). - -### 7d. Reference-config sessions, complete runs (jobs 943d, 945d; binaries with the scalar draft-KV fix) - -Config: expert cache `auto` (8,419 slots per layer, 20.9 GiB, profile of the 98x jobs), `--spec-min-p 0.5`, `--mtp-rt-dir` (106k-row draft vocabulary), MTP depth 4, INT8 K+V 32,768 cells, `--gpu-budget` 30 GiB, -seed and adaptive tier at the head defaults, greedy; 943d with the default conversation cache, 945d with `--prefix-cache-mib auto`. Both Codex runs ended on their own (`codex exit status 0`: the agent declared the task done). - -| | shipped options (943b / 945) | reference config (943d / 945d) | -| --- | --- | --- | -| tic-tac-toe: wall time, requests, context | 918 s, 51, 82k | **203 s**, 20, 37k | -| tic-tac-toe: **weighted decode tok/s** | 71.7 | **128.8** (20,291 tokens / 157.6 s; median 122.4) | -| tic-tac-toe: tokens per round / VRAM tier share / reuse | 2.92 / 49 % / 96.7 % | 2.78 / 84 % / 92.1 % | -| tic-tac-toe: time shares (first text / decode / agent idle) | 12.1 / 85.9 / 2.0 % | 20.6 / 78.0 / 1.4 % | -| tic-tac-toe: deliverable | `index.html` 10,778 B, **6/6** browser checks | `index.html` 9,226 B sha256 `8b2f7122b0024b4b04d15695ef7c6d8bfcc7f882ccdd761ec47f3a7500bd66af`, **6/6** browser checks (laptop) | -| CRM: wall time, requests, context | 1,526 s, 84, 123k | **871 s**, 72, 121k | -| CRM: **weighted decode tok/s** | 74.8 | **130.0** (89,651 tokens / 689.8 s; median 119.8) | -| CRM: decode median by context (4-16k / 16-48k / 48-96k / 96k+) | 65 / 79 / 74 / 68 | 133 / 132 / 121 / **114** | -| CRM: tokens per round / VRAM tier share / reuse | 3.36 / 43 % / 96.4 % | 3.06 / 81 % / 96.1 % (197k of 5.11M tokens re-prefilled; ideal 33k) | -| CRM: time shares (first text / decode / agent idle) | 14.9 / 84.1 / 1.0 % | 19.2 / 79.2 / 1.6 % | -| CRM: memory | RSS 53.7 -> 60.4 GB, MemAvailable min 7.4 GB | RSS 53.6 -> 59.4 GB, MemAvailable min 8.3 GB, VRAM 30.4 -> 30.8 GB of 31.8 GB | -| CRM: deliverable | 21/21 acceptance, 139 tests | **acceptance fails** (see below); its own 125 tests pass | - -Reading: the configuration, not the engine, was the gap. With the reference-equivalent options a real Codex session decodes at **129-130 tok/s weighted** (reference: 115.7 native / ~150 KAR PLE; the -vanilla runs had a different, longer-lived tier history, and one sample each carries no confidence interval), the tier serves 81-84 % of the expert entries from VRAM, and the decode rate degrades slowly with -context (133 tok/s at 4-16k to 114 at 96k+). Tokens per round fell slightly (2.8-3.1 against 2.9-3.4), so the gain is the tier plus the shorter draft step. The prefix cache still re-reads about 2.7k tokens per -turn (a 2048-token grid step plus the reply), six times the ideal suffix. - -**Why the sessions stopped, and what is left.** Neither run died of an engine error any more (the scalar draft-KV fix works: both resumed past the fallback that killed 943c / 945c). The harness's `client rc=9` of -943d is the runner's own code for "no node/Playwright on the server, browser checks not run" (the Codex exit was 0; the six checks were run on the laptop: 6/6); `run-codex.sh` no longer turns that into a -failure. One generation failed in 945d (request 5): the model emitted a native-style call to a function named `apply_patch`, which is not a declared tool (Codex 0.163 exposes `apply_patch` as a shell command); -`leleka-api` refused it (`undeclared function in tool call: apply_patch`), Codex reconnected, and the retried request produced a valid call, so the session carried on (1 of 72 generations; a model-format error, the -same class as section 5). The 945d CRM does not pass acceptance for a bug **the model wrote**: `handlers.py` defines `CRMHandler.handle(self, method)`, which overrides `socketserver.BaseRequestHandler.handle`, so -every real HTTP request raises `TypeError: handle() missing 1 required positional argument: 'method'` and the connection is dropped; the agent's 125 unit tests call the handlers in-process, never start a server, -and passed, and its final message said both phases were green. This is a task-quality result of one greedy trajectory (the shipped-options run of the same prompt produced a working app); a different engine -configuration changes numeric rounding and therefore the trajectory, and no engine fault was found in it. No rerun was made. - -## 8. Job template - -```sh -set -uo pipefail -export E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 E2E_OUT=$HOME/work/leleka-e2e/runs/942-full -export E2E_CLIENT_ARGS="--soak-n 40 --burst 20 --xlong-tokens 24000" -rm -rf $E2E_OUT; sha256sum $E2E_BIN/* -bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh; echo "run-e2e rc=$?" -``` - -## 9. Open at the time of writing - -* Job 946 (`E2E_SCENARIOS=long`, tools off) did run later but is not analysed here; its row (8.5k-token turn-1 TTFT, suffix and shared-prefix reuse) is not in section 4. The 24k-token `xlong` scenario covers cache reuse. -* Job 947 (replay of both Codex captures): queued, see section 7. -* Codex runs at the typical 180k context, with the CUPTI tracer fired in a window, and with Qwen-style sampling instead of greedy. -* Daemon-side items from `delivery-gap-audit.md` not exercised here: SIGTERM drain, engine restart/re-attach under load, `leleka up`. diff --git a/docs/experiments/2026-10-03-agent-ab-threejs.md b/docs/experiments/2026-10-03-agent-ab-threejs.md deleted file mode 100644 index c68fdb5f..00000000 --- a/docs/experiments/2026-10-03-agent-ab-threejs.md +++ /dev/null @@ -1,78 +0,0 @@ -# Three.js agent task: native Strata versus KAR PLE, 2026-10-03 - -## Scope and fixed setup - -One Codex agent per arm received the identical prompt (SHA-256 -`e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`): -build a single-file Three.js/WebGL tic-tac-toe game, verify it, and complete -the dedicated LeaseVibe test-project workflow. The agents ran sequentially in -separate empty workspaces. No operator changed either game's files or helped -either agent while it worked. The original Strata launcher profile was left -untouched. Test project tasks were `TEST-2` (baseline) and `TEST-3` (KAR PLE), -both reported Done by their agents. - -Both arms used the Linux RTX 5090 host, driver 595.91.07, CUDA 13.2, the same -Qwen3.8-Flash-Next IQ3_S shards, source commit and engine configuration listed -in [the paired inference report](2026-10-03-kar-ple-ab.md). Each had one 256K -slot, INT8 **K+V** cache with 32,768 resident cells, MTP speculation depth 4, -and Strata's ordinary expert cache. The candidate used level-2 KAR only for -the PLE table, read and decoded on CPU. The model shards and KAR artifact were -on NTFS. This was neither the proposed compressed expert cache in VRAM nor -the experimental V-only KV path. The two agents followed different tool and -generation trajectories; this is one agent run per arm, not a paired -statistical benchmark. - -## End-to-end observations - -| Metric | Native baseline | KAR PLE candidate | -| --- | ---: | ---: | -| Full agent wall time | 2,162.44 s (36m02s) | 1,810.22 s (30m10s) | -| Codex CLI input tokens | 3,297,339 | 3,226,901 | -| Codex CLI cached input tokens | 1,100,546 | 741,408 | -| Codex CLI output tokens | 52,878 | 37,439 | -| Output tokens / full wall second | 24.45 | 20.68 | -| Completed bridge requests | 97 | 95 | -| Median request decode rate | 62.0 tok/s | 118.9 tok/s | -| Decode tokens / sum of decode time | 52.35 tok/s | 44.06 tok/s | -| Prompt tokens / sum of prompt time | 3,804 tok/s | 5,312 tok/s | -| Median first-token latency | 7.49 s | 8.50 s | -| Final HTML size | 13,930 bytes | 15,771 bytes | -| Shared browser checks | 6/6 | 6/6 | - -The candidate's full task was 16.3% shorter, but its output-token count was -29.2% lower. Its output tokens per full wall second were 15.4% lower. The -per-request median decode rate is strongly affected by request length: -candidate had 30 requests below 100 generated tokens versus five in the -baseline. Weighting by all measured decode time reverses the median's apparent -gain. Neither ratio isolates an engine effect in these divergent agent traces. -MCP schema rejections and later corrected calls are ordinary parts of the -workflow; they are included in wall time and were not scored as quality defects. - -The operator's same browser test ran after both agents finished, without -editing their files: each loaded without a page error, rendered a visible -WebGL canvas, completed a row win through real clicks, blocked moves after -the win, restarted to an empty board, and reached a draw through real clicks. -Both scored 6/6. Their own agent tests reported 37 Chrome assertions and -29 Chromium assertions respectively; these are different suites and their -counts are not comparable quality scores. This task did not measure model -perplexity, long-context retrieval, tool-call fidelity over a dataset, or -V-only KV quality. - -Private prompt, final HTML files, raw event streams, bridge logs, and the -common browser test remain outside Git under -`/Users/para/.cache/strata-next/agent-ab-threejs-20261003/` and -`/Users/para/.codex-qwen-interactive/bridge-logs/`. The final HTML digests -are `c4bc939d7fabd51f2a95d95c430c04fdaf64c9e27d2fd0300baebc3b59e0bfe4` -(baseline) and `9a944c1e1d23042f362eb6078fb49aa07b45eb677ad631edd77308fff005dbc5` -(KAR PLE). - -## Decision - -This agent task provides a successful functional comparison, not evidence of -a KAR performance improvement. The earlier paired inference suite found -matched short outputs but no CPU PLE speedup. The current runtime should not -be replaced on the basis of these runs. The next performance experiment must -integrate a bounded GPU-resident compressed weight cache and CUDA decoding -into the actual inference path, then compare identical requests and agent -tasks with a quality gate. V-only KV is a separate lossy mode and needs its -own long-context and tool-call quality gate before any default use. diff --git a/docs/experiments/2026-10-03-agent-gpu-kar-threejs.md b/docs/experiments/2026-10-03-agent-gpu-kar-threejs.md deleted file mode 100644 index 1987c48b..00000000 --- a/docs/experiments/2026-10-03-agent-gpu-kar-threejs.md +++ /dev/null @@ -1,82 +0,0 @@ -# Three.js agent task with GPU KAR PLE, 2026-10-03 - -## Workload - -The same coding task as the earlier [native versus CPU KAR agent run](2026-10-03-agent-ab-threejs.md) was sent through `codex-qwen` to each available profile. The prompt SHA-256 was -`e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`. -Each agent worked alone in a separate empty directory, built a single-file -Three.js/WebGL tic-tac-toe game, verified it, and advanced one new task in the -dedicated LeaseVibe test project. The operator did not change any agent's -files or guide its MCP calls. Runs were sequential on the same RTX 5090 -(driver 595.91.07, CUDA 13.2); one 256K slot, INT8 K+V, 32K resident KV cells, -and MTP depth 4. All normal expert weights stayed in the native IQ3_S pack. -The KAR arms replaced only the PLE table; GPU KAR used a 64 MiB compressed -GPU row cache. The private archive was never published. - -The three runs below use the current launcher and fresh engine starts. -Native engine SHA-256 was -`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`; -CPU KAR engine SHA-256 was -`099c32ce2195385b0367755c25f8e9a9cdf56282980208c6c4879712bbe0e5bc`; -GPU KAR engine SHA-256 was -`f5a2dfb49a7a1c35a6549f41901dabf5505b98c6a5a9b4801ea3d2c70729f0e5`. - -## Completed agent results - -"Iterations" below means completed model requests. Tool calls count completed -shell and MCP calls. The decode rate is total engine-generated tokens divided -by total engine-reported decode time across completed requests. CLI token -counts include the agent's full conversation accounting. One task per profile -is an end-to-end observation, not a paired inference benchmark. - -| Profile | Requests | Tool calls | CLI input tokens | Cached input tokens | CLI output tokens | Weighted decode tok/s | Full task time | Independent browser checks | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| Native, fresh repeat | 49 | 59 | 3,380,308 | 3,325,362 | 49,854 | 115.7 | 634.27 s | 6/6 | -| CPU KAR PLE, fresh repeat | 70 | 70 | 5,498,472 | 5,440,802 | 64,006 | 150.3 | 707.59 s | 6/6 | -| GPU KAR PLE, fresh | 68 | 73 | 4,955,852 | 4,908,060 | 69,101 | 150.1 | 712.29 s | 6/6 | - -The independent browser check loaded each game without page errors, found a -visible WebGL canvas, played a row win with real clicks, verified that moves -stop after a win, restarted the board, and played a draw. It did not score -visual polish, accessibility, or broad model quality. Agent-authored test -suites differed and their assertion counts are not comparable. - -The fresh native agent finished 78.02 s sooner than GPU KAR and 73.32 s sooner -than CPU KAR, while generating 19,247 and 14,152 fewer output tokens, -respectively. Its weighted decode throughput was lower. The two KAR arms -finished within 4.70 s of each other and had essentially the same weighted -decode rate, despite following different agent paths. All three fresh runs -had heavy prefix reuse: 98.4% of CLI input tokens cached for native, 99.0% -for CPU KAR, and 99.0% for GPU KAR. The older native/CPU KAR runs had much -lower cache reuse, so their wall times cannot isolate the GPU row decoder's -effect. A separate fixed-prompt serving comparison found no established GPU -KAR speedup. - -All outputs are different games and different agent trajectories. These -observations show task completion and quantify cost; they do not establish a -GPU KAR throughput gain or broad quality preservation. GPU KAR's higher -generation rate than native in this sample did not compensate for the extra -agent work in full task time. GPU and CPU KAR were nearly equal. There is no -accepted end-to-end performance improvement for the PLE-only GPU cache. - -The private output files and logs remain outside Git at -`/Users/para/.cache/strata-next/agent-ab-threejs-20261003/`. The GPU game's -SHA-256 is -`6704a931d08e05377f7d0f3479078dbba338636f29152c9b681c9163681085a0`; -the native repeat's is -`ba4c30e32352cab5e0971d1e7d3c82357010a2b3237beb1df2b440b08d4e159b`; -the CPU KAR repeat's is -`682137c96cf99fa06aec1789e098662a60060a9e3d49f8845ef86097b4da737d`. - -## Unavailable profiles - -The current server has one FIFO inference sequence. `conversation-cache-slots` -parks state between requests; it does not run two simultaneous 256K agents. -The QSA attention path still stores and reads K and V. The custom offline -V→K regression had 0.3023 relative L2 attention-output error on a limited -held-out proxy. It did not implement the cited Keyless Attention method. -No physical without-key serving profile or model-level quality gate exists. -V-only has no agent result; its speed and quality effect are unmeasured. -The later two-process 2×256K agent experiment is recorded separately in -[the dual-worker report](2026-10-03-dual-256-agent.md); it does not implement -two slots within one engine. diff --git a/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md b/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md deleted file mode 100644 index ad57e4cf..00000000 --- a/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md +++ /dev/null @@ -1,66 +0,0 @@ -# Bounded compressed PLE row cache smoke, 2026-10-03 - -## Setup - -This is the first **functional** GPU cache probe following the -[offline row-locality screen](2026-10-03-ple-cache-reuse.md). The program -`gpu/kar/src/kar_row_cache_smoke.cu` was compiled on Linux for `sm_120` with -CUDA 13.2.86 and the repository's pinned `libkar` object. The new CMake target -also configured and built successfully with CUDA 13.2.86 and Ninja on that -host. Hardware was an -RTX 5090 (32,607 MiB reported VRAM), NVIDIA driver 595.91.07, 600 W reported -power limit. The private Qwen3.8-Flash-Next IQ3_S KAR v4 archive and its -provenance are described in the [paired KAR report](2026-10-03-kar-ple-ab.md). -The selected record was `per_layer_token_embd.weight#strata-part-001-of-002` -at level 2. Payload CRCs were verified before any row access; no full-archive -SHA-256 pass was added. The two pinned GGUF source-shard SHA-256 values are -`4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` -and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. -The archive's source-side SHA-256 was -`536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; -the remote file was not independently SHA-checked, as recorded in the paired -report. The repository base before this probe was `49b091c`. - -The probe reserves only a bounded compressed-row cache, an update buffer, -slot IDs, a four-entry codebook, and the current F32 output. The CPU maps -row IDs to slots with LRU replacement. Each missed PLE row admits 50 -compressed bytes from the verified archive into a 64-byte VRAM slot. It -uploads a 56-byte update record per miss and four-byte slot ID per access; -the update record includes its slot number and two padding bytes. A CUDA -scatter kernel writes the row to its assigned slot, then another kernel -decodes the selected rows in VRAM. Every batch is compared byte for byte with -a fresh, independently gathered CPU decode of the encoded archive rows. - -## Correctness checks - -Both private traces used 16 row IDs per batch and a 1 MiB cache with 16,384 -slots. The five-batch trace requested rows 0–15, reversed them, repeated -them, requested 100–115, then revisited 0–15. The eviction trace filled the -cache with rows 0–16,399, repeated the last 16, then revisited the first 16. -The observed counts matched the expected LRU behavior exactly. - -| Trace | Batches | Accesses | Hits | Misses | Row bytes admitted | Actual H2D argument bytes | CPU parity | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | -| Reuse | 5 | 80 | 48 | 32 | 1,600 | 2,112 | Exact for all batches | -| Eviction | 1,027 | 16,432 | 16 | 16,416 | 820,800 | 985,024 | Exact for all batches | - -The eviction run's archive CRC verification took 80,131 ms. The first run -preceded the verification-time field and did not record that duration. The -sum of CUDA-event stages was 0.105 ms for five reuse batches and 7.047 ms -for 1,027 eviction batches. Those event sums include update and slot-ID -copies plus the scatter and decode kernels. The source arrays were ordinary -host memory, so the event sums may omit some host-side copy or staging time. -They exclude archive verification, CPU LRU lookup, output readback, CPU -reference decoding, and the rest of model inference. No throughput or -speedup claim follows. The output hash chains were `64284b0dfd5bfad9` -and `210c15ebb02c4a16`, respectively; exact per-batch CPU parity is the -stronger correctness check. - -This smoke keeps 1 MiB of cache payload allocated; it does not hold a 10 GB -PLE record in VRAM. It proves compressed row admission, hits, eviction, and -CUDA decoding work together on the real archive under the tested traces. -It does **not** yet use actual model request row IDs or connect decoded rows -to Strata's PLE consumer. It does not establish model quality, expert/KV -pressure, or end-to-end agent speed. The next step is a captured prefill and -decode row trace, then serving-path integration with a quality gate and -paired throughput measurement against the native baseline. diff --git a/docs/experiments/2026-10-03-dual-256-agent.md b/docs/experiments/2026-10-03-dual-256-agent.md deleted file mode 100644 index 73e30f8d..00000000 --- a/docs/experiments/2026-10-03-dual-256-agent.md +++ /dev/null @@ -1,105 +0,0 @@ -# Two independent 256K workers on one RTX 5090, 2026-10-03 - -## Setup and physical concurrency - -The opt-in Linux controller `scripts/strata-dual-256-experiment.py` started two -independent native Strata workers on the same RTX 5090 (driver 595.91.07, -CUDA 13.2). Each used the verified Qwen3.8-Flash-Next IQ3_S source, context -262,144, INT8 K+V with 32,768 resident cells, MTP depth 4, and the same -baseline engine binary SHA-256 -`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. -The two workers listened on private experimental ports 18081 and 18082; -the normal service on 8080 was unchanged. The expert-cache request was -2,000 slots per worker; native sized allocation reported 2,582 actual slots. -Both workers reached readiness with 262,144-token context. Together they -used 28,218 MiB GPU memory at readiness and about 28,406 MiB while two -agents were active. The original one-worker agent profile had about 11,700 -expert slots, so this is a different memory/performance policy. - -A parallel Chat Completions smoke sent the same long synthetic request to -both ports with a barrier. Both returned `OK`, `finish_reason=stop`, and -42 completion tokens in 7.39 seconds; concurrent `/slots` sampling observed -both workers in `is_processing` state. This proves simultaneous model work on -one GPU. It is not an end-to-end agent throughput measurement. - -The controller writes credential-bearing configs only under private `/dev/shm` -paths, validates an idle GPU before starting, and stops only its recorded -worker process groups. Model weights and request data are not placed in Git. -This is a two-process experiment; a production Rust scheduler and batching -inside one engine still need separate implementation. - -## Agent task - -Two independent `codex-qwen` sessions started on the same Three.js tic-tac-toe -prompt used in the [single-worker comparison](2026-10-03-agent-gpu-kar-threejs.md). -They work in separate empty directories and use the shared dedicated MCP test -project. No operator changed their files or guided their calls. The second -agent started 25.7 seconds after the first. Both produced one working WebGL -game. An independent browser replay for each passed the same six checks used -for the single-worker games: no page error, visible canvas, row win through -clicks, locked board after a win, restart, and draw through clicks. - -| Run | Completed model requests | Tool calls | CLI input / cached tokens | CLI output tokens | Weighted decode tok/s | Wall time | Browser checks | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| Native single worker, earlier fresh run | 49 | 59 | 3,380,308 / 3,325,362 | 49,854 | 115.7 | 634.27 s | 6/6 | -| CPU KAR PLE single worker, earlier fresh run | 70 | 70 | 5,498,472 / 5,440,802 | 64,006 | 150.3 | 707.59 s | 6/6 | -| GPU KAR PLE single worker, earlier fresh run | 68 | 73 | 4,955,852 / 4,908,060 | 69,101 | 150.1 | 712.29 s | 6/6 | -| Dual worker A, native | 69 | 71 | 6,472,001 / 6,395,938 | 78,286 | 35.32 | 3,721.36 s | 6/6 | -| Dual worker B, native | 71 | 74 | 6,178,149 / 6,105,218 | 60,337 | 29.21 | 2,615.25 s | 6/6 | - -The pair finished when A finished, **3,721.36 seconds** (62m 01s) after A -started. Together they produced 138,623 output tokens, an end-to-end aggregate -of **37.25 output tok/s** over that wall time; the weighted decode-only rate -across both was 32.37 tok/s. Four bridge requests failed and were retried; -one A request waited 968.43 seconds before timing out. Its server log had -stopped progressing while the GPU was idle. The engine log shows generation -continuing after the server's last token-progress line, so the available logs -do not isolate whether parsing or HTTP delivery stalled. This is a stability failure even -though A eventually completed the task. Per-request decode rates had long -tails: A median 64.9, p10–p90 20.8–78.6 tok/s; B median 55.4, p10–p90 -19.9–71.6 tok/s. A's first 20 completed requests weighted 22.6 tok/s while -both agents competed; its last eight after B finished weighted 66.3 tok/s. - -This dual-process profile **does not improve end-to-end throughput** on this -workload. Its expert cache is much smaller than the single-worker profile, the -agents followed different paths, and the 968-second stall dominates A's wall -time. The one-run comparison is directional, not an isolated estimate of the -cost of request concurrency. It does prove two full 256K contexts and two -simultaneous requests fit on this GPU. A production one-engine two-slot -scheduler remains unbuilt and unmeasured. - -## One endpoint, two requests - -The requested interface is one endpoint that accepts two simultaneous requests -from a client. The first run above instead used two independent agent clients -on separate ports; it measures GPU feasibility and end-to-end contention but -does not by itself prove that interface. The experimental -`scripts/strata-dual-request-proxy.py` now admits one request to each worker -through a single HTTP address. A local barrier test confirmed that two -concurrent calls to that address reached distinct workers. The proxy preserves -the first worker for serial requests so a single agent can reuse its prefix -cache. A second local barrier test confirmed that both streamed responses -delivered their terminal SSE event. After both agents completed, one client -sent two simultaneous Chat Completions to that same address. Both workers -reported `is_processing=true` at the same time. Both returned 30 completion -tokens, `finish_reason=stop`, and nonempty content; their individual latencies -were 3.82 and 3.80 seconds, and the pair took 3.88 seconds. This is -HTTP-level concurrency across two processes, not continuous batching in one -model process. It is a short correctness smoke, not a speed claim for a -long-running agent. - -The experimental proxy and workers were stopped after testing. GPU memory -fell to 34 MiB; temporary credential configs under `/dev/shm` were removed. -Private model shards and the validated KAR archive were retained. The two -games and event logs remain in the ignored local experiment directory to -reproduce these measurements. - -## Ordinary Strata stability follow-up - -The experiment used the separately installed ordinary Strata source at commit -`30ec18e`. Its stability follow-up is recorded in the -[ordinary Strata report](2026-10-03-ordinary-strata-stability-ab.md), including -client-disconnect cancellation, bounded cleanup and response writes, an -engine-restart race fix, real-model disconnect recovery, and 59 passing -server tests. Those changes limit abandoned requests; the earlier -pre-disconnect stall's exact cause remains unconfirmed. diff --git a/docs/experiments/2026-10-03-expert-cache-pressure.md b/docs/experiments/2026-10-03-expert-cache-pressure.md deleted file mode 100644 index 4ee37156..00000000 --- a/docs/experiments/2026-10-03-expert-cache-pressure.md +++ /dev/null @@ -1,66 +0,0 @@ -# Expert-cache pressure from a proposed 10 GiB resident KAR record, 2026-10-03 - -## Question and method - -On the 32 GB RTX 5090, can Strata give 10 GiB to one compressed PLE record -without a material cost to its expert cache? This is a **capacity-pressure -probe**, not a KAR-serving run. The model still read its ordinary IQ4_NL PLE -table and all other normal weights. Only Strata's `--vram-reserve-mib` changed: -700 MiB in the baseline arm and 10,940 MiB in the pressure arm. The extra -10,240 MiB matches the approximate 10 GiB footprint of the first resident -level-2 PLE record measured in [the CUDA row report](2026-10-03-gpu-resident-rows.md). -The reserve is a planner budget, not an actual KAR allocation. - -Hardware was one Linux RTX 5090 (32,607 MiB reported by `nvidia-smi`), NVIDIA -driver 595.91.07. The same Qwen3.8-Flash-Next IQ3_S native pack, source GGUF -shards, Strata binary (SHA-256 -`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`), -and configuration were used in both arms; see -[the earlier paired report](2026-10-03-kar-ple-ab.md) for model digests. The -configuration used one 256K context, INT8 K+V, 32,768 resident KV cells, -MTP speculation depth 4, `--expert-cache auto`, and a native expert profile. -A private 54-token coding prompt produced 160 tokens in each run. The prompt's -SHA-256 was -`02119df5dbcaa7ae797e45fd4591ad1028c5d7e5f8c3b97a802529a8d2ecb2a7`. -The first cold pair was discarded from rate comparison because model loading -took 286.79 s in the first arm and 18.51 s in the second. The three measured -pairs alternated arm order A→B, B→A, A→B. The offline controller and private -raw output are under `scripts/bench-expert-reserve.py` and -`/home/para/.cache/strata-next/expert-reserve-warm-20261003/` respectively. - -## Observation - -| Measure | 700 MiB reserve | 10,940 MiB reserve | -| --- | ---: | ---: | -| Expert slots | 12,569 | 7,312 | -| Expert cache | 23.87 GiB | 13.86 GiB | -| Distinct CPU experts per layer, three runs | 1.34, 1.34, 1.34 | 3.35, 3.78, 3.47 | -| Distinct PCIe experts per layer, three runs | 0.90, 0.90, 0.90 | 3.06, 3.52, 3.21 | -| Decode tokens/s, paired in run order | 58.46, 105.96, 166.30 | 18.85, 81.10, 55.91 | -| Prefill tokens/s, paired in run order | 224.28, 129.01, 264.85 | 191.01, 109.49, 192.79 | - -The reserve displaced **5,257 expert slots** and about **10.01 GiB** of the -expert cache. All three pressure-arm decode rates were lower, with paired -pressure/baseline ratios 0.322, 0.765, and 0.336. These rates have large -run-to-run variation. The model repeatedly stalled on NTFS reads during -loading; the reported full process wall times ranged from 18 to 288 seconds. -The 54-token prompt is not the required 256K workload. This small sample -does not estimate a reliable end-to-end slowdown or quantify quality. - -Greedy output IDs differed between the arms starting at output index 1 in -all three pairs. The baseline arm's output was stable across its three runs; -the pressure arm produced two different 160-token sequences. Changing the -expert cache can change GPU/CPU expert arithmetic and routing, so an exact -greedy match was not assumed. No judged task-quality or tool-call gate was -run. The output difference is an additional reason not to treat this as a -runtime-acceptance test. - -## Decision for the next prototype - -Reserving an entire 10 GiB PLE part on a 32 GB card causes substantial expert -cache displacement before any CUDA row decoding is connected to inference. -The next prototype should bound PLE residency to selected blocks or packets, -or first reduce the expert cache footprint. It must then measure actual -admission/eviction, PLE decode and compute, expert hit/miss changes, and -paired full-model and agent quality. Keep the native runtime as the reference -until those gates pass. diff --git a/docs/experiments/2026-10-03-gpu-resident-rows.md b/docs/experiments/2026-10-03-gpu-resident-rows.md deleted file mode 100644 index 617cb444..00000000 --- a/docs/experiments/2026-10-03-gpu-resident-rows.md +++ /dev/null @@ -1,82 +0,0 @@ -# Resident KAR rows on RTX 5090, 2026-10-03 - -## Setup - -This isolated CUDA experiment measured the proposed compressed-VRAM geometry -for a real Qwen3.8-Flash-Next IQ3_S PLE partition. Hardware was the Linux -RTX 5090, NVIDIA driver 595.91.07, CUDA 13.2. The selected level-2 record was -`per_layer_token_embd.weight#strata-part-001-of-002` in the private v4 archive -described in [the paired report](2026-10-03-kar-ple-ab.md). The benchmark -binary was rebuilt from this repository's pinned `libkar` plus the -`strata-kar-gpu-smoke --rows` extension. The archive was opened with payload -CRC verification before timing. Data and executable builds remain outside Git -on the Linux host. - -The command was: - -```text -strata-kar-gpu-smoke MODEL.kar 'per_layer_token_embd.weight#strata-part-001-of-002' 2 100 --rows 4096 42 -``` - -It admitted one compressed level prefix to VRAM, uploaded 4,096 deterministic -row IDs, warmed the CUDA decoder, then measured 100 repeats of the same rows. -The result was: - -| Measure | Result | -| --- | ---: | -| Record shape | 200,000,000 rows × 160 values | -| Compressed record resident in VRAM | 10,000,000,016 bytes | -| Compressed bytes per row | 50.0 | -| Original IQ4_NL bytes per row | 90 | -| Initial reserve | 497.54 ms | -| Decoded output | 655,360 F32 values (2,621,440 bytes) | -| Warm CUDA decode median | 0.00512 ms | -| Output FNV-1a 64 | `4c459b6ac39d3431` | - -For this partition, the compressed GPU representation uses about **44.4% less -space per row** than its original IQ4_NL table (50 versus 90 bytes), before -GPU allocator overhead. The fast warm decoder shows that a **resident** -compressed record can supply selected rows cheaply. This does not measure -archive admission frequency, -replacement policy, row-ID transfer per request, host page faults, matrix -multiplication, or agent throughput. The 10 GB record competes directly with -the existing expert and KV caches on a 32 GB card. The timed batch reused the -same row IDs, so a varying-request benchmark is still needed. The full archive -does not fit on the card. No serving code used this GPU output, and the batch -checksum was not independently compared to CPU reconstruction; the previous -single-row CPU/CUDA parity check covers the underlying decoder only. These -limits prevent a performance or model-quality claim for the runtime. - -## Follow-up: changing row IDs and independent batch parity - -The same RTX 5090 and archive were used with a rebuilt smoke binary (CUDA -12.8.1 toolkit, driver API 13.2). The `--rows-ple` mode uses the deterministic -row generator from Strata's CPU PLE probe. For 4,096 random rows, level 2, -seed 42, and 100 warm repeats, the resident decoder's complete F32 output -checksum was `00cc55a3da2ef31b`, **identical** to the independent CPU KAR -gather's checksum on the same rows. This closes the batch parity gap in the -first measurement. The native IQ4_NL gather's different checksum is expected -because KAR level 2 is lossy; full-model quality has a separate gate. - -`--rows-ple-vary` then replaced every row ID before each timed repeat, using -pinned host memory for the ID upload. The host generated the next ID batch -outside the timed CUDA events. Each invocation verified the archive payload -CRCs, staged the 10,000,000,016-byte prefix once, and ran 100 repeats. The -medians below are CUDA-event times in microseconds, not request latency: - -| Rows per batch | ID upload | Resident decode | Upload + decode | -| ---: | ---: | ---: | ---: | -| 16 | 2.912 | 3.200 | 6.048 | -| 4,096 | 3.136 | 5.632 | 8.704 | - -The 4,096-row fixed-ID parity run had a 4.512 µs warm decode median. The -changing-ID result includes the different memory access pattern but still -excludes PLE projection, cache admission and eviction, host ID generation, -competing expert/KV cache pressure, and the rest of inference. Its final-batch -checksum (`571247f5d41f34ae`) is not compared with the CPU probe's first -batch. The 16-row changing-ID final checksum was `c4bf921377ba537e`. -No inference speedup or full-model quality result follows from these numbers. - -Next: implement a bounded resident cache, measure expert/KV displacement, -wire the decoded rows into the PLE consumer, then run paired inference and -agent quality gates. Keep the native profile available for rollback. diff --git a/docs/experiments/2026-10-03-kar-ple-ab.md b/docs/experiments/2026-10-03-kar-ple-ab.md deleted file mode 100644 index fca3758d..00000000 --- a/docs/experiments/2026-10-03-kar-ple-ab.md +++ /dev/null @@ -1,53 +0,0 @@ -# KAR PLE CPU arm on RTX 5090, 2026-10-03 - -## Question - -Does reading the Qwen3.8-Flash-Next PLE table from level-2 KAR preserve output and improve inference throughput compared with Strata's native IQ4_NL PLE table? - -## Fixed configuration - -- One NVIDIA GeForce RTX 5090, driver 595.91.07, CUDA 13.2 toolkit, Linux. -- Qwen3.8-Flash-Next IQ3_S, two pinned GGUF shards. Their SHA-256 values are `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. -- Same Strata engine source, `30ec18ec7094550fcc594fd948220d511d80464e`, in both arms. Baseline binary SHA-256: `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. Candidate binary SHA-256: `099c32ce2195385b0367755c25f8e9a9cdf56282980208c6c4879712bbe0e5bc`. -- Context 262,144; INT8 K+V cache with 32,768 resident cells; MTP speculation depth 4; expert cache auto; prefill auto; 700 MiB VRAM reserve. Both arms used the same native pack and GGUF source. The candidate changed only the PLE source to level-2 KAR. -- KAR v4: 55,295,529,472 bytes; source-side SHA-256 `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`. Rsync completed successfully and the engine verified KAR payload CRCs when opening it. At the user's request, the separate remote full-file SHA pass was skipped; the remote file's SHA-256 is therefore **not independently confirmed**. -- Arms ran sequentially on one GPU. The concurrent v5 converter was stopped during measured requests and resumed afterward. The model files were on NTFS. Raw private responses and logs remain outside Git under `/home/para/.cache/strata-next/quality-ab-e601cb3/` and `/home/para/.cache/strata-next/cold-ab-770d6a5/` on `rnr5090`. - -## Paired result - -The public synthetic eight-case suite covered arithmetic, retrieval, instruction priority, and tool calls. Five measured repetitions per case followed one warmup. Both arms passed **40/40** measured quality checks, and all **40/40** normalized outputs matched. Candidate-over-baseline median HTTP wall-time ratio was **1.0106** (a larger number is slower). Warm measured prompt-rate ratio was **0.9895** and decode-rate ratio **1.0088**. These short, largely prefix-cached outputs do not establish a decode gain. The single initial 79,258-token request had no prefix-cache reuse: baseline **6,063.9 tok/s, 13.374 s**; candidate **3,884.2 tok/s, 21.196 s**. - -A second suite used three distinct initial 79,259–79,260-token prompts with `cache_n=0` in each arm. The first-request results were: - -| Case | Baseline prefill tok/s | KAR PLE prefill tok/s | Baseline wall s | KAR PLE wall s | Quality | -| --- | ---: | ---: | ---: | ---: | --- | -| alpha | 5,988.1 | 5,332.6 | 13.626 | 15.247 | both pass | -| beta | 6,109.0 | 4,868.3 | 13.233 | 18.969 | both pass | -| gamma | 6,096.9 | 6,102.0 | 13.281 | 14.965 | both pass | - -The median paired candidate/baseline prefill-rate ratio was **0.8905**; the median first-request wall-time ratio was **1.1268**. All three first outputs and all three measured cached outputs matched between arms. This sample supports **no speedup** from the CPU PLE path. The spread is material, so it does not justify a precise slowdown claim or a production quality decision. There was no live agent workload, perplexity test, 512K context test, or test of the full compressed model. - -## Interpretation and next gate - -The candidate still held the ordinary Strata expert cache in VRAM (about 22.19 GiB for 11,697 slots after loading). KAR PLE remained mapped in host memory and was decoded on CPU. This experiment does **not** test compressed expert weights resident in VRAM or CUDA decoding in the serving path. The next useful gate is a bounded compressed GPU cache with the actual transfer, decode, multiply, eviction, and quality costs measured against the same native arm. Until that exists and passes full-model and agent-task quality gates, the testing runtime must remain on its current baseline. - -The original paired reports inherited `profile`, `storage`, and GPU-clock text from an earlier functional smoke metadata file. Those inherited labels do not describe this run. The facts above come from the current run commands, live GPU inspection, logs, and paired reports. The benchmark harness has since been changed to capture live GPU details and exclude those stale labels from future reports. - -## Sparse CUDA row microbenchmark - -The isolated `strata-kar-sparse-row-smoke` read the same v4 archive, checked its payload CRCs, assembled selected PLE rows into a compact packet, uploaded it, and decoded F32 rows on RTX 5090. Row 0's GPU FNV-1a checksum, `c6f74b955ce5a5ae`, matched the independent Rust row decoder. The table uses medians of 1,000 warm CUDA event measurements; host packet assembly was measured separately. Times from different invocations are not paired inference results. - -| Rows | Selection | Packet bytes | F32 upload bytes | Packet H2D + CUDA decode | F32 upload | Host packet build | -| ---: | --- | ---: | ---: | ---: | ---: | ---: | -| 16 | consecutive | 808 | 10,240 | 5.54 µs | 1.60 µs | 0.010 ms first | -| 128 | consecutive | 6,408 | 81,920 | 6.37 µs | 4.16 µs | 0.012 ms first | -| 4,096 | consecutive | 204,808 | 2,621,440 | 21.73 µs | 96.38 µs | 0.052 ms first | -| 4,096 | pseudorandom, seed 42 | 204,808 | 2,621,440 | 21.66 µs | 90.78 µs | 20.61 ms first; 0.369 ms warm median | - -The 4,096-row random sample was drawn from the first 200 million-row PLE part. Its whole-output GPU checksum matched Strata's KAR CPU gather checksum (`00cc55a3da2ef31b`). In the same process and for the same random row IDs, Strata's native IQ4_NL PLE gather had a **0.252 ms** warm median; CPU KAR gather had a **1.327 ms** warm median over five alternated repeats. Native's first gather had 5.485 s of storage page faults, while KAR had been warmed by the full-archive CRC scan, so those first-run times are not comparable. Repeated packet assembly plus its GPU stage was about 0.391 ms, before any scheduler, page-fault, or model integration cost. At this row count and with these cache conditions it did not establish a gain over native gather plus F32 upload. The contiguous-row GPU-stage win is real but is a microbenchmark result, not an agent throughput result. - -The current KAR bit planes place pieces of one random row far apart in the file. A row-oriented or block-oriented layout, or a bounded prepacked cache, is needed before sparse GPU decoding can plausibly improve random-access prefill. Any new layout must include conversion cost, cache residency, quality, and paired end-to-end measurements. - -## Outer LZMA sample - -Three independent 32 MiB slices of the local v4 archive were compressed with Python `lzma` preset `9 | PRESET_EXTREME`. Slices near offsets 1 GiB and 25 GiB shrank to 31,144,624 bytes (7.18% smaller) and 30,949,856 bytes (7.76% smaller). A slice near 50 GiB grew to 33,556,152 bytes. Each slice took about 9–10 seconds to compress. These samples do not predict a full-archive size. LZMA is also not a measured GPU-decodable runtime codec; its storage saving cannot be counted as an inference speedup. diff --git a/docs/experiments/2026-10-03-long-ple-serving.md b/docs/experiments/2026-10-03-long-ple-serving.md deleted file mode 100644 index 7ed60046..00000000 --- a/docs/experiments/2026-10-03-long-ple-serving.md +++ /dev/null @@ -1,83 +0,0 @@ -# Long-prompt PLE serving control, 2026-10-03 - -## Setup - -An opt-in Linux CUDA engine compared three PLE sources on the same RTX 5090: -native IQ4_NL from the original GGUF, level-2 KAR decoded on CPU, and a -64 MiB compressed KAR row cache decoded on GPU. All other weights used the -same IQ3_S native pack. The host ran NVIDIA driver 595.91.07, CUDA 13.2.86, -and a 600 W reported GPU power limit. The engine binary SHA-256 was -`de121803e66479e64f7976c12540b2d2bc2e31faf78ea3069b1f88f2197575e9`. -Source shard and KAR archive identities are in the -[CPU KAR comparison](2026-10-03-kar-ple-ab.md). The private archive remained -on NTFS; this run checked KAR payload CRCs during startup and did not repeat -a full remote SHA-256 pass. - -The prompt came from public fixture `cold-alpha` in -`benchmarks/fixtures/chat/cold-prefill-v1.json`. It contains a valid audit -code amid decoys and filler, with a required exact final answer. The Rust -tokenizer and a Qwen user/assistant frame produced 79,255 token IDs; -formatted prompt SHA-256 was -`bf5b5803d6b325b31ce640f1b94dd1ceb0bd34c77a697ac34b0b2a2b04165bca`. -Each arm used one 256K slot, INT8 K+V cache with 32,768 resident cells, -MTP depth 4, 11,763 actual expert slots, static expert residency, normal -end-of-turn stopping, and at most 128 output tokens. The native `--serve` -protocol had prompt and conversation reuse disabled. One warmup and two -measured requests ran per arm, in native, CPU KAR, GPU KAR order. Startup -and 55 GB archive verification were excluded from request rates. Raw token -IDs and private engine logs stayed outside Git and were removed after quality -inspection. - -## First measured result - -| PLE source | Median prefill tok/s | Median decode tok/s | Generated tokens | Output-ID hash stable | -| --- | ---: | ---: | ---: | --- | -| Native GGUF | 6,235.5 | 143.4 | 94 | Yes | -| CPU KAR level 2 | 6,223.7 | 148.9 | 100 | Yes | -| GPU KAR level 2 cache | 6,263.6 | 150.1 | 100 | Yes | - -The two GPU outputs were token-exact against the two CPU KAR outputs, but -both KAR arms differed from native at the token level. Decode rates across -native and KAR are therefore **not paired on the same generated sequence**. -GPU-versus-CPU KAR rates differed by less than 1% on this prompt; two repeats -and fixed arm order cannot establish a throughput improvement. Native and GPU -prefill medians differ by about +0.45% in favor of GPU, below a credible -improvement claim with this sample. Decode rates across native and KAR also -have different generated sequences and cannot be treated as matched work. - -The GPU cache reported 3,803,080 hits and 1,112 misses across warmup and -measured requests, a 99.97% hit rate. This repeated-filler prompt has very -high row reuse. The candidate uploaded 55,600 compressed row bytes and -15,279,040 H2D argument bytes in all. These are requested API payload bytes, -not measured PCIe transactions. A highly repetitive prompt may conceal the -cache-miss cost of a varied agent workload. - -## Quality check - -A separate private run captured token IDs for one measured native request and -one measured GPU KAR request after one warmup each. The output hashes were -stable against the first run: native -`4b7bbab11e1ab5b17d5d4af9fba622805418f9fa0bd0c9882d272559c2708af3` -(94 tokens), GPU KAR -`6ad5326860d9111a3b5c3572445870a61d75e2c2fc28be6fb2f24c0b71b0a293` -(100 tokens). Rust detokenization showed different reasoning trajectories, -but **both final answers were exactly `amber-731`**, satisfying the fixture's -required text. This one task passes for both arms. It is not a perplexity, -tool-call, agent-workflow, or broad long-context quality gate. The current -test runtime remains unchanged. - -## Opt-in agent harness profile - -The private `codex-qwen-ctl` model list now includes -`strata-next-kar-ple-gpu`, labeled experimental. Its tracked remote controller -source is `scripts/strata-agent-profile.py`; it selects the level-2 archive, -64 MiB compressed GPU PLE cache, and the unchanged INT8 K+V 1×256K profile. -The launcher entry on the laptop is outside this repository. The durable -Linux engine build SHA-256 is -`f5a2dfb49a7a1c35a6549f41901dabf5505b98c6a5a9b4801ea3d2c70729f0e5`. -The separate server on port 18081 reached readiness, reported context -262,144, and returned HTTP 200, `finish_reason=stop`, content `OK` for a -short Chat Completions smoke. It was then stopped and its temporary logs -removed; the normal Strata endpoint on port 8080 was not changed. No agent -task has yet been run through this GPU profile. The V-only KV profile is not -listed because it has no physical runtime or passing quality gate. diff --git a/docs/experiments/2026-10-03-ordinary-strata-stability-ab.md b/docs/experiments/2026-10-03-ordinary-strata-stability-ab.md deleted file mode 100644 index b9ee69ae..00000000 --- a/docs/experiments/2026-10-03-ordinary-strata-stability-ab.md +++ /dev/null @@ -1,82 +0,0 @@ -# Ordinary Strata: stability and speed check - -The separately installed ordinary Strata server was tested before and after -client-disconnect and engine-restart fixes. The established native agent -baseline is in the [Three.js agent report](2026-10-03-agent-gpu-kar-threejs.md): -49 model requests, 59 tool calls, 49,854 output tokens, 115.7 weighted decode -tok/s, 634.27 s wall, and 6/6 independent browser checks. The HTTP check -below isolates serving behaviour; it is not a new end-to-end agent result -or a KAR comparison. - -## Setup - -- Linux RTX 5090, driver 595.91.07, CUDA 13.2.2, 600 W power limit. -- Qwen3.8-Flash-Next IQ3_S, two source GGUF shard SHA-256 digests: - `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`, - `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. -- Same engine binary for both arms, SHA-256 - `f631b32495440f1dde716734559e757b76f5436c34ca49164cb97bd80b4b18e7`, - build manifest version 0.1.30, source ID `5117b3ee3a6ffbaf`. -- Ordinary Strata HTTP server source: baseline `30ec18e`; patched branch - `stability-client-disconnect-20261003`, commits `ee8c926`, `5361247`, - `9ed8d4d`, `df83985`. -- One 256K slot, INT8 K+V cache, 32K resident KV, MTP `--spec 4`, - `--spec-min-p 0.5`, automatic expert cache, same engine arguments and - model for both arms. -- Identical 124,984-token prompt, `temperature=0`, `max_tokens=512`, - non-streaming Chat Completions. Prompt SHA-256: - `d2edd95ece7ed1530373dbc833efb7ebb553becef2bcde641a132c86b1ee9ce0`. - Each arm starts a fresh server, makes one cold request, then repeats the - request with a warm prefix cache. Arms run sequentially without GPU - contention. Raw, private result files and the benchmark script are under - `/home/para/.cache/strata-next/ordinary-ab/` on the GPU host. The result - JSON contains a prompt digest rather than the prompt body and excludes - credentials. Server logs remain private on that host. - -## Initial five-request A/B - -| Arm | Cold wall | Cold prefill | Warm cache | Warm wall median (p10–p90) | Warm weighted decode | -| --- | ---: | ---: | ---: | ---: | ---: | -| Original | 39.538 s | 124,984 tokens / 22.856 s | 124,979 / 124,984 tokens | 6.938 s (4.807–13.096) | 62.9 tok/s | -| Patched through `5361247` | 31.367 s | 124,984 tokens / 22.840 s | 124,979 / 124,984 tokens | 5.617 s (4.984–6.133) | 95.8 tok/s | - -All requests returned exactly 512 output tokens and `finish_reason=length`. -The two cold-prefill rates were 5,468 and 5,472 tokens/s, respectively. -The four warm requests per arm had substantial decode variation, including -within the original arm. Exact greedy output hashes differed even among -repeats within the same arm, so this run does **not** pass an exact-output -quality gate and does not establish a speed improvement. TTFT was not -captured separately. The initial result is a useful smoke test but too -small for a performance claim. - -## Stability checks - -The patched Python HTTP server cancels buffered and streamed requests when -the client disconnects. If an abandoned engine run does not acknowledge STOP, -cleanup times out and kills the engine instead of holding the single FIFO -indefinitely. An old stdout pump is tied to its own process and queue; a -restart resets the new engine's ended state after process creation so the -old pump cannot revoke it during startup. A 60-second socket-write timeout -also bounds an SSE client that remains connected but stops reading. This -timeout is a mitigation for a plausible delivery stall, not proof of the -exact cause of the earlier incident. - -The ordinary server's `serve.test_disconnect` and `serve.test_server` suite -passed 59 tests. The added tests cover all four OpenAI/Anthropic × -buffered/streaming disconnect cases, STOP timeout, both stdout-pump -restart races, and a client that stops reading SSE while the model is -producing a large response. On the real IQ3_S model, closing a long request while the -slot was processing released the slot in **4.817 s**; a following request -completed with `finish_reason=stop` and 27 output tokens. The temporary -server was unloaded and stopped after the check. - -These fixes bound abandoned-work cleanup and recoverability. They do not -identify the root cause of the earlier 968-second dual-worker stall, which -occurred before client timeout and may involve response parsing or delivery. -The ordinary Python server remains distinct from the Strata Next Rust -control plane. - -An attempted full agent run on the patched ordinary server was interrupted -before completion. It has no comparable task time, token total, or quality -score and is excluded from the table. The isolated server was stopped, GPU -memory returned to 34 MiB, and its temporary credential config was removed. diff --git a/docs/experiments/2026-10-03-ple-cache-batch-capacity.md b/docs/experiments/2026-10-03-ple-cache-batch-capacity.md deleted file mode 100644 index 1d019640..00000000 --- a/docs/experiments/2026-10-03-ple-cache-batch-capacity.md +++ /dev/null @@ -1,47 +0,0 @@ -# PLE cache batch capacity and serving boundary, 2026-10-03 - -## Capacity guard - -The bounded CUDA PLE row probe now checks the number of **distinct** rows in -each decode batch against its slot count before changing the LRU cache. An -accessed row becomes most recent, so ordinary LRU preserves every row named -by a batch while the batch has at most one distinct row per slot. Without the -capacity check, an overfull batch could reuse a slot still named by an -earlier output position and silently decode the wrong row. The previous -probe's batches had at most 128 rows and its minimum 1 MiB cache had 16,384 -slots; this guard does not change those earlier results. A `slots:N` argument -allows a small capacity to test the boundary without allocating 1 MiB. - -On the Linux RTX 5090 with CUDA 13.2.86 and driver 595.91.07, the private -Qwen3.8-Flash-Next KAR v4 archive was opened with payload CRC verification. -The 4-slot trace `0 1 2 3`, `0 4 5 6`, `6 5 4 0` completed 12 row accesses -with 5 hits, 7 misses, and byte-exact CUDA/independent CPU decoded output in -all three batches. Its output hash chain was `3d7ceb5de9b5faf6`. A separate -5-distinct-row batch with the same 4 slots exited with the explicit -`a batch needs more distinct rows than cache slots` error. Both runs performed -the archive's full payload CRC pass; the valid run recorded 87,635 ms for -that pass. The code was compiled with `nvcc -std=c++17 -arch=sm_120 -O2`. - -The probe accepts `--trust-previously-verified-archive` as an explicit final -argument for repeated development runs. It still parses and checks the KAR -directory but skips the full payload CRC pass. Its output states -`payload_crc_verified=no`; the default remains full verification. This -option is only for a probe against an archive verified earlier in the same -experiment. It is not a serving integrity policy. Repeating the valid trace -with the final source and this option took 2.171 ms to open the archive and -again produced exact CPU parity and hash chain `3d7ceb5de9b5faf6`. The -overfull trace exited with the same error in this mode. - -## Serving handoff - -Three engine consumers require PLE rows. Decode computes 16 row IDs in -`ple_issue_token` and transfers 2,560 F32 values to `PleRun::emb_dev` in -`ple_finish_token`. Prefill gathers 16 IDs per token into one of two pinned -host buffers, then uploads each chunk to `m.ple_emb`. Speculative verification -gathers candidate rows into mapped host memory `h_ple_`, which its captured -graph reads. A serving CUDA cache must cover all three paths or keep an -explicit, quality-checked CPU fallback for verification. It must split a -prefill batch before its distinct-row count exceeds available slots, preserve -the lifetime of asynchronous upload buffers, and account for expert and KV -headroom before allocating VRAM. No serving path uses this probe yet; no -end-to-end speed or model-quality result is claimed here. diff --git a/docs/experiments/2026-10-03-ple-cache-reuse.md b/docs/experiments/2026-10-03-ple-cache-reuse.md deleted file mode 100644 index 4b5ef7a5..00000000 --- a/docs/experiments/2026-10-03-ple-cache-reuse.md +++ /dev/null @@ -1,93 +0,0 @@ -# PLE compressed-row cache locality screen, 2026-10-03 - -## Question and scope - -The [row-major packet probe](2026-10-03-row-major-ple-probe.md) made small -compressed-row gathers cheaper in warm host RAM. This offline screen asks how -often a bounded GPU cache *might* reuse those rows, and whether admitting -whole 16- or 64-row blocks would waste capacity and transfers. It does not -run inference or measure GPU cache performance. - -Repository HEAD for the screen was `7998f814bc8d431914de9811f594a6d3c7f1533f`. -The PLE hash constants and EOS boundary semantics came from the pinned -`engine/strata/src/kernels/ngram.cpp` and -`engine/strata/include/strata/kernels/ngram.hpp` at that revision. The script -replays the same 16 head indices per token. The target representation is the -private Qwen3.8-Flash-Next IQ3_S KAR v4 archive's level-2 PLE row: 160 values -stored in 50 compressed bytes. This 50-byte value excludes metadata, hash -tables, allocator fragmentation, cache control, and GPU transaction overhead. -The archive provenance is recorded in the [paired KAR report](2026-10-03-kar-ple-ab.md). - -## Inputs and method - -All source text, token IDs, agent events, model assets, and per-row traces -remained outside Git. The script `scripts/ple-cache-reuse.py` stores only -aggregate results. The code corpus was the first 59 sorted tracked source -files with code suffixes from `engine/strata/src`, `control-plane/src`, and `gpu/kar/src`, up to -1,104,686 bytes; its SHA-256 is -`ceaa7f954876bc39f9802965aea8f5599dec3474988f3286acca58cff64189a8`. -The pinned Strata Qwen tokenizer returned 314,064 tokens; the first 262,144 -were analyzed. The private token-array SHA-256 is -`59bcbbfb986eee79086faf1f3fa4f86a1bdd93e9ed0b68e56313b00c98880aad`. - -The other two corpora reconstruct text from completed Three.js agent event -logs: visible reasoning/messages, command text/output, and MCP call -arguments/results. They are **proxies**, not captured model request token -streams. Repeated tool output or serialized fields can exaggerate locality; -omitted system/prompt formatting can shift it. The baseline event file -SHA-256 is `5b939b92e0961274ec99be1fc6661a6566003143bdc053fa9fa442d897a96073`; -it yielded 352,676 IDs from the Rust Qwen tokenizer, of which 262,144 were -analyzed (private token-array SHA-256 -`df3d3521ecce8625d093535c20c0ae889953e9230da750854c1ad804cb0d1474`). The -KAR-ple event SHA-256 is -`f72f686a7e69851b2f3661beb27c7d4f02394565592ac97886631906c683ab47`; -all 80,628 tokenizer IDs were analyzed (private token-array SHA-256 -`c6fd5510ea5efa0e8d44f4dc012624167b7057097a5d1b7aa15d7af231146cb1`). The two arms have different text -lengths and composition, so their hit rates are not a paired performance -comparison. - -For each token the script computes eight bigram and eight trigram PLE row IDs -with the engine's 64-bit wrapping XOR hash. It then simulates fully -associative LRU caches, initially empty, at 64, 256, and 1,024 MiB nominal -compressed-payload budgets. A miss admits either the requested 50-byte row, -the aligned 16-row group (800 bytes), or the aligned 64-row group (3,200 -bytes). `Ideal admission` is miss count times those sizes. It is not measured -PCIe traffic or storage I/O. The simulation assumes free lookups and eviction, -perfect packing, and no GPU cache or producer work. - -| Corpus | Tokens | PLE row accesses | Unique rows | 64 MiB row hit | 64 MiB 16-row hit | 64 MiB 64-row hit | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | -| Tracked code | 262,144 | 4,194,304 | 1,080,010 | 74.25% | 67.82% | 58.41% | -| Baseline agent event proxy | 262,144 | 4,194,304 | 255,930 | 93.90% | 93.76% | 92.32% | -| KAR-ple agent event proxy | 80,628 | 1,290,048 | 383,788 | 70.25% | 67.21% | 57.92% | - -| Corpus | 64 MiB row admission | 64 MiB 16-row admission | 64 MiB 64-row admission | 256 MiB 64-row hit | 1,024 MiB 64-row hit | -| --- | ---: | ---: | ---: | ---: | ---: | -| Tracked code | 54.0 MB | 1,079.9 MB | 5,581.6 MB | 68.26% | 74.92% | -| Baseline agent event proxy | 12.8 MB | 209.4 MB | 1,031.4 MB | 93.83% | 94.05% | -| KAR-ple agent event proxy | 19.2 MB | 338.4 MB | 1,737.2 MB | 67.62% | 71.06% | - -The largest unique-row set occupies 54.0 MB of compressed payload, so the -ideal 64 MiB row cache has no capacity misses in these finite prefixes: its -misses are compulsory. The 16- and 64-row groups also fetch many adjacent -rows never requested. Larger block budgets recover some hits, but the ideal -admission volume remains far above row admission. This argues for -**row-granular GPU admission** or compact packets containing only requested -rows, even if the private on-disk representation uses larger blocks for -indexing and sequential reads. - -## Decision and next verification - -Treat this as a design screen, not evidence of faster inference. Implement a -small bounded compressed-row cache with explicit hit/miss and upload-byte -telemetry, plus eviction under expert/KV pressure. Measure the same token -stream and model output against the native baseline on the Linux RTX 5090. -Capture actual PLE row-ID traces from prefill and decode to repeat the reuse -analysis, especially for 256K/512K contexts and two slots. A quality gate -and paired end-to-end agent runs are required before enabling the path. - -To reproduce with the private token array and pinned source: - -```text -python3 scripts/ple-cache-reuse.py --tokens TOKENS.json --ngram-source engine/strata/src/kernels/ngram.cpp --ngram-header engine/strata/include/strata/kernels/ngram.hpp --max-tokens 262144 -``` diff --git a/docs/experiments/2026-10-03-real-ple-row-trace.md b/docs/experiments/2026-10-03-real-ple-row-trace.md deleted file mode 100644 index 33c20560..00000000 --- a/docs/experiments/2026-10-03-real-ple-row-trace.md +++ /dev/null @@ -1,94 +0,0 @@ -# Real Strata PLE row trace and bounded CUDA cache, 2026-10-03 - -## Purpose and safeguards - -The [bounded cache smoke](2026-10-03-bounded-ple-cache-smoke.md) initially -used constructed row sequences. This run captured the actual 16 PLE row IDs -computed by an isolated Linux Strata engine while it processed a model -request. The engine change is guarded by the new -`STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON` CMake option, whose default is OFF. -Even in that build, a new private `STRATA_PLE_ROW_TRACE_PATH` must be set. -The trace file was created exclusively with mode `0600`; it contained row -IDs, not prompt text or model weights. No installed service, test endpoint, -or original Strata checkout was changed. - -The host was the Linux RTX 5090, NVIDIA driver 595.91.07, CUDA 13.2.86. -The model was Qwen3.8-Flash-Next IQ3_S with the two pinned GGUF shard -SHA-256 values `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` -and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. -The native pack and normal K+V, expert, prefill, and speculation settings -came from the private baseline server configuration. The experimental -engine was built from repository base commit `139efbd` plus the trace patch. -The trace-enabled binary SHA-256 was -`91b0c6dc91a2c666b102cc8a55840df06391f8937b2369374b921fdcc9bed3e2`. -The same isolated source was then rebuilt with the trace option OFF. Its -binary SHA-256 was -`1f2f9325539a2a7ee4bc2a547ad0a92582c70d30ab56add56c53092377955a0a`. -That binary contained no trace environment marker and created no trace file. - -The short text-only prompt repeated the same public programming sentence -128 times. The pinned tokenizer produced 2,432 tokens; greedy generation was -limited to 16 new tokens. The process completed with exit code 0. This input -checks capture and decoding on the real model, but its repetition makes it -unsuitable for an agent cache hit-rate or speed estimate. Its first-request -wall time included model loading and trace I/O. The engine reported 2,431 -prefill tokens; the trace held 2,450 data lines (plus one header), including -the prompt and subsequent decode/speculative row calculations. Trace SHA-256 -was `630a7c2dc444afd67174d9979d7f827d40e112ee0f413ea5ae3fd5f908f92c3f`. - -An independent offline hash of the same 2,432 prompt token IDs matched -**all 38,912 row IDs** in the trace's first 2,432 lines, with no shift. -This confirms that the captured indices and line order reflect the pinned -Strata PLE hash for this request. The remaining 18 lines were generated or -speculative work and were not paired with a separate token-ID oracle. -The untraced control processed the same 2,432 prompt IDs and returned the -**same 16 greedy output IDs**. Their little-endian u32 sequence SHA-256 was -`1ec6b37e9ef3cc07a5c84c58437def212a508fd5f5e9c948bd8159be5ad30bc2`. -This is a non-lossy output check for this one short request, not a broader -quality gate or paired throughput measurement. - -## Real trace through the isolated GPU cache - -The full trace contained 39,200 row accesses but only 328 unique IDs. The -ideal 1 MiB row cache screen reported 99.1633% hits; 16- and 64-row blocks -had the same ideal hit rate on this repeated input but admitted 16x and 64x -more compressed payload for the compulsory misses. The 1 MiB screen assumed -50 bytes per slot and free metadata. The CUDA prototype actually reserves -64 bytes per row slot, so its physical capacity is 16,384 rows. Both sizes -are much larger than the 328 unique IDs here. - -`scripts/split-ple-row-trace.py` preserved per-token order and mapped the -global IDs into the archive's two PLE records. The first record had 10 rows -per token, the second six. The split trace SHA-256 values were -`f487da779c5eadbd8adcb028c51b0ee3aeca3c4aab72c99303abe6e70112034d` -and `f40043c0afb5d0d0c4f6b86297e795b910b1894d01a51a6d30bc1fffb1dfe536`. -On each record, `strata-kar-row-cache-smoke` verified the same private KAR -archive's payload CRCs and ran the exact captured row batches through the -compressed 1 MiB VRAM cache and CUDA decoder. - -| KAR PLE part | Batches | Row accesses | Hits | Misses | Compressed bytes admitted | Actual H2D argument bytes | CPU/CUDA values | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | -| 001 of 002 | 2,450 | 24,500 | 24,298 | 202 | 10,100 | 109,312 | Exact for every batch | -| 002 of 002 | 2,450 | 14,700 | 14,574 | 126 | 6,300 | 65,856 | Exact for every batch | - -The H2D byte column counts update records and per-batch slot IDs; it excludes -the one-time eight-byte codebook upload and CUDA driver transaction overhead. - -The KAR archive's source-side SHA-256 was -`536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; -as [previously recorded](2026-10-03-kar-ple-ab.md), the remote file was not -separately SHA-checked. The archive CRC pass took 115.6 s and 90.4 s in the -two separate invocations. The CUDA-event stage sums were 10.55 ms and -9.80 ms across 2,450 batches per part. They exclude archive verification, -CPU LRU planning, output readback, reference decoding, PLE projection, and -the rest of inference; pageable input memory may add host-side staging not -represented by those events. They are not paired A/B request timings. - -The captured row sequence and both CUDA outputs establish a concrete -functional path from real model PLE indices to bounded compressed-VRAM -admission and exact CPU/CUDA reconstruction. The CUDA cache is still a -separate executable, not the serving PLE consumer. The prompt's heavy -repetition, absent expert/KV contention, and lack of a paired quality suite -prevent any inference speed or model-quality claim. Next, capture a varied -agent or code prompt, wire the cache into serving, then run paired end-to-end -speed and quality gates before considering a test-runtime switch. diff --git a/docs/experiments/2026-10-03-row-major-ple-probe.md b/docs/experiments/2026-10-03-row-major-ple-probe.md deleted file mode 100644 index 80d30632..00000000 --- a/docs/experiments/2026-10-03-row-major-ple-probe.md +++ /dev/null @@ -1,58 +0,0 @@ -# Row-major PLE packet assembly probe, 2026-10-03 - -## Purpose and setup - -The earlier [expert-cache pressure test](2026-10-03-expert-cache-pressure.md) -showed that keeping one 10 GiB compressed PLE record in 32 GB of VRAM -displaces 5,257 expert slots. This isolated probe asks whether a row-oriented -layout can instead assemble **small compressed packets** fast enough for GPU -transfer and CUDA decoding. - -On the Linux RTX 5090, NVIDIA driver 595.91.07, a private Qwen3.8-Flash-Next -IQ3_S KAR v4 archive was opened with full payload CRC verification. The same -first PLE part, level 2, and deterministic random row IDs (seed 42) were used -in both arms. The code was built with CUDA 12.8.1 for `sm_120`. The archive's -model provenance and quality limits are in -[the prior paired report](2026-10-03-kar-ple-ab.md). - -The control arm assembled row packets directly from KAR's separate scales and -bit-plane regions. The candidate transposed **all 200 million rows of this -part** into a 10,000,000,000-byte private RAM array: five scales and two sets -of five bit-plane words per 160-value row, or 50 bytes/row. The candidate -then assembled the same GPU packet from that array. The CUDA upload and -decoder were identical in both arms. No secondary archive was written and no -10 GiB GPU allocation was made. The RAM array is an **upper bound** for a -future row-oriented on-disk layout, not a deployable bounded cache. - -| Rows per request | Source layout | First packet build | Warm packet build median | GPU upload + decode median | Packet bytes | F32 checksum | -| ---: | --- | ---: | ---: | ---: | ---: | --- | -| 16 | Current KAR | 0.1140 ms | 0.000280 ms | 0.005952 ms | 808 | `37855ae97b50a8cf` | -| 16 | Row-major RAM | 0.00245 ms | 0.000080 ms | 0.005952 ms | 808 | `37855ae97b50a8cf` | -| 4,096 | Current KAR | 20.371 ms | 0.163799 ms | 0.021664 ms | 204,808 | `00cc55a3da2ef31b` | -| 4,096 | Row-major RAM | 1.036 ms | 0.027480 ms | 0.021632 ms | 204,808 | `00cc55a3da2ef31b` | - -The 4,096-row checksum also matched the independent CPU KAR gather in the -[resident-row experiment](2026-10-03-gpu-resident-rows.md). The 16-row control -and candidate matched each other byte for byte, including each row checksum. -One-time row-major RAM construction took 2.37–3.97 s per invocation **after** -the archive scan; archive verification itself took 80–86 s. Neither cost is -included in packet or GPU stage timings. Each arm and row count had one -invocation with 100 warm GPU repetitions and five warm packet builds. These -short kernel timings do not establish end-to-end throughput. - -For 4,096 scattered rows, the row-major array cut warm host packet assembly -from 0.164 to 0.027 ms. For a 16-row token it cut first assembly from 0.114 -to 0.00245 ms, while the warm GPU stage stayed around 5.95 µs. Direct F32 -upload of 16 rows took about 1.47 µs in this same smoke target, but that -comparison excludes the original PLE table's CPU read/dequantization. The -row-major array consumes 10 GB of **host RAM**, and all requests came from -warm memory after an archive-wide CRC scan. Cold random storage reads, PLE -projection, expert/KV cache interaction, scheduler overhead, and model -quality were not measured. - -The next artifact should encode small row-major blocks inside a verified, -provenance-bound model format. A bounded GPU cache can then admit only -requested compressed blocks, decode them on the PLE stream, and evict them -without sacrificing most expert slots. Before choosing block size or a -production path, measure real PLE row reuse, cold storage page faults, full -request latency, and model/tool-call quality against the native baseline. diff --git a/docs/experiments/2026-10-03-serving-gpu-ple.md b/docs/experiments/2026-10-03-serving-gpu-ple.md deleted file mode 100644 index a6a30640..00000000 --- a/docs/experiments/2026-10-03-serving-gpu-ple.md +++ /dev/null @@ -1,139 +0,0 @@ -# Experimental GPU PLE cache in Strata serving, 2026-10-03 - -## Scope and implementation - -This is an opt-in PLE-only integration into the Linux CUDA Strata fork. The -normal expert, projection, embedding, and KV paths still use the native pack. -`--ple-kar ARCHIVE --ple-kar-level 2 --ple-kar-gpu-cache-mib N` keeps selected -50-byte compressed PLE rows in bounded 64-byte VRAM slots, uploads only cache -misses, and decodes requested rows into the existing F32 PLE consumer buffer -on CUDA. Prefill and ordinary token decode use it. Speculative verification -still gathers the same KAR rows on CPU because its captured graph reads mapped -host memory. The option is disabled by default. - -The CUDA component owns pinned update and slot-ID staging buffers. It waits -for its previous CUDA completion event before reusing them, including when -callers change streams. An overfull batch is rejected before mutating LRU -state; the engine divides a prefill gather by slot capacity so a small cache -can proceed. The archive is payload-CRC-verified before the cache opens. This -does not constitute full compressed-weight serving or a model quality gate. - -## Correctness on the target GPU - -Hardware was a Linux RTX 5090, NVIDIA driver 595.91.07, CUDA 13.2.86 and a -600 W reported power limit. The private Qwen3.8-Flash-Next IQ3_S KAR v4 -archive and source-shard identities are recorded in the -[CPU KAR comparison](2026-10-03-kar-ple-ab.md). The test preserved the verified -source shards and archive on the external model volume. - -An isolated component probe read rows on both sides of the boundary at global -row 200,000,000. Across three batches and 18 accesses it produced a byte-exact -CUDA/independent CPU match, with 8 hits and 10 misses in a 1 MiB cache. The -probe also rejected a batch with more distinct rows than slots. The archive's -payload CRCs passed. - -The integrated engine probe then gathered 32,768 adjacent rows starting at -199,990,000, crossing the same part boundary. Its 1 MiB cache had 16,384 -slots, so the engine issued two CUDA batches. The complete F32 output matched -the engine's CPU KAR gather byte for byte; FNV-1a64 was -`7e6a191b508d0461`. This probe had zero cache hits and 32,768 misses by -design, and uploaded 1,966,080 argument bytes. It checks the small-cache -batch split and the two-part row mapping. - -After lifting the prefill gather's 4,096-token guard, a final engine build -compared 65,552 rows (4,097 tokens) from the same start row, again crossing -the part boundary and splitting over the 16,384-slot cache. CPU/CUDA F32 -output was byte-exact, FNV-1a64 `450b9dc4bfd7320d`; zero hits, -65,552 misses, 3,277,600 compressed row bytes, and 3,933,120 H2D argument -bytes were reported. This covers a prefill batch larger than the old guard. -The final rebuilt engine binary SHA-256 was -`f00569d3071577d3f9ecb0bc92d3f9f86c4b1eb7ca0059b1443f52b7410874ed`. - -## First full-model functional pair and order reversal - -One process per arm used a 2,048-token synthetic prompt containing token IDs -1 through 2,048, 16 greedy output tokens, one 256K context, INT8 K+V with -32,768 resident cells, MTP depth 4, the same native pack and source GGUF -shards, and a 64 MiB GPU PLE cache in the candidate. CPU KAR and GPU-cache -arms ran sequentially. The first pair used `--expert-cache 10000`; profile -packing made the actual expert counts differ (12,691 CPU, 12,656 GPU), so it -is a functional comparison only. Both arms produced the same 16 output IDs, -SHA-256 `b4dd327bdcee9ad184003caf38747352ca5689b9208d2b46ef366fa1f50147a6`. - -The next four runs used `--expert-cache 9000`, resulting in **11,763 expert -slots in every arm**. The order was GPU, CPU, CPU, GPU. All four produced the -same 16 greedy IDs. The process binary for this four-run sequence was SHA-256 -`a27d1fc9c9f240d499346f93c1f184c7d30c076819af66691ceac0cd6b4a9b9c`. - -| Order | PLE arm | Prefill tok/s | Decode tok/s | PLE time within prefill | Output IDs | -| ---: | --- | ---: | ---: | ---: | --- | -| 1 | GPU cache | 67.34 | 34.68 | 29,278.2 ms | Same | -| 2 | CPU KAR | 1,970.40 | 78.73 | 214.0 ms | Same | -| 3 | CPU KAR | 2,182.63 | 89.41 | 138.9 ms | Same | -| 4 | GPU cache | 640.16 | 75.59 | 2,429.9 ms | Same | - -The GPU arm saw 32,752 PLE row accesses with only **3 hits** in each run. -Its 32,749 misses admitted 1,637,450 compressed bytes and sent 1,964,952 -argument bytes across H2D, versus 20,961,280 F32 PLE bytes in the CPU -prefill upload. Those are API payload sizes, not measured PCIe transactions. -The lower transfer size did **not** translate into a demonstrated speedup: -random reads and host packet assembly from the NTFS archive dominated this -low-reuse prompt. Arm order and file-cache state changed PLE time by orders -of magnitude. The final warm-order GPU arm was slower than the adjacent CPU -arm, but these one-shot runs cannot isolate the cache's own steady-state -effect. The prompt is synthetic and does not judge task quality. - -## Repeated requests in a loaded process - -The native `--serve` protocol ran each arm in one process, with two warmup -requests and five measured requests per prompt, `--prompt-cache 0`, and -`--conversation-cache-mib 0`. The same 11,763 actual expert slots, 256K -context, INT8 K+V, 32,768 resident cells, MTP depth 4, native pack, KAR -archive, and 64 MiB candidate cache were used. One synthetic prompt had -2,048 distinct token IDs; the other repeated IDs 1–128 sixteen times. CPU -started first. Every corresponding CPU/GPU request produced the same output -IDs and finish reason. For the repeated prompt, output length changed within -*both* arms in the same request order (16, 16, 16, 3, 3); this test therefore -does not establish deterministic output for repeated requests. - -| Prompt | CPU median prefill tok/s | GPU median prefill tok/s | CPU median prefill ms | GPU median prefill ms | CPU/GPU median decode ms | -| --- | ---: | ---: | ---: | ---: | --- | -| Distinct IDs | 2,978.0 | 3,027.8 | 687.7 | 676.4 | 22.3 / 21.9 (2 generated tokens) | -| Repeated IDs | 3,010.9 | 3,037.2 | 680.2 | 674.3 | 151.5 / 150.0 (mixed output lengths) | - -The measured prefill-rate differences are approximately +1.7% and +0.9%. -Five repeats per arm, fixed startup order, synthetic prompts, and short or -unstable generations do not establish a repeatable performance gain. - -## Reversed-order 128-token control - -A second same-process sequence started GPU first, then CPU. Both arms used -`--adapt-swaps 0` for static expert residency and an unreachable EOS ID so -each request completed 128 output tokens. Each prompt had two warmups and -five measured repeats, with prompt/conversation reuse disabled. Actual -expert slots were 11,763 in both arms; the binary SHA-256 was -`0566013995d6d8b2fdf817bbe9e6fcbb6a1d7c0f756d2a4382967be9fcaef6de`. -All 10 CPU/GPU output pairs were token-exact (20 outputs total), and each -prompt's five output hashes were stable within both arms. Draft acceptance -matched exactly: 71/108 for distinct IDs and 90/108 for repeated IDs. On the -final repeated -request, both arms reported 83.2% decode expert-cache hits (54,326/65,298) -and 99.29% KV-streaming hits (918,060 block reads; 26.3 MiB from RAM). - -| Prompt | Arm | Median prefill tok/s | Median decode tok/s | Median prefill ms | Median decode ms | -| --- | --- | ---: | ---: | ---: | ---: | -| Distinct IDs | CPU | 2,984.6 | 133.04 | 686.2 | 962.1 | -| Distinct IDs | GPU | 3,035.4 | 133.70 | 674.7 | 957.4 | -| Repeated IDs | CPU | 3,015.3 | 147.75 | 679.2 | 866.3 | -| Repeated IDs | GPU | 3,032.7 | 148.29 | 675.3 | 863.2 | - -Paired GPU/CPU rate ratios over five repeats were 1.0146–1.0181 for distinct -prefill, 1.0041–1.0075 for distinct decode, 1.0053–1.0080 for repeated -prefill, and 1.0029–1.0058 for repeated decode. These narrow within-process -ranges are encouraging but are smaller than startup/file-cache variation -between processes. There were only five pairs per prompt, synthetic 2K -prompts, and no native PLE arm in this control. The earlier native-versus-CPU -KAR test found no overall gain. We therefore keep the GPU path experimental -and make **no accepted end-to-end speedup claim**. A real 256K agent -workload, tool-call quality gate, at least 30 pairs for a 1% claim, cold/warm -stratification, and whole-model GPU memory-pressure measurement remain open. diff --git a/docs/experiments/2026-10-03-v-only-screen.md b/docs/experiments/2026-10-03-v-only-screen.md deleted file mode 100644 index 7d1ca443..00000000 --- a/docs/experiments/2026-10-03-v-only-screen.md +++ /dev/null @@ -1,105 +0,0 @@ -# V-only KV feasibility screen, 2026-10-03 - -## Question and scope - -**Methodology correction:** this custom V→K regression screen is not a -replication of the cited Keyless Attention method. Its results cannot be -used to judge that method or the quality effect of physically removing K. -The cited [Keyless Attention paper, §§2.2–2.4 and §4](https://arxiv.org/html/2606.21848v1) -uses a dedicated value-space query-routing projection and trains its -evaluated models from scratch. Exact conversion of existing multi-head -weights has an explicit subspace condition. Our earlier small activation -regressions did not establish that condition or implement that routing. - -Can the full QSA attention key be replaced by a cheap transform of the cached -value? This is an **offline activation and attention screen**, not a V-only -serving run. The normal K+V cache remained allocated in every model run. The -separate QSA indexer keys were unchanged. The user goal requires model quality -and throughput with a real V-only cache; these data only reject the simple -candidate studied here. - -The host was the Linux RTX 5090 (driver 595.91.07, CUDA 13.2) and the same -Qwen3.8-Flash-Next IQ3_S shards and Strata source as -[the paired report](2026-10-03-kar-ple-ab.md). Greedy runs used `--kv int8`, -one 4K context slot, `--kv-resident 4096`, `--expert-cache 8192`, -`--prefill 512`, `--spec 4`, and 160 output tokens. The short context makes -this a screening experiment, not the charter's 256K quality gate. - -An opt-in debug build copied K, V and Q activations from Strata's ordinary -speculative verifier into private files. Only the first token of each verifier -window was used, excluding speculative draft rows. The second prompt's 160 -greedy output IDs were **identical** between the original engine, the K/V -trace build and the final K/V/Q trace build. A first attempt to copy Q before -the attention kernel changed output IDs after token 26; those measurements -were discarded. Moving the diagnostic copy after attention restored all 160 -greedy IDs. Trace collection is refused in `--serve` and for more than 512 -generated tokens. - -## Reconstruction on held-out activations - -For each of 12 QSA layers and two KV heads, the candidate learned an -independent affine 2×2 map for every adjacent V pair to predict the -post-normalization, post-RoPE K pair. This is 128 small maps per head, fitted -with ridge regularization on the first coding prompt. It was compared with -directly copying V into K and with predicting each K dimension by its -training mean. The independent second coding prompt had 51 captured verifier -windows; the first had 57. Lower relative L2 error is better. - -| Held-out K predictor | Relative L2 error | -| --- | ---: | -| Copy V | 1.0933 | -| Per-dimension training mean | 0.8595 | -| Learned 2×2 V→K maps | 0.8788 | - -A within-prompt 34/23-window split also gave 0.8685 for the learned maps -versus 0.8537 for the mean. Thus the proposed small transform did not beat -the mean-K control in either split. - -## Attention proxy on real Q activations - -Using an independent, output-parity-checked trace of the second prompt, -offline attention compared each real Q with only the earlier generated-token -keys captured by this diagnostic. It did **not** include the complete prompt, -QSA indexer's selected cells, cache quantization, or the rest of the model. -Across 13,248 head/query comparisons, the results were: - -| K proxy | Best-key agreement | Mean top-5 overlap | Attention-output relative L2 | -| --- | ---: | ---: | ---: | -| Copy V | 5.87% | 27.51% | 0.3680 | -| Learned 2×2 V→K | 8.07% | 31.19% | 0.3555 | -| Position-aware 2×2 V→K | 10.74% | 35.21% | 0.3479 | -| Position-aware ridge V→K | 26.77% | 55.02% | 0.3023 | - -The third candidate removes the model's default, unscaled NeoX RoPE -(64 rotated dimensions, base 10 million) from calibration K before fitting -the same per-pair map, then applies RoPE at each held-out position to the -predicted K. It used the same 57 calibration and 51 independent held-out -verifier windows, and the same 13,248 attention comparisons. The new result -was reproduced by `scripts/kv-keyless-attention.py --rope-base 10000000`. -The fourth candidate fits a full per-layer, per-head linear V→unrotated-K map -with ridge regularization. Ridge strength was chosen solely within the -calibration trace using a chronological training/validation split, then -refitted on all 57 calibration windows. No held-out rows selected its -strength. It improved this limited attention proxy, but a 30.2% relative -attention-output error and 26.8% best-key agreement remain far from a -demonstrated quality pass. - -These errors concern only the custom predictors tested above. They do not -evaluate the paper's trained query-routing method. `Wq_keyless` conversion, -its treatment of Q/K normalization and RoPE, and a physical V-only runtime -were not implemented. No V-only memory, agent quality, or runtime speed -was measured. - -The maximum **theoretical** saving from deleting INT8 K codes and scales in -the current QSA layout is 528 bytes per token per QSA layer: 198 MiB of -resident VRAM for one 32,768-cell slot, 396 MiB for two such slots, plus up to -1.547 GiB of host mirror at 256K context per slot. The independent indexer -keys and page tables still use memory. A keyless transform or corrective -residual would have its own cost. - -The private prompts, K/V/Q traces, output IDs, and numerical reports remain -outside Git under `/home/para/.cache/strata-next/keyless-feasibility/` on the -GPU host. The repository contains only the opt-in diagnostic capture and -offline analysis scripts. The next candidate needs a held-out attention -quality pass before implementing a physical V-only cache; then it needs real -256K model output, tool-call, and agent-task comparisons against K+V. diff --git a/docs/experiments/2026-10-04-bounded-admission.md b/docs/experiments/2026-10-04-bounded-admission.md deleted file mode 100644 index 5e5d4b5f..00000000 --- a/docs/experiments/2026-10-04-bounded-admission.md +++ /dev/null @@ -1,50 +0,0 @@ -# Bounded native HTTP admission — STRA-28 - -Date: 2026-10-04. POST `/v1/responses` now reserves a request slot before -parsing/tokenization, through response-body completion/drop. The validated -`max_in_flight_requests` setting defaults to 17 (one active request plus the -existing 16-command queue), range 1–256; `STRATA_MAX_IN_FLIGHT_REQUESTS` -overrides JSON. A full runtime rejects new requests with 429 -`runtime_overloaded` and `Retry-After: 1`. Authentication runs first; drain's -503 takes precedence. Accepted work keeps its existing protocol and queue. - -`/admin/lifecycle` exposes maximum and available request capacity; native -`check-config` reports the configured limit. Health, management and stored -response routes remain outside this admission gate. Overload does not change -readiness. See [the API contract](../api-contract.md#admission-lifecycle). - -## Evidence - -- Rust 1.99.0: all 136 library tests passed. A new 32-thread reservation test - admits exactly three requests at capacity three and recovers all capacity - after drop. Existing body/trailer/drop and STOP-cleanup lifecycle tests pass. -- Clippy all-targets with warnings denied, fmt and diff checks passed. -- `smoke-native-drain.py` passed on macOS debug and Linux x86_64 musl release: - capacity two holds one active SSE and one queued JSON request. An unauthorized - malformed request gets 401; an authorized malformed request gets 429 before - parsing, including Retry-After. Drain then returns 503 at the same capacity. - Both accepted requests produce exactly `OK` (zero text tolerance), with - contiguous SSE sequence numbers and terminal completion. After release and - resume the next request succeeds; exactly three generations start overall. -- `smoke-config-check.py`: 26 cases passed on both platforms, including default - 17, explicit file capacity, valid boundaries 1/256, invalid 0/257, and environment - precedence. Preflight never launched the synthetic worker or acquired the - occupied listener. Both scripts already run in the Linux workflow; hosted - GitHub Actions has not run. - -Private control-plane preview on the laptop: -`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-admission-preview`, -**17,383,592 bytes**, SHA-256 -`da014544322555658ab81f77c97f4abc4b8a5cee4836358119d65e9cfd87baee`. -Its adjacent private JSON records source revision and checks. The active GPU -trial was not upgraded or restarted: PID 4031422/start ticks 558428413 remained -unchanged and the existing tunnel still returned ready. No inference was sent -to that trial. The isolated Linux CPU fixture directory and release build -intermediates were removed after verification; the private final binary remains. - -This bounds admitted HTTP handlers, not GPU slots, TCP connections, total -memory or generation jobs. A cancelled HTTP request may release its slot while -the worker finishes STOP cleanup under a separate generation guard. The engine -remains serial; neither batching nor performance improvement is claimed. -Real-model parity and long-running user-trial qualification for this candidate -remain pending. Development is ready for QA, not an independent QA pass. diff --git a/docs/experiments/2026-10-04-config-preflight.md b/docs/experiments/2026-10-04-config-preflight.md deleted file mode 100644 index 4804040b..00000000 --- a/docs/experiments/2026-10-04-config-preflight.md +++ /dev/null @@ -1,62 +0,0 @@ -# Native configuration preflight — STRA-25 - -`strata-next check-config [--config FILE]` validates deployment inputs without -starting a worker or binding a listener. It uses the production configuration, -key and tokenizer readers. External executables require regular-file and execute -access; bare names are searched in PATH. Embedded selection checks Linux and -payload availability without materializing it. Output excludes credentials, -arguments and raw config data; failures use fixed stage diagnostics. - -## Verification on 2026-10-04 - -- Rust 1.99.0: 134 library tests passed; all-target Clippy with warnings denied, - formatting and diff checks passed. -- `python3 scripts/smoke-config-check.py ` passed **18 checks** on both - macOS (debug) and Linux rnr5090 (x86_64 musl release). Checks include an occupied - bind port, worker execution marker, real synthetic tokenizer assets, explicit - config precedence, environment overrides, PATH/relative executable lookup, - missing/non-executable engine, missing payload, invalid tokenizer, key-file - permissions and malformed config/argument/tokenizer credential-echo rejection. -- Linux embedded CPU fixture passed the new positive embedded preflight check, - then existing sealed-memfd, READY, HTTP generation, crash restart and cleanup - tests. Embedded and external fixture outputs were exactly `A` (zero tolerance). -- The hosted Linux workflow now invokes the config smoke before packaging the - synthetic embedded worker. Hosted GitHub Actions have not run. - -Private control-plane preview: `~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-preflight-preview` -on the laptop; **17,314,312 bytes**, SHA-256 -`774c5c8f8c16ddd09d1fcb075865c243a086ee8a4fee5a657f3b4fa24bb8bb68`. -It contains no embedded engine and is not installed over the user trial. -Its adjacent JSON records the source commit. Temporary fixture binaries, remote -smoke directory and release build intermediates are removed after checking. - -This is a point-in-time input check. It does not verify ELF dependencies, driver, -model weights, port availability, GPU behavior or generation quality. JSON always -reports `readiness_checked: false`; `inference_configured` only indicates both -worker and tokenizer are configured. The active native endpoint and tunnel were -preserved and reported ready; that observation is not an idle-request assertion. - -## Controller integration — STRA-26 - -`qwen-codex-ctl native-service check-config` now invokes an explicit remote -candidate with required `--binary`, `--config`, `--working-dir` and optional -`--host`. Paths are passed as quoted positional shell arguments. The client -uses a 64 KiB stdout cap, a 30-second local SSH deadline and discards stderr; -only validated report fields are returned. It neither changes the selected -connection nor invokes systemd. It uses the SSH login environment, without -sourcing service environment files. - -Verification: 13 native-service tests and 8 native-API tests passed. New tests -exercise actual shell interpretation of paths containing spaces, quotes, dollar -and command-substitution syntax, selector/parser rejection, malformed or oversized -reports, credential-echo suppression, transport output bounds and a simulated -deadline. Installer execution twice left the launcher and 19 profile files -byte-identical. - -The installed controller passed a real SSH check against the private Linux -preflight preview with synthetic tokenizer/configuration and a marker executable. -The config named the already occupied trial port 18082; validation succeeded, -the marker was never created, and invalid config failed without echoing its -fixture secret. Active PID 4031422/start ticks 558428413, readiness and tunnel -were preserved. The isolated remote files were removed afterwards. No model, -GPU, performance or independent-QA qualification was performed by this check. diff --git a/docs/experiments/2026-10-04-console-readiness.md b/docs/experiments/2026-10-04-console-readiness.md deleted file mode 100644 index e6a3ceed..00000000 --- a/docs/experiments/2026-10-04-console-readiness.md +++ /dev/null @@ -1,56 +0,0 @@ -# Console readiness waiting — STRA-34 - -Date: 2026-10-04. `qwen-codex-ctl native-api wait-ready --wait SECONDS` -provides a read-only model-readiness gate after service startup. It works with -both the retained native trial and newer candidates. It never starts or stops a -service, switches profiles, opens a tunnel, or invokes inference. - -```sh -qwen-codex-ctl native-api wait-ready --wait 60 -# Explicit endpoint without changing the selected connection: -qwen-codex-ctl native-api wait-ready \ - --url http://127.0.0.1:18084 --no-auth --wait 5 -``` - -The selected native connection supplies its private key when configured; an -explicit URL requires explicit authentication choice. Every status response is -validated for native identity, Boolean readiness and worker state. Readiness -must agree with a ready worker. Connection failures and starting/restarting -states are retried. Authentication/HTTP/JSON failures, malformed status and -failed/stopping/unconfigured worker states fail immediately. - -A positive budget starts before the first request. Polls are 250 ms apart; -individual socket timeouts are capped at the remaining budget and eight seconds. -Late responses do not count as success. Zero/omitted wait makes one check. -Socket timeouts do not provide a hard total deadline against a server that keeps -sending partial bytes. Readiness is an instantaneous observation, not idle state, -model quality, completed work or sustained stability. - -## Evidence - -- `python3 scripts/test-native-api.py`: all 12 tests passed on macOS and Linux. - New coverage includes connection/startup/recovery progression, correct bearer - forwarding, only GET status calls, zero-wait behavior, budget including initial - request time, late-result rejection, terminal/malformed state rejection and - fail-fast nonconnection errors. A real local HTTP fixture transitions from - starting to ready under authentication without echoing its test key. -- CLI parsing and existing URL/auth rules pass. Installer coexistence, - idempotence and unrelated-file protections remain covered. -- `python3 scripts/test-native-service.py`: all 13 tests passed on macOS and - Linux. Existing service-controller behavior is unchanged. -- `scripts/check-local.sh`, already invoked by the Linux workflow, includes both - test files. Hosted GitHub Actions has not run. Rust/engine code was unchanged - and was not rebuilt for this client-only feature. -- Installed the helper through `scripts/install-qwen-native-api.py`. Reinstall - was idempotent; the launcher and 19 profile/configuration files across ordinary - and isolated trial profiles retained their byte digests. No private content - was printed or committed. -- The installed command against the existing tunnel at `127.0.0.1:18084` - returned `connection_changed: false`, native model `strata-native-iq3-s`, - `worker: ready`, and `ready: true`. This used only GET status; no GPU generation - or administrative mutation was sent. -- Owned remote CPU-test directory and local test bytecode were removed after - verification. Final source, report and installed helper remain available. - -The active runtime and tunnel remain unchanged. This feature is ready for -independent QA; the checks do not establish long-term server stability or speed. diff --git a/docs/experiments/2026-10-04-custom-regex.md b/docs/experiments/2026-10-04-custom-regex.md deleted file mode 100644 index 37aa0544..00000000 --- a/docs/experiments/2026-10-04-custom-regex.md +++ /dev/null @@ -1,50 +0,0 @@ -# Custom regex input validation preview — STRA-30 - -Date: 2026-10-04. Native Responses accepts regex-format custom tools and validates -the complete generated input before publishing a callable item. The lowered -Qwen input schema includes the regex as prompt guidance. The feature supports -top-level and namespaced tools, JSON/SSE, reasoning and continuation, preserving -input bytes and public identities. - -This is **output validation, without constrained token sampling**. Invalid output -fails the response; there is no automatic repair or retry. Lark remains rejected. -The wire shape follows the official [custom tool grammar documentation](https://developers.openai.com/api/docs/guides/function-calling#regex-cfg), -read for this implementation. Exact supported syntax and resource limits are in -[the API contract](../api-contract.md#regex-custom-input-validation-preview). - -## Evidence - -- All 140 Rust library tests passed. New catalog checks cover whole-string - alternation, exact Unicode/newline/whitespace, namespaces, empty-input match - semantics, malformed patterns, unsupported lookarounds/backreferences/lazy and - verbose/swap-greed syntax, oversized definitions, compiled-size rejection and - aggregate request limits. Existing function/text custom and replay tests pass. -- Clippy all-targets with warnings denied, fmt and diff checks passed. The - first Clippy run found test-module placement; moving it to the end resolved it. -- `smoke-custom-tools.py` passed on macOS debug and Linux x86_64 musl release. - Each run executes 22 CPU fixture generations: four prior text-tool cases, - text continuation, sixteen regex cases (valid/invalid × namespaced/top-level × - reasoning none/low × JSON/SSE), and regex continuation. -- Accepted input matched the exact multiline Unicode source (zero tolerance). - Invalid buffered calls returned 502 without output; invalid SSE ended with - `response.failed`, contiguous sequence numbers, no custom call item events and - no custom input delta/done events. Invalid grammar declarations returned 400 - without starting a generation. Continuations returned exactly `OK`. -- The expanded smoke remains in the Linux workflow. Hosted GitHub Actions has - not run. `regex` 1.13.1 and `regex-syntax` 0.8.11 were already in Cargo.lock; - this change makes them direct dependencies without upgrading package versions. - -Private preview: -`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-regex-preview`, -**17,449,504 bytes**, SHA-256 -`183fcdcce766244662bcf49cfe25dd1b3942586b138b97eb9602169db4d369f6`. -Adjacent private JSON records source revision and gates. The temporary Linux -fixture directory and release intermediates were removed; the final binary -remains private. The active GPU trial and tunnel were preserved, with no inference -or management mutation sent to that service. - -Real-model grammar-following quality, latency and sustained stability are not -qualified. Compilation/cache bounds do not imply a total process memory bound. -Historical inputs are not revalidated under later tool definitions. Earlier valid -calls/text in an SSE stream cannot be retracted when a later call fails. -Development is ready for QA; this candidate does not replace the qualified trial. diff --git a/docs/experiments/2026-10-04-generation-deadline.md b/docs/experiments/2026-10-04-generation-deadline.md deleted file mode 100644 index 48afe144..00000000 --- a/docs/experiments/2026-10-04-generation-deadline.md +++ /dev/null @@ -1,56 +0,0 @@ -# Optional active-generation deadline — STRA-29 - -Date: 2026-10-04. The control plane supports an operator-selected absolute -execution deadline through `engine.generation_timeout_s` or -`STRATA_GENERATION_TIMEOUT_S`, integer 1–86400 seconds. Omission leaves it -disabled. Native preflight reports the effective value. The clock covers the -active worker command, including blocked stdin and result-channel backpressure; -it excludes parsing, tokenization and queue wait. - -Timeout revokes readiness and kills/reaps the worker before bounded failure -delivery and the existing finite restart policy. Neither the interrupted request -nor queued work is replayed. A consuming client receives JSON 502 -`generation_failed` or terminal SSE `response.failed`. See the -[API contract](../api-contract.md#active-generation-deadline) for slow-client -delivery limits and [deployment notes](../../deploy/README.md#worker-recovery). - -## Verification - -- Rust 1.99.0: full 137-test library suite passed, including the new full-channel - deadline test. The subsequently added blocked-stdin regression and full-channel - test both passed together (138 distinct library tests now present). Clippy - all-targets with warnings denied, fmt and diff checks passed. -- The blocked-stdin test sends a command larger than pipe capacity to an engine - that does not read. Its 100 ms deadline yields explicit failure and a failed - worker. The full-channel test does not consume tokens until the supervisor - exits: cleanup still completes, failure counts once, generation activity is - released, and the channel closes after its buffered token. These are timeout - acceptance tests, not speed measurements. -- `smoke-generation-deadline.py` passed four HTTP cases on macOS debug and Linux - x86_64 musl release: streaming/non-streaming crossed with restart budget 0/1. - Every stalled command terminates with failure, original PID is gone, readiness - is revoked, queued work is not executed, and generation activity returns to zero. - Restart-enabled cases serve a fresh request with exact output `OK` (zero text - tolerance). SSE event numbering stays contiguous without a completed event. -- `smoke-config-check.py` passed 35 cases on each platform, including absent - deadline, valid 1/86400 bounds, invalid 0/86401, JSON configuration and environment - precedence. The new HTTP smoke is wired into Linux CI; hosted Actions has not run. -- A first development run exposed changed crash-channel semantics; failure - delivery was restricted to deadline expiry, and the original crash/no-replay - regression then passed in the full suite. Existing cancellation and shutdown - tests also pass with deadlines disabled. - -Private preview: -`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-deadline-preview`, -**17,437,920 bytes**, SHA-256 -`11b427c42e27cc1492770075bc970f9ad480d9644f6a17d7ab9352d3b80815a5`. -Source revision and checks are recorded in adjacent private JSON. The isolated -remote fixture directory and release intermediates were removed; the final -artifact remains private. The user's GPU trial remained PID 4031422/start ticks -558428413, with the existing tunnel returning ready; no inference or management -mutation was sent to it. - -No real-model deadline budget, speed improvement or long-term stability claim is -made. A timeout deliberately loses that worker's caches and may reload the model. -This feature is ready for QA, not independently approved or installed over the -qualified user trial. diff --git a/docs/experiments/2026-10-04-keyless-runtime.md b/docs/experiments/2026-10-04-keyless-runtime.md deleted file mode 100644 index 1dbcbd8b..00000000 --- a/docs/experiments/2026-10-04-keyless-runtime.md +++ /dev/null @@ -1,155 +0,0 @@ -# V-only QSA: реалізація та перевірка на RTX 5090 - -**Рішення:** залишити V-only експериментальним. Kernel і фізичний кеш -пройшли технічні тести. Конверсія наявної Qwen не пройшла перевірку якості -агентної роботи; багатоденний робочий запуск не дозволений цим результатом. -Ціль прискорення інференсу без втрати якості не досягнута. - -## Практична задача через console harness - -Використано той самий збережений запит: одна HTML-сторінка з хрестиками-нуликами -на Three.js/WebGL, перемогою/нічиєю, Restart, підтримкою телефона та task workflow -у спеціальному LeaseVibe test project. SHA-256 тексту запиту: -`e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`. -Агент отримував завдання через той самий launcher і Responses adapter; -оператор не підказував йому й не виправляв створюваний результат. - -| Варіант | Запити моделі / спроби | Виконані tool calls | Згенеровані токени | Середня decode, ток/с | Час агента, с | Результат задачі | -| --- | ---: | ---: | ---: | ---: | ---: | --- | -| Native K+V, попередній еталон | 49 | 59 | 49 854 | 115,7 | 634,27 | Гра створена, 6/6 незалежних перевірок | -| V-only, лінійна ініціалізація | 1 | 0 | 645 | 85,8 | 16,34 | Переплутав гру з Breakout, файла немає | -| V-only, калібрований query routing | 3 | 0 | 908 | 90,8 | 38,01 | Невідомі/незавершені tool calls, файла немає | - -У каліброваному прогоні було одне початкове звернення та два автоматичних retry -harness. Усі три виклики були відхилені до виконання інструмента. Це відрізняється -від звичайного виправлення параметрів після відповіді MCP. У гри немає готового -артефакту, тому її шість браузерних перевірок виконати неможливо. - -Decode усереднено як `сумарні output tokens / сумарний decode time`. -908 токенів отримано за 9996 мс decode; швидкості окремих спроб: -86,7, 100,1 і 103,1 ток/с. Input: 67 104, з них reused: 44 726. -Перший prompt мав 22 368 токенів, prefill тривав 25 379 мс; наступні дві спроби -повторно використали 22 363 токени кожна. Токени невдалих відповідей враховано -за журналом engine, оскільки adapter не опублікував їх як завершену відповідь. - -Ці невдалі короткі прогони не є зіставним виміром прискорення завершеної задачі: -вони зупинилися перед першою успішною дією. Попередній успішний еталон повторно -не запускався. Його повний опис — -[попередній звіт](2026-10-03-agent-gpu-kar-threejs.md). - -## Що реалізовано - -- Нативний bounded GGUF → F32 експорт реальних `Wq`, `Wk`, `Wv` та нормалізацій, - із fingerprint/digest і перевіркою геометрії; повні 83,6 GB шарди повторно - не хешувалися. Використано вже перевірений manifest. -- Початкове перетворення query у простір V: - `A = Wk Wv.T pinv(Wv Wv.T)`, `q_keyless = q A`. -- CUDA query routing після наявної Q-нормалізації та перед RoPE. Gate-половина - вихідного query/gate projection збережена. -- Єдиний INT8 V pool і його scales у resident GPU кеші й host mirror. - Attention K codes/scales не виділяються та K projection не обчислюється. -- Scores читають позиційно повернутий V; value sum читає вихідний V. - Друга постійна копія повернутого V не створюється. -- Prefill, decode, speculative verifier, page streaming і snapshots використовують - це представлення; snapshot формату K+V не відновлюється у V-only. -- Окремі ключі QSA indexer та звичайний K+V кеш MTP draft-моделі збережені. -- M-RoPE scores використовують відповідні time/height/width позиції. Числова - арифметика цього шляху перевірена; якість задач із зображеннями не кваліфікована. - -Метод — експериментальний retrofit з -[Keyless Attention](https://arxiv.org/html/2606.21848v1). -Робота авторів навчає моделі з нуля. Це не доказ, що заміна attention у вже -навченій і квантованій Qwen збереже її якість. Поточний retrofit залишає вихідні -Q-нормалізацію та gate і навчає додаткові routing matrices; він не є відтворенням -усього навчального експерименту авторів. - -## Технічні перевірки - -| Перевірка | Результат | -| --- | --- | -| CUDA query routing проти незалежного CPU matrix product | max abs `6.55651093e-7` | -| Attention, текстові позиції, 3 causal selections, переставлені сторінки | relative L2 `1.32283452e-7`; max abs `2.78549168e-8` | -| Attention, різні M-RoPE time/height/width позиції | relative L2 `1.32984469e-7`; max abs `2.55048025e-8` | -| Resident проти streamed V-only, 40 000 cells | 306 batches; 717 880 block lookups; 70 200 misses; 0 overflow; 0 failures; побітова рівність outputs | -| V-only ring restore | Outputs побітово ідентичні resident | -| Conversation snapshots, включно з K+V форматами та V-only | 2448 checks passed; немає K payload/pools у V-only | -| Routing identities і numerical gradient калібрування | 5 Python tests passed | -| Rust | 96 tests passed, fmt та Clippy passed | -| Статичний Linux CLI | GGUF/KAR smokes; точний F32/Q2_0 export; відмова overwrite; nonfinite output cleanup — passed | -| Linux CPU engine | 5 CTest tests passed | -| Фінальний CUDA CTest на вільному GPU | 3/3 passed | - -Точність CUDA gate: query max abs ≤`2e-6`; attention relative L2 і max abs -≤`1e-5`. Незалежний CPU oracle використовує double accumulation і explicit -RoPE/softmax/raw-V retrieval. Раніша спроба запустити окремий CUDA test context, -коли вся модель займала GPU, отримала OOM; після unload усі тести пройшли. -GPU validation script тепер відмовляється запускати їх на зайнятому GPU. -Це не було падінням inference engine. - -## Калібрування та якість - -Захоплено ordinary-Qwen teacher activations із двох різних prompt: -2061 prefill positions для навчання й 526 для calibration validation. -Калібрування мінімізує causal attention KL, змінюючи тільки query routing. -Вихідні projections, norms, gate і решта моделі заморожені; кешовані K -не синтезуються. Числову похідну objective перевірено finite difference. - -Виконано попередній fit із 128 sampled queries та розширений fit із 1024, -до 512 sampled keys, 200 Adam steps, learning rate 0.003. Validation використано -для порівняння fit, тому це calibration validation, не незалежний фінальний -benchmark якості. Агентна задача не входила до цих навчальних текстів. - -У розширеному fit середня по heads відносна L2-похибка attention output -на validation лежить між `0.20433868` і `1.25948095` залежно від шару; -найгірший head — `2.28521657`. Зменшення навчальної помилки не зберегло -поведінку на інших даних. Повний агентний прогін також failed. -Не оголошуємо ні збереження якості, ні неможливість методу взагалі. - -## Пам'ять - -На один QSA block (4 cells × 2 KV heads): - -| Представлення | Bytes | -| --- | ---: | -| INT8 K+V із scales | 4224 | -| INT8 V-only із scales | 2112 | - -Для 12 main QSA layers і 256K cells економія K codes/scales становить -1.546875 GiB у повному host mirror. При 32K resident економія resident cache — -198 MiB; routing matrices додають приблизно 72 MiB GPU пам'яті. Indexer та MTP -не входять у ці половини. Збереження половини QSA cache не означає половину -всієї VRAM: expert cache auto використовує доступне місце. Завантажена модель -займала 31 773 MiB GPU, після зупинки — 34 MiB. - -## Відтворення та provenance - -- GPU RTX 5090, Ryzen 9 9950X3D, 128 GB RAM, Linux. -- NVIDIA driver `595.91.07`, power limit `600 W`; - nvcc `13.2.86`, CUDA architecture `120`. -- Модель Qwen3.8-Flash-Next GSQ-RCO IQ3_S, source shard identities у - `manifests/qwen3.8-flash-next-iq3-s.json`; native expert weights, без KAR overlay. -- Конфігурація: один слот, **256K configured context**, INT8 V-only main QSA, - 32K resident, MTP spec 4, expert cache auto. Фактично заповнений prompt — - 22 368 tokens; повний 256K/512K quality gate не пройдено. -- Upstream identity збережено у `docs/upstream.md`; local base — `46a9787`. -- SHA-256 engine саме каліброваного агентного прогону: - `fdd4ace410d57eff4fe67f33e13fc5f43ed8981b597689a6047b6460e87e4cd9`. - Після прогону додано defensive buffer guards і restoration guard для MTP; - фінальна збірка має окремий hash у приватному verification record. -- SHA-256 початкового routing: - `70d4c7b440f6dddbae755c340a27d8cd2a5e626233729e85fc8ccf1a83db796f`. -- SHA-256 routing каліброваного агентного прогону: - `5c70306b0d5e0b351f0f3f60561e37e78dff44a5a3ec7628e835cd9adf8e94e0`. -- Лінійний агентний прогін є діагностичним: окремий digest його проміжної - engine-збірки перед заміною не збережено. -- Сирі captures, logs, credentials, routing weights і generated outputs — тільки - у приватних ignored/cache шляхах. Стиснені моделі не публікуються. - -Встановлено обидві пари назв launcher: `codex-qwen`/`codex-qwen-ctl` та -`qwen-codex`/`qwen-codex-ctl`. Експериментальний opt-in profile: -`strata-next-v-only --kv-mode without-key --layout 1x256 --kv-cache q8_0`. -Profile явно позначено як такий, що не пройшов quality gate. -Після експериментів server зупинено й попередні console connection/config -відновлено. Тимчасові exports, teacher captures і зайві routing/build artifacts -прибрано; перевірені source shards і потрібний фінальний prototype збережено. -Прибрано 1 693 472 325 bytes проміжних файлів (приблизно 1,58 GiB). diff --git a/docs/experiments/2026-10-04-large-embedded-package.md b/docs/experiments/2026-10-04-large-embedded-package.md deleted file mode 100644 index f2cee61c..00000000 --- a/docs/experiments/2026-10-04-large-embedded-package.md +++ /dev/null @@ -1,67 +0,0 @@ -# Large embedded static-CUDA package — STRA-24 - -Date: 2026-10-04. Scope: packaging and CPU supervision checks. No inference, -model-quality or speed claim. The user's active native endpoint and tunnel were -preserved throughout; no trial restart or profile switch occurred. - -## Implemented - -Build-time payload verification and copying now use a 64 KiB buffer with a -1 GiB hard limit, rather than loading the complete engine into a Vec. Validation -covers the exact copied SHA-256, ELF64 little-endian target architecture, -executable type and declared 40-character source revision. Errors fail the -build. The revision is provenance supplied by the builder, not a reproducibility -proof. Rust compilation/linking and runtime memfd storage still require resources -proportional to payload size. - -`engine-help` explicitly materializes the embedded engine and executes `--help` -with `CUDA_VISIBLE_DEVICES` empty, retaining the memfd through child exit. It -does not load a model. Ordinary builds remain without an embedded engine. - -## Private artifacts - -| Artifact | Bytes | SHA-256 | -| --- | ---: | --- | -| Static-CUDA engine | 593,942,184 | `389b518c3c8afaccd20bab78f538e008ff996d11dacb08abe73e315a853c6b11` | -| Combined musl control plane and engine | 611,277,088 | `4e3893ddf90fd35acf39b73a12858da072cea271bf0c6129a5559fca7306bba6` | - -Engine source: `a36e45ac780cd137aceaa33bed663edd932c73d9`; upstream pin remains -`d9ab8435f654c368c586340d490915f6addf56a3`. The combined executable is retained -privately under `~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-static-cuda-preview` -on the laptop, with adjacent provenance JSON. It is not the installed trial -runtime. Weights and tokenizer are external. No artifacts were published. - -## Verification - -- Rust 1.99.0: 134 macOS library tests passed; all-target Clippy with warnings - denied and formatting passed. Streaming tests cover exact bytes, size boundary, - overflow, architecture/digest/revision rejection, truncated input, interrupted - reads and write failures. -- A normal build reports no payload and rejects `engine-help` explicitly. -- Cross-built Linux musl CPU fixture passed embedded identity, sealed memfd, - GPU-hidden help, readiness, HTTP generation, forced worker restart, and worker - and memfd cleanup. Output was exactly `A` for both embedded and external copies - of the same fixture (zero tolerance). This is synthetic protocol evidence. -- The actual 593,942,184-byte engine was embedded successfully. On rnr5090, - `engine-info` matched the expected payload size, digest and source revision. -- `env -u LD_LIBRARY_PATH engine-help`, bounded externally - by a 20-second timeout, exited zero and printed Strata help. No GPU was visible - to the child. The outer executable had no ELF INTERP or NEEDED entries. -- The inner engine's earlier ELF audit found only host libm, libc and loader - dependencies, no RPATH/RUNPATH, and a **glibc 2.43** minimum. It was built with - CUDA 13.2.86/GCC 15 for SM 120. The host has RTX 5090 and driver 595.91.07; - this check did not exercise GPU kernels. -- Trial worker PID/start identity remained unchanged and status stayed ready. - Readiness alone does not indicate whether user requests are active. - -## Remaining gates - -The inner executable is not fully static: the host still needs compatible glibc -and an NVIDIA driver. Runtime-selected `dlopen` dependencies, a clean-node run, -older glibc baseline, real-model numerical parity, agent completion and stability -remain unverified for this package. The `shared_libraries_bundled: false` metadata -means there are no separately bundled shared objects; static toolkit code is -inside the engine. No hosted GitHub Actions run has occurred. - -The source-copy directory, remote smoke directory and release build intermediates -are removed after verification; final private binaries and provenance remain. diff --git a/docs/experiments/2026-10-04-model-switch.md b/docs/experiments/2026-10-04-model-switch.md deleted file mode 100644 index 754f7ae5..00000000 --- a/docs/experiments/2026-10-04-model-switch.md +++ /dev/null @@ -1,140 +0,0 @@ -# Managed console model switching — 2026-10-04 - -## Scope - -STRA-35 fixes the failed `codex-qwen-ctl start` selection of -`strata-next-kar-ple-gpu` while the qualified native runtime owned the GPU. -Previously the independent experiment controller rejected any occupied GPU; -it did not know how to stop and restore the native supervisor. - -The installed console now routes ordinary llama.cpp, ordinary Strata, -experimental Strata and native starts through one remote coordinator. -Existing menu numbers are preserved; `strata-native` is appended. - -## Transaction - -1. Resolve and preflight the requested model through its existing controller. - Ordinary downloads/verification happen before unloading the old model. -2. Inventory managed process roots and reject unrelated CUDA processes. - Serialize console switches with a private host lock. -3. Save the previous launch recipe privately, stop the known current owner, - and wait for its GPU memory to release. -4. Launch the selected backend and wait for its API/model readiness. -5. Only then discover the endpoint and update the harness profile. -6. If the target fails, clean up its known processes and restore the previous - recipe. Report failed restoration explicitly and retain the private journal. - -The qualified legacy native runtime has no admin drain endpoint. An explicit -model switch sends its supervisor normal SIGTERM; an in-flight native request -can be interrupted. Existing ordinary/experiment controllers retain their -busy-request guards. Unrelated GPU work is never killed. - -## Verification - -- 11 transaction/preparation tests: sequencing, preflight preservation, - unrelated and ambiguous owners, PID reuse/ancestry, idempotence, - rollback, rollback failure, failed-target cleanup and GPU-release waiting. -- 5 menu tests: stable numbering, native dispatch, all backend routing, - profile preservation on failure, installer backup and idempotence. -- All 16 passed on macOS and Linux; 13 existing native-service and 12 native-API - tests also passed on macOS. New suites are included in `check-local.sh`. -- Live RTX 5090 switch passed through the installed command: - `codex-qwen-ctl start strata-next-kar-ple-gpu --layout 1x256 --kv-cache q8_0 --wait-seconds 900`. - Previous native PID 4031422 exited; experiment supervisor 4133313 and engine - 4133347 became ready on port 18081. The private switch journal is `ready`. - Engine log confirmed the experimental level-2 PLE KAR CUDA cache arm. -- Re-selecting the same model through `qwen-codex-ctl start` preserved those - process IDs and completed successfully. The ordinary harness connection now - selects `strata-next-kar-ple-gpu`. -- A short non-streaming generation returned HTTP 200, one choice, 56 input and - 16 output tokens. Its deliberately capped output ended with `length`; this - checks generation transport, not answer quality or a complete agent task. -- Model startup took several minutes reading NTFS-backed weights. Observed - disk reads were around 150 MB/s during loading; no whole-archive SHA pass was - added. Switching the controller does not remove model I/O startup cost. -- The retained native restart recipe passed preflight. Reverse switching and - the ordinary llama.cpp/Strata service transitions were covered by dispatch - and transaction tests, but were not separately run on the GPU in this trial. - -This is a lifecycle change; engine arguments, model weights and numerical -kernels are unchanged. No inference speed or quality improvement is claimed. -KAR PLE and V-only retain their experimental quality status. CPU fault tests -exercise rollback; they are not a live GPU failure-injection trial. - -## Commands - -```sh -codex-qwen-ctl start strata-next-kar-ple-gpu -codex-qwen-ctl start strata-native -codex-qwen-ctl start -``` - -`qwen-codex-ctl` uses the same controller. Start the agent with `qwen-codex` -after the controller reports readiness. Re-selecting the already-ready profile -keeps its process. `--wait-seconds` accepts 1–7200 seconds; the default is 3600. -Native uses the retained loopback SSH tunnel, creating one if the port is free. -The coordinator only manages the known host recipes; an externally started -untracked GPU workload still yields an ownership error. - -## Configured host layout (STRA-68) - -The repository controller also accepts an **opt-in** private deployment file. -The installed controller and the active trial are not changed by this feature. -All paths are absolute and supplied by the operator, for example: - -```json -{ - "schema_version": 1, - "root": "/home/alice/.local/state/strata/switch", - "native": "/home/alice/.local/state/strata/native", - "control": "/home/alice/.local/share/strata/console-helpers", - "agent_helper": "/home/alice/.local/share/strata/agent-profile.py", - "binary": "/home/alice/.local/share/strata/releases/v1/strata-next", - "config": "/home/alice/.config/strata/native-v1.json", - "cwd": "/home/alice/.local/share/strata", - "url": "http://127.0.0.1:18082", - "model": "strata-native-iq3-s", - "key_file": "/home/alice/.config/strata/api-key" -} -``` - -Only `key_file` is optional. The deployment and key files must be private regular -files owned by the invoking user (mode 0600); existing state directories must be -private too (0700). The readiness URL must be literal loopback HTTP with a port, -without credentials or a path. Readiness requires the expected service, model -and `ready=true`; redirects are not followed. Its socket timeout is not a hard -wall deadline against a slow byte stream. - -```sh -chmod 600 /home/alice/.config/strata/deployment.json -printf '%s\n' '{"backend":"native","waitSeconds":3600}' | - python3 scripts/strata-model-switch.py \ - --deployment /home/alice/.config/strata/deployment.json start -``` - -For this explicit mode, the native CLI runs `provision --config` before the -transaction can unload any current model. It resolves pinned assets, embedded -engine and `native_model`/derived tokenizer using the existing native bootstrap; -its bounded subprocess has private/null output and is killed/reaped on timeout. -No old PID file is needed for a first launch. An existing saved live recipe is -retained, including its selected environment. Use separate state directories for -separate native recipes; this remains a single-native-profile controller. Keep -versioned binary/config/model paths immutable while a model is running or being -switched so that rollback can reuse the saved recipe. - -Without `--deployment`, the existing host defaults and preflight behavior remain. -This does **not** install `qwen_remote`, `strata_remote` or the agent helper, nor -make their own backend-specific paths portable: those helpers must already be -configured on the destination host. It also does not replace the native runtime -with Python; Python here is only the console management tool. - -Validation adds private manifest, cold recipe, timeout/reap, authenticated -readiness and legacy-helper regression cases to the controller suite. The hosted -`smoke-controller-deployment.py` runs the actual combined native CLI with a -synthetic CPU engine, provisions a tiny verified GGUF offline, starts the native -profile from an empty state, preserves its PID on failed preflight, then fails a -simulated alternate backend and restores the original native process. The -synthetic Responses output must be exactly `A` before and after rollback (zero -tolerance). GPU ownership and the alternate backend are test adapters. This is -CPU process/transaction coverage; actual CUDA, real-model quality, clean-node -helper installation and GPU failure rollback remain separate acceptance gates. diff --git a/docs/experiments/2026-10-04-native-console.md b/docs/experiments/2026-10-04-native-console.md deleted file mode 100644 index 01aa2b82..00000000 --- a/docs/experiments/2026-10-04-native-console.md +++ /dev/null @@ -1,153 +0,0 @@ -# Native Responses console trial — 2026-10-04 - -## Result and scope - -The native **text** Responses profile completed a real, unassisted console -agent task on Linux RTX 5090. The agent built a playable Three.js tic-tac-toe -game, ran its own browser checks and completed LeaseVibe TEST-10. An observer -then independently checked the final game: **23/23 passed**, no page errors. -This qualifies a user trial of this profile, not the whole project, a long -stability soak, or a performance improvement. - -The test used the actual `qwen-codex` launcher and Codex CLI 0.160.0 with its -normal approval review enabled. No task assistance, corrective prompts or -completion actions were supplied by the observer. Four rejected tool items -were ordinary MCP workflow/claim validation; the agent handled the workflow. -One model response used an undeclared function name. The native server rejected -it before tool execution and the harness retried successfully. This was not a -zero-error run. - -## Measured run - -| Metric | Result | -| --- | ---: | -| Full task wall time, excluding model startup | 2,587.43 s (43:07) | -| Main agent completed model responses / iterations | 68 | -| Main agent output tokens, including reasoning | 68,403 | -| Reasoning tokens (subset of output) | 25,419 | -| Main agent cumulative input tokens | 6,170,118 | -| Main agent reused input tokens | 1,218,680 | -| Main agent weighted decode rate | 116.91 tok/s | -| Largest actual prompt | 131,759 tokens | -| Completed shell and MCP tool items | 74 | -| MCP items | 42 | -| All engine generations, including approval reviews and rejected response | 132 | -| All engine output tokens | 71,313 | -| All engine weighted decode rate | 117.18 tok/s | -| All engine request decode mean / median | 131.30 / 126.80 tok/s | -| All engine request decode p10–p90 | 102.87–165.38 tok/s | -| All engine prefill / decode time | 1,483.139 / 608.567 s | - -Weighted decode means generated tokens divided by summed engine decode time; -it excludes prefill, tools, MCP, browser tests and client work. It is not the -end-to-end task rate. Approval review requests share the worker and compete -for prefix reuse. Cache state is mixed: the first engine request reused zero -tokens; the run then contains both reused and cold prefixes. All engine input -tokens total 9,935,033, with 1,604,457 reused. No cache reset was forced per turn. - -This is one functional run, not a paired A/B experiment. Confidence intervals, -TTFT distributions, PCIe traffic, draft acceptance and expert-cache distributions -were not collected for this report. It establishes no speedup or regression -relative to the earlier benchmark. - -## Quality evidence - -- TEST-10 (`6aa33214-1e3f-4dd4-97ce-7c8f157f8f1f`) independently read back as - **Done**, with final work record and evidence. -- Agent's own Node/CDP harness: **132/132 assertions**, exit zero. It covers - winning lines, draw, restart, occupied cells, mouse/touch/keyboard input, - multiple viewports, pixel checks, CDN failure and a hover negative control. -- Observer's separate browser check: **23/23**, covering visible WebGL, all - eight winning lines, terminal locking, restart, draw, occupied cells, mobile - interaction/layout and absence of page errors. The agent's game was not edited. -- Final single-file game: 19,027 bytes; SHA-256 - `7837bbede7bff9de5f127c514cec32311b82159f37b27c7e2cb8a72e550139d6`. -- Console reached its final completed turn. Tool calls and outputs traversed - native Responses, including MCP text-part output and namespace identities. - Raw SSE frames for the entire session were not captured; terminal-event - coverage also comes from the earlier real API checks and local tests. - -Earlier attempts are retained as failures/incomplete runs: MCP text-part replay -and late developer instructions exposed protocol gaps which were fixed; a later -452.02 s run produced a playable game but left TEST-9 incomplete. Exit zero was -not accepted as task completion. A template fidelity fix kept assistant -commentary and tool calls in one turn before the successful fresh run. - -## Versions and configuration - -- Full agent run: control plane **a3770ed**, following console integration - **a60ebe5**. Follow-up deployed revision **93e2a9b** additionally preserves - call identity when parallel tool results arrive out of order, and reports - the existing greedy temperature default as zero. Sampling did not change. -- The complete agent run was not repeated on 93e2a9b. Instead, its changed path - passed a real-model paired check: ordered/reversed delivery produced identical - greedy JSON, `{"Oslo":3,"Paris":17}`, numerical tolerance **0**. Both responses - completed and reported temperature zero. -- All **116 Rust tests**, formatting and Clippy with warnings denied passed. - Rust 1.99.0, Linux x86_64 musl release build successful. -- Deployed supervisor: 17,132,528 bytes, SHA-256 - `74b116ad22eaf8382447bb71886dfc6a6d3e68142118f369f8be9cb0735dee2f`. -- Engine 0.1.35, fork `engine-fork-f80a3e0`, executable SHA-256 - `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. - Imported upstream remains `d9ab8435f654c368c586340d490915f6addf56a3`; - engine code was not changed in this milestone. -- RTX 5090 32,607 MiB, driver 595.91.07, CUDA 13.2.86, 600 W limit; - Ryzen 9 9950X3D, 128 GB RAM. -- Qwen3.8-Flash-Next IQ3_S, one slot, configured context 262,144, INT8 KV, - 32,768 resident KV tokens, auto expert cache/prefill, MTP spec=4/min-p=0.5, - existing expert profile, VRAM reserve 700 MiB. No KAR or V-only enabled. -- Model's previously verified source shards total 83,617,662,656 bytes, digests - `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` and - `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. - No new whole-model hashing was performed. -- Unchanged task prompt SHA-256: - `e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`. - -## Run the trial - -The loopback endpoint is running on rnr5090:18082, exposed through the retained -SSH tunnel at laptop port 18084. The isolated test profile was used throughout; -the user's normal connection has not been changed. To select native Responses: - -```sh -qwen-codex-ctl connect strata-native --url http://127.0.0.1:18084 --no-auth -qwen-codex-ctl status -qwen-codex -``` - -`status` reports `strata-native-iq3-s`, 1 × 256K, Responses ready; `/ready` -returned HTTP 200 after the final deployment and real-model follow-up. -The launcher uses the Rust endpoint directly, with no Python serving bridge. -The local launcher/controller itself still uses Python. - -The retained tunnel survives the tool session but not a laptop reboot. If it -is absent, recreate it (do not run a second listener on an occupied port): - -```sh -ssh -fN -o ExitOnForwardFailure=yes -L 127.0.0.1:18084:127.0.0.1:18082 rnr5090 -``` - -This native endpoint is externally supervised; the launcher does not yet own -its start/stop lifecycle. It is not configured as a boot service. `ctl stop` -explicitly directs the user to the owning service instead of stopping unrelated -processes. No HTTP authentication is implemented: keep the endpoint loopback -only and use SSH, as deployed. - -## Remaining gates - -Text and function tools are supported. Image input, custom/freeform/web tools, -encrypted reasoning, durable response history, native lifecycle profiles and -authentication remain outside this trial. Structured output is prompted and -validated, not constrained decoding. Process-local history does not survive a -restart. Full 256K occupancy, 1×512K, 2×256K and multi-day stability are not -qualified by this 131,759-token maximum run. KAR GPU and V-only retain separate -quality gates. Hosted GitHub Actions have not run; a hosted repository is not -yet set up. - -Private raw events, timing, engine log, usage summaries, final game and QA -screenshots are retained under the laptop's -`~/.cache/strata-next/native-console-20261004/`; remote runtime/config/assets -remain under the same cache subdirectory on rnr5090. Credentials and captures -are not in Git. Disposable capture home/work directories and obsolete native -runtime copies were removed. The deployed binary, tokenizer, configuration, -tunnel, private evidence and final game are retained for the user trial. diff --git a/docs/experiments/2026-10-04-native-responses.md b/docs/experiments/2026-10-04-native-responses.md deleted file mode 100644 index e1bd9a29..00000000 --- a/docs/experiments/2026-10-04-native-responses.md +++ /dev/null @@ -1,111 +0,0 @@ -# Native Responses API on the real IQ3_S model - -## Scope and provenance - -This is a functional protocol and supervisor qualification on the RTX 5090, -not a paired throughput benchmark or a completed agent-quality gate. -The ordinary production endpoint was not switched. - -- Control plane: `0f1efa2` plus the accompanying `RESUME`/`REUSED` parser fix; - Rust 1.99.0, release `x86_64-unknown-linux-musl`. -- Static CLI: 16,983,824 bytes, SHA-256 - `ee1dd490c64efb636025da74868dad1a59662eb2f95409513f7b900b01d534be`. - Linux ELF inspection found no interpreter or required shared libraries. - This describes the control-plane executable, not the separate CUDA engine. -- Engine: existing baseline `engine-fork-f80a3e0/build/strata`, engine 0.1.35, - SHA-256 `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. - Imported upstream provenance remains in `docs/upstream.md`. -- Hardware: RTX 5090 32 GiB, Ryzen 9 9950X3D, 128 GB RAM; - NVIDIA driver 595.91.07, CUDA 13.2.86, configured power limit 600 W. -- Model: private Qwen3.8-Flash-Next IQ3_S source shards, 83,617,662,656 bytes. - Previously verified SHA-256 identities, without another full-file scan: - `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` - and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. -- Configuration: one worker, 262,144 context, INT8 K+V, 32,768 resident KV, - automatic expert cache/prefill, MTP spec4 with minimum probability 0.5, - 700 MiB VRAM reserve; copied baseline engine arguments and environment. - No KAR or V-only mode. Greedy requests, reasoning effort `none`. -- Rust directly supervises C++; Python only drives these offline HTTP checks. - Test endpoint: loopback port 18082. Private evidence directory on the Linux - host: `/home/para/.cache/strata-next/native-responses-20261004`. - -## Defect found and fixed - -The engine loaded and reached READY, but the first real generation got HTTP -503 because the Rust wire parser rejected `RESUME 0` as an unknown tag. -The supervisor correctly isolated the failed worker and initiated recovery. -The failure is retained as `text-json.pre-resume-fix.json` and `runtime.log`. - -Upstream emits `RESUME ` before prefill and `REUSED ` afterward. -Both are now validated as unsigned counts and consumed as nonterminal metadata; -`DONE` remains the source of final usage. Unknown tags, malformed/overflowing -counts, and inconsistent terminal counters still fail closed. Regression -coverage includes the real message order in the mock-worker exchange. - -## Text and tool calls after the fix - -Each row is one functional request, sequentially after a fresh worker load. -The tool SSE request reuses the preceding tool prompt; the other rows report -zero prefix reuse. OS/model storage caches were not flushed. These short, -different requests and cache states must not be compared as speed variants. - -| Request | Result | Input / output tokens | Reused | HTTP wall | First visible delta | -| --- | --- | ---: | ---: | ---: | ---: | -| Text JSON: 2 + 2 | `4`, completed | 26 / 2 | 0 | 0.3424 s | N/A | -| Text SSE: HELLO | `HELLO`, completed | 20 / 3 | 0 | 0.2287 s | 0.1721 s | -| Tool JSON | Correct typed call, completed | 307 / 39 | 0 | 1.6837 s | N/A | -| Tool SSE | Correct typed call, completed | 307 / 39 | 300 | 0.3076 s | 0.3073 s | - -Both tool responses contain exactly one `record_value` call with integer -`value: 7` and string `label: "native-smoke"`. Arguments are schema-validated -before publishing. JSON and SSE agree on the semantic call. Both SSE responses -have contiguous sequence numbers and exactly one terminal event. Output token -usage includes protocol/end tokens, not only visible text. Raw synthetic -responses and event sequences are retained privately. - -## Cancellation, recovery, and tool continuation - -- After four text deltas from a long generation, the HTTP client disconnected. - The same worker accepted the next arithmetic request and returned `4`. - Disconnect through completed follow-up took **0.3925 s** in the final run - (an earlier successful check took 0.1819 s). These include the next request's - inference, not an isolated STOP latency. -- The test killed only the verified owned engine child during another active - generation. The stream emitted exactly one `response.failed`; a new request - returned HTTP 503, and readiness was false with no context. The supervisor - started a different child after its configured two-second backoff, without - replaying the failed generation. -- Replacement readiness took **25.4056 s**, including reload, with warm OS - caches and a one-second readiness polling interval. A fresh post-recovery - request returned `4` in **0.4369 s**. The prior and replacement worker PIDs - were 3992120 and 3993068. This is one recovery measurement, not a percentile - or a cold-start promise. -- An initial lifecycle-driver attempt stopped because it treated the expected - HTTP 503 from `/ready` as an exception. The driver was corrected to read that - response body; the final complete lifecycle run above used a fresh runtime. - No runtime change was required for this driver defect. -- A further actual-model two-turn check produced a valid typed `record_value` - call, then received its result using `function_call_output` and - `previous_response_id`. The model returned the exact tool confirmation - `RECORDED-731`. The two requests took **1.7437 s** and **0.3842 s**. - -All 102 Rust tests, format, Clippy with warnings denied, and diff checks passed. -The regression keeps mock-worker token/terminal output unchanged while adding -the real prefix metadata lines. No model weights or compute kernels changed. -These checks establish supported protocol behavior; they do not establish -full-model numerical parity across a recorded agent workload. - -The isolated runtime was stopped after measurement. Temporary tokenizer assets, -configuration, and uploaded CLI are removed; private scripts, logs, and result -JSON files remain for reproduction. The latest static CLI is retained locally. -Model shards and baseline artifacts were not changed. -After cleanup, GPU usage returned to 34 MiB / 0%, and port 18082 had no listener. -The temporary local musl release build was removed (93.8 MiB). - -## Remaining qualification - -Live reasoning, structured output, full recorded Codex/MCP replay, sustained -soak, and a paired end-to-end performance comparison remain open. Passing -these small checks does not authorize switching the production console profile -or enabling experimental V-only/KAR modes. Hosted GitHub Actions has not run; -the project does not yet have its GitHub repository. diff --git a/docs/experiments/2026-10-04-required-tools.md b/docs/experiments/2026-10-04-required-tools.md deleted file mode 100644 index 400dbfd4..00000000 --- a/docs/experiments/2026-10-04-required-tools.md +++ /dev/null @@ -1,55 +0,0 @@ -# Required and forced function choice — STRA-32 - -Date: 2026-10-04. The native Responses candidate adds `tool_choice: "required"` -and the documented top-level function selector -`{"type":"function","name":"lookup"}`. Required permits one or more calls; -combined with `parallel_tool_calls: false`, it permits exactly one. Forced -function choice permits exactly one call to the selected function. - -The model receives prompt guidance. The runtime validates generated calls before -publishing callable items and checks the minimum at successful completion. -There is no constrained sampling or automatic retry. Token-limit incomplete -responses may contain zero complete calls. Wrong names and excessive counts -are still rejected. Ordinary SSE can publish valid text or a first valid call -before a later failure; those events cannot be retracted. - -The selector must contain only type/name and identify a declared top-level -function. Invalid selectors or a required choice with no callable tools fail -before generation. Custom/namespaced forced selectors and allowed-tools remain -unsupported. Original request metadata, tool arguments and historical replay -are retained. See the [API contract](../api-contract.md#tool-choice-and-call-count) -and [official tool-choice semantics](https://developers.openai.com/api/docs/guides/function-calling#tool-choice). - -## Verification - -- Rust 1.99.0: 141 library tests passed, including prompt guidance, required - missing-call rejection, forced wrong-call rejection and incomplete exemption. - Clippy all-targets with warnings denied, fmt and diff checks passed. -- The extended `scripts/smoke-tool-policy.py` passed on macOS debug and Linux - x86_64 musl release, with 84 HTTP generations on each: - auto/default, none, required and forced choices; zero/one/mixed/duplicate calls; - parallel false; token-limit incomplete; JSON/SSE crossed with reasoning - none/low. Eight malformed request configurations fail with 400 before - generation; two unsupported choice kinds fail with 501. Generation metrics - confirm no additional worker requests for rejected configurations. -- Accepted Unicode custom input, function arguments and metadata match the - synthetic baseline exactly (zero tolerance). Invalid output returns JSON 502 - or terminal SSE `response.failed`; sequence numbers are contiguous. Forbidden - call/input events are never published. Completed versus incomplete status is - preserved. -- Linux CI invokes the expanded matrix. Hosted GitHub Actions has not run. - -This is a CPU-verified development candidate awaiting independent QA and real -model qualification. No speedup, model policy-following quality or sustained -stability is claimed. The qualified GPU user trial and tunnel remain unchanged; -readiness does not prove the trial has no active requests. - -## Private artifact - -`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-required-tools-preview`, -**17,440,536 bytes**, SHA-256 -`1c2fdcf7ef92286b518fd67ba66c893f1fcff947f483849bdb041c77e126f732`. -The adjacent private JSON records source revision and checks. This is the Rust -supervisor candidate; its external worker and tokenizer remain deployment -inputs. No active profile or service was upgraded. Owned CPU fixture files and -release intermediates were removed after verification. diff --git a/docs/experiments/2026-10-04-response-resources.md b/docs/experiments/2026-10-04-response-resources.md deleted file mode 100644 index 99d8dc87..00000000 --- a/docs/experiments/2026-10-04-response-resources.md +++ /dev/null @@ -1,41 +0,0 @@ -# Stored Responses retrieval and deletion — STRA-27 - -Date: 2026-10-04. The new preview provides authenticated GET and DELETE on -`/v1/responses/{response_id}` for its existing process-local history. Retrieval -returns the exact saved terminal response. Deletion removes that response and -its replay transcript atomically. The shared 64-entry/128 MiB serialized-data -budget now counts both the complete response and transcript. Full API scope and -official reference links are in [the contract](../api-contract.md#stored-response-resources). - -## Evidence - -- Rust 1.99.0: 135 library tests passed, including combined byte accounting, - FIFO eviction, rejection without evicting valid data, identity checks and - deletion reclaiming queue/data bytes. Existing failed-generation and replay - tests passed. Clippy all-targets with warnings denied, fmt and diff checks passed. -- `python3 scripts/smoke-response-history.py ` passed on macOS debug and - Linux x86_64 musl release. Its 28 combinations cover plain text, reasoning, - structured JSON, function calls, custom tools, reasoning with custom tools and - incomplete length stops, each with streaming/non-streaming and store true/false. -- Every retained object matched its original terminal JSON exactly, including - IDs, tool arguments, reasoning, metadata, usage and status (zero tolerance). - Authentication rejection, unknown/query/repeated-delete errors, successful - continuation, deleted-parent rejection and descendant preservation passed. -- Retrieval/deletion remained available while the isolated fixture runtime was - drained and its synthetic worker was killed. This was a CPU fixture, not the - active GPU service. The hosted Linux workflow includes this smoke; GitHub - Actions execution remains pending. - -Private preview on the laptop: -`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-history-preview`, -**17,363,752 bytes**, SHA-256 -`4e575a73f8763cd949cf273d374107ce537245cbef36f68dc71a7d03c62aa1c3`. -Source revision is recorded in adjacent private JSON. This control-plane-only -binary was not installed over the user trial. The active endpoint and tunnel -remained ready. The isolated remote smoke directory and release intermediates -were removed; the final private preview remains. - -No real-model parity, speedup or long-term stability is claimed. History is not -durable; it is shared under the optional single operator key. Deletion cannot -erase copies already in descendant histories or in-flight continuations and is -not cancellation. Retrieval query options/stream resumption are unsupported. diff --git a/docs/experiments/2026-10-04-signal-grace.md b/docs/experiments/2026-10-04-signal-grace.md deleted file mode 100644 index b428ecf1..00000000 --- a/docs/experiments/2026-10-04-signal-grace.md +++ /dev/null @@ -1,62 +0,0 @@ -# Signal admission grace — STRA-33 - -Date: 2026-10-04. The native supervisor can wait for admitted inference work -before interrupting its worker on SIGTERM/SIGINT. Top-level `shutdown_grace_s` -or `STRATA_SHUTDOWN_GRACE_S` accepts 0–20 seconds; default 0 keeps the previous -immediate interruption policy. Native `check-config` reports the effective value. - -Signal arrival marks lifecycle `shutting_down` and `draining` under the admission -lock. Resume cannot reopen it. With positive grace, the listener remains open -while admitted HTTP requests and generation commands finish; new inference gets -503 and readiness becomes false. The wait ends when both counters reach zero, -checked every 25 ms, or at its deadline. Worker shutdown then follows the existing -STOP/QUIT path. Existing administrative drain/resume remains reversible. - -See [the contract](../api-contract.md#signal-shutdown-grace) and -[deployment procedure](../../deploy/README.md#drain-before-maintenance). - -## Evidence - -- Rust 1.99.0: all 142 library tests passed; Clippy all-targets with warnings - denied, fmt and diff checks passed. The added lifecycle test covers irreversible - signal drain, a previously admitted request enqueueing after signal, separate - HTTP/worker guard lifetimes, timeout and idle completion. -- `smoke-signal-drain.py` passed six CPU cases on each of macOS debug and Linux - x86_64 musl release: SIGTERM and SIGINT crossed with five-second successful - drain, one-second expiry, and default zero grace. -- Successful drain retained an active SSE response and a queued JSON response. - Both produced exactly `OK` (zero tolerance against the synthetic baseline). - SSE sequences were contiguous and ended with `response.completed`; both - generations ran, QUIT was observed, STOP was unnecessary, and the worker exited. -- During grace, readiness returned 503, new inference returned `runtime_draining`, - and resume returned the still-draining shutdown state. Health remained available. -- Expiry/default cases emitted terminal SSE `response.failed`, rejected queued - work without replay, sent STOP/QUIT, and left no worker process. One-second - expiry did not interrupt before 0.9 seconds; cooperative fixture shutdown - finished within five seconds in all cases. These are test bounds, not throughput - or production shutdown-latency measurements. -- `smoke-config-check.py` passed 45 checks on each platform, including default, - file/env precedence, 0/20 boundaries, invalid values and sanitized failures. - No worker was launched and an occupied listener port was undisturbed. -- Existing `smoke-native-drain.py` passed on both platforms, preserving reversible - maintenance, auth/429/503 precedence and exact SSE/queued JSON output. -- CI includes the new CPU signal fixture and expanded config checks. Hosted - GitHub Actions has not run. - -## Limits and artifact - -Grace bounds only the initial admission drain. Worker and HTTP connection cleanup -follow it; standalone execution gains no total exit deadline. The rendered -systemd unit retains its 45-second hard stop. Longer maintenance uses explicit -admin drain before signal. A stalled request may be interrupted after grace. -No real-model qualification, speedup or soak claim is made. Independent QA remains -pending. The active GPU trial and SSH tunnel were preserved; only read-only status -was checked, which does not establish absence of active requests. - -Private supervisor candidate: -`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-signal-grace-preview`, -**17,444,848 bytes**, SHA-256 -`154174705da6c73f290480fda3390714bf52b026868a695df89390064890d35f`. -The adjacent private JSON records source revision and checks. The external worker -and tokenizer remain deployment inputs. Owned remote CPU fixture files, local -fixture bytecode and release intermediates were removed; final evidence is kept. diff --git a/docs/experiments/2026-10-04-tool-policy.md b/docs/experiments/2026-10-04-tool-policy.md deleted file mode 100644 index f85802d3..00000000 --- a/docs/experiments/2026-10-04-tool-policy.md +++ /dev/null @@ -1,48 +0,0 @@ -# Native tool choice and single-call policy — STRA-31 - -Date: 2026-10-04. Native Responses supports `tool_choice: "none"` by omitting -current tool declarations from the model prompt and refusing generated callable -items. Original tools/choice metadata and historical tool replay are preserved. -`parallel_tool_calls: false` now enforces at most one function/custom call across -namespaces. The prompt guides the model; complete and live paths enforce the -count before publishing a disallowed call. Auto/default behavior remains intact. - -See [the policy contract](../api-contract.md#tool-choice-and-call-count) and its -official API reference. This controls tool calls in one response, not concurrent -GPU requests or token-level constrained sampling. In a live stream the first -valid call may already be visible before a later violation fails the response; -it cannot be retracted. Required/named/allowed-tools choices remain unsupported. - -## Evidence - -- Rust 1.99.0: all 141 library tests passed, including prompt equivalence between - none and no declarations, retention of historical calls/results, validation of - hidden declarations, original response metadata, and rejection of two mixed - function/custom calls when only one is allowed. Clippy all-targets with - warnings denied, fmt and diff checks passed. -- `smoke-tool-policy.py` passed 36 CPU HTTP cases on macOS debug and Linux - x86_64 musl release: nine policies/outputs × JSON/SSE × reasoning none/low. - The matrix covers auto/default two calls, false zero/one function/one custom/two - calls, and none with plain text or forbidden custom/mixed calls. -- Accepted arguments and Unicode custom input were preserved - exactly (zero tolerance); text returned exactly `OK`. Tools, metadata, effective - default choice and parallel flags matched the request. -- Violations returned JSON 502 or terminal SSE `response.failed`. SSE sequence - numbers remained contiguous. None published zero callable items; ordinary live - false mode published only the first valid function call, with no second custom - item/input events. Buffered reasoning published no callable items on failure. -- Unsupported required/named choices returned 501 without additional generation. - The smoke is wired into Linux CI. Hosted GitHub Actions has not run. - -Private preview: -`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-tool-policy-preview`, -**17,440,336 bytes**, SHA-256 -`a13719af9b7ad28821b09ddaffc3b75b8949a3dd4798512a1c19c50dbcf8db9a`. -Adjacent private JSON records source revision and checks. The isolated remote -fixture directory and release intermediates were removed; the final executable -remains private. The active GPU trial and existing tunnel were preserved, with -no inference or management mutation sent to them. - -No real-model policy-following quality, speedup or sustained stability is claimed. -This is a development candidate ready for QA, not an upgrade of the qualified -user trial. diff --git a/docs/experiments/2026-10-05-linux-gpu-qualification.md b/docs/experiments/2026-10-05-linux-gpu-qualification.md deleted file mode 100644 index bef9a9f9..00000000 --- a/docs/experiments/2026-10-05-linux-gpu-qualification.md +++ /dev/null @@ -1,200 +0,0 @@ -# Linux GPU package qualification — 2026-10-05 - -## Scope - -The user ended the active project trial and explicitly made the RTX 5090 host -available for qualification. The previous runtime recipe and state were saved -privately before an idle check, authenticated unload and owned-process stop. -All requests in this report use synthetic inputs owned by the evaluator. -User project prompts, code and credentials were not inspected. - -This report separates package/deployment correctness, API correctness, model -quality and performance. It does not establish full KAR residency, a successful -V-only retrofit, a speedup, or completion of the whole Linux epic. - -## Artifact and hardware - -- Runtime source: `9409dc92ff9223e294ea2e027cf7fd4776bad027`. -- Actual hosted CUDA build: [run 37299581677](https://github.com/paveldhq/strata-next/actions/runs/37299581677), - including green verify, musl CLI, CLI container, CUDA engine, embedded package, - runtime image and private artifact upload. -- Private archive: 851,293,705 bytes, SHA-256 - `e45c30acb94430ee2b2f155d3c388177a56a428701e3c03b3b0a3d21298b2faa`. -- Combined executable SHA-256: - `2e07b2f3dc194576a43b902455ca91d9dc28368ac98aade1ed950f7fc98b42a3`. -- Embedded engine: 612,514,560 bytes, SHA-256 - `b629bac51a6a1d47097abf9c9e34fc25e806c3fa3fe94240cf93885c75643d22`. - CUDA 13.0.1; direct dependencies are libc, libm and the loader; minimum glibc - is 2.38. The host NVIDIA driver remains a dependency. -- Runtime image uses the pinned Ubuntu 26.04 base with glibc 2.43. - Its archive manifest digest is - `75c40b6fe1c78545ca556c79ab4503eeaf7fece1f342fbb2f418f6370f3d065b`; - its config digest is - `523a12493bc46173be2db8541760cfca6a39eefd9d3bd1bbf92191e74210cd25`. - Docker import reports the former; build provenance identifies the latter. - Both are present in the verified archive, and the contained executable hash - was independently checked after import. -- Host: Ubuntu 26.04.1, RTX 5090 32,607 MiB, driver 595.91.07, - Ryzen 9 9950X3D, 128 GB RAM. Source weights reside on the existing NVMe volume. -- Qwen3.8-Flash-Next IQ3_S source shards: 83,617,662,656 bytes, - SHA-256 `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` - and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. -- One slot, 262,144 configured context, INT8 K+V, 32,768 resident KV tokens, - auto expert cache/prefill, existing expert profile, MTP spec=4/min-p=0.5, - VRAM reserve 700 MiB. KAR, V-only and vision are disabled. - -The comparison baseline uses the previous external engine -`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f` -and old serving pack with the current control plane. The candidate uses the -new embedded engine and a fresh native-prepared pack. The baseline CLI artifact -was built from PR merge `b678eadb8d878c659d44e60734a92bf8f483d3f6`, whose tree -`e4a4438ab40907d196885b2d0d042648ab816939` equals the runtime source tree above. - -## Native preparation and startup - -The native `provision` command verified both full GGUF hashes, generated a new -versioned serving pack and verified a separately pinned MTP bundle. It returned -`native_model_prepared=true`, `mtp_pack_structurally_validated=true` and -`worker_started=false` at 11:10 UTC. - -The generated dense file is 1,538,035,200 bytes and exactly matches the existing -offline-prepared file: SHA-256 -`d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13`. -The native expert table also matches exactly. The only index difference is the -generator comment. There were no float conversions; original quantized bytes -were preserved. This is IQ3 preparation, not KAR conversion. - -The new combined executable then started a fresh per-user unit with -`engine.executable=@embedded`, `native_model`, pinned MTP, driver policy, -loader probe, private authentication and durable history. Native `start-ready` -confirmed the exact managed PID/model and a ready worker at 11:25:44 UTC. -No separate engine installation or Python serving process was used. - -The imported image separately passed a read-only, network-disabled, UID 65532 -check: exact binary hash, driver/GPU visibility and absence of `python3`. -Container model startup and deployment rollback are recorded separately below. - -## Actual GPU rollback and durable continuation - -The native service catalog passed eight assertions at 11:35:37 UTC. Selecting -the already active target retained its PID. Switching to an intentionally invalid -target used the real embedded CUDA engine: loader preflight passed, then the -engine rejected missing PLE/native configuration before becoming ready. - -The controller drained and stopped the previous real GPU service, detected the -target startup failure, stopped that target, restarted the previous embedded -profile and waited for its model to become ready. Its durable transaction ended -in `rolled_back`. This is an actual full-model restart, not a simulated restore. -It does not test GPU OOM or driver-loss recovery. - -A previously stored response survived unchanged across that restart. Its -`previous_response_id` continuation returned the exact expected marker. The -failed target had no remaining process, and lifecycle counters showed no -orphaned request or generation. The retained source/pack/MTP were reverified -during restoration. The restored unit was then gracefully drained and stopped -before container qualification. - -## Fresh container deployment - -The verified image loaded the actual model and MTP with a read-only root, -nonroot UID 1000, all capabilities dropped and no-new-privileges. Source weights, -MTP and manifests were mounted read-only; a fresh private `/state` held the -native-generated pack and history. Production processes were the Rust control -plane and embedded engine; the image contained no Python executable. - -Native preparation inside the container checked both full source hashes. Its -dense file, expert table and index matched the host's new native pack exactly. -All 32 quality outputs matched the baseline after the same normalization, -tolerance zero. All 11 API checks and the separate JSON/SSE tool episode passed. -Graceful container stop returned exit 0, no OOM, and GPU use fell to 34 MiB. - -The first invocation used a wrong port because the image's `STRATA_BIND` -environment overrode the configuration; explicitly setting the intended bind -fixed this test setup. A replay attempted during the concurrent quality screen -correctly refused its idle precondition without generating requests; the -subsequent isolated replay passed. Both failed setup records are retained. -This proves fresh container userspace and pack deployment on the installed -driver, not installation of a driver on a new physical host. - -## Quality and API results - -The existing eight-case `quality-v1` corpus covered arithmetic, short and long -retrieval, instruction priority, no-tool behavior and forced function calls. -Each arm ran one warmup and three measured repeats per case, temperature zero, -reasoning none, maximum 128 output tokens. The unsupported Chat `seed` field -was omitted explicitly. Both arms passed 24/24 measured cases and 8/8 warmups. -All 32 paired normalized outputs matched exactly, tolerance zero; only generated -call identities were excluded from comparison. - -Acquisition, hashing and other qualification traffic overlapped these runs. -Their timings are not a valid paired performance measurement. No throughput -improvement is claimed. - -Additional real-model checks: - -- A declared two-step forced function/tool-result episode passed JSON and SSE, - with exact expected semantics, complete named events, identities, argument - chunks and one terminal per request. Four generations per run; both baseline - and embedded arms passed, with no remaining worker slots or queued jobs. -- Both arms passed 11 checks covering stored response retrieval, input items, - continuation, deletion, required/none policies, disconnect after actual output, - slot release without server restart and exact follow-up generation. -- The baseline passed 112 storage/policy assertions across JSON/SSE, - reasoning none/low and none/auto/required/forced function policies. - Full stored terminals matched the returned objects, including reasoning, - metadata and usage. An independent SSE verifier additionally checked every - captured stream's complete item/chunk/sequence graph. -- SIGKILL of the owned baseline engine after a real output delta produced one - `response.failed`. The control-plane PID stayed unchanged; the supervisor - loaded a new worker, released all slots and generated the exact expected - recovery text. This completed at 11:18:59 UTC; the failed request was not retried. - -## Actual Codex CLI capture and limits - -Codex CLI 0.160.0 ran in an isolated synthetic workspace with its own minimal -stdio MCP tool. The task read an orders CSV, obtained a discount via MCP, wrote -a JSON total and read it back. The private evaluator captured full Responses -request bodies and raw SSE without authorization headers. - -The first attempt was incomplete because the evaluator's MCP fixture required -approval while the CLI used approval policy `never`. The model correctly -refused to invent the missing policy. A second fresh attempt used automatic -approval review and an accurately annotated read-only MCP fixture. Shell and -MCP calls completed and the generated JSON exactly matched the independent -oracle: subtotal 186, discount 10, total 176, code `POLICY-731`. - -The strict final-text judge nevertheless **failed**: the model added an -explanation before the requested exact final marker. This failure is retained. -All nine captured SSE responses across both attempts passed independent -protocol validation. There were no malformed tool arguments or missing -terminal events in those captures. - -Replaying the three successful-attempt requests as non-streaming JSON returned -HTTP 200 but did **not** reproduce all text byte for byte. Differences included -an additional read-only `ls` in a shell command, heredoc whitespace and reasoning -wording. Cache state differed; no serializer defect was isolated by this test. -Do not describe this as a strict raw Codex replay parity pass. The separate -controlled JSON/SSE tool episode above did pass exact semantic comparison. - -## Actual CUDA CI - -[GPU workflow 37305522699](https://github.com/paveldhq/strata-next/actions/runs/37305522699) -ran the existing `keyless-cuda` job against runtime source `9409dc9` on the -freed RTX 5090 with CUDA 13.2.2. All three CTests passed: query routing, -V-only streaming and conversation snapshots. Query maximum absolute error was -`6.55651093e-7`; attention relative L2 error was at most `1.32984469e-7`. -The stream test covered 306 batches with zero failures and an identical ring -restore; snapshot testing passed 2,448 assertions. - -The one-job ephemeral runner deregistered itself and removed its credentials. -These synthetic CUDA correctness results do not reverse the previously failed -pretrained-model V-only quality gate. V-only remains experimental and disabled -in the model qualification above. - -## Private evidence - -Artifacts, source hashes, MTP pins, configuration, raw responses, synthetic -workspace results, telemetry and process records remain in the private -`qualification-9409dc9` and remote `linux-qualification-20261005` directories. -No weights, request captures, API keys or generated artifacts are committed. -Detailed checkpoints are attached to LeaseVibe STRA-9 and STRA-12. diff --git a/docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md b/docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md deleted file mode 100644 index 5e83d3b7..00000000 --- a/docs/experiments/2026-10-14-cpu-kernel-layout-and-pinning.md +++ /dev/null @@ -1,61 +0,0 @@ -# CPU kernel experiments: activation layout and thread pinning (STRA-211, STRA-214 input) - -**Status:** exploratory. Kernel-level numbers only. No inference was run, no claim about tokens per second, and the -machine was not in a controlled state, so nothing here is an accepted performance result (charter 4.3/4.4, Gate D). - -## Setup - -- Machine: reference laptop `RHW-WIN-265U-NPU r1` (Core Ultra 7 265U, one DDR5 module). The drift fields of that record - were NOT re-captured for these runs, and the OS was running its normal desktop load (browsers, security agent), so the - record's benchmark pre-conditions are not met. -- Software: Windows 11 build 26100, MSVC 19.50.35717 (`/O2 /arch:AVX2`), Rust 1.99.0, code of commit `164bfa6` plus the - experimental functions in this change. -- Data: 767 MiB of pseudo-random MXFP4 weights (526,344 rows of 90 blocks, the gpt-oss-20b hidden size 2880) and one - Q8_0 activation row. Weight bytes read per second are reported. Free RAM about 7.7 GB. -- Method: variants are interleaved inside every repeat in a rotating order and compared as **paired ratios** against the - first variant, because the absolute speed of the same kernel changed by almost 2x between runs. - -## Core topology (observed) - -12 physical cores: 2 of the faster efficiency class (4 logical threads with SMT) and 10 of the slower class (8 E-cores and -2 low-power E-cores, no SMT). A run with 8 to 10 threads therefore uses mostly the slower cores. - -## Results - -Raw memory read bandwidth, measured twice with a plain C streaming program, was stable: about 36 GB/s at 10 or more -threads (36.3 first, 36.5 second). - -| Run | Kernel | threads 1 / 4 / 8 / 10 (best GB/s) | -| --- | --- | --- | -| first (`bench_mxfp4`, 7 repeats, sequential) | AVX-VNNI ggml layout | 5.2 / 18.2 / 27.5 / 28.1 | -| first | AVX2 ggml layout | 5.5 / 16.5 / 25.8 / 27.7 | -| second (`bench_variants`, 15 interleaved repeats, medians) | AVX2 ggml layout | 5.8 / 12.2 / 12.4 / 13.7 | - -The same AVX2 kernel measured 27.7 GB/s in the first run and 13.7 GB/s in the second at 10 threads, with raw memory -bandwidth unchanged. The cause is unknown (candidates: scheduler placement on the slower cores, power state, background -load). Absolute kernel numbers from these runs must not be quoted. - -Paired ratios against the ggml-layout AVX2 kernel (median [min .. max] of 15 pairs): - -| Variant | 1 thread | 4 threads | 8 threads | 10 threads | -| --- | --- | --- | --- | --- | -| q8r: f32 scales pre-converted, 2 accumulators | 1.255 [0.74 .. 1.39] | 1.135 [0.95 .. 1.26] | 1.088 [1.00 .. 1.49] | 1.035 [0.75 .. 2.99] | -| q8r4: same layout, 4 blocks and 4 accumulators per iteration | 1.316 [1.06 .. 1.41] | 1.130 [0.96 .. 1.28] | 1.127 [0.88 .. 1.38] | 1.061 [0.78 .. 2.88] | -| AVX-VNNI, ggml layout | 1.036 [0.79 .. 1.20] | 1.040 [0.95 .. 1.18] | 1.075 [0.82 .. 1.33] | 1.034 [0.83 .. 2.83] | - -Thread pinning (kernel q8r4, 11 interleaved repeats, ratio against no pinning, medians): pinning the fast cores first, -one thread per fast core first, or the slow cores only gave 0.78 to 1.07 at 2 to 12 threads, with ranges as wide as -0.47 to 1.66. No pinning policy beat the OS default. - -## What can and cannot be said - -- Single thread: the pre-converted layout with four accumulators was faster in all 15 pairs (1.06 to 1.41, median 1.32). - The per-thread kernel is compute-bound, so this is plausible, and it is the only effect that survives the noise. -- Many threads: medians of 1.03 to 1.13 with ranges that include slowdowns; **inconclusive**, and expected, since the - workload is then limited by memory bandwidth. -- Pinning: **no benefit found**; recorded as a negative result for this machine state. -- A proper decision needs the controlled conditions of the reference record: quiet machine, power plan and mode recorded, - soak, repeated pairs, and the drift capture. - -Experimental code: `leleka_dot_mxfp4_q8r_avx2` and `leleka_dot_mxfp4_q8r4_avx2` (tested for bit identity with the ggml-layout -kernel, and for the stated tolerance), `crates/cpu-sys/src/topology.rs`, and the three `bench_*` examples. diff --git a/docs/experiments/2026-10-14-experimental-modes-port.md b/docs/experiments/2026-10-14-experimental-modes-port.md deleted file mode 100644 index f19f0d08..00000000 --- a/docs/experiments/2026-10-14-experimental-modes-port.md +++ /dev/null @@ -1,145 +0,0 @@ -# Experimental Strata modes: Rust port status (2026-10-14) - -Branch `claude/port-experimental` (based on `claude/port-main`). Everything here is **experimental and off by -default**: `OptIn::default()` enables nothing, every closed program refuses to open without an enabled mode, and -refuses again while its PTX pin does not match. The six PTX were compiled with nvcc 13.2.86 and pinned on 2026-10-15 -(commit `53758bb69`); since the 2026-11-03 re-sync (below) four of them are older than their `.cu` and refuse to open until -the server rebuilds them. - -## What exists - -| Item | Rust reference (`crates/experimental-ref`) | CUDA program (`crates/cuda-driver/src/experimental_*.cu`) | -| --- | --- | --- | -| Q4_0 / K8V4 / rotated-INT8 KV, FWHT-256 | `fwht`, `q4_0`, `kv_q8`, `layout`, `cache` | `kv_q4` (FWHT, Q4_0 append step/batch, gather), `kv_q8` (INT8 append/gather, K8V4 K half, V-only) | -| Keyless V-only cache, query routing | `keyless` (artifact parser, fmaf routing, RoPE keys), `attn` | `keyless`, `qsa_attn` (modes 2/3/4 + merge) | -| Control vectors | `cvec` (GGUF parse, tables, apply twin) | `cvec` | -| KV streaming / ring | `kv_stream` (planner arithmetic, CLOCK resolver oracle) | `kv_stream` (reset, resolve, copy, ring table, u4 copy) | -| Remote experts (second GPU tier) | `remote_experts` (selection, 512 MiB admission, grouping, RemoteMeta 1608 B, scatter) | none: reuses the existing grouped expert kernels | -| Seal plan | `docs/cuda-seal-plan-additions-experimental.json` (`oracle/gen_seal_additions.py`) | flags `-ptx -O3 -arch=sm_120 -std=c++17`, precise math | - -Rust driver: `cuda-driver/src/experimental.rs` (modes, opt-in, pins, entry signatures, geometry, admission; pure), -`experimental_gpu.rs` (Linux facade, a bounds-, alias- and signature-checked launch builder, one drain per sequence), -`experimental_gpu_smoke.rs` (`#[ignore]`d). Runtime: `leleka-runtime/src/experimental.rs` + `NativeBackendConfig::experimental`. - -## Verification (no nvcc, no GPU) - -* Golden fixtures are produced by compiling the Original's own host C++ (extracted verbatim with awk) on the dev - machine: KV formats (Separate and Fused FMA contraction), streaming plan (480 cases) and CLOCK resolver, control - vector loader (19 cases), remote-experts selection/grouping/meta/scatter (40 + 200 cases). -* The literal `.cu` text is executed by a thread-per-CUDA-thread CPU emulation (`oracle/emu`) and compared bit for - bit with the Rust references (`tests/emulated_kernels.rs`); `tests/literal_port.rs` guards that every Original - kernel-body line is still present in each port. -* `experimental.rs` cross-checks every entry's parameter kinds and `__launch_bounds__` against the `.cu` text. -* `cargo check --target x86_64-unknown-linux-gnu --all-targets -p leleka-cuda-driver --features cuda-driver -p leleka-runtime` is clean of new warnings. - -## Open items (honest) - -1. None of the six programs has run on a GPU (compiled with nvcc 13.2.86 on 2026-10-15; four need a reseal after the - re-sync, see below). Root: reseal, then run - `cargo test -p leleka-cuda-driver --features cuda-driver -- --ignored experimental_gpu`. -2. nvcc FMA contraction decides Q4_0 bytes (Separate vs Fused models are both fixtures); the Q4 smoke reports which - model the device matches. `cvec` uses the fast `__expf` exactly as the Original: its pending-write path is not a - bit claim. -3. Streaming host tier: the facade copies from `DeviceBuffer`s; real pinned, mapped host memory (zero-copy) is not - bound. Miss order of the resolve kernel is nondeterministic on device; the smoke checks invariants, not order. -4. The forward pass does not consume the new cell formats, the keyless artifact, the streaming plan or the cvec hook - (the runtime's QSA path is a different, INT8-resident layout). `experimental::ensure_consumed` therefore refuses - any enabled mode at Load instead of letting an opt-in silently do nothing; flip `FORWARD_CONSUMER_WIRED` only - with the consumer. -5. Remote experts: the second CUDA context, pinned zero-copy staging and the launches of the existing grouped - expert kernels need two devices. Selection, admission, grouping, metadata and scatter are tested; `experimental_routed` - / `experimental_experts` prefill patches are not ported. -6. Host write-through (`host_*`/`stage_*` mapped pointers of the append kernels) is passed as null. - -## Re-sync to Strata pin `41cf05a0` (2026-11-03) - -The ports were made against the first import (`d9ab8435`, engine 0.1.35). The 2026-10-25 upstream sync (`docs/upstream.md`, pin -`41cf05a0`, engine 0.1.50) moved the Original kernels and the ports were not re-synced, so four of the six `literal_port` -tests failed on `main` (1, 5, 20 and 197 Original kernel-body lines missing). Branch `claude/experimental-resync` closes that. -It was done on a host without nvcc and without a GPU: the `.cu` text, the guard, the pins and the reseal tooling are done here; the PTX of four -programs has to be rebuilt on the server (list below). Nothing on the shipped 5090 serve path was touched: the six programs are -experimental, opt-in and off by default, and `engine/strata` is unmodified. - -### What drifted, and what was done - -| Program | Original change since the first import (device code) | Guard found missing | Decision | -| --- | --- | --- | --- | -| `kv_stream` | `resolve_kernel`: `if (lookups > 0) atomicAdd(&s_lookups, lookups)` (upstream #783), same counter value | 1 line | Re-ported literally | -| `kv_q4` | `kv_append_q4_kernel` gained `step_stride` and `planes` (multi-token append: `blockIdx.z = step_idx * planes + plane`) | 5 lines | Re-ported literally; the entry keeps its ABI and passes `step_stride = 0`, `planes = 2`, which is the Original's single-step launch | -| `kv_q8` | `kv_append_q8_kernel` with `step_stride` / `cur_stride` (S26 multi-token append, 4 lines); `kv_gather_q8_wide_kernel` and `q8_pair_to_f16x2` (16 lines, only under `STRATA_EXPERIMENTAL_SM60`) | 20 lines | Template re-ported literally and instantiated single-token (`MULTI = false`); the SM60-only gather is excluded in the guard (sm_60/sm_70 build, compiled out of the Original's own ready-made engine, not part of an sm_120 or sm_86 program) | -| `qsa_attn` | The chunk kernel became `attn_chunk_body` with `reduce12_gfx906` / `reduce12_head_of_lane`; new alternate schedules and batch variants of the same arithmetic: `attn_chunk_kernel_pre75` (+ `shfl_x`, `warp_sum_x`, `warp_max_x`, `reduce12`, `head_of_lane`, `load_v1`), `attn_merge_v2_kernel` (+ `merge_max_block`, `merge_sum_block`), `attn_chunk_q8_v3_kernel`, the slot and row kernels | 197 lines | `attn_chunk_body` and its two helpers re-ported literally (66 lines), instantiated with the three flags off, which is the previous kernel's arithmetic; the 14 alternates are excluded in the guard, each with its reason | -| `keyless`, `cvec` | none (`cvec.cu` gained a host accessor, `cvec_tables`, not device code) | 0 | unchanged | - -The 16 SM60 lines and the 131 lines of alternate schedules are named in `tests/literal_port.rs` (`KV_Q8_EXCLUDED`, `QSA_ATTN_EXCLUDED`) with the -reason. The lists are checked both ways: an entry that no longer exists in the Original fails, and so does a new, unlisted device function of the -Original. The Original itself checks the alternates bitwise against the reference schedule the port carries (`qsa_merge_daily_parity.cpp` for -`pre75` and `merge_v2`, `kv_steps_parity.cpp` for the multi-token appends); that is a statement about the Original, not something re-measured here. -The guard is now 8 tests: the six pairs, a self-test that a changed, removed or unlisted function and a stale exclusion are all caught, and one for -the function-name parser. - -### Verification (no GPU, no nvcc) - -* `cargo test -p leleka-experimental-ref` passes (`literal_port` 8 of 8, with the other golden and emulation tests), and Clippy `-D warnings` on the crate is clean. - `check-local.sh --fast` no longer carries `literal_port` as debt. Results per platform: see "Test results" below. -* The `.cu` text is executed, not only compared: the thread-emulation harness (`oracle/run_emulated_kernels.sh`, g++ 13 and glibc in WSL - Ubuntu) was run on the previous and on the re-synced sources. Every fixture value of `fwht`, `q4`, `q8` (INT8 K+V, streamed host copy, V-only, K8V4), - `route`, `cvec` and the four attention scenarios (`m2`, `m3`, `m4`, `m4_mrope`) is bitwise identical between the two, as the entry-level reasoning above predicts - (every new parameter is neutral at the entries). The streaming scenario's miss order and slot hashes differ from run to run, also between two runs of the same - source (device-side atomics, item 3 of the open list); `kv_stream_resolver_copy_and_ring_match_the_model` checks invariants and passes on a fixture produced from the - re-synced source. The committed `emulated_kernels.json` (made with another libm) is left as it was and still passes against the Rust references. -* Golden fixtures regenerated from the unmodified Original at `41cf05a0`: `kv_golden_separate.json`, `stream_plan_golden.json` and `cvec_golden.json` are byte-identical to the - committed ones (the host code they extract did not change in a way their inputs can see). `kv_golden_fused.json` regenerates differently only because g++ contracts - `x * id + 8.5f` differently from the clang that made the committed file; under g++ it is identical for the old and the new Original, so the committed file is kept. - `remote_golden.json`: see open item 8. -* `cargo test -p leleka-cuda-driver --features cuda-driver experimental` passes, including `every_entry_signature_matches_its_cuda_source` (parameter kinds and - `__launch_bounds__` of all 17 entries against the `.cu` text) and the two new pin tests below. - -### Test results (2026-11-03, laptop, no GPU) - -| Check | Windows | WSL Ubuntu 24.04 (g++ 13, glibc) | -| --- | --- | --- | -| `cargo test -p leleka-experimental-ref` | 63 unit + 25 integration pass (`literal_port` 8 of 8) | the same | -| `cargo clippy -p leleka-experimental-ref --all-targets --no-deps -- -D warnings` | clean | clean | -| `cargo test -p leleka-cuda-driver --features cuda-driver` | 431 passed, 0 failed, 74 ignored | 433 passed, 0 failed, 77 ignored (inside `check-local.sh --product`) | -| `cargo check --all-targets -p leleka-cuda-driver --features cuda-driver -p leleka-runtime` (compiles the Linux-gated `experimental_gpu`) | not applicable | pass | -| `scripts/check-local.sh --fast` | exit 0, only the two known-debt warnings (rustfmt of `leleka-model-format` / `leleka-experimental-ref`, Clippy of `leleka-model-format`) | not run | -| `scripts/check-local.sh --product` | not run (`cargo build --locked` of all default-members: pass) | in a private namespace: every step that touches these crates passes (fmt and Clippy hard gates, `leleka-runtime` 624 tests, cuda-driver 433); the two host-dependent deploy tests stay debt; two steps FAIL-ENV, the all-members `cargo build` and the CPU / iGPU / NPU crate tests, because the namespace has no network and `wgpu-hal` was not in the cargo registry cache | -| thread emulation of the `.cu` text (previous vs re-synced source) | not run (needs g++ and std::barrier) | bitwise identical, see above | - -### Pins: the sealed PTX is older than four of the sources - -The sealed PTX and `PINS[..].ptx_sha256` were left untouched. `PINS[..].source_sha256` is the digest of the `.cu` the PTX was built from; for `kv_q4`, -`kv_q8`, `kv_stream` and `qsa_attn` it now names the previous source. A stale PTX must not load, so `experimental::admit` has a third gate, `source_is_sealed` -(digest of the checked-in `.cu` equals the pin), and `PENDING_RESEAL` lists the four programs: they refuse to open with the typed `Unpinned` error (the -runtime reports "experimental PTX is not pinned") until they are resealed. The unit test `pending_reseal_lists_exactly_the_unsealed_sources` makes the list -exact in both directions, so a reseal that forgets to empty it, or a `.cu` edit without a reseal, turns the build red. No path to these programs exists -today anyway (`FORWARD_CONSUMER_WIRED` is false), so the gate costs nothing now. `docs/cuda-seal-plan-additions-experimental.json` carries the new `cu_pin` of -the four sources, so `compile_assets.py` builds exactly this text. `scripts/gpu-bringup/reseal_own.py` gained `--plan` (and refreshes the plan's `seal_sha256` / -`seal_length` when the entry has them) so that it can reseal these assets; its dry run was exercised here against the committed PTX (the four `source_sha256` -fields are patched, the PTX digests stay). - -### To do on the server (nvcc 13.2.86, scripts/gpu-bringup) - -PTX to reseal: `experimental_kv_q4` (`PINS[0]`), `experimental_kv_q8` (`PINS[1]`), `experimental_kv_stream` (`PINS[2]`), `experimental_qsa_attn` (`PINS[4]`). -`experimental_keyless` (`PINS[3]`) and `experimental_cvec` (`PINS[5]`) are unchanged and stay sealed. Group name `experimental`; the recipe is -`-ptx -O3 -arch=sm_120 -std=c++17`, precise math, from the plan. - -1. `scripts/gpu-bringup/compile_assets.py --toolkit --no-rope --group experimental --only experimental_kv_q4,experimental_kv_q8,experimental_kv_stream,experimental_qsa_attn --out DIR` - (it verifies the `cu_pin`, every `.entry` name and the parameter counts; the entries and their ABI did not change). -2. `scripts/gpu-bringup/reseal_own.py --ptx-dir DIR --plan docs/cuda-seal-plan-additions-experimental.json experimental_kv_q4 experimental_kv_q8 experimental_kv_stream experimental_qsa_attn` - (dry run), then again with `--write`: new PTX files, `PINS[0,1,2,4]` in `experimental.rs`, `seal_sha256` / `seal_length` in the plan. -3. Set `PENDING_RESEAL` in `crates/cuda-driver/src/experimental.rs` to `&[]`. -4. Rebuild the sm_86 companions and the generated table (`scripts/gpu-bringup/sm86_assets.py build`, `docs/sm86-assets.md`): `ptx-sm86/experimental_{kv_q4,kv_q8,kv_stream,qsa_attn}.ptx`, - `ptx-sm86/MANIFEST.json`, `sm86_table.rs` (the table is keyed by the digest of the sealed sm_120 body, so the four old companions stop matching after step 2). -5. `cargo test -p leleka-cuda-driver --features cuda-driver experimental`, then on a GPU `-- --ignored experimental_gpu` (smoke group `new-pins`). No numerical claim - exists for the new PTX until those run; the emulation above is of the `.cu` text. - -### Open items added by the re-sync - -7. The Original's multi-token appends (`kv_append_q4_steps`, `kv_append_q8_steps`, used by the verify and S26 paths) are in the ported kernel text but have no entry, no Rust - facade and no launch test: the entries instantiate the single-token launch. Adding them means new entries in the sealed ABI, so it belongs with the next reseal and a consumer. -8. Host-side drift that `literal_port` cannot see (no `.cu`): `remote_experts.cpp` changed (the helper may be any visible ordinal except the primary `STRATA_PRIMARY_DEVICE`, - `auto_size` slot admission against free memory, a `RemoteMeta` extension for the reduce path, Hadamard-folded experts). The Rust `remote_experts` reference and the generator - `oracle/gen_remote_golden.sh` still describe the old selection (the generator's `awk` fragments no longer compile against the new file), so `remote_golden.json` is the old - behaviour. K8V4 streaming (`--kv k8v4 --kv-resident`: `kKvHybrid` in the host code of `kv_stream.cu` and `layer.cpp`) exists in the Original and is still `NotStreamable` in - `layout.rs` / `kv_stream.rs`. Neither is reachable (no consumer); both need a Rust reference change and new goldens, which is outside the kernel re-sync. diff --git a/docs/experiments/2026-10-14-kar-levels-gpu-port.md b/docs/experiments/2026-10-14-kar-levels-gpu-port.md deleted file mode 100644 index 544287f3..00000000 --- a/docs/experiments/2026-10-14-kar-levels-gpu-port.md +++ /dev/null @@ -1,120 +0,0 @@ -# KAR level decode on CUDA (levels 2..5) — port status, 2026-10-14 - -## Scope - -An additive Rust-runtime path to decode NESTED KAR records (bit-planes, top-down -nesting) at a runtime level 2..=5 on CUDA, plus the plain F32 row multiply that -`gpu/kar/src/kar_expert.cu` pairs with it. The KAR level is the number of nested -bit-planes read from a record: level `L` indexes the 2^L-entry f16 table with -`L` plane bits (plane 0 is the most significant), times the f16 group scale, -rounded once in binary32. This note records what was verified and what is open. -It makes no performance and no model-quality claim. - -## What exists - -| Piece | Location | -|---|---| -| Nested record descriptor (`KarNestedRecord`, `KarInspection::nested_records`) | `crates/model-format/src/kar_nested.rs` | -| Literal CPU model of the kernels (window planning, packet layout, thread/block decomposition, plane word and group-scale addressing, argument guard, multiply reduction order) | `crates/model-format/src/kar_kernel_model.rs`, tests in `crates/model-format/tests/kar_kernel_model/` | -| Real-archive cross check against the file-backed CPU oracle | `control-plane/tests/kar_kernel_model.rs` | -| CUDA source (not compiled) | `crates/cuda-driver/src/kar_decode_levels.cu` | -| Placeholder PTX and zero pin (fails closed) | `crates/cuda-driver/src/kar_decode_levels.ptx`, `KAR_DECODE_LEVELS_PIN` | -| Pure geometry, admission, pin and error code | `crates/cuda-driver/src/kar_decode_levels.rs` | -| Linux-gated driver wrapper and ffi include | `kar_decode_levels_gpu.rs`, `kar_decode_levels_ffi.rs` | -| Root-only GPU smoke (`#[ignore]`) | `crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs` | -| Policy, overlay-aware selection, byte ranges, stager, expert map, scratch ledger, CPU reference expert MLP | `crates/model-format/src/kar_levels.rs`, tests in `crates/model-format/tests/kar_levels/` | -| Planner-vs-driver geometry cross-check | `crates/leleka-runtime/src/model_binding/kar_levels.rs` | -| KAR routed-expert weight SOURCE (verify, map, stage, run) | `crates/leleka-runtime/src/model_binding/kar_expert_source.rs` | -| Binding hook, stage branch, Load wiring | `qwen4exp_input.rs` (`with_kar_expert_source`), `qwen_forward/moe_expert.rs` (`execute_cuda_kar`), `backend.rs` (`NativeBackendConfig::kar_expert_source`) | - -Without a configured KAR expert source behaviour is unchanged. Edits to -existing files are module/export lines (`model-format` `lib.rs`/`kar.rs`, -`cuda-driver` `lib.rs`/`ffi.rs` include, `model_binding/mod.rs`), one -`Context` field for the cached module (constructors and `destroy`), the -`ModelBinding` field/builder, a `moe_expert.rs` refactor of the shared-expert -and combine tail into `finish_with_parts` plus a KAR branch, and the -`NativeBackendConfig` field with its Load wiring. - -## Wired into the engine - -`NativeBackendConfig::kar_expert_source` (pinned base archive, optional -pinned overlay, base/overlay level 2..=5, scratch budget) makes `serve_load` -open `KarExpertSource`: full SHA-256 pin and every payload CRC on the retained -descriptor, the complete 48-layer gate/up/down map with exact shapes, and plan -checks for the first and last expert, all before the binding is published. The -source identity is mixed into the mode digest, the source is refused together -with the optimized MMQ owners, and Load probes the CUDA program so an unpinned -PTX fails at Load. In `MoeExpertStage::execute` the routed experts then come -from `KarExpertSource::routed_mlp` (plan, budget admission, stage from the -archive, one-drain device FFN, finite check); the shared expert, the router -weighting and the combine are the unchanged GGUF path. The MMQ weight cache is -not mixed in: the combination returns an identity error. - -## Design - -A decode request is a flat element range of one record. Only the bytes that -range can touch are staged into a single device packet: the level-`L` book (the -table at f16 index `2^L - 2` of the books section), the scales of the covered -groups, and `L` plane windows. Ranges need not align to words or groups, and the -last group may be partial; `head32 = start % 32` and `head_group = start % group` -carry the sub-word and sub-group phase into the kernel. Levels outside 2..=5, -above the stored plane count, or outside the record's certified dial -(`planes_min..=planes_max`) are refused by the planner, by the host geometry -check and by the device argument guard. Bottom-up nesting is refused. -A policy gives a level per tensor class (routed expert, shared expert, dense -FFN, attention/ssm, embedding, output, other) for the base archive and -separately for an overlay. An overlay record replaces the same-named base -record; it is not additive. Scratch is accounted as packet + decoded F32 -weights + input + output + a 4-byte status word, each rounded to 256 bytes. - -Fail-closed behaviour: the driver refuses the zero PTX pin before any driver -call; every launch sequence is drained with one `cuCtxSynchronize`; an -uncertain completion poisons the context and leaks the raw-owned argument -tables; a device status word (bad argument, non-finite scale/book, non-finite -product) and a host finite scan both gate returned values. - -## Verified - -macOS CPU (executed): -- The kernel model reproduces a transcription of `kar_codec::decode_range` bit - for bit over randomized synthetic records for levels 2..=5, group sizes 32, - 64, 96, 128, 256, 1024, partial last groups, word-unaligned ranges, multi-block - ranges, expert row windows with odd row lengths, and overlay-style per-archive - dials. Four deliberate addressing mutations each make the suite fail. -- `strata-control` writes NESTED archives with the production `kar_writer`, - opens them with the shared inspector and compares kernel-model windows - bit-for-bit with `kar::decode_tensor_range` (payload CRCs verified). -- f16 widening matches an exact reference and `quant-core` for all 65,536 inputs. -- Selection, overlay consistency, budget ledger, stager (against the reference - stager), expert-map validation and the CPU reference expert MLP (against an - f64 recomputation) run in `leleka-model-format` tests. -- Pure `cuda-driver` geometry/admission/pin tests and the planner-vs-driver - geometry cross-check were executed through a scratch shim crate (outside the - repository) because `cuda-driver` and `leleka-runtime` no longer build on - macOS after the source-port import. - -Type-checked only (`cargo check --all-targets --target x86_64-unknown-linux-gnu`; -clippy clean for the new files): the Linux-gated driver wrapper, ffi include, -the ignored GPU smokes, the `leleka-runtime` source, binding hook, stage branch -and Load wiring. The runtime-crate unit tests only compile; they were not run. - -## Open (needs nvcc and/or a GPU) - -- No nvcc build: `kar_decode_levels.cu` (decode, multiply, SwiGLU) has never been - compiled. It is a hand transcription of the Rust model and `kar_expert.cu`; a - compile error or a divergence from the model is possible. -- The PTX is a placeholder and `KAR_DECODE_LEVELS_PIN` is zero, so Load with a - KAR expert source fails closed (`KAR level-decode PTX is not pinned`) until - the source and PTX digests are frozen after a build and smoke. -- The two ignored GPU smokes (levels 2..=5 exact decode, multiply order, fail - closed paths, mixed-level expert MLP within a stated tolerance) have never run. - Device behaviour, including `atomicOr` status handling and the poison paths, - is unverified. -- The end-to-end token path with a real KAR archive is unexercised: no archive, - no GPU, no output comparison against the GGUF path, no model-quality result. -- Per-token cost is untouched by design work: each routed expert re-stages three - windows from the archive and decodes them; there is no resident or cached - compressed expert bank. No throughput, latency or memory measurement exists. -- Sparse row-id gathers (`kar_decode_rows`) and a fused decode-in-GEMV kernel are - not implemented; overlay provenance (`model resolve-kar-overlay`) is verified - outside this code and only its pinned archive SHAs are consumed. diff --git a/docs/experiments/2026-10-28-s0-7-vanilla-arms.md b/docs/experiments/2026-10-28-s0-7-vanilla-arms.md deleted file mode 100644 index d8d2a937..00000000 --- a/docs/experiments/2026-10-28-s0-7-vanilla-arms.md +++ /dev/null @@ -1,279 +0,0 @@ -# S0.7 Vanilla comparator arms: shipped defaults and lossy-paths-off (STRA-247) - -Date 2026-10-28. Leaf STRA-247 of STRA-245. Server evidence (Linux, RTX 5090) is measured on `rnr5090`; the Windows command is -UNVERIFIED-ON-WINDOWS until STRA-254 runs it on the laptop. Nothing on this page was run at 256k and nothing touched the laptop. - -## 1. What this page fixes - -Two vanilla comparator arms for the pass/fail rows of E4: - -- arm (a): vanilla Strata at its shipped defaults; -- arm (b): the same vanilla with its LOSSY default paths switched off (section 4: exactly one variable on the pinned build). - -It also records what vanilla prints about its CPU kernel family at start-up (section 7), and where the per-turn TTFT, decode tok/s and -per-round timing come from (section 6). - -## 2. Binary and source provenance - -- Source read: `engine/strata` of the branch worktree `.git/wt/stra-247` (branch `claude/stra-247` off `claude/merge-opt` 2457d81d), - never the main checkout (that one is on `main` at the old pin `d9ab8435`, engine 0.1.35; the former generate.cpp lines 1715 and 1791 come from it). -- Pin read from `docs/upstream.md`, "Current pin": upstream commit `41cf05a06a25dd29103b7b27a2279a3f60c21876` (short `41cf05a0`), - engine and Control 0.1.50, Terminal and app 0.2.5. -- Comparator installed on the server (`~/work/vanilla-strata`, read only here): the release called 0.2.6. - - Control (Python launcher) `VERSION` 0.1.51, `COMMIT` `562a0c2ed7169ff6373f893b162106d55a828297`. The git subject of that commit says the Qwen engine - packages stay 0.1.50 and there was no C++ change since 0.2.5. - - Engine binary `~/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata`, `BUILD.json` source `f-0243-rel 1aff6d14117b`, - cuda 13.0, archs 75, 86, 89, 120; `engine-component.json` `build_id` `1aff6d14117b+cuda13.0`, variant `cuda13`. -- The question left open by the inference "pin = app 0.2.5, comparator = release 0.2.6" is narrowed by git, not closed: - `git diff --name-only 1aff6d14 41cf05a0 -- src include serve cmake CMakeLists.txt third_party` lists 0 files, so the sources the binary says it was built from - (`1aff6d14`, the commit "Version 0.2.5") and the pin have the same engine tree. Between the pin and the release commit `562a0c2e`, `git diff --stat 41cf05a0 562a0c2e -- serve src include` - shows `serve/server.py` (7 lines: a one-token reply shows no tok/s, an empty messages list is a 400), `serve/frontend.py` (7 lines), one line of `src/program/generate.cpp` - (a comment) and DeepSeek-only files. The line numbers below are therefore the pin's, and they describe the installed engine. - Not verified: that the binary was compiled from that tree with the flags of this repository's CMake; upstream's packaging recipes were not run here (`docs/upstream.md`). - -Binary identity, commands run on the server and their output: - -``` -$ strata --version -strata 0.1.50 -$ sha256sum /strata -ae49d5da81b9b65d50af1108c4b3f8b289ee198d9992d66268b7e885cf1a4776 strata -$ sha256sum ~/work/vanilla-strata/dl/strata-engine-0.1.50-linux-x86_64-cuda-cuda13.tar.gz -90c601dc1060af48aaccf85062975a11c4ae25690ec242e3bc93e99457c9380b (equals the line of dl/SHA256SUMS.txt) -``` - -The binary's digest equals the `strata` entry of `engine-component.json` (214,533,384 bytes). - -## 3. The CPU-family lines of the pin (AC1) - -Command, run in `.git/wt/stra-247`: `sed -n '3485p;3687p' engine/strata/src/program/generate.cpp`. Output: - -``` - std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which this engine's " - std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s " -``` - -- generate.cpp:3485-3490 the refusal: "this CPU (%s) does not support AVX2 with FMA and F16C", then `return 2` (exit status 2). -- generate.cpp:3502 and 3505: notes of the experimental older-CPU build (`isa_floor` builds). -- generate.cpp:3674-3677: a canonical Q2_0 pack (no `native_experts.txt`) on a CPU without AVX-512. -- generate.cpp:3687-3692: "this CPU has no AVX-512: the expert kernels run on - (multi-token for the i-quant gate/up rows)", reached for a native pack when `cpu_avx512_ok()` is false. -- `cpu_avx512_ok()` is `src/kernels/cpu/expert_layout.cpp` from line 42: false under `STRATA_FORCE_AVX2=1` (line 44), under `STRATA_FORCE_ISA` below the AVX-512 level - (`cpu_isa_cap()` lines 26-38), and when CPUID or XCR0 lacks the bits. -- The 512-bit IQ-row gating (`STRATA_NO_IQ512`, `STRATA_NO_IQ256`, the gather switch; `src/kernels/cpu/native_expert.cpp` 300-340) prints nothing. - On AVX-512 hardware vanilla prints nothing about its kernel family. - -## 4. Classification of every row of section 1.3 of `docs/upstream-digest-2026-10-25.md` (BA D8, E4) - -The digest section 1.3 has 11 data rows. The table below has one row for each, in the digest's order, with exactly one class. -Classes (by mechanism, not by a KL threshold): - -- LOSSY: the path leaves out or approximates model work that the baseline path does; the output can differ by more than a reordering of the same arithmetic. -- ROUNDING-ONLY: the same arithmetic on the same operands in another kernel or order; only floating-point rounding differs. -- PLACEMENT-OR-SCHEDULING: the same work on another device, at another time or in another buffer layout (cache slots, copies, chunking, graph launch), - or work that does not touch the verified output (the drafter, a guard, request framing). - -A row that bundles several switches takes the class of its most output-changing member; the members are listed under the table. -All line numbers are in `engine/strata` at the pin. - -| # | Digest row | Class | Evidence at the pin | In row (b) list | -|---|---|---|---|---| -| 1 | `STRATA_ROUTE_TAIL_SKIP=7` | LOSSY | `src/core/expert_source.cpp:5083` a skipped tail expert contributes zero (memset of its row); default decision `src/program/generate.cpp:10110-10155` (ON unless all experts resident, 90 percent or more cached, NVFP4, batch or peer GPU) | yes: `STRATA_ROUTE_TAIL_SKIP=0` | -| 2 | PcieAuto | PLACEMENT-OR-SCHEDULING | `src/program/generate.cpp:2195-2196` (share of missed experts refined from measured CPU and link rates), enabled at `generate.cpp:3649`, off with `STRATA_PCIE_FRAC_DEFAULT=old` (3618-3619) | no | -| 3 | `STRATA_PREFILL_CPU_SHARE=auto` below 1024 tokens | PLACEMENT-OR-SCHEDULING | `src/prefill/prefill.cpp:202-206` and the printed note at 2425-2429: the idle CPU pool takes experts the GPU would stream; the same experts, other device; upstream measures mean KL about 0.004 (borderline, see B1) | no | -| 4 | `STRATA_RING_BYTES` (#583) on native packs | PLACEMENT-OR-SCHEDULING | `src/prefill/prefill.cpp:294-297` and 306-309: ring slots, cache loan and auto chunk list change, so the prompt's experts are read through another mix of resident and streamed groups | no | -| 5 | sm_120 set and `PF_FUSED` on 80+ SM cards | ROUNDING-ONLY | `include/strata/core/sm120_series.hpp:4-17` (the set is bitwise; `PF_FUSED` "rounds differently, KL-checked"); `src/prefill/moe_fused_iq.cu:4-12` (int8 codebook weights, int32 dot, exact until one float add) and 1407-1419 (default gate: 12.0 card, 80+ SMs; KL against MMQ 0.0002 over 5998 positions) (borderline, see B2) | no | -| 6 | sm_86 set and `DEQUANT_WIDE` | PLACEMENT-OR-SCHEDULING | `src/core/nv_defaults.cpp:26-34` (nine switches), `generate.cpp:1538-1551` (`ADAPT_NOWAIT`, `ADAPT_LAG=2`: when swapped-in experts become usable), `src/kernels/cpu/native_expert.cpp:323-326` (`CPU_IQ_ALL_EXACT1`), `src/kernels/cuda/dequant_bf16.cu:200-203, 283-289` (bitwise) | no | -| 7 | async adaptive tier chosen by measurement | PLACEMENT-OR-SCHEDULING | `include/strata/core/adapt_async_default.hpp:1-12` (not bit-exact run to run, as the adaptive tier itself), `generate.cpp:8188-8200` | no | -| 8 | bitwise switches (`COMMIT_BATCH`, `ONE_TOKEN_COMMIT`, `HEAD_MIX_MULTI`, multi-block argmax, fused norm+rope, `MMVQ_IL`, cluster top-k and argmax, MTP catch-up skip, `SH_FORK_LATE`) | PLACEMENT-OR-SCHEDULING | `sm120_series.hpp:4-12` (bitwise equal to the kernels they replace), `src/core/verify.cpp:169` (`MMVQ_IL`), 304-310 (`HEAD_MIX_MULTI`), 1962-1964 (`SH_FORK_LATE`), `src/core/mtp.cpp:73-80` (the drafter's K/V catch-up for rejected rows is skipped by default: drafter state only, the verified tokens are the verifier's) | no | -| 9 | `STRATA_NAN_GUARD=1` | PLACEMENT-OR-SCHEDULING | `src/core/verify.cpp:4151-4158`, `include/strata/core/verify.hpp:109-113`: a device check of the head logits for NaN or infinity, recorded in the window graph; it changes no value | no | -| 10 | conversation cache auto, `--ple-inflight` 256, `--ple-io direct` stays direct | PLACEMENT-OR-SCHEDULING | `include/strata/core/conversation_memory.hpp:70` and `generate.cpp:9508` (RAM budget of parked conversations), `generate.cpp:491` (outstanding reads), `generate.cpp:4126-4184` (PLE I/O mode) | no | -| 11 | server: model-card sampling when a request sends none, `max_tokens` keeps room for the answer, empty assistant turns dropped | PLACEMENT-OR-SCHEDULING | `serve/server.py:5082-5087` (the request's own fields win; explicit 0 stays greedy), 8051-8068 (`MODEL_CARD_SAMPLING`), 4890-4907 (output cap clamped to the room left; "requests are never truncated"); a request-framing row that is neutralised by explicit sampling and `max_tokens` (E7(b)); the "empty assistant turns" change was not located at the pin by grep and is not covered by the neutralisation | no | - -Members of the bundled rows: - -- Row 5: `STRATA_SIDE_MIXER=2`, `STRATA_ATTN_DAILY=1`, `STRATA_GR_UP75=1`, `STRATA_GR_DOWN_TG=1`, `STRATA_GU_SWIGLU=1` (bitwise, `sm120_series.hpp:7-12`) and `STRATA_PF_FUSED` (rounds differently). - Off switches: `STRATA_SM120_PERF=0` (the set) and `STRATA_PF_FUSED=0`. -- Row 6, on a compute capability 8.6 card only (the RTX 3080 laptop; not on the 5090): `ADAPT_NOWAIT=1` and `ADAPT_LAG=2` (placement and timing of adaptive swaps), - `CPU_IQ_ALL_EXACT1=1` (ggml's AVX2 single-token dot bit for bit; active only on a CPU without AVX-512 in the process, `native_expert.cpp:323-338`, so inactive on both of the owner's machines), - `SIDE_MIXER=2`, `ATTN_DAILY=1`, `GR_UP75=1`, `GU_SWIGLU=1`, `QSA_ROWS=1`, `B6_MMVQ_ROWS=1` and `DEQUANT_WIDE` (bitwise per the comments above; not each re-proved here). - Off switch: `STRATA_SM86_PERF=0`. -- Row 8: the digest says "no" for output change; this page read `sm120_series.hpp` and the lines cited and did not re-prove each switch. - -Borderline rows, stated so that nobody has to guess: - -- B1 (row 3): the CPU prefill share has the same measured KL order as the tail skip (about 0.004 against 0.003 to 0.006, `generate.cpp:10112`) but executes every expert. Classified by mechanism. -- B2 (row 5): `docs/upstream-port-plan.md` row 3.2 labels `PF_FUSED` lossy; the kernel is an exact int8 dot with one float add per 32 values (`moe_fused_iq.cu:4-12`), and its measured KL against MMQ is 0.0002. -- If the owner or TECH_LEAD prefers a KL threshold, B1 and B2 move to LOSSY and row (b)'s list gains `STRATA_PREFILL_CPU_SHARE=0` and `STRATA_PF_FUSED=0`; arm (a) does not change. - Until someone decides that, row (b) is the one-variable list below. No series starts on a row that is not classified (STRA-246 checks the list against this table). - -Row (b) environment, a literal list (the only LOSSY row): - -``` -STRATA_ROUTE_TAIL_SKIP=0 -``` - -Instrumentation set in both arms, log lines only: `STRATA_DECODE_TIMING=1`, `STRATA_VERIFY_PROFILE=1`. Arm (a): no other `STRATA_*` variable. - -## 5. Linux commands (VERIFIED on the server, 2026-10-28) - -Run directory `~/work/leleka-e2e/runs/stra247-vanilla-arms/` on `rnr5090` (outside Git). The GPU was idle (2 MiB used, no compute process) and the holder -job (`kar_holder2.py`) was idle before each start; one engine at a time. The launcher's own state (`xdg-config`, `xdg-state`) was redirected into that directory -with `XDG_CONFIG_HOME` and `XDG_STATE_HOME`, so nothing in `~/.config/strata` or `~/.local/state/strata` was written (their file times are unchanged); -`settings.json` was copied from `~/.config/strata/settings.json`. - -``` -export XDG_CONFIG_HOME=$R/xdg-config XDG_STATE_HOME=$R/xdg-state # R = the run directory -export STRATA_DECODE_TIMING=1 STRATA_VERIFY_PROFILE=1 -# arm (b) adds: export STRATA_ROUTE_TAIL_SKIP=0 -# control adds: export STRATA_FORCE_AVX2=1 -cd ~/work/vanilla-strata/control -bin/strata launch --model iq3_s --family qwen --model-path /home/para/work/leleka/models/leleka-gates/assets/model \ - --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-tui --yes -# ... one request (section 6) ... -bin/strata launch --stop -``` - -`--vision off` matches the earlier launch config (`vision: off`); without it the launcher wants to download a 0.9 GB picture reader. The engine arguments the launcher -produced are the ones of the earlier launch (`--pack .../packs/iq3_s --native .../Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf --ple-gguf ...-00002-of-00002.gguf ---expert-profile .../control/data/expert-profile.bin --expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp .../Strata-data/mtp/rt --max-context 262144 --kv int8 --ple-io ram ---kv-resident 32768`). Wall time from launch to ready: arm (a) 262 s, arm (b) 286 s, control 204 s (page cache state not controlled; these are not a measurement of anything). - -Raw logs, kept outside Git: `arm-a/`, `arm-b/`, `arm-control/` each with `env.txt` (the environment given), `launch.out`, `engine.log`; `arm-a/` and `arm-b/` also `request.json`, `response.json`, `request.meta`. -Digests of the engine logs: `arm-a` `7f590a74cff9e5af...`, `arm-b` `1c27b67529e75ce1...`, `arm-control` `354f902da14703a9...` (sha256 prefixes). -Capturing `/proc//environ` of the engine worked for arm (a) only (it showed `STRATA_DECODE_TIMING`, `STRATA_VERIFY_PROFILE`, `STRATA_NO_ACQUIRE`, `STRATA_RUNTIME_PROFILE`; the last two are set by the launcher); -for arm (b) and the control the capture wrote an empty file (the `pgrep` pattern most likely matched the shell running it, not the engine), so the effect of `STRATA_ROUTE_TAIL_SKIP=0` and `STRATA_FORCE_AVX2=1` is shown by the logs (sections 8 and 7), not by the process environment. - -Windows command, UNVERIFIED-ON-WINDOWS (written from `engine/strata/strata_cli`, `strata_control/paths.py:19-21` which puts per-user state in `%LOCALAPPDATA%\Strata`, and -`docs/laptop-vs-vanilla.md`; STRA-254 verifies it on the laptop and records the printed lines): - -``` -$env:STRATA_DECODE_TIMING = '1'; $env:STRATA_VERIFY_PROFILE = '1' -# arm (b) adds: $env:STRATA_ROUTE_TAIL_SKIP = '0' -strata launch --model iq3_s --family qwen --model-path --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-tui --yes -``` - -On the laptop (compute capability 8.6) the sm_86 row of section 4 applies and the sm_120 row does not; `docs/laptop-vs-vanilla.md` section 11 already ran vanilla with the tail skip off there -(its engine log has no "ROUTE_TAIL_SKIP=7 is ON" line and no skip counters). - -## 6. The short request and the log lines for TTFT, decode tok/s and per-round timing (AC4, AC6) - -Request (about 1,263 prompt tokens, below 2k; greedy and `max_tokens` explicit). The generator and the command are the same for both arms: - -``` -python3 - > request.json <<'PY' -import json -body = "\n".join("Line %d: the quick brown fox jumps over the lazy dog %d times." % (i, i) for i in range(1, 61)) -prompt = ("Below are 60 numbered lines. Read them, then write a long, detailed essay about foxes and dogs. " - "Do not stop early.\n\n" + body) -print(json.dumps({"model": "qwen3.8-flash-next-iq3_s", - "messages": [{"role": "user", "content": prompt}], - "temperature": 0, "top_k": 1, "max_tokens": 50, "stream": False})) -PY -curl -sS -m 600 -H 'Content-Type: application/json' -d @request.json http://127.0.0.1:8090/v1/chat/completions > response.json -``` - -E7(b), whether vanilla honours the explicit values: the response of both arms reads (field `usage.completion_tokens`, `finish_reason`) - -``` -"finish_reason": "length" "usage": {"prompt_tokens": 1263, "completion_tokens": 50, "total_tokens": 1313, ...} -``` - -so vanilla stopped at exactly 50 tokens, the cap, with no end-of-sequence before it. Greedy is consistent with the evidence, not proved by it: the 50 reply tokens (the `reasoning_content`; the model was still in its thinking) -have the same sha256 (`a60f13aaf7a486cb...`) in arm (a) and arm (b). The code reads: the request's own fields win over the model card's sampling, and an explicit 0 stays greedy (`serve/server.py:5082-5087`). -No end-of-sequence suppression was needed for this request; for a run that must produce a fixed length with a model that may stop earlier, that mechanism was not located and is not claimed. - -Where each quantity is logged. One sample line each, from arm (a), the short request (not a 256k run; the first requests of an engine include CUDA graph captures, so these numbers are -samples of the format, not a measurement and not a comparison between arms: arm (a) decoded this request at 57.4 tok/s and arm (b) at 145.3 tok/s, which says nothing about the arms): - -- Per-request prompt read time (the TTFT component) and decode tok/s, always printed by the serve path (`generate.cpp:15669`), also in the response JSON `timings` (`prompt_ms`, `predicted_per_second`): - -``` -strata serve: prompt 1263 tokens = 0 reused + 1263 read in 1595 ms (792.0 tok/s), 50 generated in 872 ms (57.4 tok/s), drafts accepted 30 of 40, 1 checkpoints -``` - -- STRATA_DECODE_TIMING=1 (`generate.cpp:14343-14344`), one line per request, per-round (per window) timing: - -``` -strata decode timing: 20 windows, avg T 3.00, 2.50 tokens/window, 43.58 ms/window = verify 41.65 (GPU-reach wait 8.80 + per-layer host 31.36 [plan 0.09 actq 0.08 jobs 0.02 CPU 2.24] + stage 28.93) + commit/emit 0.02 + draft 1.00; per layer-window: CPU experts 1.01 (1.79 entries), VRAM hits 26.18, PCIe 0.62; adapt wait 0.89 join 0.02, 24.0 swaps/window -``` - -- STRATA_VERIFY_PROFILE=1 (`src/core/verify.cpp:953`), the per-stage split of the window, printed with the line above (first 220 characters; the line continues with the QSA layers): - -``` -strata decode GPU stages (ms/window): GDN layers: q8+qkv/q-idx gemv 0.77 conv 0.11 ab 0.02 z 0.02 rec 0.28 out-proj 0.58 router+plan+bell 0.45 shared+quant 0.61 waitA 0.24 VRAM hits 1.27 waitB 1.33 PCIe grp 0.18 waitCPU 27.64 -``` - -The launcher sends a 53-token warm-up request first; its lines are the first `strata serve: prompt 53 tokens` and `strata decode timing: 1 windows` lines of each log. The 1,263-token request is the second pair. -Per-turn TTFT of a streaming session is measured by the client (STRA-246's schema); the engine's `read in ... ms` is the server-side part. - -## 7. `vanilla_cpu_family` (ARCHITECT comment 395f0394 section 2) - -Determined by negative line + control + predicate, not "printed": - -- (a) Printed lines: none on the normal start-ups. `grep -c "no AVX-512"` on the normal start-up logs: arm (a) 0, arm (b) 0. -- (b) Reading rule: on a native pack the absence of the generate.cpp:3687 line means `cpu_avx512_ok()` was true in that process; the line means false. A negative indicator only; the silent 512-bit IQ-row gating (`STRATA_NO_IQ512` and others) is not covered. -- (c) Positive control: a start-up with `STRATA_FORCE_AVX2=1` and nothing else changed (`arm-control`). `grep -c "no AVX-512"` on its log: 1. The line, verbatim (log line 4, before the pack is read): - -``` -strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows) -``` - -- (d) Predicate dump from a build of the same pin: moved to STRA-307. Its result (branch `claude/stra-307`, commits e94369a1 and 20f7abab, page `docs/experiments/2026-10-28-s0-7c-vanilla-predicate-dump.md`, verdict QA PASS and TL APPROVE - recorded on the item): on the server `iq_avx2_parity` built from the pin prints `avx512 1` with the `STRATA_*` variables scrubbed and `avx512 0` with `STRATA_FORCE_AVX2=1`. - It proves the predicate of the pin's source, not the release binary; this page adds the binary's own control line (c). -- (e) Binary identity: section 2 (`strata 0.1.50`, sha256 `ae49d5da...4776`). - -The same block as one fenced json block (extract it to a file in the run root, outside Git, for the key check): - -```json -{ - "vanilla_cpu_family": { - "printed": "none printed", - "reading_rule": "native pack: absence of the generate.cpp:3687 line means cpu_avx512_ok() was true in that process (negative indicator only); the line means false", - "control": { - "env": "STRATA_FORCE_AVX2=1", - "printed": "strata generate: this CPU has no AVX-512: the expert kernels run on AVX-2 (multi-token for the i-quant gate/up rows)" - }, - "predicate": { - "tool": "iq_avx2_parity built from pin 41cf05a0 (STRA-307, claude/stra-307 e94369a1+20f7abab)", - "output": "avx512 1 (STRATA_* scrubbed); avx512 0 (STRATA_FORCE_AVX2=1)" - }, - "binary_identity": { - "engine_version": "strata 0.1.50", - "sha256": "ae49d5da81b9b65d50af1108c4b3f8b289ee198d9992d66268b7e885cf1a4776" - } - } -} -``` - -The key check of this leaf (a command that does not need STRA-246); the full `validate.py` check of the block inside a vanilla S0.1 record is deferred to STRA-315: - -``` -python -c "import json,sys;d=json.load(open(sys.argv[1]));b=d.get('vanilla_cpu_family',d);p=b['predicate'];assert set(b)=={'printed','reading_rule','control','predicate','binary_identity'};assert set(b['control'])=={'env','printed'};assert set(b['binary_identity'])=={'engine_version','sha256'};assert (isinstance(p,dict) and set(p)=={'tool','output'}) or (isinstance(p,str) and p.startswith('unavailable:'));print('block keys OK')" -``` - -## 8. Do the two arms coincide on the server? (AC3) - -The route tail skip default is decided at start-up (`generate.cpp:10110-10155`). The server logs: - -Arm (a), `grep -n "ROUTE_TAIL_SKIP" arm-a/engine.log`: - -``` -43:strata serve: STRATA_ROUTE_TAIL_SKIP=7 is ON (default): a missed expert that every token of a verify window routes at rank 7 or lower is skipped (+10..20% decode on 12-16 GB cards that miss experts, answers differ slightly from 0.1.41); STRATA_ROUTE_TAIL_SKIP=0 turns it off -``` - -Arm (b), `grep -n "ROUTE_TAIL_SKIP" arm-b/engine.log` prints nothing (0 lines). The engine prints a ROUTE_TAIL_SKIP line only when the skip is ON (`generate.cpp:10153`) or off by a default rule -(10145 and 10148); with the variable set to 0 explicitly it prints neither, so "off" shows as the missing ON line. The counters agree: arm (a) logs -`strata serve: route tail skip: 963 missed experts skipped (1078 entries) since the start` after the warm-up and `2087 missed experts skipped (2293 entries)` after the request; -arm (b) logs no such line. The expert cache is 12,575 slots in both arms and 93.6 percent of decode lookups hit it in arm (a), so the 90-percent rule did not switch the default off. -The effective configurations of the two arms differ (tail skip ON against off), so on this server the rows differ and E4 has two vanilla arms to pass. The control start-up also printed the ON line -(its only change is `STRATA_FORCE_AVX2=1`). - -## 9. Moved to other leaves, and not verified - -- STRA-254: Windows start-up checks of vanilla (the Windows command above is UNVERIFIED-ON-WINDOWS until then), and the printed lines on the laptop. -- STRA-307: the predicate dump (section 7 (d)); done on its branch, not merged here. -- STRA-315: `validate.py` of the sample block inside a vanilla S0.1 record. -- Not verified here: the Windows engine behaviour; that arm (b) changes nothing but the tail skip (the process environment of arm (b) could not be read back, section 5); each bitwise claim of rows 5, 6 and 8 - (taken from the sources' comments); that the engine binary was compiled from the pinned tree; anything at 256k; run-to-run noise of any timing in this page. diff --git a/docs/experiments/2026-10-28-s0-7b-index.md b/docs/experiments/2026-10-28-s0-7b-index.md deleted file mode 100644 index 0df38018..00000000 --- a/docs/experiments/2026-10-28-s0-7b-index.md +++ /dev/null @@ -1,14 +0,0 @@ -# STRA-245 experiment pages index (SC7) - -Date 2026-10-28. Owned by STRA-288 (S0.7b). One line per page of the STRA-245 tree, in the order the pages were written. A leaf that adds a page under `docs/experiments/` for STRA-245 appends ONE line -here in its own commit (STRA-254 appends the laptop addendum line). Page names follow SC7: `docs/experiments/2026-10-28--.md`. -The pages below are the ones present on the Train A branch `claude/train-a-stra-245` when this index was written (7e45428f) plus this leaf's own pages; pages of leaves not yet merged are added by their leaves. - -| Leaf | Page | What it holds | -| --- | --- | --- | -| STRA-247 (S0.7) | [2026-10-28-s0-7-vanilla-arms.md](2026-10-28-s0-7-vanilla-arms.md) | Vanilla comparator arms (shipped defaults, lossy paths off), the CPU-family lines of the pin, the classification of the digest section 1.3 rows | -| STRA-307 (S0.7c) | [2026-10-28-s0-7c-vanilla-predicate-dump.md](2026-10-28-s0-7c-vanilla-predicate-dump.md) | `cpu_avx512_ok()` predicate dump from a build of the pin, two outputs | -| STRA-256 (S3.1) | [2026-10-28-s3-1-laptop-safety-protocol.md](2026-10-28-s3-1-laptop-safety-protocol.md) | Laptop safety protocol, owner-precondition checklist, thresholds schema (with `2026-10-28-s3-1-laptop-thresholds.schema.json`, `...bootstrap.json`, `2026-10-28-s3-1-check_bootstrap.py`) | -| STRA-249 (S3.5) | [2026-10-28-s3-5-sm86-switch-audit.md](2026-10-28-s3-5-sm86-switch-audit.md) | Audit of the sm_86 exact-speed switches against our counterparts | -| STRA-250 (S6.1) | [2026-10-28-s6-1-lossy-audit.md](2026-10-28-s6-1-lossy-audit.md) | Lossy-default audit of the shipped 5090 and 3080 profiles | -| STRA-288 (S0.7b) | [2026-10-28-s0-7b-runbook.md](2026-10-28-s0-7b-runbook.md) | Runbook preamble: server access, the ours pin, workload identity, model digest mapping, cache-state resets, locks, run hygiene, per-arm overhead | diff --git a/docs/experiments/2026-10-28-s0-7b-runbook.md b/docs/experiments/2026-10-28-s0-7b-runbook.md deleted file mode 100644 index 44d146b2..00000000 --- a/docs/experiments/2026-10-28-s0-7b-runbook.md +++ /dev/null @@ -1,323 +0,0 @@ -# S0.7b Runbook preamble: access, commands, workload identity, model digest mapping, cache-state resets, machine lock, ours pin (STRA-288) - -Date 2026-10-28. Leaf STRA-288 of STRA-245, Train A layer L2. Branch `claude/stra-288` (worktree `.git/wt/stra-288`, off `claude/train-a-stra-245` 7e45428f). -A fresh session starts any 5090 run leaf from its own body plus this page. Every server value below was read or measured on `rnr5090` on 2026-10-28 and -the command that produced it is quoted. Every Windows value is a rule or a source pointer, marked `verified by STRA-254` (the laptop is not touched here). -Evidence level of everything on this page: setup and COMPONENT_STARTUP facts. Nothing here is an end-to-end comparison. - -Contents: 1 access and layout, 2 worktree, branch and the ONE ours pin, 3 secrets and environment, 4 workload (commands, source snapshot, H0), 5 model digest -mapping, 6 cache state, 7 machine locks and queue, 8 run hygiene (SC11-SC14), 9 per-arm overhead and the series floor, 10 briefing facts for run leaves, -11 Windows items (verified by STRA-254), 12 reading checks, 13 not verified. - -## 1. Access and layout of the server - -| Item | Value (command) | -| --- | --- | -| How to reach it | `ssh rnr5090` (alias in the user's ssh config; user `para`, `hostname` prints `homelab`, `uname -srm`: `Linux 7.0.0-38-generic x86_64`, Ubuntu 26.04.1 LTS) | -| CPU, RAM, GPU | AMD Ryzen 9 9950X3D (`nproc` 32), 121 GB RAM (`free -g`), RTX 5090, driver 595.99.02 (`nvidia-smi --query-gpu=name,driver_version,memory.used --format=csv`) | -| Python on the server | `python3 --version`: 3.14.4. Offline tooling must still run on Python 3.9 (the laptop has only 3.9): stdlib only, no `match`, no `X \| Y` annotations at run time | -| Tools that do NOT exist | `which cmake` prints nothing (no cmake); `which bc fincore sha256sum` find all three (`fincore` is `/usr/bin/fincore`). Builds of the engine are not made on the server (section 8, SC14) | -| Root file system | `df -h /`: 260 G, 2.4 G available, 100 percent. NOTHING new is written under `~` or `/tmp`. The disk guard of section 8 refuses a run there | -| Work file system | `/data` (`/dev/nvme0n1p7`, 458 G, 223 G available). Work and outputs of this train live under `/data/leleka-e2e/` | -| Existing trees on root (read only for us) | `~/work/leleka-e2e` (scripts, `bin-sm120`, 48 earlier run dirs), `~/work/leleka-rest` (the ours source tree and `bin-e2e4`), `~/work/leleka-head/src/crates` (workload source), `~/work/gpu-runs` (holder, `MODEL.lock`), `~/work/vanilla-strata` (vanilla launcher, section 5), `/home/para/work/leleka/models/leleka-gates/assets` (model files) | -| The laptop | local to the orchestrator and not reachable by ssh from the server. Its facts come from STRA-254 (section 11) | - -Rules that follow from the table: never `apt`/`pip` install, never delete or rewrite files of other jobs, read `/proc` and `nvidia-smi` for state, and write only -under `/data/leleka-e2e/` (plus the holder queue file of section 7 when a GPU job needs the holder). - -## 2. Worktree, branch and the ONE ours pin (SC9) - -- Local worktree and branch of this leaf: `C:\Users\pavel\work\leleka\.git\wt\stra-288`, branch `claude/stra-288` (committed, not pushed). - Train A integration branch: `claude/train-a-stra-245` (worktree `.git/wt/train-a`). Wave-1 repository base before the train: `claude/merge-opt` 2457d81d. -- The Strata upstream pin is not touched here: `docs/upstream.md` "Current pin" `41cf05a06a25dd29103b7b27a2279a3f60c21876` (engine 0.1.50, app 0.2.5). - `engine/strata` is read in a BRANCH worktree, never in the main checkout (that one is on `main` at the older pin `d9ab8435`). - -**The wave-1 ours pin (SC9): commit `ffb264e0` ("perf(prefill): idle-gap switches on by default after the identity and paired replay gates", branch `claude/upstream-rest`, -2026-10-28T02:38:12+01:00), built binary set `~/work/leleka-rest/bin-e2e4`.** Why this one, with the evidence: - -- The only built "ours" with the prefill idle-gap defaults on is `bin-e2e4` (built 2026-10-28 01:37 UTC on the server, `docs/upstream-port-plan.md` line 328 says `rt-qpf4` / `bin-e2e4` have the defaults on). The job `rest-e2e-ab2` ran it for the four paired arms. -- The source tree beside it, `~/work/leleka-rest`, is byte-identical to commit `ffb264e0` for `crates desktop-core control-plane deploy gpu Cargo.toml Cargo.lock rust-toolchain.toml`. - Command on the server, then the same list from `git archive ffb264e0 ` extracted locally and sorted the same way: - -``` -cd ~/work/leleka-rest && find crates desktop-core control-plane deploy gpu Cargo.toml Cargo.lock rust-toolchain.toml -type f -not -path "*/target/*" -print0 | sort -z | xargs -0 sha256sum -# 1738 files; comm -12 against the archive of ffb264e0: 1738 equal, 0 only on the server, 0 only in the commit -# the same comparison against a56e02a7 (switches default off): 1727 equal, 11 differ; against 2457d81d (merge-opt): 1352 equal, 386 only on the server -``` - -- No file of that tree is newer than the binary: the newest source file is `crates/cuda-driver/src/qsa_resident_transport.rs` (01:36), `bin-e2e4/leleka-inference` is 01:37:25 (`find ... -newer`, empty). -- Limit, stated: no build id is embedded in the binaries (the engine does not print the `leleka-serve build:` line of the capture contract today, STRA-251), so "binary = this commit" rests on - the byte-identical tree and the timestamps, not on a printed id. The build command of the release binaries is not recorded on the server (`build.sh` builds only the `rt` and `drv` test binaries). - The freeze STRA-304 (5090) rebuilds or re-verifies and writes the final `ours_build_id`; until then wave-1 diagnostics use this pin and say so. -- Relation to Train A: `claude/merge-opt` 2457d81d contains `ffb264e0` (`git merge-base --is-ancestor` true) and adds laptop and gpt-oss work (183 changed files under the serving tree paths); - `claude/train-a-stra-245` (7e45428f) adds, over merge-opt, only evidence scripts, docs, and the dev-only example `crates/native-cpu-expert/examples/kernel_ab.rs` - (`git diff --stat claude/merge-opt claude/train-a-stra-245 -- crates Cargo.toml Cargo.lock deploy`: `Cargo.lock` +1, `native-cpu-expert/Cargo.toml` +3, `examples/kernel_ab.rs` +1535 and nothing else). - So a source reader on Train A reads the merge-opt serving code; a 5090 binary is the `ffb264e0` one. A fix leaf that changes serving code ends the series (E1) and needs its own build and its own freeze. - -Build identity of the pinned set (the four fields of `ours_build_id`): - -| Field | Value | How obtained | -| --- | --- | --- | -| commit | `ffb264e042d83f7db823a6ba4310aa7d129915dd` (`git rev-parse ffb264e0`) | above | -| target triple | `x86_64-unknown-linux-gnu` | `file ~/work/leleka-rest/bin-e2e4/leleka-inference`: ELF 64-bit LSB pie executable, x86-64, dynamically linked, interpreter `/lib64/ld-linux-x86-64.so.2`, BuildID `88f7c765e76710546e77d7b464408fb30393ec4b`; `readelf -p .comment`: `rustc version 1.99.0 (b940084d7 2026-09-28)` and `GCC: (Ubuntu 15.2.0-16ubuntu1) 15.2.0` (the server's own compiler: this set was built ON the server; the older `bin-sm120` set shows GCC 13.3.0 of the WSL build) | -| cargo features | none beyond the defaults: sm_120 default build. The only optional feature is `strata-desktop-core/sm86` (`desktop-core/Cargo.toml` `[features]`); the sm86 build is 120 MB (`docs/e2e-run.md` section 1) and `bin-e2e4/leleka-inference` is 72,481,056 bytes | size and the feature list; the exact cargo command of this build is NOT recorded (section 13) | -| shipped profile | `deploy/rust-runtime/profiles/rtx5090-32g.json` of the pin: sha256 `b5ebb652ad9b091e0e045e44d8adeb49fa7319c2f365c2ad150a3d567221e0cb` (`git show ffb264e0:deploy/rust-runtime/profiles/rtx5090-32g.json \| sha256sum`; the server copy `sha256sum ~/work/leleka-rest/deploy/rust-runtime/profiles/rtx5090-32g.json` prints the same value). Train A / merge-opt copy: `d0397550f821f58479172b53b08519b63ea34b35cd532204dffaaddb3aefefb7` (see the note below) | commands quoted | - -Note on the profile file: `git diff ffb264e0 2457d81d -- deploy/rust-runtime/profiles/rtx5090-32g.json` shows that merge-opt (and so Train A) added `"prefill_capacity": 8192`, `"prefix_cache_block": 8192` and the 8192 sentence of the description; the pin's own profile file has neither. -The wave-1 runs on the server do not read the profile file: the `rest-e2e-ab2.sh` shape passes the same values as engine arguments (`--original-prefill-capacity 8192 --prefix-cache-block 8192`, section 10), so the VALUES in force equal Train A's profile (hash `d0397550...`) -while the build is the pin's. The STRA-304 freeze must record one commit, its binary and the profile hash of that same commit; whether the 8192 default belongs in the frozen profile is decided by STRA-267 and the S6.2 decision record, not here. - -Binary digests of the pinned set (server, `sha256sum ~/work/leleka-rest/bin-e2e4/*`): - -``` -81f5cc1241bd4ff0312d23f3f5db0074e1cc186add7edb9bc1497e5ae390aa84 leleka-cli -145e7b28e2196a6498d27ceb87d28433d1284a700d79afc5d41f9c2955e20d51 leleka-daemon -730a956ad2a1d4e0df5ca7209281949e52a2bdee4882610d9fe979d2b96d2ac6 leleka-inference -667340222b5035071d4415daae1bd5cc66286881cfcaccf934b34f6c07ff18dc strata-next -``` - -The older set `~/work/leleka-e2e/bin-sm120` (built 2026-10-24) is NOT the pin: it lacks the idle-gap defaults. An experiment arm that sets env switches is an experiment build, never "ours" (SC9). - -## 3. Secrets and environment (E2E_BASE_URL, E2E_MODEL, E2E_API_KEY) - -- The three names are the interface of every client script (`replay_session.py`, `long_session.py`). Their VALUES are never written to a record, a log, a page or a commit. -- Ours: `scripts/e2e/run-e2e.sh` (server copy `~/work/leleka-e2e/scripts/e2e/run-e2e.sh`) generates the API key into a mode 0600 file under `~/work/leleka-e2e/state/` and, for an external client - (`E2E_RUN_CMD`), exports the base URL and model name to the client process and passes the key only through that process's environment. Nothing prints them. -- Vanilla: started with `--access local` (loopback only, no key needed, `serve/server.py` line 3842 `api_key = ""`); the replay driver then runs with an empty key. The base URL is the launch port on 127.0.0.1. -- Rules: no `set -x`, no `env` or `printenv` into a file that goes into a run directory, no `echo` of the three variables. Use `--key-file` or the environment, never a command-line key (it would show in `ps`). -- Leak check after a run (prints file names only, never contents; the pattern is read from the key file): `grep -rlFf ~/work/leleka-e2e/state/api-key `; expected: no output. -- The arm environment files that ARE recorded (`env.txt` of STRA-247) list `STRATA_*` and `LELEKA_*` switches only. - -## 4. Workload: commands, source snapshot, H0 - -### 4.1 The session and the replay driver - -The measured session: 5 turns, target 245,000 prompt tokens, 300 output tokens per turn, context 262,144, cut from the source snapshot of 4.2 (turn 1 = 45,766 prompt tokens). -Observed on the 5090 with the pinned binary: the four `rest-gap-*` arms of job `rest-e2e-ab2` (client log, `long-session.json`) show `input_tokens` 45766, 95706, 151643, 197915, 242849 and 300 output tokens each. - -The driver is `scripts/e2e/replay_session.py` (STRA-308, on this branch; sha256 `d933fcfdc7fdec17b56c757a2e9319172de6944b601a80780913b56b7584be1f`) over `scripts/e2e/long_session.py` -(sha256 `6d7017ea3032dbd06d4994fac5e84012c7671382b1ec3d5993a159ac22b2863d`). Both are copied to `/data/leleka-e2e/work/stra-288/scripts/e2e/` on the server and parse under the server's Python 3.14. -Commands (interface as in the file's docstring; STRA-308 verified it with fake engines on Python 3.9, nothing against a real engine): - -``` -python3 scripts/e2e/replay_session.py record-h0 --base-url "$E2E_BASE_URL" --out H0.json --turns 5 --target-tokens 245000 --max-output 300 --context 262144 --src ~/work/leleka-head/src/crates -python3 scripts/e2e/replay_session.py replay --h0 H0.json --base-url "$E2E_BASE_URL" --out RUN.json --expect-prompt-sha SHA[,SHA...] --src ~/work/leleka-head/src/crates -``` - -The long-session baseline (what the driver is built on, the old script): `long_session.py --turns 5 --target-tokens 245000 --max-output 300 --context 262144`. -Exit codes of the driver: 0 ok, 1 request failure, 2 usage or damaged H0, 3 prompt-hash mismatch (the pair is invalid). Only `time.monotonic` is used. Every request carries `"temperature": 0` and `max_output_tokens` = N_k. -Observation that STRA-309 must handle: the four `rest-gap-*` client logs show `reply_sha256` `e3b0c44298fc1c14` (the sha256 of the empty string) and `status` `incomplete` in all 20 turns, i.e. the reply text the old -client collects was empty (300 tokens produced, nothing in `output_text` deltas; the model was in its reasoning part). A recorded H0 then holds empty reply texts: prompts stay identical across arms, which is all the replay needs, -but nobody should read "reply matches H0" as a content check. - -### 4.2 Source snapshot (the text the session is made of) - -| | Value | -| --- | --- | -| Server path | `~/work/leleka-head/src/crates` (the default `--src` of both scripts) = `/home/para/work/leleka-head/src/crates` | -| Content | the `.rs` files larger than 1500 bytes under it, in sorted path order (this is what `long_session.collect()` selects): 678 files, 12,581,441 bytes (700 `.rs` files in total) | -| Snapshot hash (method below) | `7d23ef5588e0245c9769a4c0377edbbc96f4dbb0449bd3f523457e248ce3298c` | -| Windows path (named by `docs/laptop-vs-vanilla.md`) | `C:\Users\pavel\work\wsrun\src-snap\crates`; its hash is computed by the same method and compared by STRA-254 (verified by STRA-254). It lies outside `C:\Users\pavel\work\leleka`, so reading it needs the owner's per-path permission | - -The hash method (stdlib, runs unchanged on Python 3.9 on either machine; one line `sha256 relative/path` per selected file, paths with `/`, in sorted order, then the sha256 of those lines): - -``` -import hashlib, os, sys -src = os.path.expanduser(sys.argv[1]); files = [] -for root, _d, names in os.walk(src): - for n in sorted(names): - p = os.path.join(root, n) - if n.endswith(".rs") and os.path.getsize(p) > 1500: files.append(p) -files.sort(); lines = [] -for p in files: - lines.append("%s %s\n" % (hashlib.sha256(open(p, "rb").read()).hexdigest(), os.path.relpath(p, src).replace(os.sep, "/"))) -print(len(files), "files,", sum(os.path.getsize(p) for p in files), "bytes"); print("snapshot_sha256", hashlib.sha256("".join(lines).encode()).hexdigest()) -``` - -Server output of that script (kept on the server as `/data/leleka-e2e/tmp/srchash.py`): `678 files, 12581441 bytes` and `snapshot_sha256 7d23ef5588e0245c9769a4c0377edbbc96f4dbb0449bd3f523457e248ce3298c`. -The 45,766-token figure for turn 1 depends on this content; it is checked by the first recorded H0 (`prompt_tokens` of turn 1) and by the engine, not by the hash. If the two machines' hashes differ, the machines do not run the same workload and no pair is valid. - -### 4.3 Where H0 lives and how it reaches the laptop (planned interface of STRA-309) - -- STRA-309 (depends on this leaf) records H0 once. Planned location, outside Git: `/data/leleka-e2e/runs/h0/h0-.json` with its `sha256sum` line beside it (`h0-.sha256`). The file holds prompt hashes and reply text, so it never goes into Git. -- To the laptop: a copy made by the owner or the orchestrator into `C:\Users\pavel\work\leleka\artifacts\runs\h0\` (main checkout, section 8), verified on arrival by `Get-FileHash -Algorithm SHA256` equal to the server's line. An agent does not pull it by itself without that check. -- This page quotes the PLANNED interfaces of STRA-308 and STRA-309; those leaves verify them once they exist. They are not dependencies of this leaf. - -## 5. Model digest mapping ("same model digest" when the two engines read different packs) - -Ours reads the sealed KAR archive plus the two GGUF shards (tensor directory and PLE); vanilla reads the SAME two GGUF shards natively for the experts and PLE, plus a small packed `dense.bin` made from them. -There is no packed `experts.bin` for the iq3_s model: the vanilla pack directory points at absolute offsets inside shard 1 (`native_experts.txt`: "absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", total 50,292,326,400 bytes). -The mapping that makes the digest the same is therefore: both arms are derived from the two GGUF shards below, and the KAR provenance file names them by sha256. - -Server hashes (live `sha256sum`, run 2026-10-28 from 19:57 UTC with `nice -n 19 ionice -c3`; shard 1 took 66 s and shard 2 112 s; the raw list is `/data/leleka-e2e/runs/stra288-runbook/hashes.txt`): - -``` -4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3 /home/para/work/leleka/models/leleka-gates/assets/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf -316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113 /home/para/work/leleka/models/leleka-gates/assets/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf -d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13 /home/para/.local/share/strata/Strata-data/packs/iq3_s/dense.bin -d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13 /home/para/work/leleka/models/leleka-gates/assets/data/iq3_s/dense.bin -b2a014878c3b61d6a6f915e194055a5e68ede34f9465dd1cb13249d902f008ac /home/para/.local/share/strata/Strata-data/packs/iq3_s/index.txt -d9ac2dfa3ee63c55c9c6a6db26f72da0cec0ee41733f007e5cbbbba71617aa5d /home/para/.local/share/strata/Strata-data/packs/iq3_s/native_experts.txt -8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf /home/para/work/leleka/models/leleka-gates/assets/data/expert-profile.bin -8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf /home/para/work/vanilla-strata/control/data/expert-profile.bin -09398406be61f1f54c93861f449e48b8df0bfccbc9ec9b2b7636775a6ea9244f /home/para/work/leleka/models/leleka-gates/assets/data/mtp-rt/experts.bin -c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a /home/para/work/leleka/models/leleka-gates/assets/data/mtp-rt/dense.bin -b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91 /home/para/work/leleka/models/leleka-gates/assets/data/mtp-rt/draft_vocab.bin -``` - -and, separately, `sha256sum` of vanilla's own MTP files (`~/.local/share/strata/Strata-data/mtp/rt/*`): `dense.bin c724dc0b...329070a`, `draft_vocab.bin b1e1d3a7...cb91`, `experts.bin 09398406...244f` (full values equal the three MTP lines above; the `dense.txt` files differ in name only -and are not part of the mapping: `991456cf4eb266eb8a888c349e548d11bc640f5dbd9149439aa9786af0f732fd` on vanilla's copy). - -| Item | Ours reads | Vanilla reads | Server fact that ties them | -| --- | --- | --- | --- | -| Weights, experts and PLE | KAR `qwen-iq3-s-l2-v4.kar` (55,295,529,472 bytes) loaded by the holder into a sealed memfd; GGUF shards as tensor directory and for PLE (`--shard0/--shard1`) | the same two GGUF shards: `--native` shard 1, `--ple-gguf` shard 2 | KAR provenance `qwen-iq3-s-l2-v4.kar.provenance.json` lists `shards[0].gguf_sha256 = 4c1eb2ce...` and `shards[1].gguf_sha256 = 316b46f3...`, equal to the live hashes above | -| Dense tensors | from the KAR | `dense.bin` of the pack (1,538,035,200 bytes) | pack `conversions.json` lists the same two shard names and sizes (54,817,524,224 and 28,800,138,432); `dense.bin` equals the copy in `assets/data/iq3_s` | -| Expert profile | `LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE` (the profile names `data/expert-profile.bin`) | `--expert-profile ~/work/vanilla-strata/control/data/expert-profile.bin` | both are `8f59b4aa...` (the laptop's file has the same hash, `docs/laptop-vs-vanilla.md` section 1) | -| MTP draft pack | `--mtp-pack /home/para/work/leleka/models/leleka-gates/assets/data/mtp-rt` | `--mtp ~/.local/share/strata/Strata-data/mtp/rt` | experts.bin, dense.bin and draft_vocab.bin are byte-identical | -| Artifact digest label | `sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3` (`crates/leleka-runtime/src/backend.rs:59`, `crates/deploy/src/layout.rs:45`, daemon config of `run-e2e.sh`) | none: vanilla has no such label | the label is ours; the mapping rests on the shard hashes | - -KAR archive hash: the file is `qwen-iq3-s-l2-v4.kar`, 55,295,529,472 bytes. Its recorded `sha256sum` output (the file `qwen-iq3-s-l2-v4.kar.sha256.tmp` next to it, written 2026-10-12) reads -`536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5 /home/para/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar`, and the provenance field `archive_sha256` has the same value. -I started a live re-hash and STOPPED it after about 17 GB because another agent's GPU job (STRA-267, `gpu.lock` held) was running and the read competed with it; the KAR value on this page is therefore the recorded one, not today's. -`derived_f32_sha256 c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479` (provenance) is the digest of the f32 view that the archive was derived from the shards with (`strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257`). - -The Windows hashes (the two shards on the laptop, its pack, the KAR if one is used there) are recorded by STRA-254 AC5 (verified by STRA-254). The laptop pack digest label `sha256:80d5e333...66a3` is the same label as ours here. - -Vanilla binary and launcher on the server (from STRA-247, `docs/experiments/2026-10-28-s0-7-vanilla-arms.md`): launcher `~/work/vanilla-strata/control` (`VERSION` 0.1.51, `COMMIT` `562a0c2e...`), engine -`~/.local/share/strata/components/engine/0.1.50-linux-x86_64-cuda-cuda13/strata`, `strata --version` prints `strata 0.1.50`, sha256 `ae49d5da81b9b65d50af1108c4b3f8b289ee198d9992d66268b7e885cf1a4776`. - -## 6. Cache state and its non-privileged resets (SC5) - -Series cache state, one definition for every pair (item common paragraph): WARM-OS / EMPTY-ENGINE: the model files are in the OS page cache as left by the previous arm, the engine process is fresh, the engine's prefix cache is empty, -and ONE discarded warm-up block is run after every boot. Cold and warm runs are never pooled. The state is recorded before every arm with the tool below. - -Order that matters: hashing a model file reads all of it and REWRITES the page-cache state (the two shards, 83.6 GB, were fully resident afterwards: `fincore` fractions 1.0 and 1.0, `Cached` 120,742,544 kB). So hash first, take the cache snapshot after, and -re-prime (read once) before the discarded warm-up block if the state was disturbed. Never hash during a series. - -Allowed methods (all run as the normal user): - -1. NO RESET (state "as left"), measured and recorded: `python3 /data/leleka-e2e/work/stra-288/cache_state.py snapshot FILE...` prints per file resident bytes, size, fraction (from `fincore -b`) plus `MemAvailable` and `Cached`. -2. EVICT the run's own model files with `posix_fadvise(POSIX_FADV_DONTNEED)`: `cache_state.py reset FILE...` (same precedent as `scripts/laptop/lap_run.sh` with `COLD=1`, lines 63-70). It evicts only clean pages of the files it names, writes nothing, needs no privilege. - Files to name for a cold state: the two GGUF shards, `data/iq3_s/dense.bin` (and vanilla's pack copy `~/.local/share/strata/Strata-data/packs/iq3_s/dense.bin`), the MTP `experts.bin`/`dense.bin`, `expert-profile.bin`. Vanilla's PACK files must be added to the list the laptop script uses (it names only `*.gguf` and `*.kar`). - It does NOT evict the sealed KAR memfd of the holder (a process-owned memory file), and it does not evict pages a running engine has mapped: use it only when no engine of that arm is running. -3. Anything else (system-wide cache drops, standby-list flushes, root commands) is forbidden for agents and listed only as owner-run: `sudo` plus the kernel cache-drop file is owner-run; the Windows standby-list tool (`EmptyStandbyList`) is owner-run. - The words below appear only on lines marked owner-run or forbidden: sudo, drop_caches, EmptyStandbyList, rm -rf (rm -rf is forbidden on any run directory, section 8). - -Measured on the server today (command `cache_state.py reset` on vanilla's pack file `~/.local/share/strata/Strata-data/packs/iq3_s/dense.bin`, 1,538,035,200 bytes, user `para` uid 1000, no engine running): - -``` -before: resident_bytes 230985728 of 1538035200 (fraction 0.1502) -reset: reset_seconds 0.001; after: resident_bytes 0 (fraction 0.0), Cached 120953028 kB -> 120728868 kB -``` - -The two shards were NOT reset on purpose: another agent's job (STRA-267) was running and may read them. The resident fraction of the shards after hashing was 1.0 (above). A cold arm is therefore one `reset` of the named files -(sub-second to seconds) plus the longer start-up that follows; both are recorded, never pooled with warm arms. - -Windows rule (verified by STRA-254): "a non-privileged method, or no reset": the state is defined and recorded from the standby and available byte counters before every arm; any privileged method is an owner action. - -## 7. Machine locks and the queue - -- Orchestrator admission is level 1: at most one timing leaf per machine (SC4). CPU-only microbenchmarks count, because the CPU pool is a decode component. -- `/data/leleka-e2e/gpu.lock` is the agents' GPU lock on the server. Take it with `mkdir /data/leleka-e2e/gpu.lock` (atomic); if the command fails, another agent has the GPU and you do NOT run: record a blocker. Write `owner` inside it (leaf key, role, UTC; - the STRA-267 lock reads `STRA-267 DEV 2026-10-28T19:58:40Z`). Release with `rmdir` of your own lock only. A lock whose owner is not you is never removed by an agent, even if it looks stale; ask the orchestrator. -- Before any GPU use, also check: `nvidia-smi --query-compute-apps=pid,name,used_memory --format=csv` (empty), `ps` for `leleka-inference`, `strata-next`, `leleka-daemon`, `strata`, `rt-*` and holder jobs, and `ls ~/work/gpu-runs/holder2/jobs/*.running` (a `.running` marker with a live job, apart from the long dead `220-expert-tier.running` of 2026-10-16, means the holder is busy). -- Model jobs go through the holder: `~/work/gpu-runs/holder2/run_holder2.sh` holds `~/work/gpu-runs/MODEL.lock` and one sealed 55 GB KAR memfd; `kar_holder2.py` runs the `*.sh` files of `~/work/gpu-runs/holder2/jobs/` ONE at a time, priority names in `jobs/PRIORITY`, otherwise oldest first, `jobs/STOP` stops it between jobs. - `run-e2e.sh` refuses to start unless it inherited the memfd (`LELEKA_STRA169_KAR_FD`), `MODEL.lock` exists, nothing else uses the GPU, no stack process of the user runs and ports 18766, 18080, 8081 are free. -- ONE holder job per series block, looping its arms (the `scripts/upstream-rest/jobs/rest-e2e-ab2.sh` pattern: `for arm in ...; do ( export ...; bash run-e2e.sh ) ; done`), never one job per arm: the holder snapshots its job list per pass and late entries waited 1-4 hours (`docs/e2e-run.md`). -- In-run lock (SC13), defined here as rules, exercised by STRA-316 (runner), STRA-291 (laptop watchdog) and STRA-254: Linux = atomic `mkdir` of a lock directory in the run root with an `owner` file (leaf, run id, PID, UTC, `/proc/sys/kernel/random/boot_id`); Windows = an exclusive `CreateNew` with `FileShare.None` handle on a file under `artifacts\locks`. - A runner REFUSES when the lock is held (it does not wait forever); a lock left by a dead process is never taken over automatically on the laptop (SC3: inspection after a crash). -- SC14: builds and tests (cargo, cmake, compilers) never run on a machine while a timing job runs there. The server has no cmake and its root disk is full (the cargo target directory `~/work/leleka-rest-target` is on it), so no engine build is made there now; `bin-e2e4` was built there earlier by cargo while the disk had room (compiler string in section 2), the older `bin-sm120` set in WSL on the laptop (`docs/e2e-run.md` section 1). -- Foreign load: a holder job queued earlier can start in the middle of a leaf. Record the top processes' CPU in the sample series; a cell with a non-harness process above 5 percent of a core for 2 s is marked invalid (threshold proposed by DEVOPS 7b25fb7b, owned by BA/TL). - -## 8. Run hygiene (SC11-SC14, DEVOPS comment 7b25fb7b) - -| Rule | Server | Laptop | -| --- | --- | --- | -| Run root (outside any git tree) | `/data/leleka-e2e/runs////` with `ledger.jsonl` beside the `` directories (`/data/leleka-e2e/runs//ledger.jsonl`, append-only, one fsynced JSON line per event). The kernel A/B run directory is `/kernel-ab/` (existing: `/data/leleka-e2e/runs/kernel-ab`). | `C:\Users\pavel\work\leleka\artifacts\runs` in the MAIN checkout (verified by STRA-254 for the laptop's own paths) | -| Why not `~/work/leleka-e2e/runs` | The leaf text names `~/work/leleka-e2e/runs////`. That directory is on the root file system, which has 2.4 G free, so the 20 GB disk guard refuses it today. The 48 earlier run dirs stay there, read only. New runs use `/data/leleka-e2e/runs`. | not applicable | -| Never inside a worktree | not applicable (no repository on the server) | NEVER `.git\wt\\artifacts`: `scripts/dev/worktree.sh clean` removes the worktree directory together with its ignored files, so raw logs would vanish after the merge | -| Git ignore check | not applicable | `git check-ignore -v artifacts/runs/x` in the main checkout prints `.gitignore:31:artifacts/ artifacts/runs/x` (exit 0; same output in this worktree); a runner refuses to start unless it matches | -| Disk guard | refuse a run when `df --output=avail -B1G /data \| tail -1` is below 20 (today 223) | refuse when the run volume has less than 20 GB free | -| Invalid runs | never `rm -rf` a run directory: forbidden, the job template of `docs/e2e-run.md` section 8 contains such a line and must not be copied into a series job. An invalid run is KEPT and renamed `.invalid-`, so no pair is dropped silently | same | -| Committed evidence | sanitized records and hashes only; raw logs, H0, captures, power series stay in the run root | same | - -## 9. Per-arm overhead on the 5090 and the series floor (AC4) - -**Dedicated GPU slot: NOT RUN.** When this leaf looked for the GPU (2026-10-28 about 20:05 UTC), `/data/leleka-e2e/gpu.lock` existed with owner `STRA-267 DEV 2026-10-28T19:58:40Z` and the holder was running `stra-267-chunk8192-qpair` -(`ps` showed `rt-qpf4`; `ls ~/work/gpu-runs/holder2/jobs/*.running`). By the GPU rule this leaf did not run beside it. The job script prepared for the slot stays at `/data/leleka-e2e/work/stra-288/job.sh` (one ours arm: state snapshot, `run-e2e.sh` -with the pinned binary and the shipped-shape environment of `rest-e2e-ab2.sh`, `replay_session.py record-h0` as the session, then a timed `cache_state.py reset`). - -**What exists instead, measured on this machine with the pinned binary today (not by this leaf):** the four ours arms of job `rest-e2e-ab2` (2026-10-28 01:37-02:14 UTC, `bin-e2e4`, shipped-shape environment: expert slots auto, GPU budget 30 GiB, prefill capacity 8192, -prefix cache auto/reply/8192, spec-min-p 0, `LELEKA_CHAIN=all`, session = the 5-turn 245k long session). Command that produced the numbers: -`stat -c '%y' ~/work/leleka-e2e/runs/rest-gap-/{api-key-init.err,load.txt,client.rc}` plus the holder log lines `=== ` and `run-e2e done ` in `~/work/gpu-runs/holder2/jobs/rest-e2e-ab2.log`, and `wall_s` of `long-session.json`. - -| Arm | Start | Model ready | Session end | Done | Start-up s | `load_seconds` | Session s | Shut-down s | Arm total s | -| --- | --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | -| before1 | 01:37:41 | 01:45:37 | 01:46:50 | 01:46:56 | 476 | 471 | 73 | 6 | 555 | -| after1 | 01:46:56 | 01:55:22 | 01:56:32 | 01:56:38 | 506 | 501 | 70 | 6 | 582 | -| after2 | 01:56:38 | 02:03:44 | 02:04:55 | 02:05:01 | 426 | 420 | 71 | 6 | 503 | -| before2 | 02:05:01 | 02:13:12 | 02:14:24 | 02:14:30 | 491 | 486 | 72 | 6 | 569 | - -- Mean arm total 552 s (range 503-582); start-up 426-506 s dominates; session 70-73 s (sum of the five turns' `wall_s`, e.g. 72.5 s for before1; TTFT 10.1-13.1 s per turn with prefix reuse); shut-down 6 s; no cool-down between arms. -- The cache state of these arms was not recorded (uncontrolled WARM-OS as left); no reset was run between arms. The planning figure of 6 minutes per arm (360 s) is BELOW every measured ours arm (503-582 s). -- Reset: `cache_state.py reset` took 0.001 s for a 1.5 GB file (section 6). A cold start-up after resetting the two shards was not measured. -- Vanilla start-up on the same server (STRA-247, `strata launch ... --tune skip`, 256k, wall from launch to ready): arm (a) 262 s, arm (b) 286 s, control 204 s. A vanilla 256k session wall on the 5090 is not measured yet (STRA-258 measures it). - -**Series plan as a FLOOR.** Per block (ours + vanilla default + vanilla lossy-paths-off): ours 552 s measured + 2 x vanilla start-up (about 262 + 286 s) = about 1,100 s, before any vanilla session wall, any reset, the discarded warm-up block after boot and any cool-down: -30 blocks x 1,100 s = about 33,000 s = 9.2 hours as a lower bound of overhead plus ours-session. The 19-hour series estimate of the plan is a floor and is not contradicted by these numbers; it must not be shortened on the 6-minute-per-arm assumption. -The dedicated measurement with the replay driver (start-up under a recorded cache state, session, reset) is a follow-up for a free GPU slot: `job.sh` above, under the `gpu.lock` of section 7. - -## 10. Facts the F6 briefing of a run leaf must supply (STRA-258 and the other 5090 leaves) - -| Fact | Value | -| --- | --- | -| ssh, roots | `ssh rnr5090`; work and outputs under `/data/leleka-e2e/`; run root `/data/leleka-e2e/runs////` | -| Ours binaries, ports | `~/work/leleka-rest/bin-e2e4/` (section 2), started by `~/work/leleka-e2e/scripts/e2e/run-e2e.sh` inside a holder job (ports 18766, 18080, 8081 on 127.0.0.1) | -| Ours job environment (shipped shape, from `rest-e2e-ab2.sh`) | `E2E_BIN=$HOME/work/leleka-rest/bin-e2e4`, `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto`, `E2E_GPU_BUDGET=32212254720`, `LELEKA_CHAIN=all`, `E2E_SAMPLE_S=10`, `E2E_ENGINE_ARGS="--prefix-cache-mib auto --prefix-cache-tail reply --original-prefill-capacity 8192 --prefix-cache-block 8192 --spec-min-p 0"`, `E2E_OUT=`, `E2E_RUN_CMD=`. Difference from the profile file: `run-e2e.sh` defaults the expert profile to `~/work/gpu-runs/baseline/profile.bin`, the profile names `data/expert-profile.bin` | -| Vanilla binary and launch | engine and launcher in section 5; launch from `~/work/vanilla-strata/control`: `bin/strata launch --model iq3_s --family qwen --model-path /home/para/work/leleka/models/leleka-gates/assets/model --context 256k --kv int8 --vision off --parallel 1 --tune skip --access local --port 8090 --no-tui --yes`, stop with `bin/strata launch --stop`; redirect the launcher's state with `XDG_CONFIG_HOME` and `XDG_STATE_HOME` into the run directory (copy `~/.config/strata/settings.json` there) so `~/.config/strata` is not written; instrumentation `STRATA_DECODE_TIMING=1 STRATA_VERIFY_PROFILE=1`; arm (b) adds `STRATA_ROUTE_TAIL_SKIP=0` (the only lossy row, STRA-247 section 4) | -| Vanilla endpoint | `/v1/responses` exists in the installed server (`serve/server.py` lines 4716, 6762); STRA-247 used `/v1/chat/completions`. The replay driver against vanilla has not been run yet | -| Engine arguments the launcher produced | `--pack .../packs/iq3_s --native --ple-gguf --expert-profile .../control/data/expert-profile.bin --expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp .../Strata-data/mtp/rt --max-context 262144 --kv int8 --ple-io ram --kv-resident 32768` | -| Series state | cache state of section 6, lock rules of section 7, overhead floor of section 9 | -| Workload | section 4: driver, snapshot hash, H0 | - -## 11. Windows values (verified by STRA-254) - -Rules and pointers only; this leaf never touched the laptop (TL round 4, F1). Each item is verified and its values recorded by STRA-254 and appended to the index page `docs/experiments/2026-10-28-s0-7b-index.md`. - -- Run root: `C:\Users\pavel\work\leleka\artifacts\runs` (main checkout) (verified by STRA-254). -- Source snapshot path `C:\Users\pavel\work\wsrun\src-snap\crates`, snapshot hash by the method in 4.2 (verified by STRA-254). -- Model volume, the two shards' hashes and the pack digest (verified by STRA-254, its AC5). -- Vanilla install and launch (`%LOCALAPPDATA%\Strata`, command of the STRA-247 page, `UNVERIFIED-ON-WINDOWS` until then) (verified by STRA-254). -- Cache state: "a non-privileged method, or no reset", counters before each arm (verified by STRA-254). -- Lock: exclusive `CreateNew` + `FileShare.None` under `artifacts\locks`; never taken over after a crash without owner inspection (STRA-291, verified by STRA-254). -- Power and laptop preconditions (Turbo, charger, lock/sleep policy, the enforced power limit via `enforced.power.limit`): owner preconditions, an agent only reads them (SC3). Execution policy: `powershell -NoProfile -ExecutionPolicy Bypass -File ...` per process; never `Set-ExecutionPolicy` (DEVOPS D-3). -- The laptop is also the dev host: while a laptop GPU job runs no build, test or Python job runs on it (SC14). `bash` on the laptop PATH is the WSL launcher: harness scripts use PowerShell and Python only. - -## 12. Reading checks (AC6) - -Check A: a fresh session starts STRA-258 from its body plus this page. STRA-258 (read in full: summary, AC1-AC4, architectureHandoff) needs, and finds on this page: - -| STRA-258 needs | Where on this page | -| --- | --- | -| Where it runs and how to reach the server | section 1 | -| Exclusive GPU, lock, queue | section 7 (`gpu.lock`, holder, one holder job per block) | -| Vanilla binary, launch, the two variants and their environment | sections 5 and 10, plus the STRA-247 page it names | -| The 256k session, the driver and H0 | section 4 (H0 is STRA-309's output; STRA-258 does not list STRA-309 in its dependsOn, so until an H0 exists the leaf has to use `long_session.py` directly or record one itself: gap found) | -| Where raw logs and records go (outside Git, 256k class quoted) | section 8; the leaf body says `~/work/leleka-e2e/runs/`, which is superseded by `/data/leleka-e2e/runs/` (section 8) | -| Timing flags and the 10.3-15.7 ms comparison | its own body and the STRA-247 page (`STRATA_DECODE_TIMING`, `STRATA_VERIFY_PROFILE` lines) | -| Cache state for the runs | section 6 | - -Result of the reading: STRA-258 can be started from its body plus this page; the two gaps (no H0 dependency; run-root path in its body) are named here and in the work result. This reading was made by the DEV of this leaf, not by an independent fresh session. - -Check B: a fresh session starts a laptop leaf from its body plus this page plus the STRA-254 addendum: sections 2-4 and 6-8 supply the rules; every Windows value is a pointer to STRA-254 (section 11). Not checked against the addendum, which does not exist yet. - -## 13. Not verified - -- The dedicated AC4 GPU run (section 9): not run, GPU lock held by STRA-267. The per-arm numbers are from the existing four-arm job, not from a run with the replay driver or under a recorded cache state. -- That `bin-e2e4` was built from `ffb264e0` with the default feature set: inferred from tree equality, timestamps and binary size; the cargo command is not recorded. -- The KAR hash was not recomputed today (stopped, section 5); the shard and pack hashes were. -- `replay_session.py` has not been run against a real engine, ours or vanilla, and not on Windows; it only parses under Python 3.14. -- Turn 1 = 45,766 tokens was observed in the old client's logs, not re-measured with the replay driver. -- The profile file hash is of Train A's copy; the `ffb264e0` copy differs (section 2). -- Everything Windows (section 11), and the laptop's power state: unknown to the owner as of comment 1ddd7fcf. -- Cold-start cost of the shards after a `reset` (not measured to avoid disturbing the running STRA-267 job). diff --git a/docs/experiments/2026-10-28-s0-7c-vanilla-predicate-dump.md b/docs/experiments/2026-10-28-s0-7c-vanilla-predicate-dump.md deleted file mode 100644 index 8fe3fdbc..00000000 --- a/docs/experiments/2026-10-28-s0-7c-vanilla-predicate-dump.md +++ /dev/null @@ -1,127 +0,0 @@ -# S0.7c Vanilla predicate dump (STRA-307): both outputs produced on the server - -Date: 2026-10-28. Item: STRA-307, part of STRA-245. Branch `claude/stra-307`, created from `claude/merge-opt` (2457d81d). -Evidence level: COMPONENT, item (d) of the `vanilla_cpu_family` block (ARCHITECT comment 395f0394, section 2). -This page replaces the first attempt (commit e94369a1, outcome "build unavailable": no cmake, root filesystem full). Attempt 2 built -the tool with the server's g++ directly and put the run root on `/data`. - -## Limit of this evidence (fixed wording) - -This dump proves the predicate of the pin's source, not the release binary. The pin is app 0.2.5 / engine 0.1.50, the comparator is called -release 0.2.6 / engine 0.1.50 (`docs/laptop-vs-vanilla.md` header); STRA-247 records the printed version and digest of the installed -vanilla build. Nothing on this page says anything about the installed vanilla executable. - -## Result in one line - -On the server (AMD Ryzen 9 9950X3D), the pin's own predicate `cpu_avx512_ok()` prints `avx512 1` with all `STRATA_*` variables scrubbed -and `avx512 0` with `STRATA_FORCE_AVX2=1`. The two outputs differ in that one flag and in no other line (51 lines each; `diff` shows one -changed line). The IQ env state is `-` (unset) in both runs. - -## Pin, source and build (AC1) - -| Field | Value | -| --- | --- | -| Pin read from `docs/upstream.md` (this branch) | `41cf05a06a25dd29103b7b27a2279a3f60c21876` (engine 0.1.50, app 0.2.5), short `41cf05a0` | -| engine/strata path used (local) | `C:\Users\pavel\work\leleka\.git\wt\stra-307\engine\strata`, the branch worktree `.git/wt/stra-307` at commit e94369a1 (checked out from `claude/merge-opt`); never the main checkout, which is at the old pin `d9ab8435` (ARCHITECT A9) | -| How it reached the server | `git -c core.autocrlf=false archive HEAD engine/strata/{CMakeLists.txt,cmake,include,src,third_party}` from that worktree, extracted to `/data/leleka-e2e/runs/stra-307/src/engine/strata` | -| llama.cpp / ggml | `3cf03257f219afbe7334045ff7c6a06ac68c627d` (equals `third_party/ggml/VERSION.txt` and the `GIT_TAG` in `CMakeLists.txt`), `git fetch --depth 1` of that SHA into `/data/leleka-e2e/runs/stra-307/llama.cpp`; `git rev-parse HEAD` there prints the same SHA; ggml 0.24.0 | -| Tool | `iq_avx2_parity` (`src/kernels/cpu/iq_avx2_parity.cpp`, target at `CMakeLists.txt` lines 1871-1872); the predicate lines are 556-558 | -| Compiler | GNU g++ / gcc (Ubuntu 15.2.0-16ubuntu1) 15.2.0 | -| Target triple | `x86_64-linux-gnu` (`g++ -dumpmachine`) | -| GGML_NATIVE | ON: ggml-cpu compiled with `-march=native` (the CMake default; `STRATA_PORTABLE` is not set, so the `GGML_NATIVE OFF` branch is not taken) | -| STRATA_PORTABLE | OFF (the option default; also `STRATA_ISA_FLOOR` empty) | -| Build type flags | `-O3 -DNDEBUG` (Release, the project default), C++20 for the engine sources, C++17 for ggml-cpu, `-std=gnu11` for ggml C | -| Run root | `/data/leleka-e2e/runs/stra-307` (outside Git, on `/data`); the root filesystem was not written to | -| Binary | `/data/leleka-e2e/runs/stra-307/build/iq_avx2_parity`, sha256 `5d1b5132ab5e9b2671279aa5fae57c8c0b08dc8313619a4623a33fcab8628275` | - -### Deviation from the AC1 wording (stated, not hidden) - -AC1 asks for `cmake --build --target iq_avx2_parity` to exit 0 and for the values to be read "from the CMake cache". The -server has no `cmake` (attempt 1), and installing it was not allowed (orchestrator decision on STRA-307, comment 91a3354e: build with -the server's g++ directly, same route as STRA-248). So: - -- the tool was built by `/data/leleka-e2e/runs/stra-307/build.sh`, which runs 42 `g++`/`gcc` compile commands and an `ar` + link step - by hand and exits 0 (it printed only the `ls -l` of the binary; `compile.log` and `link.log` are both 0 bytes); -- there is **no CMake cache**. The compiler id/version, triple and GGML_NATIVE / STRATA_PORTABLE state above come from `g++ --version`, - `g++ -dumpmachine` and from the flags the script passes, which were transcribed from `engine/strata/CMakeLists.txt` (lines 1689-1730, - 1738-1851: the `strata_kernels_cpu` sources and their per-file ISA flags, the AVX-VNNI define, the ggml static build with - `GGML_OPENMP` off, `GGML_CPU_REPACK` on, llamafile off, `GGML_SCHED_MAX_COPIES=4`) and from ggml's `CMakeLists.txt` (x86 branch, - `GGML_NATIVE` gives `-march=native`); -- `STRATA_AVXVNNI=1` was set by hand for `q2_avx2.cpp` and `iq_avx2.cpp`; CMake would have set it from a compile check of the - intrinsics, which g++ 15.2.0 passes (the files compiled without error with it); -- the project's warning flags were not passed (they do not change code generation); this is a hand-made equivalent of the CMake - build, not a CMake build, and a reader who needs the exact CMake artifacts must repeat the build where cmake >= 3.24 exists. - -The predicate itself (`cpu_avx512_ok()` in `src/kernels/cpu/expert_layout.cpp`, from line 42) is the `STRATA_FORCE_AVX2` environment -check, the ISA-cap check and a CPUID/XCR0 test; it does not depend on how the rest of the engine was compiled. - -## The two runs (AC2), no model, CPU only - -Both runs: `env -i PATH=/usr/bin:/bin ...` (so no `STRATA_*` variable of the login shell can leak in), working directory -`/data/leleka-e2e/runs/stra-307`, exit status 0, 0.13 s each. Raw outputs are outside Git at `run_scrubbed.txt` (sha256 -`8973213c9b9bca74ffbec08f6f57da9d595e5974e801cce6270457d7f9b19086`) and `run_force_avx2.txt` (sha256 -`19da2a92f5be123398e6477d0eae6d0ef9adbbdb1dc12d5bf9378cf4d628b751`) in that directory. - -### Run A: all STRATA_* scrubbed (the shipped state) - -Command: `env -i PATH=/usr/bin:/bin ./build/iq_avx2_parity`. First three lines, verbatim: - -``` -iq_avx2_parity: AMD Ryzen 9 9950X3D 16-Core Processor (avx2 1, avx512 1), CPU -1, core type 00h - STRATA_IQ256_GATHER -, STRATA_NO_AVXVNNI -, STRATA_IQ_MT_MIN -, STRATA_IQ_PREFETCH - - variants this CPU runs: gather+vnni; this thread's: vnni -``` - -Last line, verbatim: `iq_avx2_parity: 0 failures` - -### Run B: STRATA_FORCE_AVX2=1 - -Command: `env -i PATH=/usr/bin:/bin STRATA_FORCE_AVX2=1 ./build/iq_avx2_parity`. First three lines, verbatim: - -``` -iq_avx2_parity: AMD Ryzen 9 9950X3D 16-Core Processor (avx2 1, avx512 0), CPU -1, core type 00h - STRATA_IQ256_GATHER -, STRATA_NO_AVXVNNI -, STRATA_IQ_MT_MIN -, STRATA_IQ_PREFETCH - - variants this CPU runs: gather+vnni; this thread's: vnni -``` - -Last line, verbatim: `iq_avx2_parity: 0 failures` - -### Difference between the two outputs - -`diff run_scrubbed.txt run_force_avx2.txt`, verbatim: - -``` -1c1 -< iq_avx2_parity: AMD Ryzen 9 9950X3D 16-Core Processor (avx2 1, avx512 1), CPU -1, core type 00h ---- -> iq_avx2_parity: AMD Ryzen 9 9950X3D 16-Core Processor (avx2 1, avx512 0), CPU -1, core type 00h -``` - -The two outputs differ in exactly the avx512 predicate. The parity lines in between (rows against ggml's dot, the scalar / gather / -vnni variants, 0 failures) are identical in both runs, because the tool checks the AVX2 i-quant variants either way. - -## What this tells and what it does not - -- Tells: in the pin's source, on this CPU, `cpu_avx512_ok()` is true by default and `STRATA_FORCE_AVX2=1` turns it off; the IQ env - variables the tool prints (`STRATA_IQ256_GATHER`, `STRATA_NO_AVXVNNI`, `STRATA_IQ_MT_MIN`, `STRATA_IQ_PREFETCH`) are unset in the - shipped state. It is the engine's own predicate, as printed by the engine's own code. -- Does not tell: which kernel family the installed vanilla executable selected (STRA-247's negative line plus positive control carry - that), and it does not say which family any release other than the pin would select. The pin is not the comparator release. -- The i-quant gating state beyond these four variables (for example which of the AVX-512 or AVX2 i-quant rows a model run takes) is not - printed by this tool without a model, and nothing is inferred here. - -## Acceptance state - -| AC | State | Evidence | -| --- | --- | --- | -| AC1 | met with the deviation above | binary built, link exit 0; pin, compiler, triple, GGML_NATIVE, STRATA_PORTABLE and the worktree path recorded; no CMake cache exists | -| AC2 | met | both outputs quoted verbatim; avx512 flag 1 then 0; the outputs differ in that line only | -| AC3 | met | the fixed sentence above appears once; the forbidden phrases appear 0 times | -| AC4 | met | `git diff --name-only ..HEAD` lists this page only | -| AC5 | not applicable | the build was possible, so no "unavailable" rows remain | - -## Not verified - -No CMake configure was run (no cmake on the server). No model was loaded, nothing ran at 256k, no GPU job was started or disturbed -(GPU 0 percent, 2 MiB used before the build). The build used 8 parallel compile jobs for 17 s; no timing job ran meanwhile. -The root filesystem of the server is still 100 percent full (2.5 GB free), unchanged by this work; that is a separate server-health item. diff --git a/docs/experiments/2026-10-28-s3-1-check_bootstrap.py b/docs/experiments/2026-10-28-s3-1-check_bootstrap.py deleted file mode 100644 index 14915198..00000000 --- a/docs/experiments/2026-10-28-s3-1-check_bootstrap.py +++ /dev/null @@ -1,367 +0,0 @@ -#!/usr/bin/env python3 -"""Checks for STRA-256 (S3.1): the laptop thresholds schema, its BOOTSTRAP instance, the safety-protocol page. - -Offline tool, Python 3.9, standard library only (production serving never runs this). -Reads files only: no GPU, no nvidia-smi, no powercfg, no setting is ever changed. - - check_bootstrap.py validate the BOOTSTRAP file against the schema - check_bootstrap.py --validate FILE validate FILE against the schema (STRA-292 uses this) - check_bootstrap.py --rules one line per stop / resume rule of SC3, marked field or numeric - check_bootstrap.py --criteria one row per floor of monitor.sh / lap_run.sh, each found by grep - check_bootstrap.py --self-test mutated BOOTSTRAP files must be rejected - check_bootstrap.py --bootstrap-fields the START-UP fields of the BOOTSTRAP file - options: --scripts-dir DIR (default /scripts/laptop), --schema FILE, --bootstrap FILE, --page FILE - -Exit codes: 0 ok, 1 check failed, 2 usage or unreadable input. -""" -import argparse -import copy -import json -import os -import re -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -STEM = "2026-10-28-s3-1-" -DEFAULT_SCHEMA = os.path.join(HERE, STEM + "laptop-thresholds.schema.json") -DEFAULT_BOOTSTRAP = os.path.join(HERE, STEM + "laptop-thresholds.bootstrap.json") -DEFAULT_PAGE = os.path.join(HERE, STEM + "laptop-safety-protocol.md") -DEFAULT_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(HERE)), "scripts", "laptop") - - -# ---------------------------------------------------------------- minimal JSON Schema interpreter - -def _type_ok(value, name): - if name == "object": - return isinstance(value, dict) - if name == "array": - return isinstance(value, list) - if name == "string": - return isinstance(value, str) - if name == "boolean": - return isinstance(value, bool) - if name == "integer": - return isinstance(value, int) and not isinstance(value, bool) - if name == "number": - return isinstance(value, (int, float)) and not isinstance(value, bool) - if name == "null": - return value is None - raise ValueError("unsupported type in schema: %r" % (name,)) - - -def validate(value, schema, path="$"): - """Return a list of error strings (empty = valid). Supports the keywords the schema file uses.""" - errors = [] - if "const" in schema and not (value == schema["const"] and type(value) == type(schema["const"])): - errors.append("%s: must be %r, got %r" % (path, schema["const"], value)) - if "enum" in schema and value not in schema["enum"]: - errors.append("%s: %r is not one of %r" % (path, value, schema["enum"])) - if "type" in schema and not _type_ok(value, schema["type"]): - errors.append("%s: expected %s, got %s" % (path, schema["type"], type(value).__name__)) - return errors - if isinstance(value, (int, float)) and not isinstance(value, bool): - if "minimum" in schema and value < schema["minimum"]: - errors.append("%s: %r is below the floor %r" % (path, value, schema["minimum"])) - if "maximum" in schema and value > schema["maximum"]: - errors.append("%s: %r is above the ceiling %r" % (path, value, schema["maximum"])) - if "exclusiveMinimum" in schema and value <= schema["exclusiveMinimum"]: - errors.append("%s: %r must be above %r" % (path, value, schema["exclusiveMinimum"])) - if isinstance(value, str) and "minLength" in schema and len(value) < schema["minLength"]: - errors.append("%s: shorter than %d" % (path, schema["minLength"])) - if isinstance(value, list): - if "minItems" in schema and len(value) < schema["minItems"]: - errors.append("%s: fewer than %d items" % (path, schema["minItems"])) - if "items" in schema: - for i, item in enumerate(value): - errors.extend(validate(item, schema["items"], "%s[%d]" % (path, i))) - for needed in schema.get("x-mustContain", []): - if needed not in value: - errors.append("%s: must contain %r" % (path, needed)) - if isinstance(value, dict): - props = schema.get("properties", {}) - for key in schema.get("required", []): - if key not in value: - errors.append("%s: missing required field %r" % (path, key)) - if schema.get("additionalProperties") is False: - for key in value: - if key not in props: - errors.append("%s: unknown field %r" % (path, key)) - for key, sub in props.items(): - if key in value: - errors.extend(validate(value[key], sub, "%s.%s" % (path, key))) - for branch in schema.get("allOf", []): - if "if" in branch: - if not validate(value, branch["if"], path): - errors.extend(validate(value, branch.get("then", {}), path)) - elif "else" in branch: - errors.extend(validate(value, branch["else"], path)) - else: - errors.extend(validate(value, branch, path)) - return errors - - -def load_json(path): - try: - with open(path, "r", encoding="utf-8") as handle: - return json.load(handle) - except (OSError, ValueError) as exc: - print("cannot read %s: %s" % (path, exc), file=sys.stderr) - sys.exit(2) - - -def dig(obj, dotted): - """Value at a dotted path, or raise KeyError.""" - for part in dotted.split("."): - obj = obj[part] - return obj - - -def schema_has(schema, dotted): - node = schema - for part in dotted.split("."): - node = node.get("properties", {}).get(part) - if node is None: - return False - return True - - -# ---------------------------------------------------------------- SC3 stop / resume rules - -# (id, marker, schema field, exact sentence that must appear on the page) -# field = the rule is a schema field (machine-checked by validate()). -# numeric = the rule is an exact numeric sentence on the page (checked by text here). -RULES = [ - ("R01", "numeric", "retry.max_reruns_per_arm_slot", "At most one re-run per arm slot."), - ("R02", "numeric", "retry.consecutive_invalid_pairs_end_block", "Two consecutive invalid pairs end the block."), - ("R03", "field", "cooldown.between_arms_s", "Cool-down 120 s between arms."), - ("R04", "field", "cooldown.after_abort_s", "Cool-down 600 s after any abort."), - ("R05", "field", "halt.on_events", "The first BSOD, unexpected reboot or STALL stops all laptop GPU work."), - ("R06", "field", "resume.requires_orchestrator_recorded_owner_inspection", - "Nothing resumes until the orchestrator records that the owner inspected the machine."), - ("R07", "field", "resume.source", "Resume is from the pair ledger."), - ("R08", "field", "resume.interrupted_pair_invalid", "A pair interrupted by a crash is invalid."), - ("R09", "field", "lock.one_gpu_job_at_a_time", "One laptop GPU job at a time (lock file)."), - ("R10", "field", "preconditions.on_unmet", - "If a precondition is not met the agent stops without changing anything and records 'owner precondition not met'."), - ("R11", "numeric", "under_load.stall_gap_s", "A gap of more than 10 s between two samples is a STALL and aborts the run."), - ("R12", "numeric", "run.cap_minutes", "Under BOOTSTRAP a run is capped at 15 minutes."), -] - - -def cmd_rules(args): - schema = load_json(args.schema) - boot = load_json(args.bootstrap) - try: - with open(args.page, "r", encoding="utf-8") as handle: - page = handle.read() - except OSError as exc: - print("cannot read %s: %s" % (args.page, exc), file=sys.stderr) - return 2 - flat = " ".join(page.split()) - bad = 0 - for rid, marker, field, sentence in RULES: - problems = [] - if marker not in ("field", "numeric"): - problems.append("unmarked") - if " ".join(sentence.split()) not in flat: - problems.append("sentence missing on page") - if not schema_has(schema, field): - problems.append("schema field missing") - else: - try: - dig(boot, field) - except KeyError: - problems.append("bootstrap value missing") - status = "ok" if not problems else "FAIL " + ", ".join(problems) - if problems: - bad += 1 - print("%s %-7s %-60s %s | %s" % (rid, marker, field, status, sentence)) - print("rules: %d, failing: %d" % (len(RULES), bad)) - return 1 if bad else 0 - - -# ---------------------------------------------------------------- floors of the two scripts - -def _gt(path, number): - return lambda b: dig(b, path) <= number - - -def _ge(path, number): - return lambda b: dig(b, path) >= number - - -# (id, criterion, [(script file, regex)], schema field, bootstrap check) -CRITERIA = [ - ("C01", "STALL > 10 s", [("monitor.sh", r"now - prev\)\) -gt 10")], "under_load.stall_gap_s", _gt("under_load.stall_gap_s", 10)), - ("C02", "limit < 100 W", [("monitor.sh", r"l\+0 > 0 && l\+0 < 100")], "under_load.power_limit_floor_w", _ge("under_load.power_limit_floor_w", 100)), - ("C03", "temperature > 90 C", [("monitor.sh", r'"\$\{temp:-0\}" -gt 90')], "under_load.temperature_ceiling_c", _gt("under_load.temperature_ceiling_c", 90)), - ("C04", "P5 with memory clock < 2000 MHz and throttle 0x4/0x20", - [("monitor.sh", r'= P5 \] && \[ "\$\{memc:-0\}" -lt 2000 \].*& 0x24')], "under_load.oem_profile", - lambda b: b["under_load"]["oem_profile"]["pstate"] == "P5" and b["under_load"]["oem_profile"]["memory_clock_mhz_below"] >= 2000 - and 4 in b["under_load"]["oem_profile"]["throttle_reason_bits"] and 32 in b["under_load"]["oem_profile"]["throttle_reason_bits"]), - ("C05", "preflight limit >= 100 W", [("lap_run.sh", r"l\+0 >= 100")], "idle_preflight.limit_min_w", _ge("idle_preflight.limit_min_w", 100)), - ("C06", "SW power cap or SW thermal slowdown active at idle refuses", - [("lap_run.sh", r"grep -E \"SW Power Cap\|SW Thermal Slowdown\""), ("lap_run.sh", r"REFUSED: SW power cap / thermal slowdown active at idle")], - "idle_preflight.sw_power_cap_active_refuses", - lambda b: b["idle_preflight"]["sw_power_cap_active_refuses"] is True and b["idle_preflight"]["sw_thermal_slowdown_active_refuses"] is True), - ("C07", "P5 at idle refuses", [("lap_run.sh", r"REFUSED: performance state P5")], "idle_preflight.p5_refuses", - lambda b: b["idle_preflight"]["p5_refuses"] is True), - ("C08", "COOLDOWN 120 s", [("lap_run.sh", r"COOLDOWN:-120")], "cooldown.between_arms_s", _ge("cooldown.between_arms_s", 120)), - ("C09", "RUN_TIMEOUT 900 s replaced by a caller parameter", [("lap_run.sh", r"RUN_TIMEOUT:-900")], "run.timeout_source", - lambda b: b["run"]["timeout_source"] == "caller_parameter"), - ("C10", "lock mkdir", [("lap_run.sh", r'mkdir "\$HOME/LAPTOP_GPU\.lock"')], "lock.method", - lambda b: b["lock"]["method"] in ("mkdir", "exclusive_create") and b["lock"]["one_gpu_job_at_a_time"] is True), - ("C11", "scripts read power.limit (N/A on this GPU); schema reads enforced.power.limit", - [("monitor.sh", r"power\.limit,temperature\.gpu"), ("lap_run.sh", r"Current Power Limit")], "power_limit_source", - lambda b: b["power_limit_source"] == "enforced.power.limit"), -] - - -def cmd_criteria(args): - boot = load_json(args.bootstrap) - schema = load_json(args.schema) - if not os.path.isdir(args.scripts_dir): - print("scripts directory not found: %s (use --scripts-dir)" % args.scripts_dir, file=sys.stderr) - return 2 - cache = {} - bad = 0 - print("id | criterion | script:line | schema field | bootstrap | result") - for cid, text, greps, field, check in CRITERIA: - where = [] - problems = [] - for fname, regex in greps: - if fname not in cache: - try: - with open(os.path.join(args.scripts_dir, fname), "r", encoding="utf-8") as handle: - cache[fname] = handle.read().splitlines() - except OSError as exc: - print("cannot read %s: %s" % (fname, exc), file=sys.stderr) - return 2 - hits = [i + 1 for i, line in enumerate(cache[fname]) if re.search(regex, line)] - if hits: - where.append("%s:%d" % (fname, hits[0])) - else: - problems.append("not found in %s: %s" % (fname, regex)) - if not schema_has(schema, field): - problems.append("schema field %s missing" % field) - try: - ok = bool(check(boot)) - except (KeyError, TypeError): - ok = False - if not ok: - problems.append("bootstrap does not satisfy the floor") - try: - shown = json.dumps(dig(boot, field)) - except KeyError: - shown = "-" - if problems: - bad += 1 - print("%s | %s | %s | %s | %s | %s" % (cid, text, ", ".join(where) or "-", field, shown, "ok" if not problems else "FAIL " + "; ".join(problems))) - print("criteria: %d, failing: %d" % (len(CRITERIA), bad)) - return 1 if bad else 0 - - -# ---------------------------------------------------------------- the other modes - -def cmd_validate(args, target): - schema = load_json(args.schema) - data = load_json(target) - errors = validate(data, schema) - if errors: - for err in errors: - print("INVALID: " + err) - return 1 - return 0 - - -def cmd_bootstrap(args): - code = cmd_validate(args, args.bootstrap) - if code == 0: - print("bootstrap valid against schema") - return code - - -MUTATIONS = [ - ("floor removed: under_load.power_limit_floor_w", lambda d: d["under_load"].pop("power_limit_floor_w")), - ("floor lowered: power_limit_floor_w = 90", lambda d: d["under_load"].__setitem__("power_limit_floor_w", 90)), - ("ceiling raised: temperature_ceiling_c = 95", lambda d: d["under_load"].__setitem__("temperature_ceiling_c", 95)), - ("stall gap widened: stall_gap_s = 30", lambda d: d["under_load"].__setitem__("stall_gap_s", 30)), - ("dead reading source: power.limit", lambda d: d.__setitem__("power_limit_source", "power.limit")), - ("fail-open run: unreadable.run = IGNORE", lambda d: d["unreadable"].__setitem__("run", "IGNORE")), - ("confirm_samples = 0", lambda d: d["sampling"].__setitem__("confirm_samples", 0)), - ("nvidia-smi timeout 30 s", lambda d: d["sampling"].__setitem__("nvidia_smi_timeout_s", 30)), - ("cool-down after abort 60 s", lambda d: d["cooldown"].__setitem__("after_abort_s", 60)), - ("OEM profile bits lose 0x20", lambda d: d["under_load"]["oem_profile"].__setitem__("throttle_reason_bits", [4, 1])), - ("preflight floor 50 W", lambda d: d["idle_preflight"].__setitem__("limit_min_w", 50)), - ("BOOTSTRAP without run cap", lambda d: d["run"].pop("cap_minutes")), - ("BOOTSTRAP countable", lambda d: d["records"].__setitem__("countable_under_bootstrap", True)), - ("unknown field", lambda d: d.__setitem__("extra", 1)), - ("validity band widened: spread 50 W", lambda d: d["validity_band"].__setitem__("spread_within_arm_w", 50)), - ("agent may change settings", lambda d: d["preconditions"].__setitem__("agent_may_change_settings", True)), -] - - -def cmd_self_test(args): - schema = load_json(args.schema) - boot = load_json(args.bootstrap) - if validate(boot, schema): - print("self-test: the unmutated bootstrap is already invalid", file=sys.stderr) - return 1 - survived = 0 - for name, mutate in MUTATIONS: - mutated = copy.deepcopy(boot) - mutate(mutated) - errors = validate(mutated, schema) - if errors: - print("rejected: %s -> %s" % (name, errors[0])) - else: - survived += 1 - print("NOT REJECTED: %s" % name) - print("self-test: %d mutations, %d survived" % (len(MUTATIONS), survived)) - return 1 if survived else 0 - - -def cmd_bootstrap_fields(args): - boot = load_json(args.bootstrap) - try: - line = "thresholds_source=%s run_cap_minutes=%s confirm_samples=%s nvidia_smi_timeout_s=%s band=%s/%s/%s" % ( - boot["thresholds_source"], boot["run"]["cap_minutes"], boot["sampling"]["confirm_samples"], - boot["sampling"]["nvidia_smi_timeout_s"], boot["validity_band"]["limit_floor_w"], - boot["validity_band"]["arms_mean_limit_within_w"], boot["validity_band"]["spread_within_arm_w"]) - except KeyError as exc: - print("bootstrap lacks field %s" % exc, file=sys.stderr) - return 1 - print(line) - return 0 - - -def main(argv=None): - parser = argparse.ArgumentParser(description="STRA-256 S3.1 checks (offline, stdlib only)") - parser.add_argument("--validate", metavar="FILE") - parser.add_argument("--rules", action="store_true") - parser.add_argument("--criteria", action="store_true") - parser.add_argument("--self-test", dest="self_test", action="store_true") - parser.add_argument("--bootstrap-fields", dest="bootstrap_fields", action="store_true") - parser.add_argument("--schema", default=DEFAULT_SCHEMA) - parser.add_argument("--bootstrap", default=DEFAULT_BOOTSTRAP) - parser.add_argument("--page", default=DEFAULT_PAGE) - parser.add_argument("--scripts-dir", dest="scripts_dir", default=DEFAULT_SCRIPTS) - args = parser.parse_args(argv) - if args.validate: - code = cmd_validate(args, args.validate) - if code == 0: - print("%s valid against schema" % args.validate) - return code - if args.rules: - return cmd_rules(args) - if args.criteria: - return cmd_criteria(args) - if args.self_test: - return cmd_self_test(args) - if args.bootstrap_fields: - return cmd_bootstrap_fields(args) - return cmd_bootstrap(args) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/docs/experiments/2026-10-28-s3-1-laptop-safety-protocol.md b/docs/experiments/2026-10-28-s3-1-laptop-safety-protocol.md deleted file mode 100644 index f7126763..00000000 --- a/docs/experiments/2026-10-28-s3-1-laptop-safety-protocol.md +++ /dev/null @@ -1,163 +0,0 @@ -# S3.1 Laptop safety protocol, owner-precondition checklist and thresholds schema (STRA-256) - -Date: 2026-10-28. Leaf STRA-256 of STRA-245. Branch `claude/stra-256`, based on `claude/merge-opt` at `2457d81`. -Machine: any (this page is read, nothing on it is executed on the laptop). This leaf observes nothing and measures nothing. - -Files of this leaf (the only four paths it adds): - -- this page; -- `docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json`, the SCHEMA of the thresholds file (the measured values come from S3.7, STRA-292 validates the S3.7 file against this schema); -- `docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json`, a START-UP instance of that schema; -- `docs/experiments/2026-10-28-s3-1-check_bootstrap.py`, a stdlib-only (Python 3.9) checker. - -Consumers: STRA-291 (watchdog), STRA-292 (validates the S3.7 thresholds file with `check_bootstrap.py --validate`), STRA-319 (`state.ps1`, the read-only reader), STRA-254. - -Sources read for this page: the scripts `scripts/laptop/monitor.sh` and `scripts/laptop/lap_run.sh` (guard), `scripts/dev/laptop-turbo.ps1` (owner setter), `docs/laptop-vs-vanilla.md` sections 1, 11 and 13, and the standing conventions SC3 and SC10 of STRA-245. - -## 1. Owner preconditions - -The laptop has had two BSODs (0x19C WIN32K_POWER_WATCHDOG_TIMEOUT, 2026-10-16 and 2026-10-23) under the OEM 30 W profile. Every precondition below is performed by the OWNER. No agent step sets any of them. An agent only READS and records. - -If a precondition is not met the agent stops without changing anything and records 'owner precondition not met'. An agent never changes a power, display, lock or sleep setting. - -### 1.1 The setter, cited as owner-run only - -`scripts/dev/laptop-turbo.ps1` is the OWNER-RUN SETTER, started by the owner, never by an agent: `powershell -ExecutionPolicy Bypass -File scripts\dev\laptop-turbo.ps1`. It is NOT a reader. What it does: - -- `powercfg /setactive ` (owner-run, inside laptop-turbo.ps1); -- `powercfg /change standby-timeout-ac 0`, `hibernate-timeout-ac 0` and `monitor-timeout-ac 0` (owner-run, inside laptop-turbo.ps1); -- `powercfg /setacvalueindex SUB_VIDEO VIDEOCONLOCK 0` (owner-run, inside laptop-turbo.ps1); -- it prints only the active scheme and one `nvidia-smi` line (name, `enforced.power.limit`, `power.max_limit`, SM clock, pstate). It does not print the sleep, hibernate or display timeouts and does not read the lock / sign-in requirement. - -Armoury Crate sets the GPU power limit (its performance mode); a script cannot. The script leaves the sign-in requirement to Settings. - -### 1.2 Checklist - -READ is the read-only command an agent runs through STRA-319 (`state.ps1`), or 'owner attestation only' where no read-only command exists. The agent records the output and compares it with EXPECTED VALUE. - -| # | Precondition (owner-run) | READ (agent, read-only) | EXPECTED VALUE | -| --- | --- | --- | --- | -| P1 | OEM Turbo scheme active | `powercfg /getactivescheme` | scheme name `Turbo` (note its GUID for P3, P4) | -| P2 | GPU power mode (Armoury Crate Turbo / Manual) | `nvidia-smi --query-gpu=enforced.power.limit,pstate --format=csv,noheader` | `enforced.power.limit` at or above 100 W (last seen 138.94 W after an owner run of the script; the state since then is unknown) and pstate not P5 at idle. That Turbo is selected in Armoury Crate beyond the limit it produces: owner attestation only | -| P3 | Charger connected | `Get-CimInstance Win32_Battery \| Select-Object BatteryStatus` | `BatteryStatus` 2 (on AC); no Win32_Battery instance: owner attestation only | -| P4 | Sleep and hibernate timeouts off on AC | `powercfg /q SUB_SLEEP` (settings STANDBYIDLE, HIBERNATEIDLE) | Current AC Power Setting Index `0x00000000` for both | -| P5 | Display-off timeouts off on AC | `powercfg /q SUB_VIDEO` (settings VIDEOIDLE, VIDEOCONLOCK) | Current AC Power Setting Index `0x00000000` for both | -| P6 | Lock / sign-in requirement | owner attestation only | Settings > Accounts > Sign-in options > 'require sign-in' = Never | -| P7 | Screen unlocked, session logged in | owner attestation only | unlocked at the start of every laptop GPU job and not locked by the owner during it | -| P8 | Owner has acknowledged the BSOD history and the exposure budget of section 6 | owner attestation only (recorded by the orchestrator) | acknowledgement naming the larger figure of section 6 | - -Notes: - -- The setter's commands appear in this page only in section 1.1, each labelled owner-run; no agent step sets any of them. -- P2 reads `enforced.power.limit`, not `power.limit` (section 4). -- A read that fails, is empty or is N/A is 'precondition not met' (fail closed), not 'assume fine'. -- The laptop state is unknown today (owner, 2026-10-28: 'До ноута я не підходив ще'); no laptop GPU job starts until the owner has run the setter and the orchestrator has recorded the P1-P8 reads. - -## 2. Stop and resume rules (SC3) - -Each rule is marked `field` (a field of the thresholds schema, checked by `check_bootstrap.py`) or `numeric` (an exact numeric sentence, checked by text). `python docs/experiments/2026-10-28-s3-1-check_bootstrap.py --rules` prints one line per rule. - -| id | marker | schema field | rule (exact sentence) | -| --- | --- | --- | --- | -| R01 | numeric | `retry.max_reruns_per_arm_slot` | At most one re-run per arm slot. | -| R02 | numeric | `retry.consecutive_invalid_pairs_end_block` | Two consecutive invalid pairs end the block. | -| R03 | field | `cooldown.between_arms_s` | Cool-down 120 s between arms. | -| R04 | field | `cooldown.after_abort_s` | Cool-down 600 s after any abort. | -| R05 | field | `halt.on_events` | The first BSOD, unexpected reboot or STALL stops all laptop GPU work. | -| R06 | field | `resume.requires_orchestrator_recorded_owner_inspection` | Nothing resumes until the orchestrator records that the owner inspected the machine. | -| R07 | field | `resume.source` | Resume is from the pair ledger. | -| R08 | field | `resume.interrupted_pair_invalid` | A pair interrupted by a crash is invalid. | -| R09 | field | `lock.one_gpu_job_at_a_time` | One laptop GPU job at a time (lock file). | -| R10 | field | `preconditions.on_unmet` | If a precondition is not met the agent stops without changing anything and records 'owner precondition not met'. | -| R11 | numeric | `under_load.stall_gap_s` | A gap of more than 10 s between two samples is a STALL and aborts the run. | -| R12 | numeric | `run.cap_minutes` | Under BOOTSTRAP a run is capped at 15 minutes. | - -R01-R10 are SC3 verbatim in substance; R11 is the monitor.sh stall rule SC3 refers to; R12 is the BOOTSTRAP cap of section 5. The native-Windows watchdog (S3.8, STRA-291) is mandatory for every laptop GPU job; its thresholds come from S3.7. - -## 3. The thresholds file schema - -`docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json`. The numeric constraints are FLOORS: a file may be stricter than the scripts, never looser (a floor removed or lowered makes the file invalid; `--self-test` proves it with 16 mutations). - -IDLE-PREFLIGHT conditions are separated from UNDER-LOAD conditions, because P5 means different things in each: at idle P5 refuses the run; under load P5 together with a low memory clock and a throttle reason is the OEM-profile signature that aborts it (monitor.sh does not abort a plain P5 with reason 0x1 'idle' while the model is being loaded into VRAM, a clock ramp seen in T1_short). - -| block | field | floor | taken from | action | -| --- | --- | --- | --- | --- | -| `idle_preflight` | `limit_min_w` | >= 100 W | lap_run.sh `l+0 >= 100` | refuse | -| `idle_preflight` | `sw_power_cap_active_refuses`, `sw_thermal_slowdown_active_refuses` | true | lap_run.sh: SW Power Cap / SW Thermal Slowdown `: Active` at idle | refuse | -| `idle_preflight` | `p5_refuses` | true | lap_run.sh: performance state P5 at idle | refuse | -| `under_load` | `power_limit_floor_w` | limit < 100 W | monitor.sh `l+0 < 100` | kill, abort file | -| `under_load` | `temperature_ceiling_c` | > 90 C | monitor.sh `-gt 90` | kill, abort file | -| `under_load` | `stall_gap_s` | > 10 s | monitor.sh `now - prev ... -gt 10` | kill, STALL, all GPU work stops | -| `under_load.oem_profile` | `pstate`, `memory_clock_mhz_below`, `throttle_reason_bits` | P5, memory clock < 2000 MHz, throttle mask 0x4 (SW power cap) and 0x20 (SW thermal slowdown) = 0x24 | monitor.sh `= P5 ... -lt 2000 ... & 0x24` | kill, abort file | -| `run` | `timeout_source` | `caller_parameter` | lap_run.sh `RUN_TIMEOUT:-900` is replaced: a 900 s default would kill a ~1,300 s arm | timeout set by the caller | -| `cooldown` | `between_arms_s` | >= 120 s | lap_run.sh `COOLDOWN:-120` | wait | -| `cooldown` | `after_abort_s` | >= 600 s | SC3 | wait | -| `lock` | `method`, `path` | `mkdir` (or an exclusive create of the same name on native Windows), `$HOME/LAPTOP_GPU.lock` | lap_run.sh `mkdir "$HOME/LAPTOP_GPU.lock"` | one laptop GPU job at a time | -| `sampling` | `confirm_samples` | >= 1, default 1 | monitor.sh triggers on the first sample; S3.7 may raise it | - | -| `sampling` | `nvidia_smi_timeout_s` | 1..5 | F12: a call that exceeds 5 s counts as a missing sample | fail closed | -| `sampling` | `stall_check_off_sampler_thread` | true | F12: a hung nvidia-smi cannot hide a stall | - | -| `unreadable` | `preflight`, `run` | `REFUSE`, `ABORT` | section 4 | fail closed | -| `validity_band` | `limit_floor_w`, `arms_mean_limit_within_w`, `spread_within_arm_w` | 100 W, <= 10 W, <= 20 W | E2 stable-limit band (BA round 2 D7) | pair validity, section 7 | -| `records` | `must_carry`, `countable_under_bootstrap` | `thresholds_source`, `thresholds_sha256`; false | F12 | section 5 | - -`python docs/experiments/2026-10-28-s3-1-check_bootstrap.py --criteria` prints one row per criterion and greps each number in `scripts/laptop/monitor.sh` or `scripts/laptop/lap_run.sh`, with the line, so a reviewer can diff them. - -## 4. Divergence from the scripts - -`monitor.sh` queries `power.limit` (`--query-gpu=...,power.limit,...`) and `lap_run.sh` preflight parses 'Current Power Limit' of `nvidia-smi -q`. On the laptop GPU `power.limit` is N/A (commit 96484f0: only `enforced.power.limit` works; `laptop-turbo.ps1` reads it for that reason). The consequences on the target machine: - -- `monitor.sh`: the reading is empty, `${lim:-0}` becomes 0, and the test `l > 0 && l < 100` is false, so its 'limit below 100 W' check can NEVER fire. `docs/laptop-vs-vanilla.md` section 13 records a drop from 110-126 W to 51 W (P3) that the guard did not catch. -- `lap_run.sh`: the reading is empty, so the preflight REFUSES every run (`REFUSED: power limit ?`). - -A thresholds file that copied 'exactly the monitor.sh floors' would copy a check that is dead on the target. Therefore: - -- the schema field `power_limit_source` is `enforced.power.limit` (the only allowed value, default); the value 100 W is kept on that source; -- an N/A, empty or non-numeric reading FAILS CLOSED, in preflight (the run is refused) and during the run (the run is aborted): `unreadable.preflight` = `REFUSE`, `unreadable.run` = `ABORT`; -- the two scripts are not edited by this leaf (SC10: they are PORTED by S3.8, not reused silently and not dropped); the port must read `power_limit_source`. - -## 5. The BOOTSTRAP instance (F12) - -`docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json` reproduces every criterion of section 3 on the enforced limit. It breaks the deadlock between the watchdog (STRA-291), which needs thresholds, and S3.7, which measures them with the watchdog. It is START-UP ONLY: - -- Under BOOTSTRAP a run is capped at 15 minutes (`run.cap_minutes` = 15). -- Every record carries `thresholds_source` and the sha256 of the thresholds file (`records.must_carry`). -- The validator (STRA-246) rejects a countable pair recorded under BOOTSTRAP (`records.countable_under_bootstrap` is false). -- Basis of the 100 W floor: the recorded good run at 110.0-126.6 W (`docs/laptop-vs-vanilla.md` section 11, `g2-vanilla-noskip`) and the bad event at 51 W (section 13). -- `confirm_samples` is 1 (monitor.sh's immediate trigger); the per-call `nvidia-smi` timeout is 5 s and counts as a missing sample; the stall is checked off the sampler's thread. - -`python docs/experiments/2026-10-28-s3-1-check_bootstrap.py --bootstrap-fields` prints these START-UP fields. - -## 6. Exposure budget - -From the arm times of `docs/laptop-vs-vanilla.md` (ours 1,226 s run A and 1,281 s run A3, mean about 1,253 s; vanilla default 1,341 s; vanilla with the skip off 1,416.6 s, sections 1, 4, 10 and 11) one 3-arm block is 4,010 s, plus three 120 s cool-downs. - -- The 30-pair series: 30 x (4,010 + 3 x 120) s = 36.4 h wall and 33.4 GPU-hours (30 x 4,010 s). With re-runs about 45-49 h wall. -- Diagnostics and sweeps: about 10 GPU-hours. -- PLUS about 21.7 GPU-hours for every alternative that does not exit as SLOWER and for every FIXED end-to-end component (30 pairs x 2 arms x 1,300 s; BA comment dabfd08e). - -The owner's acknowledgement (OR4, precondition P8) must name the larger figure: 33.4 + 10 GPU-hours for the series and diagnostics, plus 21.7 GPU-hours per such alternative or fixed component. - -These are planning figures from the cited arm times, not measurements of this leaf. - -## 7. Validity band of E2 - -The 'stable limit' of E2 is a schema block `validity_band`, applied to the power-limit sample series after a run (validity, not safety; abort is section 3): the limit stays at or above 100 W, the means of the limits of the arms of a pair are within 10 W, and the spread within one arm is at most 20 W (BA round 2 D7). The recorded good run (110.0-126.6 W, spread 16.6 W) is inside the band. `--bootstrap-fields` prints `band=100/10/20`. - -## 8. Checks - -Run from the repository root, Python 3.9, no packages: - -| command | expected | -| --- | --- | -| `python docs/experiments/2026-10-28-s3-1-check_bootstrap.py` | exit 0, `bootstrap valid against schema` | -| `... --validate ` | exit 0 when the file validates (STRA-292) | -| `... --rules` | exit 0, one line per rule of section 2 | -| `... --criteria` | exit 0, one row per criterion of section 3 with the script line | -| `... --self-test` | exit 0, every mutated bootstrap rejected | -| `... --bootstrap-fields` | exit 0, `thresholds_source=BOOTSTRAP run_cap_minutes=15 confirm_samples=1 nvidia_smi_timeout_s=5 band=100/10/20` | - -## 9. Not verified here - -- Nothing was run on the laptop; no `nvidia-smi`, `powercfg` or Win32_Battery read was made. The commands of section 1.2 are the ones the leaf prescribes; their exact output format on the laptop is checked by STRA-319. -- The scripts' behaviour on N/A is derived from reading them and from commit 96484f0, not from a run. -- The arm times of section 6 are those of the cited documents; the 1,300 s per arm and the 21.7 GPU-hours are the planning figures of STRA-245. diff --git a/docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json b/docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json deleted file mode 100644 index b5309e49..00000000 --- a/docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "schema_version": 1, - "thresholds_source": "BOOTSTRAP", - "power_limit_source": "enforced.power.limit", - "unreadable": {"preflight": "REFUSE", "run": "ABORT"}, - "sampling": { - "interval_s": 1, - "nvidia_smi_timeout_s": 5, - "timeout_counts_as_missing_sample": true, - "stall_check_off_sampler_thread": true, - "confirm_samples": 1 - }, - "idle_preflight": { - "limit_min_w": 100, - "sw_power_cap_active_refuses": true, - "sw_thermal_slowdown_active_refuses": true, - "p5_refuses": true - }, - "under_load": { - "power_limit_floor_w": 100, - "temperature_ceiling_c": 90, - "stall_gap_s": 10, - "oem_profile": {"pstate": "P5", "memory_clock_mhz_below": 2000, "throttle_reason_bits": [4, 32]} - }, - "run": {"timeout_source": "caller_parameter", "cap_minutes": 15}, - "cooldown": {"between_arms_s": 120, "after_abort_s": 600}, - "retry": {"max_reruns_per_arm_slot": 1, "consecutive_invalid_pairs_end_block": 2}, - "halt": {"on_events": ["BSOD", "UNEXPECTED_REBOOT", "STALL"], "scope": "ALL_LAPTOP_GPU_WORK"}, - "resume": { - "requires_orchestrator_recorded_owner_inspection": true, - "source": "pair_ledger", - "interrupted_pair_invalid": true - }, - "lock": {"method": "mkdir", "path": "$HOME/LAPTOP_GPU.lock", "one_gpu_job_at_a_time": true}, - "preconditions": {"on_unmet": "STOP_NO_CHANGE_RECORD_OWNER_PRECONDITION_NOT_MET", "agent_may_change_settings": false}, - "validity_band": {"limit_floor_w": 100, "arms_mean_limit_within_w": 10, "spread_within_arm_w": 20}, - "records": {"must_carry": ["thresholds_source", "thresholds_sha256"], "countable_under_bootstrap": false}, - "basis": { - "limit_floor_w": "recorded good run 110.0-126.6 W (docs/laptop-vs-vanilla.md section 11) against the bad event at 51 W (section 13)", - "floors": "scripts/laptop/monitor.sh and scripts/laptop/lap_run.sh at claude/merge-opt 2457d81", - "start_up_only": "BOOTSTRAP serves STRA-254 and STRA-292 until S3.7 supplies measured values; no countable pair is recorded under it" - } -} diff --git a/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json b/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json deleted file mode 100644 index a373db22..00000000 --- a/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json +++ /dev/null @@ -1,186 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "leleka/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json", - "title": "Laptop GPU watchdog thresholds (STRA-256 S3.1)", - "description": "Schema of the thresholds file read by the native-Windows watchdog (STRA-291), validated by STRA-292 and filled with measured values by S3.7. Every numeric constraint is a FLOOR taken from scripts/laptop/monitor.sh (runtime) or scripts/laptop/lap_run.sh (preflight): a file may be stricter, never looser. Interpreted by docs/experiments/2026-10-28-s3-1-check_bootstrap.py (stdlib only). Extra keyword x-mustContain: the array must contain every listed value.", - "type": "object", - "additionalProperties": false, - "required": [ - "schema_version", "thresholds_source", "power_limit_source", "unreadable", "sampling", - "idle_preflight", "under_load", "run", "cooldown", "retry", "halt", "resume", "lock", - "preconditions", "validity_band", "records" - ], - "properties": { - "schema_version": {"const": 1}, - "thresholds_source": { - "enum": ["BOOTSTRAP", "S3.7"], - "description": "BOOTSTRAP = the start-up instance of STRA-256 (cap 15 minutes per run, never countable); S3.7 = measured values." - }, - "power_limit_source": { - "enum": ["enforced.power.limit"], - "default": "enforced.power.limit", - "description": "nvidia-smi field the power limit is read from. power.limit is N/A on the laptop GPU (commit 96484f0), so it is not an allowed value; the scripts monitor.sh and lap_run.sh read it and diverge here (page, section 'Divergence from the scripts')." - }, - "unreadable": { - "type": "object", - "additionalProperties": false, - "required": ["preflight", "run"], - "description": "FAIL CLOSED: an N/A, empty or non-numeric reading of power_limit_source (or of any field a rule needs) refuses the run in preflight and aborts it during the run.", - "properties": { - "preflight": {"const": "REFUSE"}, - "run": {"const": "ABORT"} - } - }, - "sampling": { - "type": "object", - "additionalProperties": false, - "required": ["interval_s", "nvidia_smi_timeout_s", "timeout_counts_as_missing_sample", "stall_check_off_sampler_thread", "confirm_samples"], - "properties": { - "interval_s": {"type": "integer", "minimum": 1, "maximum": 1, "description": "monitor.sh samples at 1 Hz (MON_INTERVAL default 1)."}, - "nvidia_smi_timeout_s": {"type": "integer", "minimum": 1, "maximum": 5, "description": "Per-call nvidia-smi timeout; a timeout counts as a missing sample (fail closed)."}, - "timeout_counts_as_missing_sample": {"const": true}, - "stall_check_off_sampler_thread": {"const": true, "description": "The stall gap is checked by a thread other than the sampler, so a hung nvidia-smi cannot hide a stall."}, - "confirm_samples": {"type": "integer", "minimum": 1, "default": 1, "description": "Consecutive samples a runtime condition must hold before the abort. 1 = monitor.sh's immediate trigger (default); S3.7 may raise it."} - } - }, - "idle_preflight": { - "type": "object", - "additionalProperties": false, - "required": ["limit_min_w", "sw_power_cap_active_refuses", "sw_thermal_slowdown_active_refuses", "p5_refuses"], - "description": "Conditions checked at IDLE, before the run (lap_run.sh preflight). A violation REFUSES the run (exit 4 in the script).", - "properties": { - "limit_min_w": {"type": "number", "minimum": 100, "description": "Refuse unless enforced limit >= this (lap_run.sh: l+0 >= 100)."}, - "sw_power_cap_active_refuses": {"const": true}, - "sw_thermal_slowdown_active_refuses": {"const": true}, - "p5_refuses": {"const": true, "description": "At idle a P5 state is a refusal."} - } - }, - "under_load": { - "type": "object", - "additionalProperties": false, - "required": ["power_limit_floor_w", "temperature_ceiling_c", "stall_gap_s", "oem_profile"], - "description": "Conditions checked WHILE the job runs (monitor.sh). A violation kills the job and writes the abort file.", - "properties": { - "power_limit_floor_w": {"type": "number", "minimum": 100, "description": "Abort when enforced limit < this (monitor.sh: l > 0 && l < 100). With N/A the script's test never fires; here an unreadable value aborts (unreadable.run)."}, - "temperature_ceiling_c": {"type": "number", "maximum": 90, "exclusiveMinimum": 0, "description": "Abort when temperature > this (monitor.sh: -gt 90)."}, - "stall_gap_s": {"type": "number", "maximum": 10, "exclusiveMinimum": 0, "description": "Abort and STALL when two consecutive samples are more than this far apart (monitor.sh: -gt 10)."}, - "oem_profile": { - "type": "object", - "additionalProperties": false, - "required": ["pstate", "memory_clock_mhz_below", "throttle_reason_bits"], - "description": "Under load, P5 with a low memory clock and a SW power cap / SW thermal slowdown reason is the OEM profile signature.", - "properties": { - "pstate": {"const": "P5"}, - "memory_clock_mhz_below": {"type": "integer", "minimum": 2000, "description": "monitor.sh: memory clock < 2000 MHz."}, - "throttle_reason_bits": { - "type": "array", - "minItems": 2, - "items": {"type": "integer", "minimum": 1}, - "x-mustContain": [4, 32], - "description": "clocks_throttle_reasons.active bits: 0x4 SW power cap, 0x20 SW thermal slowdown (mask 0x24)." - } - } - } - } - }, - "run": { - "type": "object", - "additionalProperties": false, - "required": ["timeout_source"], - "properties": { - "timeout_source": {"const": "caller_parameter", "description": "lap_run.sh's RUN_TIMEOUT default 900 s would kill a ~1,300 s arm; the ported watchdog takes the timeout from its caller."}, - "cap_minutes": {"type": "integer", "minimum": 1, "maximum": 15, "description": "Hard cap per run. Required for BOOTSTRAP (15)."} - } - }, - "cooldown": { - "type": "object", - "additionalProperties": false, - "required": ["between_arms_s", "after_abort_s"], - "properties": { - "between_arms_s": {"type": "integer", "minimum": 120, "description": "lap_run.sh COOLDOWN default 120; SC3."}, - "after_abort_s": {"type": "integer", "minimum": 600, "description": "SC3: 600 s after any abort."} - } - }, - "retry": { - "type": "object", - "additionalProperties": false, - "required": ["max_reruns_per_arm_slot", "consecutive_invalid_pairs_end_block"], - "properties": { - "max_reruns_per_arm_slot": {"type": "integer", "minimum": 0, "maximum": 1}, - "consecutive_invalid_pairs_end_block": {"type": "integer", "minimum": 1, "maximum": 2} - } - }, - "halt": { - "type": "object", - "additionalProperties": false, - "required": ["on_events", "scope"], - "properties": { - "on_events": {"type": "array", "minItems": 3, "items": {"enum": ["BSOD", "UNEXPECTED_REBOOT", "STALL"]}, "x-mustContain": ["BSOD", "UNEXPECTED_REBOOT", "STALL"]}, - "scope": {"const": "ALL_LAPTOP_GPU_WORK"} - } - }, - "resume": { - "type": "object", - "additionalProperties": false, - "required": ["requires_orchestrator_recorded_owner_inspection", "source", "interrupted_pair_invalid"], - "properties": { - "requires_orchestrator_recorded_owner_inspection": {"const": true}, - "source": {"const": "pair_ledger"}, - "interrupted_pair_invalid": {"const": true} - } - }, - "lock": { - "type": "object", - "additionalProperties": false, - "required": ["method", "path", "one_gpu_job_at_a_time"], - "properties": { - "method": {"enum": ["mkdir", "exclusive_create"], "description": "lap_run.sh: mkdir $HOME/LAPTOP_GPU.lock (atomic directory). The native-Windows port may use an exclusive create of the same name."}, - "path": {"type": "string", "minLength": 1}, - "one_gpu_job_at_a_time": {"const": true} - } - }, - "preconditions": { - "type": "object", - "additionalProperties": false, - "required": ["on_unmet", "agent_may_change_settings"], - "properties": { - "on_unmet": {"const": "STOP_NO_CHANGE_RECORD_OWNER_PRECONDITION_NOT_MET"}, - "agent_may_change_settings": {"const": false} - } - }, - "validity_band": { - "type": "object", - "additionalProperties": false, - "required": ["limit_floor_w", "arms_mean_limit_within_w", "spread_within_arm_w"], - "description": "E2 'stable limit' band (BA round 2 D7), applied to the sample series AFTER the run; it is validity, not safety.", - "properties": { - "limit_floor_w": {"type": "number", "minimum": 100}, - "arms_mean_limit_within_w": {"type": "number", "exclusiveMinimum": 0, "maximum": 10}, - "spread_within_arm_w": {"type": "number", "exclusiveMinimum": 0, "maximum": 20} - } - }, - "records": { - "type": "object", - "additionalProperties": false, - "required": ["must_carry", "countable_under_bootstrap"], - "properties": { - "must_carry": {"type": "array", "items": {"type": "string"}, "x-mustContain": ["thresholds_source", "thresholds_sha256"]}, - "countable_under_bootstrap": {"const": false} - } - }, - "basis": { - "type": "object", - "description": "Free text: where the numbers come from. Not interpreted." - } - }, - "allOf": [ - { - "if": {"properties": {"thresholds_source": {"const": "BOOTSTRAP"}}, "required": ["thresholds_source"]}, - "then": { - "properties": { - "run": {"required": ["cap_minutes"], "properties": {"cap_minutes": {"const": 15}}} - } - } - } - ] -} diff --git a/docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md b/docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md deleted file mode 100644 index 9b24a55c..00000000 --- a/docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md +++ /dev/null @@ -1,112 +0,0 @@ -# S3.5 sm_86 exact-speed-switch audit (STRA-249) - -Static comparison of the sm_86 speed switches that vanilla Strata turns on by default against our counterparts. Reading only: no build, -no GPU job, no code change, no measurement. A gap found here is a second-wave leaf, not a fix in this leaf. - -## 1. Basis - -| Item | Value | -| --- | --- | -| Source read | `engine/strata/` in the branch worktree `.git/wt/stra-249` (branch `claude/stra-249`, cut from `claude/merge-opt` at `2457d81d`), never the main checkout | -| Upstream pin | `41cf05a06a25dd29103b7b27a2279a3f60c21876` (engine 0.1.50, app 0.2.5), `docs/upstream.md` "Current pin" | -| Cited lines | all file:line cites below are lines of that tree; the check command of section 6 prints nothing | -| Out of scope | identifying a kernel from our sealed PTX (hashed entry names); any timing; any quality run | - -## 2. Counts, side by side - -| Source | Count | Names | -| --- | --- | --- | -| `sed -n '26,34p' engine/strata/src/core/nv_defaults.cpp` (inside the `mj == 8 && mn == 6` block, opened at `engine/strata/src/core/nv_defaults.cpp:21`, off switch `:22`) | 9 | ADAPT_NOWAIT, ADAPT_LAG=2, CPU_IQ_ALL_EXACT1, SIDE_MIXER=2, ATTN_DAILY, GR_UP75, GU_SWIGLU, QSA_ROWS, B6_MMVQ_ROWS | -| the start-up line, `engine/strata/src/core/nv_defaults.cpp:65` (prints `set.size()`, which skips a switch the user already set, `:55`) | 9 on an untouched sm_86 environment | the same nine (the name list is printed at `:67`) | -| `docs/laptop-vs-vanilla.md` line 24 | 9 | the same nine | -| `docs/upstream-digest-2026-10-25.md` line 80 (section 1.3) | 10 | the nine plus DEQUANT_WIDE | -| this page | 12 rows | the nine, DEQUANT_WIDE (row 10), and two further sm_86-keyed defaults found by source search (rows 11, 12) | - -Why the digest has ten and the engine prints nine: DEQUANT_WIDE is NOT in the `nv_defaults.cpp` table. Its sm_86 default lives in the kernel file -(`engine/strata/src/kernels/cuda/dequant_bf16.cu:284`, cc 6.1 or 8.6 at `:295`), so `STRATA_SM86_PERF=0` does not turn it off (only `STRATA_DEQUANT_WIDE=0` does, -`:285`) and the start-up line does not list it. - -Command 2 of the leaf, `grep -rn "SM86_PERF" engine/strata/src`, prints exactly three lines, all in `nv_defaults.cpp` (`:22` the table's off switch, `:66` the message, `:82` -the off switch of `apply_spec_adapt_default`, which is opt-in and not part of the nine): - -``` -engine/strata/src/core/nv_defaults.cpp:22: if (off("STRATA_SM86_PERF")) return t; -engine/strata/src/core/nv_defaults.cpp:66: sm86 ? "sm_86 (Ampere)" : "sm_60 (Pascal)", set.size(), sm86 ? "STRATA_SM86_PERF" : "STRATA_SM60_PERF"); -engine/strata/src/core/nv_defaults.cpp:82: if (off("STRATA_SM86_PERF")) return; -``` - -How the table is applied: `engine/strata/src/program/generate.cpp:2889` calls `apply_nv_defaults` only when every visible CUDA device has the same compute capability. -On the laptop RTX 3080 (sm_86, one GPU) that holds. A second search for other per-card switches (`major == 8 && minor == 6`, `sm86`, `sm_86`) found rows 10, 11 and 12 and -nothing else; `engine/strata/src/core/arch_defaults.cpp:126` prints a similar line but only for gfx12 / gfx1151 (AMD), not sm_86. - -## 3. Legends - -Speed: `ours slower` / `ours equal` / `ours faster` / `unknown`. At delivery every speed cell is `unknown`: a speed claim cannot be made from reading alone. - -Lossless: every cell is a reading of source comments and code ("by source reading"). It is NOT the tensor or greedy comparison that `AGENTS.md` requires for a real non-lossy claim. -The vendor's own claim is quoted where it exists (`engine/strata/include/strata/core/nv_defaults.hpp:4`: a switch is in the table only when "its token ids equal the default's"). - -Counterpart: a lookup in `docs/upstream-port-plan.md` rows 2.1 and 2.2 (lines 38-39, quoted in section 4) plus the diff list at lines 255-290, row 2.4 (line 41), row 3.3 (line 51), -and a grep of `crates/` (command and result stated in the cell). `none` = no row and no grep hit. - -Owner: the port-plan row. STRA-221 is the tracker item for the sm_86 companions of sealed PTX (STRA-221, Backlog); it is named only where no port-plan row exists, and is not an owner table. - -## 4. The table - -| # | Switch (value) | Default-on evidence | Kernel or path selected (vanilla) | Our counterpart | Lossless (by source reading) | Speed (ours vs vanilla) | Owner | -| --- | --- | --- | --- | --- | --- | --- | --- | -| 1 | `STRATA_ADAPT_NOWAIT=1` | `engine/strata/src/core/nv_defaults.cpp:26` | no kernel; host policy: a verify window starts before the adaptive expert tier's copies have landed (`engine/strata/src/program/generate.cpp:1539`; users `:10237`, `:10329`) | none implemented: port-plan row 3.3 (line 51, status todo) names ADAPT_LAG but not NOWAIT; grep `ADAPT_NOWAIT\|NOWAIT` in `crates/`: 0 hits | NOT established, by source reading: `engine/strata/src/program/generate.cpp:10329` says evictions reach the device table before the copies land and the pool computes an evicted expert from the earlier activation, so which device rounds an expert can change; the vendor table header claims equal token ids (`nv_defaults.hpp:4`), the digest (1.3) says "adapt flags yes" change output. Not recommended for default until a greedy comparison | unknown (no speed claim from reading) | port-plan row 3.3 | -| 2 | `STRATA_ADAPT_LAG=2` | `engine/strata/src/core/nv_defaults.cpp:27` | no kernel; host policy: a window takes the tier's swaps only when 2 windows old (`engine/strata/src/program/generate.cpp:1549`; user `:10237`) | none implemented: port-plan row 3.3 (line 51, status todo); grep `ADAPT_LAG\|adapt_lag` in `crates/`: 0 hits | NOT established, by source reading: the comment at `engine/strata/src/program/generate.cpp:1546` says the answers are "as reproducible" as lag 1, i.e. deterministic in window count, not equal to lag 1; swapped-in experts reach the GPU one window later than at lag 1. Not recommended for default until a greedy comparison | unknown (no speed claim from reading) | port-plan row 3.3 | -| 3 | `STRATA_CPU_IQ_ALL_EXACT1=1` | `engine/strata/src/core/nv_defaults.cpp:28` | CPU: `iq256_gu_rows_exact_one` for a one-token gate/up row of IQ types 16, 17, 18, 21, 22 (`engine/strata/src/kernels/cpu/native_expert.cpp:329`, call `:333`). Gate `:323-325` needs ggml-cpu built for AVX2 and not AVX-512, and `:329` needs `!cpu_avx512_ok()`, so on an AVX-512 core it is inert unless `STRATA_FORCE_AVX2=1` (source reading; the log line `strata ab: GATE=STRATA_CPU_IQ_ALL_EXACT1 active=1` at `:332` shows when it fires) | none: grep `exact_one\|EXACT1\|ALL_EXACT` in `crates/` gives only an unrelated `exact128-slot` comment at `crates/cuda-driver/src/original_expert_slots.rs:206`; the vendored `crates/native-cpu-expert/src/native_expert.cpp` has 0 matches of `exact_one`; no port-plan row (row 2.3 does not name it) | equal output claimed, by source reading: `engine/strata/src/kernels/cpu/native_expert.cpp:320` says the rows are ggml-cpu's AVX2 single-token dot "bit for bit" | unknown (no speed claim from reading; may be inert on both of our AVX-512 hosts, which STRA-247 and STRA-271 can read off the vanilla start-up log) | no port-plan row; STRA-221 tracker; second-wave candidate only if the switch is active | -| 4 | `STRATA_SIDE_MIXER=2` | `engine/strata/src/core/nv_defaults.cpp:29` | no new kernel; scheduling: the mixer's input-only work (GDN gates, QSA indexer chain, gate projection, QSA queries) on side streams inside the verify graph (`engine/strata/src/core/verify.cpp:189`; uses `:1145`, `:1069`; side stream member `engine/strata/include/strata/core/verify.hpp:552`) | none implemented: port-plan row 2.1 and diff-list line 271 say MISSING (our window is one stream); grep `SIDE_MIXER\|side_mixer` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/core/verify.cpp:187` "bitwise the same outputs" (scheduling only) | unknown (no speed claim from reading; the port-plan estimate of 300-700 us is an estimate, not a measurement) | port-plan row 2.1 | -| 5 | `STRATA_ATTN_DAILY=1` | `engine/strata/src/core/nv_defaults.cpp:30` | CUDA decode attention: chunk pass `attn_chunk_kernel_pre75` (`engine/strata/src/kernels/cuda/qsa_decode_attn.cu:561`, selected via `daily_attn` `:854` and `pre75_attn` `:882`) and the merge `attn_merge_v2_kernel` (`:943`, follows ATTN_DAILY) | none implemented: port-plan row 2.1 and diff-list line 269 say MISSING (ours is the old decode chunk kernel); grep `ATTN_DAILY\|attn_daily` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/qsa_decode_attn.cu:849` "bit for bit the default kernel's partials"; the merge is "bitwise the same output" (`:951`) | unknown (no speed claim from reading) | port-plan row 2.1 | -| 6 | `STRATA_GR_UP75=1` | `engine/strata/src/core/nv_defaults.cpp:31` | CUDA hyper-connection up projection: `gr_up75_kernel` for 3 or more tokens (`engine/strata/src/kernels/cuda/fused_gr.cu:442`, launched `:1350`, gate `up75_on` `:1193`) | partial: port-plan row 2.1 and diff-list line 272 say PARTIAL (`chain_gr_up8/16` already hoist the loads); grep `GR_UP75\|up75` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/fused_gr.cu:1191` "bitwise gr_up_multi_kernel" | unknown (no speed claim from reading) | port-plan row 2.1 | -| 7 | `STRATA_GU_SWIGLU=1` | `engine/strata/src/core/nv_defaults.cpp:32` | CUDA routed experts: gate/up, SwiGLU and the q8_1 blocks in one launch, `native_gu_swiglu_kernel` (`engine/strata/src/kernels/cuda/iq_kernels.cu:2766`, launched `:4145`, gate `gu_swiglu_on` `:4110`) | partial or none: port-plan row 2.1 and diff-list line 275 say MISSING / PARTIAL (our `chain_swiglu_quant_kernel` fuses SwiGLU with the quantizer only, `crates/cuda-driver/src/chain_window.cu:701`); grep `GU_SWIGLU\|gu_swiglu` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/iq_kernels.cu:4107` "bitwise the same hq" | unknown (no speed claim from reading) | port-plan row 2.1 | -| 8 | `STRATA_QSA_ROWS=1` | `engine/strata/src/core/nv_defaults.cpp:33` | CUDA QSA block scores for up to 4 queries: `block_scores_rows_kernel` (`engine/strata/src/kernels/cuda/qsa_select.cu:1075`, taken at `:1719` only for the exact value "1", wrapper `:1795`) | none: no port-plan row names QSA_ROWS (row 2.5 is top-k, not scores); grep `QSA_ROWS\|block_scores_rows` in `crates/`: 0 hits (only an unrelated JSON key `completed_qsa_rows`); our stage names `qsa_block_scores_topk` (`crates/cuda-driver/src/original_verify_window_planner.rs:129`) say nothing about the variant, and PTX is out of scope | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/qsa_select.cu:1718` "the same bits" | unknown (no speed claim from reading) | no port-plan row; STRA-221 tracker; gap candidate for a second-wave leaf | -| 9 | `STRATA_B6_MMVQ_ROWS=1` | `engine/strata/src/core/nv_defaults.cpp:34` | CUDA MMVQ multi-column exact layout, activation fragment loaded once per weight block, 2 rows (`b6_launch` `engine/strata/src/kernels/cuda/native_mmvq.cu:1457`, call `:1478`, mode `:1161`); only formats with a B6 specialization, and not with `STRATA_TSUM` (`:1461`) | none: no port-plan row names it (row 2.1 names interleaved MMVQ, a different switch); grep `B6_MMVQ\|b6_rows` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/native_mmvq.cu:1315` "every output is bitwise the default exact layout's" | unknown (no speed claim from reading) | no port-plan row; STRA-221 tracker; gap candidate for a second-wave leaf | -| 10 | `STRATA_DEQUANT_WIDE` (not in the table; card default on cc 6.1 and 8.6) | `engine/strata/src/kernels/cuda/dequant_bf16.cu:295` (kernel file, not `nv_defaults.cpp`; `STRATA_SM86_PERF=0` does not turn it off) | CUDA dequantization of Q4_K, Q5_K, Q6_K, IQ4_XS (types 12, 13, 14, 23, `:282`) as 8 values per thread, 16-byte stores (`wide8`, taken at `:363-364` via `dequant_wide_on` `:284`) | not ported: port-plan row 2.4 (line 41) and analysis line 106 ("not applicable" to sm_120; our `leleka_prefill_dequant_*` run one thread per element; a thread-per-8 variant "could only matter on the 3080 (not measured)"); grep `DEQUANT_WIDE\|dequant_wide` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/dequant_bf16.cu:200` "bitwise the same (dequant_wide_parity)" | unknown (no speed claim from reading; port-plan line 146 bounds it at 0.3 % of a chunk on the 5090 only, not on the 3080) | port-plan row 2.4 | -| 11 | Q8_0 dense MMVQ, one row per block (no switch name; opt-out `STRATA_NO_MMVQ_ROWS2`) | `engine/strata/src/kernels/cuda/native_mmvq.cu:1307` (cc 8.6 class at `:1275`, `n_out >= 2048`) | CUDA: `native_mmvq_multi_kernel` with 1 row per block for Q8_0 projections (`q8_0_rows1` `:1296`, used `:1491-1498`); not governed by `STRATA_SM86_PERF` | none: no port-plan row; grep `MMVQ_ROWS2\|q8_0_rows1` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/native_mmvq.cu:1270` "every output is the same bits" | unknown (no speed claim from reading) | no port-plan row; STRA-221 tracker; gap candidate for a second-wave leaf | -| 12 | MMVQ_IL rows tables keyed to cc 86 (opt-outs `STRATA_MMVQ_IL_T1`, `STRATA_MMVQ_IL_Q3K`) | `engine/strata/src/kernels/cuda/native_mmvq.cu:3104` (2-4 columns, `kIlRows_86` `:3031`) and `:3090` (1 column, `kIl1Rows_86` `:3078`); the opt-outs default on (`il_env_on` `:3092`); lookup `native_mmvq_il_rows_for` `:3143`, `il_rows` `:3195`. Whether the whole IL path is default-on was not traced here (digest 1.3 lists MMVQ_IL as a default bitwise switch for all cards) | CUDA interleaved-activation MMVQ, rows per warp from a per-architecture table (`native_mmvq_il_kernel` `:1669`) | none: port-plan row 2.1 names "interleaved MMVQ 2-4 columns" and diff-list line 276 says MISSING (we run the old exact `head_n*_t*` kernels); grep `MMVQ_IL\|mmvq_il` in `crates/`: 0 hits | equal output claimed, by source reading: `engine/strata/src/kernels/cuda/native_mmvq.cu:2985` "bitwise the same output, so the table is only speed" | unknown (no speed claim from reading) | port-plan row 2.1 | - -Row-by-row result: 12 rows. 9 are in the vanilla table (rows 1-9), 1 is a card default outside it (row 10), 2 are further sm_86-keyed defaults found by source search (rows 11, 12). -Lossless by source reading: 10 rows give an equal-output claim (3-12), 2 rows (1, 2) are NOT established and are not recommended for default. - -Port-plan rows 2.1 and 2.2, `sed -n '38,39p' docs/upstream-port-plan.md`, quoted: - -> | 2.1 | sm_120 bitwise decode set (`SIDE_MIXER=2`, `ATTN_DAILY`, `GR_UP75`, `GR_DOWN_TG=1`, `GU_SWIGLU`; interleaved MMVQ 2-4 columns; `ba2c2d5f`, `94104176`, `75afe3f4`, `ffac97f7`, ...) | compare each against our chain kernels / MMVQ; port what is not already ours | I, R | diff list below, nothing implemented | -> | 2.2 | #783 decode series and F7 ports (multi-token router, float4 combine, fused per-head RMSNorm+RoPE, batched K/V append, exact-T GDN, MTP catch-up skipping rejected rows, late shared-expert fork, multi-block argmax) | diff the list against `docs/chain-kernels.md`; port the missing | I, R | diff list below, nothing implemented | - -Row 2.2 names none of the twelve switches. Of the twelve, 5 are named by row 2.1 (4, 5, 6, 7, 12), 1 by row 2.4 (10), 2 by row 3.3 (1, 2), 4 by no row (3, 8, 9, 11). - -## 5. Rows handed to STRA-271 (S3.4) for measurement - -Every speed cell above is `unknown`. All twelve rows are passed to STRA-271 at COMPONENT level (kernel or stage timing, same workload, paired); nothing here is an end-to-end claim. -Suggested order for STRA-271, by what source reading shows: - -| Group | Rows | Why measure first | -| --- | --- | --- | -| we have no counterpart and the switch is bitwise by claim | 4, 5, 7, 8, 9, 11, 12 | decode-path kernels the 3080 runs every round; the port-plan numbers for 4, 5, 7, 12 are estimates, rows 8, 9, 11 have no estimate at all | -| partial counterpart | 6 | delta against `chain_gr_up8/16` unknown | -| not ported, bounded only on the 5090 | 10 | the 0.3 % bound in the port plan is for sm_120, not the 3080 | -| placement policy, equal output NOT established | 1, 2 | a speed result is only usable after a greedy comparison against lag 1 and against vanilla | -| may be inert on our hosts | 3 | read the vanilla start-up log for `GATE=STRATA_CPU_IQ_ALL_EXACT1 active=1` before measuring (STRA-247 records that log) | - -Gaps this audit found, for second-wave leaves (not fixed here): rows 3, 8, 9, 11 have no port-plan row and no counterpart; rows 1, 2 sit in port-plan row 3.3 (todo) and need a quality gate; -row 10 is marked "not applicable" in the plan on 5090 evidence only. None of these is a claim that ours is behind: it is `unknown` until measured. - -## 6. Verification commands (run in the worktree root) - -``` -sed -n '26,34p' engine/strata/src/core/nv_defaults.cpp -grep -rn "SM86_PERF" engine/strata/src -grep -o 'engine/strata/[A-Za-z0-9_/.+-]*:[0-9]*' docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md | while IFS=: read f n; do sed -n "${n}p" "$f" | grep -q . || echo "MISSING $f:$n"; done -grep -c "by source reading" docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md -grep '^| ' docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md | grep -ci "faster\|slower" -grep '^| ' docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md | grep -ci "unknown" -grep -c "STRA-271" docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md -grep -c "none\|port-plan\|grep" docs/experiments/2026-10-28-s3-5-sm86-switch-audit.md -git diff --name-only ..HEAD -``` - -Limits: no kernel was identified from PTX; no output was compared; no speed was measured; the 3080 laptop and the 5090 server were not touched. "Lossless" is a reading of comments and code -paths, not a result. diff --git a/docs/experiments/2026-10-28-s6-1-lossy-audit.md b/docs/experiments/2026-10-28-s6-1-lossy-audit.md deleted file mode 100644 index 30dfe338..00000000 --- a/docs/experiments/2026-10-28-s6-1-lossy-audit.md +++ /dev/null @@ -1,279 +0,0 @@ -# S6.1 Lossy-default audit of the shipped rtx5090-32g and rtx3080-16g profiles (STRA-250) - -Status: read-only audit, 2026-10-28. Leaf STRA-250 of STRA-245. Branch `claude/stra-250`, base `2457d81d` (the tip of `claude/merge-opt`; every path, line number -and count below was read in that tree, not in the main checkout). Nothing was run on a GPU and no model was loaded: every class is a reading of code, profile files and -recorded documents, with the path and line that carry it. Nothing in the engine, the profiles or `engine/strata` was changed. - -Vanilla defaults belong to STRA-247; this page carries one cross-reference section for them (section 6) and no measurement of vanilla. - -## 1. Classes and scope - -* `lossless`: the default moves bytes, caches, schedules or traces, or a recorded byte comparison shows the output equal; no arithmetic order changes. -* `lossy`: the default changes the output by design (a mode the code itself labels as changing the output). No such mode is ON by default in either shipped profile. -* `unknown-until-q_pair`: the default changes the order of arithmetic or the expert placement (rounding level) and the files read carry no q_pair result for the shipped value - on the shipped machine. The leaf that produces the result is named per row: STRA-267 (S2.5) for the 5090 profile on sm_120, STRA-293 (S3.9) for the laptop profile on sm_86. - The command is `python scripts/quality/q_pair.py LOG_A LOG_B` (exit 0 if every common forced row is identical). - An existing gate that is NOT a q_pair result (q_tail_gate over 30-70k tokens, a 612-row teacher-forced gate on short prompts) is quoted in the row and does not move it out of this class. - -Scope (bounded, round 5 of the STRA-245 tree): (a) every key of both profile files, sections 2 and 3; (b) the admitted sets of `serve_tuning.rs`, section 4; -(c) the `LELEKA_*` / `STRATA_*` names in `original_serve*.rs` (section 5) and in the prefill chunk path files (section 5b); (d) all other names listed by name, section 7. - -## 2. rtx5090-32g profile: one row per key (27 rows; classes: 19 lossless, 0 lossy, 8 unknown-until-q_pair) - -| row | key | shipped value | class | evidence | -| --- | --- | --- | --- | --- | -| K50-01 | `name` | rtx5090-32g | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:2; label only (crates/deploy/src/profile.rs:238) | -| K50-02 | `description` | prose | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:3; no engine effect (crates/deploy/src/profile.rs:239); it states `Not a formally quality-gated profile` | -| K50-03 | `select.sm_min` | 120 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:4; selector only, `Profile::matches` (crates/deploy/src/profile.rs:226-233, 381-386) | -| K50-04 | `select.sm_max` | 130 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:4; selector only (crates/deploy/src/profile.rs:226-233) | -| K50-05 | `select.vram_mib_min` | 30000 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:4; selector only (crates/deploy/src/profile.rs:226-233) | -| K50-06 | `select.vram_mib_max` | 1000000 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:4; selector only (crates/deploy/src/profile.rs:226-233) | -| K50-07 | `gpu_budget_bytes` | 32212254720 (30 GiB) | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:5; `--gpu-budget` (crates/deploy/src/config.rs:176-179); sizes the VRAM expert tier, i.e. which experts compute on the GPU and which on the CPU pool; the tier changes placement only (docs/quality-gate.md section 8: P1-P6, 612 rows, d_top1 p99 0.176-0.235, flips 1.6-2.3 %, short prompts, 5090); no CPU-leg versus GPU-leg bit-identity record was found in the files read; STRA-267 (5090, sm_120); q_pair logs: none | -| K50-08 | `spec_min_p` | 0.0 | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:6; `--spec-min-p` (crates/deploy/src/config.rs:218-220); ceiling of the adaptive draft floor, drafts only, verification untouched (docs/adaptive-spec.md:106-111, 122-124) but window shape changes batch rounding: adaptive identical to the fixed-4 pass in 16/30 requests, fixed-3 13/30, fixed-6 13/30, fixed-4 against its own repeats 15/20 (docs/adaptive-spec.md:106-111); STRA-267 (5090, sm_120); q_pair logs: none | -| K50-09 | `expert_profile` | data/expert-profile.bin | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:7; starting VRAM placement (`LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE` set by `plan.rs:270-279`; read at crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:224); placement class as K50-07; STRA-267 (5090, sm_120); q_pair logs: none | -| K50-10 | `context_tokens` | 262144 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:8; `--context-tokens` (crates/deploy/src/config.rs:180-181), admitted 1..=262144 (crates/deploy/src/profile.rs:325-327); a ceiling, no arithmetic | -| K50-11 | `prefill_capacity` | 8192 | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:9; `--original-prefill-capacity` (crates/deploy/src/config.rs:206-208), admitted set {256,512,1024,2048,3072,4096,6144,8192} (crates/deploy/src/profile.rs:44); chunk size changes the rounding order of the prompt path: 16,000 tokens answered identically at 2048, 4096, 6144 and differently at 8192 on one prompt (docs/prefill-throughput.md:52-57, open: rounding or defect); STRA-267 (5090, sm_120); q_pair logs: none | -| K50-12 | `kar_source` | memfd | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:10; where the pinned archive bytes live (crates/deploy/src/profile.rs:47-54; digest pinned crates/deploy/src/profile.rs:15-16); same bytes | -| K50-13 | `expert_source` | resident | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:11; where the routed-expert bytes live (crates/deploy/src/profile.rs:65-73); same bytes | -| K50-14 | `min_driver_major` | 595 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:12; preflight gate only (crates/deploy/src/profile.rs:257) | -| K50-15 | `min_vram_total_mib` | 30000 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:13; preflight gate only (crates/deploy/src/profile.rs:258) | -| K50-16 | `min_ram_total_bytes` | 107374182400 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:14; preflight gate only (crates/deploy/src/profile.rs:263) | -| K50-17 | `min_ram_available_bytes` | 113000000000 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:15; preflight gate only (crates/deploy/src/profile.rs:264) | -| K50-18 | `engine_env.LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER` | yes | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:16; per-layer slot sizing of the VRAM tier (crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:225-227); placement class as K50-07; STRA-267 (5090, sm_120); q_pair logs: none | -| K50-19 | `engine_env.LELEKA_CHAIN` | all | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:16; groups glue, ab, gr, tiny, head, mtp (not qsa) (crates/cuda-driver/src/original_verify_window_chain.rs:62-87); NOT bit-identical at 30-70k context: 5,993 of 64,355 rows identical, d_top1 p99 0.327, max 4.31, argmax flips 697 (1.08 %), control for rounding noise p99 0.394 / flips 1.45 % (docs/chain-kernels.md:70-79); passes the q_tail_gate 1.25x rule only, 5090, 30-70k context, no 256k q_pair; FINDING F1; STRA-267 (5090, sm_120); q_pair logs: none | -| K50-20 | `memory.prefix_cache_mib` | auto | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:17; cache budget (crates/deploy/src/profile.rs:90-92, 166-168); a hit reproduces the full read bit for bit (docs/prefix-cache.md:34-36, job 922 equality, 14 requests); grid nodes exact by construction (docs/prefix-cache.md:169) | -| K50-21 | `memory.prefix_cache_tail` | reply | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:17; request-end checkpoints at the end of the decode; the cells past the prompt are decode-produced, so the state is not what a prefill would produce (docs/prefix-cache.md:165-168); the same doc marks `reply` EXPERIMENTAL and not to be defaulted before the agreement gate (line 168) and also records it as the 5090 default (lines 190-198: d_top1 p99 0.401, flips 1.45 % against a control of p99 0.394 / 1.45 %, ~70k context, q_tail_gate); FINDING F2; STRA-267 (5090, sm_120); q_pair logs: none | -| K50-22 | `memory.prefix_cache_block` | 8192 | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx5090-32g.json:17; tokens per prefix block and chunk-grid step, caps every chunk (crates/deploy/src/profile.rs:97-100, 172-176); grid nodes are exact by construction but the grid sets the chunk cut, same class as K50-11 (8192 differed on one prompt, docs/prefill-throughput.md:52-57); STRA-267 (5090, sm_120); q_pair logs: none | -| K50-23 | `memory.soft_floor_mib` | 4096 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:17; memory governor: caches shed below it (crates/deploy/src/profile.rs:104-106, 194-196); sheds reuse, never values | -| K50-24 | `memory.hard_floor_mib` | 2048 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:17; new requests refused with 503 below it (crates/deploy/src/profile.rs:107-109, 197-200) | -| K50-25 | `memory.reserve_mib` | 2048 | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:17; slack above the soft floor (crates/deploy/src/profile.rs:110-112, 201-204) | -| K50-26 | `memory.lock` | try | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:17; keeps the sealed memfd resident (crates/deploy/src/profile.rs:116-118, 209) | -| K50-27 | `memory.heal` | true | lossless | deploy/rust-runtime/profiles/rtx5090-32g.json:17; pulls swapped memfd pages back (crates/deploy/src/profile.rs:119-121, 213-216) | - -## 3. rtx3080-16g profile: one row per key (27 rows; classes: 22 lossless, 0 lossy, 5 unknown-until-q_pair) - -`engine_env` is `{}` in this file and contributes 0 keys (the AC1 one-liner counts leaves). Absent keys take the engine's defaults, which section 5 classifies: `spec_min_p` absent -= 0.0 (`crates/leleka-runtime/src/backend_original_serve.rs:152`), `LELEKA_CHAIN` absent = off. The deploy layer adds `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto` and -`LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE` when the profile file validates (`crates/deploy/src/plan.rs:270-279`) and the resource preset adds the CPU worker count and the mapped -working set (`crates/deploy/src/resources.rs:330-337`). - -| row | key | shipped value | class | evidence | -| --- | --- | --- | --- | --- | -| K30-01 | `name` | rtx3080-16g | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:2; label only (crates/deploy/src/profile.rs:238) | -| K30-02 | `description` | prose | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:3; no engine effect; it states `Experimental` and `no quality claim` | -| K30-03 | `select.sm_min` | 80 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:4; selector only (crates/deploy/src/profile.rs:226-233) | -| K30-04 | `select.sm_max` | 120 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:4; selector only (crates/deploy/src/profile.rs:226-233) | -| K30-05 | `select.vram_mib_min` | 14000 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:4; selector only (crates/deploy/src/profile.rs:226-233) | -| K30-06 | `select.vram_mib_max` | 24000 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:4; selector only (crates/deploy/src/profile.rs:226-233) | -| K30-07 | `gpu_budget_bytes` | 16106127360 (15 GiB) | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx3080-16g.json:5; `--gpu-budget` (crates/deploy/src/config.rs:176-179), lowered by the workstation preset to 13 GiB (docs/laptop-vs-vanilla.md:152); sizes the VRAM expert tier, placement class as K50-07; STRA-293 (laptop, sm_86); q_pair logs: none | -| K30-08 | `context_tokens` | 262144 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:6; `--context-tokens` (crates/deploy/src/config.rs:180-181); a ceiling, no arithmetic | -| K30-09 | `prefill_capacity` | 6144 | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx3080-16g.json:7; `--original-prefill-capacity` (crates/deploy/src/config.rs:206-208); `6144 changes the rounding order of the prompt path ... no quality gate yet` (docs/laptop-vs-vanilla.md:79, 152); 16,000 tokens identical at 2048/4096/6144 on one prompt (docs/prefill-throughput.md:52-57); q_pair or R-hash arms 2048 against 6144 `Not run` (docs/laptop-vs-vanilla.md:79); STRA-293 (laptop, sm_86); q_pair logs: none | -| K30-10 | `kar_source` | file | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:8; where the archive bytes live (crates/deploy/src/profile.rs:47-54); same bytes | -| K30-11 | `expert_source` | mapped | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:9; where the routed-expert bytes live (crates/deploy/src/profile.rs:65-73); same bytes | -| K30-12 | `min_driver_major` | 595 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:10; preflight gate only (crates/deploy/src/profile.rs:257) | -| K30-13 | `min_vram_total_mib` | 14000 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:11; preflight gate only (crates/deploy/src/profile.rs:258) | -| K30-14 | `min_vram_free_mib` | 14500 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:12; preflight gate only (crates/deploy/src/profile.rs:259-262) | -| K30-15 | `min_ram_total_bytes` | 23622320128 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:13; preflight gate only (crates/deploy/src/profile.rs:263) | -| K30-16 | `min_ram_available_bytes` | 10737418240 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:14; preflight gate only (crates/deploy/src/profile.rs:264) | -| K30-17 | `wsl_memory_gib` | 32 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:15; advice only for `.wslconfig` (crates/deploy/src/profile.rs:265-267) | -| K30-18 | `expert_profile` | data/expert-profile.bin | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx3080-16g.json:16; starting VRAM placement (set as `LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE` by plan.rs:270-279 when the file validates); placement class as K50-07; STRA-293 (laptop, sm_86); q_pair logs: none | -| K30-19 | `expert_profile_sha256` | 8f59b4aa...975baf | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:17; integrity pin of the profile file (crates/deploy/src/profile.rs:271-272, 345-349) | -| K30-20 | `memory.prefix_cache_mib` | auto | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:19; cache budget; a hit reproduces the full read bit for bit (docs/prefix-cache.md:34-36); grid nodes exact by construction (docs/prefix-cache.md:169) | -| K30-21 | `memory.prefix_cache_tail` | prompt | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx3080-16g.json:19; one checkpoint at n-1 at the end of the prefill = an extra chunk boundary; differs from a grid-only full read by where the chunks were cut, rounding level, same as any chunk-size change (docs/prefix-cache.md:164, 169-170); docs/laptop-vs-vanilla.md:80 (tail only moves where a checkpoint is taken; run A not checked with q_pair); STRA-293 (laptop, sm_86); q_pair logs: none | -| K30-22 | `memory.prefix_cache_block` | 6144 | unknown-until-q_pair | deploy/rust-runtime/profiles/rtx3080-16g.json:19; grid step caps every chunk (crates/deploy/src/profile.rs:97-100); same class as K30-09 (docs/laptop-vs-vanilla.md:79, 152); STRA-293 (laptop, sm_86); q_pair logs: none | -| K30-23 | `memory.soft_floor_mib` | 4096 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:19; memory governor floor (crates/deploy/src/profile.rs:104-106); raised by the preset (docs/laptop-vs-vanilla.md); values untouched | -| K30-24 | `memory.hard_floor_mib` | 2048 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:19; refusal floor (crates/deploy/src/profile.rs:107-109) | -| K30-25 | `memory.reserve_mib` | 1024 | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:19; slack above the soft floor (crates/deploy/src/profile.rs:110-112) | -| K30-26 | `memory.lock` | off | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:19; no memfd on this profile (crates/deploy/src/profile.rs:116-118) | -| K30-27 | `memory.heal` | false | lossless | deploy/rust-runtime/profiles/rtx3080-16g.json:19; no memfd on this profile (crates/deploy/src/profile.rs:119-121) | - -## 4. Admitted sets of `crates/leleka-runtime/src/serve_tuning.rs` (and the matching profile checks) - -| row | set | where | class | evidence | -| --- | --- | --- | --- | --- | -| A-01 | prefill chunk in {256, 512, 1024, 2048, 3072, 4096, 6144, 8192} | `serve_tuning.rs:14,68-70`; `crates/deploy/src/profile.rs:44,328-334` | unknown-until-q_pair | every member is a different chunk cut, rounding level; the engine default is 2048 (`original_serve_stack.rs:109`); 6144 and 8192 are the shipped values (K30-09, K50-11); STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86); q_pair logs: none | -| A-02 | prefix block a multiple of 256 and <= 8192 (0 = the prefill chunk) and not larger than the chunk | `serve_tuning.rs:122-126,146-152`; `profile.rs:140-144` | unknown-until-q_pair | the block is the chunk-grid step; same class as A-01; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86); q_pair logs: none | -| A-03 | cpu_workers 1..=15 | `serve_tuning.rs:85-93` (engine pool admits 1..=64 at `original_serve_stack.rs:158`) | unknown-until-q_pair | no record of worker-count independence of the result in the files read; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86); q_pair logs: none | -| A-04 | context_tokens 1..=262144 | `serve_tuning.rs:58-66` | lossless | a ceiling | -| A-05 | kv_resident 0 or >= 20480, fixed for the life of the process; default 32768 | `serve_tuning.rs:76-84,16` | lossless | resident window of the same int8 cells; streaming of K/V, not a format change | -| A-06 | spec_min_p finite within 0..=1 | `serve_tuning.rs:94-102` | unknown-until-q_pair | see K50-08 / SRV `LELEKA_SPEC_ADAPTIVE`; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | -| A-07 | prefix_cache_mib `auto` / `off` / `0` / MiB; prefix_cache_tail off / prompt / reply; prefix_retention_min | `serve_tuning.rs:107-131` | unknown-until-q_pair | the tail value `reply` / `prompt` is the unknown part (K50-21, K30-21); budget and retention are lossless; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | - -## 5. Names read on the serve path in `original_serve*.rs`: 51 distinct names (38 lossless, 0 lossy, 13 unknown-until-q_pair) - -Command: `grep -rhoE '(LELEKA|STRATA)_[A-Z0-9_]+' crates/leleka-runtime/src --include='original_serve*.rs' | sort -u | wc -l` (files: 16, all under -`crates/leleka-runtime/src/qwen_forward/`, among them `original_serve_residency.rs`). The grep also matches comment mentions and the prefix token `LELEKA_ORIGINAL_SERVE_`; each is a -row. "Unset value" is the value in force when the variable is absent. Column "evidence" quotes the code or document that carries the class. - -| row | name | file:line | unset value | class | evidence | -| --- | --- | --- | --- | --- | --- | -| S-01 | `LELEKA_ADAPT_DECAY` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:443,448 | 0.7 (generate.cpp constant) | unknown-until-q_pair | adaptive-tier count decay, placement; adapt_every 4 / adapt_swaps 96 are ON (crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:174-175); docs/quality-gate.md section 8 P2/P6 PASS, 612 rows; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | -| S-02 | `LELEKA_ADAPT_MARGIN` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:443,448 | 1.5 | unknown-until-q_pair | adaptive-tier swap margin, placement; as LELEKA_ADAPT_DECAY | -| S-03 | `LELEKA_ADAPT_MIN_COUNT` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:442,448 | 2.0 | unknown-until-q_pair | adaptive-tier swap threshold, placement; as LELEKA_ADAPT_DECAY | -| S-04 | `LELEKA_BRINGUP_TRACE` | crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:34 | off | lossless | timing trace only (also read in the prefill path, row P-06) | -| S-05 | `LELEKA_CHAIN` | crates/leleka-runtime/src/qwen_forward/original_serve_config.rs:176 (comment; read at crates/cuda-driver/src/original_verify_window_chain.rs:62) | off (no group) | lossless | unset on the laptop profile; the 5090 profile sets `all`, see K50-19 (U, finding F1) | -| S-06 | `LELEKA_CPU_POOL` | crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:176,190 | Direct path | lossless | same arithmetic as the legacy path, copies skipped (pool.rs:179-181); `crosscheck` mode compares every float bit for bit (pool.rs:184-186); no recorded crosscheck result was read | -| S-07 | `LELEKA_CPU_POOL_FENCE` | crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:208,447 | one fence per group | lossless | synchronisation granularity only | -| S-08 | `LELEKA_CPU_POOL_LOOKAHEAD` | crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:210,453 | off (opt-in) | lossless | router lookahead is opt-in; unset = off | -| S-09 | `LELEKA_CPU_POOL_PLAN` | crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:156,159 | off (15 workers) | lossless | unset = constant 15 workers (stack.rs:112); `on` = pool_plan::default_workers | -| S-10 | `LELEKA_CPU_PREFETCH` | crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:219,459; crates/leleka-runtime/src/qwen_forward/prefetch_policy.rs:19-34 | Windows: adaptive (cheaper of pass / no pass by moving average); elsewhere: on | lossless | the laptop prefetch policy: `The bytes read and the arithmetic are the same in both modes` (prefetch_policy.rs:8); measured 8.70 -> 10.58 tok/s warm, 6.85 vs 5.22 cold (prefetch_policy.rs:4-6); timing choice, no q_pair needed | -| S-11 | `LELEKA_CPU_PREFETCH_OFF_FILE` | crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:81,84 | no file = no effect | lossless | A/B bring-up file | -| S-12 | `LELEKA_EXPERT_TIER_GPU` | crates/leleka-runtime/src/qwen_forward/original_serve_residency_gpu.rs:1,116,118 | unset (ignored test) | lossless | gates an #[ignore] test, not production | -| S-13 | `LELEKA_OPEN_CACHE` | crates/leleka-runtime/src/qwen_forward/original_serve_pool.rs:216,457 | off (opt-in) | lossless | unset = off; `not measured on a device yet` (pool.rs:216) | -| S-14 | `LELEKA_ORIGINAL_SERVE_` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:219 | prefix token of a format string | lossless | not a switch: `format!("LELEKA_ORIGINAL_SERVE_{name}")`; its members are the rows LELEKA_ORIGINAL_SERVE_* below plus names listed in section 7 (e.g. _EXPERT_PER_LAYER, _PCIE_FRAC, _PREFILL_BORROW, _CAPACITY, _KV_RESIDENT) | -| S-15 | `LELEKA_ORIGINAL_SERVE_CPU_WORKERS` | crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:155,158 | 15 (stack.rs:112); preset may set it (crates/deploy/src/resources.rs:335-337) | unknown-until-q_pair | worker count of the CPU expert pool, admitted 1..=64 here and 1..=15 by serve_tuning.rs:86; no record that the result is independent of the worker count was found in the files read; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86); q_pair logs: none | -| S-16 | `LELEKA_ORIGINAL_SERVE_DUMP_ROUTING` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:703,718 | off | lossless | writes a routing file, no effect on values | -| S-17 | `LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:224 | none; deploy sets it when the profile file validates (plan.rs:270-279) | unknown-until-q_pair | starting placement, K50-09 / K30-18; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | -| S-18 | `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:214,221 | 0 (tier off); deploy sets `auto` (plan.rs:270-273) | unknown-until-q_pair | VRAM tier size; the shipped runs have the tier ON; placement class as K50-07; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | -| S-19 | `LELEKA_ORIGINAL_SERVE_SEED` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:145,260-269; crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs:1,29-30 | ON, up to 4096 swaps | unknown-until-q_pair | prompt-routing seed, placement only; docs/quality-gate.md section 8: P5 vs P1 p99 0.146 / max 0.447, P6 shipped default p99 0.235 (+7 % over the Original's 0.219), flips 2.3 %, verdict PASS, 612 rows, short prompts; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | -| S-20 | `LELEKA_PCIE_AUTO` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:557,576,616,638 | off (only `lag` enables) | lossless | unset = fixed share; `Only the split changes, never what an expert computes` (residency.rs:561-562) | -| S-21 | `LELEKA_PCIE_LOCKED_ONLY` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:328,434,438,796 | off | lossless | unset = unrestricted split | -| S-22 | `LELEKA_PREFILL_LOAN_TIERS` | crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:145,219,222,305 | on in the shipped 5090 profiles (engine default off) | lossless | identity PASS (chunk residual hashes equal) and paired A/B n=10: TTFT sum -3.0 s +-0.3; unset = full loan | -| S-23 | `LELEKA_PREFIX_RETENTION_S` | crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs:77,80 | 3600 s | lossless | cache lifetime only; the profile `prefix_retention_min` is absent in both files | -| S-24 | `LELEKA_PREFIX_TRACE` | crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:1464,1469 | off | lossless | operator text only | -| S-25 | `LELEKA_QSA_CLUSTER` | crates/leleka-runtime/src/qwen_forward/original_serve_verifier.rs:31,272-273 | ON (QSA_CLUSTER_DEFAULT = true; the driver turns it off below sm_90, so off on the sm_86 laptop) | lossless | cluster decode top-k writes the same ids as qsa_topk_ref in 24 model-free cases; end to end q_tail_gate over 1,502 forced rows: d_top1 median/p99/max 0.0000 and 0 argmax flips for all 7 arms (docs/upstream-port-plan.md:42, 142-143) | -| S-26 | `LELEKA_REFILL_DEFER` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:1155,1161; crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:316 | off (EXPERIMENTAL) | lossless | unset = off | -| S-27 | `LELEKA_ROUTE_TAIL_SKIP` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:52,64,87 | 0 = OFF (`unwrap_or(0)` at line 64) | lossless | ours is off by default; the mode is lossy (`changes the output`, residency.rs:51-55) and would be class lossy if enabled; vanilla's default differs, see section 6 | -| S-28 | `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:54,80 | 90.0 (percent) | lossless | only consulted when tail skip is on | -| S-29 | `LELEKA_SEED_TRACE` | crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:314,1253,1260,1266,1296 | off | lossless | trace only | -| S-30 | `LELEKA_SERVE_OVERLAP` | crates/leleka-runtime/src/qwen_forward/original_serve_native.rs:117,121 | ON (draft enqueued behind the commit event, generate.cpp order) | lossless | enqueue order of already-defined work; `off` is the earlier serialized order | -| S-31 | `LELEKA_SERVE_PROFILE` | crates/leleka-runtime/src/qwen_forward/original_serve_profile.rs:1,9,12; crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:1561 | off | lossless | span timing only | -| S-32 | `LELEKA_SERVE_PUBLISH` | crates/leleka-runtime/src/qwen_forward/original_serve_host.rs:119,122,409 | batched publication | lossless | same twelve index checkpoints, one batch versus one by one | -| S-33 | `LELEKA_SERVE_SWAP_WAIT` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:947,981,984 | ON (wait for adaptive swaps at a round start) | lossless | makes `the resident set no longer depend on when the copies finished` (residency.rs:944-946); timing only | -| S-34 | `LELEKA_SPAN_CACHE` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:528,540 | ON | lossless | caches span lookups; `off` is the A/B control | -| S-35 | `LELEKA_SPEC` | crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs:376,384,390,398,1076 | unset = mode17 (verify window 6, MTP window 4) unless adaptive | unknown-until-q_pair | window width; verified tokens are the verifier's, width changes batch rounding (docs/adaptive-spec.md:106-111); STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | -| S-36 | `LELEKA_SPEC_ADAPTIVE` | crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs:354,363,378,389,397-405 | ON (ADAPTIVE_DEFAULT = true, engine.rs:354) | unknown-until-q_pair | adaptive window is the shipped default; exactness argued by verification, measured 16/30 identical against fixed-4 (docs/adaptive-spec.md:106-111); STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86); q_pair logs: none | -| S-37 | `LELEKA_SPEC_ADAPTIVE_MAX_T` | crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs:378,391 | 8 (MAX_T) | unknown-until-q_pair | widest adaptive window; as LELEKA_SPEC_ADAPTIVE | -| S-38 | `LELEKA_SPEC_ARMS` | crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs:410,414; crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:273,710 | none (empty) | lossless | A/B harness switch, unset = single policy | -| S-39 | `LELEKA_SPEC_MTP_MAX_T` | crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs:377,387 | spec (4) or the adaptive maximum | unknown-until-q_pair | draft chain length; as LELEKA_SPEC_ADAPTIVE | -| S-40 | `LELEKA_SPEC_SUFFIX` | crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs:377,388 | 3 (suffix draft ON, mode17 SUFFIX = 3) | unknown-until-q_pair | prompt-lookup drafting changes the window contents; as LELEKA_SPEC_ADAPTIVE | -| S-41 | `LELEKA_TRACE_LOGPROBS` | crates/leleka-runtime/src/qwen_forward/original_serve_native.rs:110,162 | off | lossless | diagnostic dump | -| S-42 | `LELEKA_TRACE_RESIDUAL` | crates/leleka-runtime/src/qwen_forward/original_serve_native.rs:114,171 | off | lossless | diagnostic dump | -| S-43 | `STRATA_CKPT_REREAD` | crates/leleka-runtime/src/qwen_forward/original_serve_conversation.rs:37,47,59,234; crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:803,1184 | off (checkpoints are restored) | lossless | a check of the checkpoint (answer must match the restored one token for token), not a default | -| S-44 | `STRATA_MTP_PREFILL_SYNC` | crates/leleka-runtime/src/qwen_forward/original_serve_config.rs:197 | unset (comment; per_group_sync false) | lossless | named in a comment only, not read in ours; synchronisation granularity | -| S-45 | `STRATA_OLD_SAMPLER` | crates/leleka-runtime/src/qwen_forward/original_serve_config.rs:203,208,373-375 | unset = Split top-k path | unknown-until-q_pair | sampler kernel choice mirrors sampler.cu (config.rs:203-205); the q_pair corpus is greedy / teacher-forced and does not exercise sampled requests, so a q_pair result cannot settle it; STRA-267 (5090, sm_120); STRA-293 (laptop, sm_86) | -| S-46 | `STRATA_PREFILL_STREAM_MIN` | crates/leleka-runtime/src/qwen_forward/original_serve_config.rs:277 (comment: 1024); crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs:12,29 (code: 4096) | 4096 rows (code); the config.rs comment says 1024 (finding F6) | lossless | copy ordering of expert streaming; `identical greedy ids` at chunk 8192, +13..27 % prefill tok/s (cache_original_prompt.rs:16-17); also row P-14 | -| S-47 | `STRATA_ROPE_TABLE` | crates/leleka-runtime/src/qwen_forward/original_serve_config.rs:120 | unset = analytic form | lossless | named in a comment: the table form is `not supported here` | -| S-48 | `STRATA_ROUTE_TAIL_SKIP` | crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:51,311 | not read in ours (comments) | lossless | upstream name in comments; ours reads LELEKA_ROUTE_TAIL_SKIP | -| S-49 | `STRATA_SAMPLER_ONE_BLOCK` | crates/leleka-runtime/src/qwen_forward/original_serve_config.rs:204,210,372-373 | off | lossless | unset = Split path (see STRATA_OLD_SAMPLER) | -| S-50 | `STRATA_SPEC_COUPLED` | crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs:406,408 | off (coupled draft sampling false) | lossless | unset = off | -| S-51 | `STRATA_VERIFY_PROFILE` | crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs:1116 | unset (comment; read in the driver) | lossless | GPU stage timing report only | - -### 5b. Names in the prefill chunk path files: 14 distinct names (14 lossless, 0 lossy, 0 unknown-until-q_pair) - -The file list is the output of `find crates/leleka-runtime/src -type f -name '*.rs' | grep -E 'prefill|chunk|original_prompt|prompt' | grep -v '/original_serve'` (31 files, none -matches the glob of section 5), relative to `crates/leleka-runtime/src/`: -`backend_original_prompt.rs`, `qwen_forward/cache_original_prompt.rs`, `chunk_modules.rs`, `executor_original_prompt.rs`, `executor_prefill_chunk.rs`, `gdn_chunk_device.rs`, -`gdn_chunk_fused.rs`, `gdn_chunk_numeric_gpu.rs`, `gdn_chunk_producer.rs`, `gdn_prefill_batch.rs`, `gdn_prefill_batch_gpu.rs`, `gdn_prompt_device.rs`, `gr_attention_chunk.rs`, -`gr_batch_chunk.rs`, `moe_group_chunk.rs`, `moe_mmq_chunk.rs`, `moe_prefill_batch.rs`, `moe_prompt_finish.rs`, `mtp_decode_chunk.rs`, `mtp_state_chunk.rs`, `original_mtp_prefill.rs`, -`original_mtp_scalar_prefill.rs`, `original_prompt_embedding.rs`, `prefill_profile.rs`, `prompt_device_rows.rs`, `qsa_prefill_batch.rs`, `qsa_prompt_device.rs`, `qsa_prompt_index.rs`, -`session_chunk.rs`, `session_chunk_verify.rs`, `session_original_prompt.rs` (all except the first one under `qwen_forward/`). Command over those files: -`grep -hoE '(LELEKA|STRATA)_[A-Z0-9_]+' | sort -u | wc -l`. Two names also occur in section 5 (`LELEKA_BRINGUP_TRACE`, `STRATA_PREFILL_STREAM_MIN`). - -| row | name | file:line | unset value | class | evidence | -| --- | --- | --- | --- | --- | --- | -| P-01 | `LELEKA_BRINGUP_TRACE` | crates/leleka-runtime/src/qwen_forward/prefill_profile.rs:1 | off | lossless | per-chunk timing trace (also row S-04) | -| P-02 | `LELEKA_PREFILL_GDN_MIRROR` | crates/leleka-runtime/src/qwen_forward/gdn_chunk_device.rs:11,152 | ON | lossless | reuse of a resident GDN state mirror versus a canonical re-upload of the same values (`always upload the canonical host values (the A/B arm)`) | -| P-03 | `LELEKA_PREFILL_MOE_SPAN_CACHE` | crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs:44,52 | ON | lossless | span lookup cache, `0` restores the walk | -| P-04 | `LELEKA_PREFILL_PROFILE_SYNC` | crates/leleka-runtime/src/qwen_forward/prefill_profile.rs:6,119,138 | off | lossless | drains the device per span for attribution only | -| P-05 | `LELEKA_PREFILL_QSA_PREFETCH` | crates/leleka-runtime/src/qwen_forward/prompt_device_rows.rs:419 (comment); read at crates/cuda-driver/src/qsa_resident_transport.rs:38,74 | ON (QSA_PREFETCH_DEFAULT = true) | lossless | starts the prior-KV prefix copy on a side stream; ordering of a copy, same bytes | -| P-06 | `LELEKA_PREFILL_STAGED_INPUT` | crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs:39,42,296 | ON | lossless | KAR inputs staged chunk-wide on the device versus per-token host path (the A/B arm); `0` keeps the host path | -| P-07 | `LELEKA_PREFILL_STREAM` | crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs:15,23 | ON | lossless | per-chunk expert streaming; `identical greedy ids`, 16,000 tokens at chunk 8192 (cache_original_prompt.rs:16-17) | -| P-08 | `LELEKA_PREFILL_STREAM_SEQ` | crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs:31 | unset (test harness switch, `-1` = environment) | lossless | in-process A/B override | -| P-09 | `LELEKA_STRA169_RUN_GDN_BATCH_RESOURCES` | crates/leleka-runtime/src/qwen_forward/gdn_prefill_batch_gpu.rs:13 | unset (gates a GPU test) | lossless | test gate | -| P-10 | `LELEKA_STRA169_RUN_GDN_CHUNK_COMPONENT` | crates/leleka-runtime/src/qwen_forward/gdn_chunk_numeric_gpu.rs:404,481 | unset (gates a GPU test) | lossless | test gate | -| P-11 | `LELEKA_TRACE_DRIVER_ERRORS` | crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs:601 | off | lossless | prints driver errors | -| P-12 | `LELEKA_TRACE_PREFILL_R` | crates/leleka-runtime/src/qwen_forward/executor_original_prompt.rs:437,439 | off | lossless | FNV-1a of the final residual per chunk, `off by default` | -| P-13 | `STRATA_PREFILL_BF16X2` | crates/leleka-runtime/src/qwen_forward/gdn_prefill_batch.rs:29; crates/leleka-runtime/src/qwen_forward/moe_prefill_batch.rs:33 | 0 = HighOnly, the original default | lossless | named in comments: HighOnly is the literal profile; HighPlusLow is `separately profile-bound` and not selected here | -| P-14 | `STRATA_PREFILL_STREAM_MIN` | crates/leleka-runtime/src/qwen_forward/cache_original_prompt.rs:12,29 | 4096 rows | lossless | see row S-46; copy ordering | - -Not covered by the file set above, read in `crates/cuda-driver/src` and named here only so the second wave can find them (not classified here): `LELEKA_PREFILL_GDN_NOSTORE` -(default ON, `prefill_stage.rs:78,84`, identity gate cited in docs/upstream-port-plan.md row 2.4), `LELEKA_PREFILL_GDN_KH` (default off, `prefill_stage.rs:96-103`, sm_120 only), -`LELEKA_PREFILL_FAST_REC` (off, `prefill_stage.rs:61`), `LELEKA_MMQ_STREAMK` / `LELEKA_MMQ_NO_STREAMK` (stream-K policy latched per device, `arch_ptx.rs:27,85`). - -## 6. Vanilla Strata defaults (cross-reference to STRA-247 only; nothing measured or classified here) - -* Route tail skip, vanilla: ON by default on CUDA builds (owner decision 0.1.42), rank 7: `engine/strata/src/program/generate.cpp:10110-10153` (the handoff's `generate.cpp` is - `src/program/generate.cpp`; the skip itself is `src/core/expert_source.cpp:4763-4894`). Conditions that turn the default OFF: every expert resident; at least - `STRATA_TAIL_SKIP_MAX_CACHED` percent (default 90) of the experts cached; NVFP4 experts; `--batch` slots; a peer or helper GPU; an unsupported decode architecture - (`decode_defaults_arch_ok()`). It changes the output (comment: KL ~0.003-0.006). Ours: OFF, `unwrap_or(0)` (row S-27, line 64 below). So `off` is ours only. See STRA-247. -* CPU prefill share, vanilla: ON by default for chunks below 1024 tokens since 0.1.41 (`STRATA_PREFILL_CPU_SHARE` unset behaves as `auto` with `STRATA_PREFILL_CPU_SHARE_MAX=1024`; - CUDA builds, one GPU, no batch slots; layer split, batch slots and HIP stay off), `engine/strata/src/prefill/prefill.cpp:193-221`; mean KL against the share off about 0.004 - (comment, lines 202-205). `STRATA_PREFILL_CPU_SHARE=0` turns it off. Ours: ABSENT (row below). See STRA-247. - -| row | item | ours | evidence | -| --- | --- | --- | --- | -| V-01 | route tail skip | OFF by default (`LELEKA_ROUTE_TAIL_SKIP`, unset = 0, lossy when enabled) | `crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs:64`; command `sed -n '64p' ...` in section 8 | -| V-02 | CPU prefill share | ABSENT: no such switch in `crates/` or `scripts/` | command `grep -rn -i "prefill.*cpu.*share\|PREFILL_CPU_SHARE" crates scripts` printed nothing (section 8) | - -## 7. Everything else: not on the shipped serve path as scoped, not classified (434 names) - -These are the distinct `LELEKA_*` / `STRATA_*` tokens found in `crates/**/*.rs` minus the names of sections 5 and 5b. Command that produced the list: -`grep -rhoE '(LELEKA|STRATA)_[A-Z0-9_]+' crates --include='*.rs' | sort -u` (497 distinct tokens, 441 of them `LELEKA_*`) minus the 63 names of sections 5 and 5b, with -`comm -23`. Caveat: this list is by token, not by reader. Some of these are read on the serve path by files outside the bounded file set (for example `LELEKA_MEMORY_*` and -`LELEKA_MAPPED_WORKING_SET_GIB`, which the profile `memory` rows K50-23..27 and K30-23..27 classify; `LELEKA_CHAIN_*` groups behind K50-19; `LELEKA_SPEC_*` controller constants -in docs/adaptive-spec.md; `LELEKA_ORIGINAL_SERVE_PCIE_FRAC`, `_PREFILL_BORROW`, `_CAPACITY`, `_KV_RESIDENT`; `LELEKA_PREFILL_*` switches in `crates/cuda-driver`). They are -listed so that nothing is silently dropped; none is classified. - -`LELEKA_AB_DATE`, `LELEKA_AB_REPLAY`, `LELEKA_ASSETS`, `LELEKA_BANK_THP`, `LELEKA_CAPTURE_DIR`, `LELEKA_CB_WARMUP`, `LELEKA_CHAIN_`, `LELEKA_CHAIN_AB`, `LELEKA_CHAIN_DOWN`, `LELEKA_CHAIN_GLUE`, `LELEKA_CHAIN_GR`, `LELEKA_CHAIN_HEAD`, `LELEKA_CHAIN_MTP`, `LELEKA_CHAIN_QSA`, `LELEKA_CHAIN_TINY`, `LELEKA_CHAIN_UP8`, `LELEKA_CHUNK_DRAIN`, `LELEKA_CHUNK_DRAIN_FILE`, `LELEKA_CONVERSATION_CACHE`, `LELEKA_CONVERSATION_CACHE_MIB`, `LELEKA_CONVERSATION_CACHE_SLOTS`, `LELEKA_CONVERSATION_CANCEL_PROBES`, `LELEKA_CONVERSATION_EVERY`, `LELEKA_CONVERSATION_MAX_NEW`, `LELEKA_CONVERSATION_SYSTEM_REPEAT`, `LELEKA_CPU_ISA`, `LELEKA_CPU_POOL_PIN_HOST`, `LELEKA_CUDA_CASE`, `LELEKA_CUDA_MOCK_HARNESS`, `LELEKA_CUDA_MOCK_ROOT`, `LELEKA_CUDA_Q5_MOCK_ROOT`, `LELEKA_CUDA_Q6_MOCK_ROOT`, `LELEKA_CUDA_REAL_GPU`, `LELEKA_CUDA_TRACE_CALLBACKS`, `LELEKA_CUDA_TRACE_SYNC`, `LELEKA_DLL_DIRS`, `LELEKA_EXPERIMENTAL_EXPERTS_USED`, `LELEKA_EXPERIMENTAL_FAKE_BITS`, `LELEKA_EXPERIMENTAL_KAR_EXPERT_LAYERS`, `LELEKA_EXPERIMENTAL_KAR_EXPERT_LEVELS`, `LELEKA_EXPERIMENTAL_KAR_LEVELS`, `LELEKA_EXPERIMENTAL_KAR_TENSORS`, `LELEKA_FAMILY_CLOSE_FAILURE`, `LELEKA_FAMILY_EXPECT_FAILURE`, `LELEKA_FAMILY_GPU_ROOT`, `LELEKA_FAMILY_IQ2S_ENABLED`, `LELEKA_FAMILY_IQ3S_ENABLED`, `LELEKA_FAMILY_IQ3XXS_ENABLED`, `LELEKA_FAMILY_IQ4NL_ENABLED`, `LELEKA_FAMILY_IQ4XS_ENABLED`, `LELEKA_FAMILY_MODES`, `LELEKA_FAMILY_N`, `LELEKA_FAMILY_NATIVE`, `LELEKA_FAMILY_PUBLIC_CASE`, `LELEKA_FAMILY_PUBLIC_MODE`, `LELEKA_FAMILY_Q2_ENABLED`, `LELEKA_FAMILY_Q4K_ENABLED`, `LELEKA_FAMILY_Q8_ENABLED`, `LELEKA_FAMILY_QUANTIZER_PTX`, `LELEKA_FAMILY_REAL_GPU`, `LELEKA_FAMILY_ROOT`, `LELEKA_FAMILY_UNIT_ELF`, `LELEKA_FORCE_SMS`, `LELEKA_GATEWAY_TOKEN`, `LELEKA_GPTOSS_GGUF`, `LELEKA_HEAD_EVIDENCE`, `LELEKA_HEAD_NATIVE_ORACLE`, `LELEKA_HEAD_NATIVE_SHA256`, `LELEKA_IGPU_MOE_TILE`, `LELEKA_IGPU_TILE`, `LELEKA_LAPTOP_ARMS`, `LELEKA_LAPTOP_BENCH`, `LELEKA_LAPTOP_CELLS`, `LELEKA_LAPTOP_CPU_WORKERS`, `LELEKA_LAPTOP_EXPERTS`, `LELEKA_LAPTOP_KAR_FILE`, `LELEKA_LAPTOP_MAX_CONTEXT`, `LELEKA_LAPTOP_MAX_NEW`, `LELEKA_LAPTOP_ORDER`, `LELEKA_LAPTOP_PREFIX_BLOCK`, `LELEKA_LAPTOP_PREFIX_MIB`, `LELEKA_LAPTOP_PROMPT_CACHE`, `LELEKA_LAPTOP_PROMPT_IDS`, `LELEKA_LAPTOP_REPEAT`, `LELEKA_LAPTOP_SEQUENCE`, `LELEKA_LAPTOP_SKIP_FAILED`, `LELEKA_LAPTOP_SOAK_S`, `LELEKA_LAPTOP_SPEC_MIN_P`, `LELEKA_MAPPED_WORKING_SET_GIB`, `LELEKA_MARGINS`, `LELEKA_MEMORY_`, `LELEKA_MEMORY_CACHE_SHARE_PERCENT`, `LELEKA_MEMORY_ENFORCE`, `LELEKA_MEMORY_HARD_FLOOR_MIB`, `LELEKA_MEMORY_HEAL`, `LELEKA_MEMORY_HYSTERESIS_MIB`, `LELEKA_MEMORY_LOCK`, `LELEKA_MEMORY_NO_TRIM`, `LELEKA_MEMORY_PSI_FULL_REJECT`, `LELEKA_MEMORY_PSI_GUARD_MIB`, `LELEKA_MEMORY_PSI_SOME_SHED`, `LELEKA_MEMORY_RESERVE_MIB`, `LELEKA_MEMORY_RESIDENCY_S`, `LELEKA_MEMORY_SAMPLE_MS`, `LELEKA_MEMORY_SOFT_FLOOR_MIB`, `LELEKA_MEMORY_SWAPOUT_PAGES_PER_S`, `LELEKA_MEM_ABORT_GIB`, `LELEKA_MEM_BALLAST_MIB`, `LELEKA_MEM_BIG`, `LELEKA_MEM_BIG_EVERY`, `LELEKA_MEM_EXPERTS`, `LELEKA_MEM_FILL_MAX`, `LELEKA_MEM_FILL_TOKENS`, `LELEKA_MEM_HARD_BELOW_MIB`, `LELEKA_MEM_KAR_FILE`, `LELEKA_MEM_LEAK_SAMPLE_S`, `LELEKA_MEM_LEAK_SECS`, `LELEKA_MEM_LEAK_TSV`, `LELEKA_MEM_LEAK_WARMUP_PCT`, `LELEKA_MEM_PREFIX_MIB`, `LELEKA_MEM_PROBE_SECS`, `LELEKA_MEM_READER_FILE`, `LELEKA_MEM_READER_GIB`, `LELEKA_MEM_READER_NEW`, `LELEKA_MEM_READER_REQS`, `LELEKA_MEM_REQUESTS`, `LELEKA_MEM_SCENARIO`, `LELEKA_MEM_SESSIONS`, `LELEKA_MEM_SESSION_CAP`, `LELEKA_MEM_SMOKE`, `LELEKA_MEM_SOFT_BELOW_MIB`, `LELEKA_MEM_TOKENS`, `LELEKA_MEM_WARMUP`, `LELEKA_MMQ_NO_STREAMK`, `LELEKA_MMQ_NO_STREAMK_FILE`, `LELEKA_MMQ_STREAMK`, `LELEKA_MMQ_STREAMK_FILE`, `LELEKA_MODEL_SHA256`, `LELEKA_MTP_RT_BANK_GPU`, `LELEKA_MTP_SCALAR_SHORT_GPU`, `LELEKA_NO_TRIM_FILE`, `LELEKA_NPU_CPU_THREADS`, `LELEKA_NPU_PROFILE`, `LELEKA_OPENVINO_DEVICE`, `LELEKA_OPENVINO_ROOT`, `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY`, `LELEKA_ORIGINAL_SERVE_BUDGET_GIB`, `LELEKA_ORIGINAL_SERVE_CAPACITY`, `LELEKA_ORIGINAL_SERVE_EXPERT_`, `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER`, `LELEKA_ORIGINAL_SERVE_KV_RESIDENT`, `LELEKA_ORIGINAL_SERVE_LONG_ARMS`, `LELEKA_ORIGINAL_SERVE_LONG_CONVERSATION`, `LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR`, `LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR`, `LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW`, `LELEKA_ORIGINAL_SERVE_LONG_QUESTION`, `LELEKA_ORIGINAL_SERVE_LONG_REPEAT`, `LELEKA_ORIGINAL_SERVE_LONG_SMOKE`, `LELEKA_ORIGINAL_SERVE_LONG_TEXT_FILE`, `LELEKA_ORIGINAL_SERVE_LONG_TOKENS`, `LELEKA_ORIGINAL_SERVE_MAX_CONTEXT`, `LELEKA_ORIGINAL_SERVE_NAN_GUARD`, `LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES`, `LELEKA_ORIGINAL_SERVE_NAN_INJECT`, `LELEKA_ORIGINAL_SERVE_PCIE_FRAC`, `LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED`, `LELEKA_ORIGINAL_SERVE_PREFILL_BORROW`, `LELEKA_ORIGINAL_SERVE_REPLAY`, `LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB`, `LELEKA_ORIGINAL_SERVE_RT_DIR`, `LELEKA_ORIGINAL_SERVE_SMOKE`, `LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB`, `LELEKA_PCIE_DMA_BATCH`, `LELEKA_PCIE_DMA_MANY`, `LELEKA_PCIE_FLAGB`, `LELEKA_PCIE_GRID`, `LELEKA_PCIE_KERNEL`, `LELEKA_PFX_BLOCK`, `LELEKA_PFX_CANCEL`, `LELEKA_PFX_CAPACITY`, `LELEKA_PFX_END`, `LELEKA_PFX_GROW`, `LELEKA_PFX_LAPTOP`, `LELEKA_PFX_MAX_NEW`, `LELEKA_PFX_MIB`, `LELEKA_PFX_MODE`, `LELEKA_PFX_SCENARIO`, `LELEKA_PFX_SESSIONS`, `LELEKA_PFX_SHARED`, `LELEKA_PFX_SMOKE`, `LELEKA_PFX_START`, `LELEKA_PFX_TURNS`, `LELEKA_PFX_VERIFY`, `LELEKA_PLE_`, `LELEKA_PLE_AHEAD`, `LELEKA_PLE_AHEAD_VERIFY`, `LELEKA_PLE_DIRECT`, `LELEKA_PLE_INFLIGHT`, `LELEKA_PLE_PROBE_ARCHIVE`, `LELEKA_PLE_PROBE_DUMP`, `LELEKA_PLE_PROBE_ROWS`, `LELEKA_PLE_READER`, `LELEKA_PLE_ROW_CACHE`, `LELEKA_PLE_SYNC_SUBMIT`, `LELEKA_PREFILL_AHEAD`, `LELEKA_PREFILL_ALIGNED_COPY`, `LELEKA_PREFILL_ALLOC_TRACE`, `LELEKA_PREFILL_CHUNK`, `LELEKA_PREFILL_COPY_STATS`, `LELEKA_PREFILL_DEFER_FREE_MIB`, `LELEKA_PREFILL_DEFER_GUARDS`, `LELEKA_PREFILL_DEPTH`, `LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA`, `LELEKA_PREFILL_FAST_DEQUANT`, `LELEKA_PREFILL_FAST_REC`, `LELEKA_PREFILL_FUSED_SCANS`, `LELEKA_PREFILL_GDN_KH`, `LELEKA_PREFILL_GDN_NOSTORE`, `LELEKA_PREFILL_GDN_POOL`, `LELEKA_PREFILL_GUARD_GRID`, `LELEKA_PREFILL_ISSUER`, `LELEKA_PREFILL_STAGE_GPU`, `LELEKA_PREFILL_STALL_TRACE`, `LELEKA_PREFILL_STREAM_JITTER`, `LELEKA_PREFILL_TOPUP`, `LELEKA_PREFILL_ZERO_MEMSET`, `LELEKA_PREFIX`, `LELEKA_PRESET`, `LELEKA_PUBLIC_EVALUATION`, `LELEKA_Q5_CASE`, `LELEKA_Q5_EVIDENCE`, `LELEKA_Q5_NATIVE_ORACLE`, `LELEKA_Q5_REAL_INPUT`, `LELEKA_Q5_TRUSTED_PTX`, `LELEKA_Q6_CASE`, `LELEKA_Q6_EVIDENCE`, `LELEKA_Q6_NATIVE_ORACLE`, `LELEKA_Q6_REAL_INPUT`, `LELEKA_Q6_TRUSTED_PTX`, `LELEKA_QSA_LATE`, `LELEKA_QSA_LATE_GPU`, `LELEKA_QSA_LATE_SEQ`, `LELEKA_QSA_LATE_SM86`, `LELEKA_QSA_TOPK`, `LELEKA_REAL_GU_DIR`, `LELEKA_REAL_GU_MANIFEST_SHA`, `LELEKA_REAL_GU_OUTPUT_DIR`, `LELEKA_REPLAY_ARMS`, `LELEKA_REPLAY_CAPACITY`, `LELEKA_REPLAY_COUNT`, `LELEKA_REPLAY_DIR`, `LELEKA_REPLAY_FIRST`, `LELEKA_REPLAY_FORCE`, `LELEKA_REPLAY_MAX_CONTEXT`, `LELEKA_REPLAY_MAX_NEW`, `LELEKA_REPLAY_OUT`, `LELEKA_REPLAY_PREFIX_MIB`, `LELEKA_REPLAY_PREFIX_TAIL`, `LELEKA_REPLAY_REPS`, `LELEKA_REPLAY_SPEC_MIN_P`, `LELEKA_RING_SERIALIZE`, `LELEKA_RING_SERIALIZE_CMD_FILE`, `LELEKA_RING_SERIALIZE_COPY_FILE`, `LELEKA_RING_SERIALIZE_FILE`, `LELEKA_ROUTE`, `LELEKA_RUNTIME_TOKEN`, `LELEKA_RUN_REAL_NATIVE_D4`, `LELEKA_SHADOW_DEVICE`, `LELEKA_SKIP_CPU`, `LELEKA_SLOT_LOG`, `LELEKA_SM86_TRACE`, `LELEKA_SMOKE_ARMS`, `LELEKA_SMOKE_CHAT`, `LELEKA_SMOKE_FORCE_DIR`, `LELEKA_SMOKE_FORCE_PASSES`, `LELEKA_SMOKE_MAX_CONTEXT`, `LELEKA_SMOKE_MAX_NEW`, `LELEKA_SMOKE_MIN_P`, `LELEKA_SMOKE_ORDER`, `LELEKA_SMOKE_PROMPTS`, `LELEKA_SMOKE_PROMPT_CACHE`, `LELEKA_SMOKE_PROMPT_IDS`, `LELEKA_SMOKE_REPEAT`, `LELEKA_SMOKE_SAMPLED`, `LELEKA_SPECULATION_LOG`, `LELEKA_SPEC_BIAS_RATE`, `LELEKA_SPEC_COST_ALPHA`, `LELEKA_SPEC_DECAY`, `LELEKA_SPEC_DRAFT_STEP_MS`, `LELEKA_SPEC_EXPLORE`, `LELEKA_SPEC_MARGIN`, `LELEKA_SPEC_MIN_P_LO`, `LELEKA_SPEC_STATS`, `LELEKA_SPEC_TRACE`, `LELEKA_SPLIT_LOG`, `LELEKA_SSD_KEEPALIVE`, `LELEKA_SSD_KEEPALIVE_MS`, `LELEKA_SSD_KEEPALIVE_WINDOW_S`, `LELEKA_STAGE_PRIORITY`, `LELEKA_STAGE_VERIFY`, `LELEKA_STATE`, `LELEKA_STRA169_`, `LELEKA_STRA169_CANDIDATE_CAPTURE`, `LELEKA_STRA169_CAPTURE_DIR`, `LELEKA_STRA169_EXPERT_PROFILE`, `LELEKA_STRA169_IQ3S_SHARD0`, `LELEKA_STRA169_IQ3S_SHARD1`, `LELEKA_STRA169_KAR_ARCHIVE`, `LELEKA_STRA169_KAR_FD`, `LELEKA_STRA169_KAR_PROVENANCE`, `LELEKA_STRA169_KAR_STAGING`, `LELEKA_STRA169_LAYER0_DIR`, `LELEKA_STRA169_MMQ_REFERENCE_DIR`, `LELEKA_STRA169_MMQ_REFERENCE_MANIFEST_SHA`, `LELEKA_STRA169_MTP_PACK`, `LELEKA_STRA169_MTP_STAGING`, `LELEKA_STRA169_NATIVE_BASELINE`, `LELEKA_STRA169_PAIR_METADATA`, `LELEKA_STRA169_PAIR_METADATA_SHA`, `LELEKA_STRA169_PAIR_OUTPUT`, `LELEKA_STRA169_RUN_COMBINED_BOUNDARIES`, `LELEKA_STRA169_RUN_COMBINED_REUSE`, `LELEKA_STRA169_RUN_FIVE_PUBLIC_CASES`, `LELEKA_STRA169_RUN_FIXED_DRAFT_MOE`, `LELEKA_STRA169_RUN_GDN_BATCH`, `LELEKA_STRA169_RUN_GDN_FUSED_T1`, `LELEKA_STRA169_RUN_GDN_MTP_JOURNAL`, `LELEKA_STRA169_RUN_GDN_PRODUCTS`, `LELEKA_STRA169_RUN_GDN_QK_SLOT`, `LELEKA_STRA169_RUN_GDN_ROW_QUEUE`, `LELEKA_STRA169_RUN_GROUPED_CHUNK_PROOF`, `LELEKA_STRA169_RUN_GROUPED_DOWN`, `LELEKA_STRA169_RUN_GR_DEVICE_GUARD`, `LELEKA_STRA169_RUN_GR_HANDOFF`, `LELEKA_STRA169_RUN_GR_MICROBATCH`, `LELEKA_STRA169_RUN_GR_OUTPUT_WORKSPACE`, `LELEKA_STRA169_RUN_LAYER0_MMQ_DIAGNOSTIC`, `LELEKA_STRA169_RUN_MMQ_NUMERIC`, `LELEKA_STRA169_RUN_MOE_GROUP`, `LELEKA_STRA169_RUN_MOE_PREFILL_BATCH`, `LELEKA_STRA169_RUN_MTP_BATCH_NUMERIC`, `LELEKA_STRA169_RUN_MTP_KV_RING_PROOF`, `LELEKA_STRA169_RUN_NATIVE_RESIDENT_MMQ_MODEL`, `LELEKA_STRA169_RUN_OWNED_ASYNC_COPY`, `LELEKA_STRA169_RUN_PLE_CLOSED_QUEUE`, `LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY`, `LELEKA_STRA169_RUN_PUBLIC_NATIVE_DOWN_PAIR`, `LELEKA_STRA169_RUN_QSA_ATTENTION_SCRATCH`, `LELEKA_STRA169_RUN_QUEUED_GR`, `LELEKA_STRA169_RUN_RESIDENT_MMQ_MODEL`, `LELEKA_STRA169_RUN_ROUTED_RESIDENT_QUEUE`, `LELEKA_STRA169_RUN_ROUTER_SCRATCH`, `LELEKA_STRA169_RUN_SINGLELOAD_PROOF`, `LELEKA_STRA172_RUN_GROUPED_GU21_GU23`, `LELEKA_STRA172_RUN_GROUPED_GU21_GU23_NC4`, `LELEKA_STRA172_RUN_GR_BATCH_INJECT_WORKSPACE`, `LELEKA_STRA172_RUN_HEAD_GREEDY`, `LELEKA_STRA172_RUN_MMQ_TRIPLET`, `LELEKA_STRA172_RUN_MTP_INPUT_PREFIX`, `LELEKA_STRA172_RUN_OWNED_GATE_UP_UPLOAD`, `LELEKA_STRA172_RUN_QSA_SELECTED_KV`, `LELEKA_STRA172_RUN_ROUTED_COLUMNS_LOAN`, `LELEKA_STRA172_RUN_ROUTED_FINITE_GUARD`, `LELEKA_STRA172_RUN_ROUTED_GROUP_WORKSPACE`, `LELEKA_STRA172_RUN_SHARED_TAIL`, `LELEKA_SUFFIX_RESET`, `LELEKA_SWEEP_CONTEXT`, `LELEKA_SWEEP_KS`, `LELEKA_SWEEP_MAX_NEW`, `LELEKA_SWEEP_REPS`, `LELEKA_S_FP16_ARGS`, `LELEKA_S_GEMV`, `LELEKA_S_GEMV_Q8K`, `LELEKA_S_GEMV_Q8_SPLIT`, `LELEKA_S_GEMV_SPLIT`, `LELEKA_S_Q8_ARGS`, `LELEKA_TOKENIZER_DIR`, `LELEKA_TOKENIZER_REFERENCE`, `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB`, `LELEKA_TOKENIZER_TEXTS`, `LELEKA_TRACE_LADDER`, `LELEKA_TRACE_PLE`, `LELEKA_TRACE_POISON`, `LELEKA_VERIFY_WINDOW_GPU`, `LELEKA_WARM`, `LELEKA_WINDOW_MODULE_CACHE`, `LELEKA_WSL_DISTRO`, `STRATA_ADAPT_CALLBACK_WARMUP`, `STRATA_ARENA_LOCK`, `STRATA_ARENA_PIN_GIB`, `STRATA_COMMIT_SYNC`, `STRATA_CPU_YMM`, `STRATA_DEC_BATCH`, `STRATA_D_FMTS`, `STRATA_FORCE_AVX2`, `STRATA_GU_FMTS`, `STRATA_HC_SPLIT`, `STRATA_IQ_GATHER`, `STRATA_IQ_MT_MIN`, `STRATA_IQ_PREFETCH`, `STRATA_KEYLESS_ROUTING`, `STRATA_KQ256`, `STRATA_KV_MAIN_OFF`, `STRATA_KV_RING_OFF`, `STRATA_KV_ROT`, `STRATA_LOGPOS`, `STRATA_LOGPOS_TOPK`, `STRATA_NAN_GUARD`, `STRATA_NAN_INJECT`, `STRATA_NO_IQ256`, `STRATA_NO_IQ4NL`, `STRATA_NO_IQ512`, `STRATA_OLD_IQ_MMVQ`, `STRATA_PARTIAL_PIN`, `STRATA_PARTIAL_PIN_GIB`, `STRATA_POOL_SPIN_US`, `STRATA_PREFILL_ISSUER`, `STRATA_PREFILL_RING`, `STRATA_PROMPT_ATTN_V1`, `STRATA_Q2`, `STRATA_Q2_BLOB_BYTES`, `STRATA_QSA_CLUSTER`, `STRATA_QSA_WARP`, `STRATA_SCORES_MULTI`, `STRATA_SNAPSHOT_FULL_CAPTURE`, `STRATA_STAGER_RING`, `STRATA_STAGER_THREADS`, `STRATA_TEST_CACHE_FAIL`, `STRATA_TEST_VERIFY_STALL`, `STRATA_VERIFY_DEVICE_PLAN`, `STRATA_WATCHDOG_S`, `STRATA_WINDOW_DOWN`, `STRATA_WINDOW_GU` - -## 8. DISPOSITION of a default found lossy or unknown - -A default found lossy is a finding returned to TECH_LEAD for a second-wave fix leaf (revert to a lossless value, or mark the mode experimental and keep it off); this leaf changes -nothing: no profile, no `serve_tuning.rs`, no code, no `engine/strata`, no sealed PTX. A default classed `unknown-until-q_pair` stays shipped until its leaf (STRA-267 on the 5090, -STRA-293 on the laptop) returns a q_pair result; no default found here is classed `lossy` in the sense of section 1 (no output-changing mode is ON in ours). - -### Findings for the second wave - -* F1. The 5090 profile ships `LELEKA_CHAIN=all` (K50-19). The chain kernels are not bit-identical to the Original's at 30-70k context (5,993 of 64,355 rows identical, 697 argmax flips, - 1.08 %, docs/chain-kernels.md:70-79); the profile text and the doc call them within rounding noise by the q_tail_gate rule. No 256k q_pair exists. Needs STRA-267. -* F2. The 5090 profile ships `memory.prefix_cache_tail = reply` (K50-21). docs/prefix-cache.md:168 says EXPERIMENTAL, off by default, not to be defaulted before the agreement gate; - docs/prefix-cache.md:190-198 records it as the profile default after a ~70k-token q_tail_gate. The two statements in one document disagree; the gate was not run at 256k. -* F3. Chunk and grid defaults are rounding-level changes with no q_pair: 8192 on the 5090 (K50-11, K50-22; 8192 answered differently on one 16,000-token prompt, docs/prefill-throughput.md:52-57, - whether rounding or a defect was left open) and 6144 on the laptop (K30-09, K30-22; docs/laptop-vs-vanilla.md:79). No log pair for 8192/2048 or 6144/2048 is in the repository (section 9). -* F4. Adaptive speculative window and `spec_min_p`, expert placement (seed ON, adaptive tier ON, per-layer slots, expert profile) are gated only by docs/quality-gate.md section 8 - (612 rows, short prompts, 5090) and docs/adaptive-spec.md:106-111; neither machine has a 256k q_pair for them. Needs STRA-267 and STRA-293. -* F5. `LELEKA_ORIGINAL_SERVE_CPU_WORKERS` / `cpu_workers`: no record found that the result is independent of the worker count. -* F6. Documentation mismatch, no class: `STRATA_PREFILL_STREAM_MIN` is 4096 in code (`cache_original_prompt.rs:29`) and 1024 in the `original_serve_config.rs:277` comment. -* F7. Handoff correction: vanilla's tail-skip default is at `engine/strata/src/program/generate.cpp:10110-10153`, not at a top-level `generate.cpp`. -* F8. Nothing lossy is ON by default in ours: route tail skip is off (S-27) and there is no CPU prefill share (V-02). The conditional ON defaults of vanilla (section 6) are STRA-247's. - -## 9. q_pair logs for chunk 8192 and 6144 - -Logs that exist for chunk 8192 and for chunk 6144: none. `git ls-files` lists 0 files ending in `.log`; `artifacts/runs` in the main checkout is not populated; the only comparison of -chunk sizes in the repository is a greedy-id comparison on one 16,000-token prompt (docs/prefill-throughput.md:52-57), which is not a q_pair result. docs/laptop-vs-vanilla.md:79 -states that q_pair or R-hash arms 2048 against 6144 were `Not run`. `scripts/quality/q_pair.py` exists (usage: `q_pair.py LOG_A LOG_B [--pass N] [--control LOG_A2]`, exit 0 if every common forced row is identical). - -## 10. Counts printed side by side - -The command outputs are produced by the verification run recorded with the item; the page-side counts are: - -| item | command output (recorded with the item) | page count | -| --- | --- | --- | -| profile key rows, rtx5090-32g | 27 | 27 | -| profile key rows, rtx3080-16g | 27 | 27 | -| names in `original_serve*.rs` | 51 | 51 | -| names in the prefill chunk path files | 14 | 14 | -| route tail skip line 64 | `unwrap_or(0)` default | S-27 | -| CPU prefill share grep | empty output | V-02 ABSENT | - -## 11. Commands run in the worktree and their output (AC1-AC3, q_pair log search) - -``` -$ python -c "import json,sys;f=lambda d:sum(f(v) if isinstance(v,dict) else 1 for v in d.values());print([f(json.load(open(p))) for p in sys.argv[1:]])" deploy/rust-runtime/profiles/rtx5090-32g.json deploy/rust-runtime/profiles/rtx3080-16g.json -[27, 27] -$ grep -rhoE '(LELEKA|STRATA)_[A-Z0-9_]+' crates/leleka-runtime/src --include='original_serve*.rs' | sort -u | wc -l -51 -$ (the prefill chunk path file list of section 5b, 31 files, 0 of them matching original_serve*) grep -hoE '(LELEKA|STRATA)_[A-Z0-9_]+' | sort -u | wc -l -14 -$ sed -n '64p' crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs - let rank = std::env::var("LELEKA_ROUTE_TAIL_SKIP").ok().and_then(|v| v.trim().parse::().ok()).filter(|r| (1..TOP_K as u32).contains(r)).unwrap_or(0); -$ grep -rn -i "prefill.*cpu.*share\|PREFILL_CPU_SHARE" crates scripts -(empty output, exit status 1) -$ ls *.log 2>/dev/null -(empty: none) -$ grep -rn "q_pair" docs/prefill-throughput.md docs/laptop-vs-vanilla.md | head -docs/laptop-vs-vanilla.md:79, 80, 152 (the three lines quoted in K30-09 and section 9); docs/prefill-throughput.md: no match -``` - -Page-side counts: 27 and 27 profile-key rows, 51 names in section 5, 14 names in section 5b. The row for route tail skip is S-27 (line 64 as read in this worktree). diff --git a/docs/experiments/2026-10-30-draft-vocab-en.md b/docs/experiments/2026-10-30-draft-vocab-en.md deleted file mode 100644 index ff85324c..00000000 --- a/docs/experiments/2026-10-30-draft-vocab-en.md +++ /dev/null @@ -1,81 +0,0 @@ -# The English draft vocabulary (`draft_vocab_en.bin`): what upstream does, what we ported, how it is gated (claude/draft-vocab) - -Date 2026-10-30. Branch `claude/draft-vocab` from `main` (e92513b7, contains speed-train3 83df1cfa). Nothing below was measured on a GPU: the unit tests are CPU-only, the A/B and identity jobs are written -and not yet run (section 5). Item P1 of `docs/upstream-review/decode.md` (branch `claude/upstream-review-decode`). - -## 1. What upstream does (Strata pin 41cf05a0; the same files at v0.2.7.1 and v0.2.8) - -| Item | Fact | -| --- | --- | -| File format | `draft_vocab*.bin`: little-endian int32 token ids, no header. The draft layer computes its logits over those head rows only (`mtp.cpp`, `gather_rows` of the main head into `dhead_`; `id_to_sub` / `sub_to_id` in `sampler.cu` map between full ids and subset rows). A token outside the subset can never be drafted | -| Shipped files (`data/`, Git blobs of upstream; left out of our tree by `docs/upstream.md`) | `draft_vocab.bin` 425,196 bytes, 106,299 ids (English, code and every CJK token; also copied to `/rt/draft_vocab.bin` by `tools/mtp_rt.py`), `draft_vocab_en.bin` 162,100 bytes, 40,525 ids (ascending, a strict subset of the default list, 65,774 rows fewer), `draft_vocab_cyrillic.bin` 235,852 bytes, 58,963 ids, `draft_vocab_fr.bin` 184,844 bytes, 46,211 ids. Built with `tools/draft_vocab.py` (`--base`, `--add han,kana,hangul,cjk_punct,cjk,cyrillic`, `--corpus ... --coverage 0.99`) | -| sha256 | default `b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91`; **en `369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25`**; cyrillic `25d7fd1670a2e0ec885868d1718d410a3baab03bceeacf0a156cf93ffe4e1ef4`; fr `42b9993629f757c17ad30fc8c242533cb702330f359e85ba729a70d10ef12a81`. Identical at 41cf05a0, v0.2.7.1, v0.2.8 (`git show :data/ \| sha256sum`) | -| Selection | `setup --draft-vocab en\|cyrillic\|fr` copies the file to `rt/draft_vocab.bin` (`setup.py`, `refresh_draft_vocab`); the engine flag `--mtp-draft-vocab FILE` (`generate.cpp:3233`, `Mtp::set_draft_vocab`) reads another file instead of `/draft_vocab.bin` | -| Default | **Not on by default.** The default subset (with CJK) stays for Qwen3.8 at 0.2.6, 0.2.7 and 0.2.8. `setup` only prints `--draft-vocab en` as a tip (a card under 14 GB, or 12 GB on Intel) and "does not set it: it measured +3.1% decode on English prompts, and it would cut the Chinese, ..." (`docs/DGX_SPARK_LINUX.md:47`) | -| Claims | release notes 0.2.7: `--mtp-draft-vocab draft_vocab_en.bin` "+2.7 to +3.1% decode for English text"; `DETAILS.md:309`: "~110 MiB less VRAM, English 1-2% faster, CJK gets almost no drafts"; `fr` 141 -> 158 tok/s in French on an RTX 5090 (reporter's number). All upstream numbers, none of ours | -| Related fix | 0.2.7 `#3911`: a penalty for a history token outside the short draft row wrote past the row. Ours is not affected (`coupled_penalize_kernel` maps through `id_to_sub` and skips an id outside the subset; `docs/upstream-review/decode.md` B5) | - -## 2. Our status before this change - -`crates/cuda-driver/src/original_mtp_rt.rs` read `/draft_vocab.bin` (int32 ids, silently ignored when absent or malformed in size, ids checked against the vocabulary), `original_mtp_draft_head.rs` gathers the main -head rows and builds the id -> subset-row inverse map, `original_mtp_loader.rs::bind_bytes` sizes the startup reserve from the file's size, and the product passes `--mtp-rt-dir` (`crates/deploy/src/config.rs`, -`run-e2e.sh`). The server asset `models/leleka-gates/assets/data/mtp-rt/draft_vocab.bin` has the digest of upstream's default list. **`draft_vocab_en.bin` is not in our assets**; the vanilla install has all four files -(`~/work/vanilla-strata/control/data/`, the same digests), which is the read-only source for the frozen copy. - -Finding for the other gates: the replay-based identity jobs (`speedtrain3-id.sh` and its ancestors) do not set `LELEKA_ORIGINAL_SERVE_RT_DIR`, so their stack takes `OriginalMtpFullOwner::assemble` (no RT directory, no -subset) and drafts over the full 248,320-row head. The product (`--mtp-rt-dir`) drafts over the 106k subset. Those identity results therefore cover the draft path of the full head, not the product's. `draftvocab-id.sh` sets the -directory in every process. - -## 3. The port: `LELEKA_DRAFT_VOCAB` (opt-in, experimental) - -`crates/cuda-driver/src/original_mtp_draft_vocab.rs`, hooked into the two reads of `original_mtp_rt.rs` (`read_draft_vocab`, `observed_draft_vocab_bytes`). - -| Value | Meaning | -| --- | --- | -| unset, empty, `0`, `off`, `default` | `rt/draft_vocab.bin` exactly as before: nothing read, nothing logged | -| `en`, `cyrillic`, `fr` | `draft_vocab_.bin` in the same RT directory as `draft_vocab.bin` | -| anything else | a path | - -* A selected file must hash to a recorded upstream digest (a name: its own digest). Another digest, a symlink, a non-file, a size that is not whole int32s, more than 262,144 ids, or an id outside the vocabulary (the - existing `validate_subset`) is **refused**: the load fails, the engine does not start with another subset. -* A file that does not exist **falls back** to `rt/draft_vocab.bin` and logs `leleka-serve draft-vocab: LELEKA_DRAFT_VOCAB file not found, FALLBACK to rt/draft_vocab.bin`. A harness must treat that line as an - invalid arm (`draftvocab-ab.sh` does). Reason for fallback rather than refusal on a missing file: the literal request; the digest check is the fail-closed part. -* One line per bind when set: `leleka-serve draft-vocab: LELEKA_DRAFT_VOCAB subset=en ids=40525 sha256=... file=...`. -* The startup reserve (`bind_bytes`) follows the selected file's size, so the VRAM the smaller draft head frees (about 65,774 rows x the head's row bytes, upstream says ~110 MiB) shows as more expert slots under - `EXPERT_SLOTS=auto`; with a fixed slot count it is just free memory. -* Default behaviour is unchanged: `draft_vocab_follows_the_original_size_filter` and the other CPU tests of the crate pass (422 passed, 77 GPU tests ignored). -* `draft_vocab_en.bin` is upstream data and stays out of Git (`.gitignore` of upstream matches it; AGENTS.md rule). Frozen copy for the jobs: `/data/leleka-e2e/decode/assets/draft_vocab_en.bin`, created by the jobs - from the vanilla install copy and refused unless its sha256 is the one above. - -Tests (`cargo test -p leleka-cuda-driver --features cuda-driver --lib draft_vocab`, WSL; 11 tests): setting parsing, table consistency (digests unique and lowercase hex, file names, counts), default reads and logs -nothing, a missing file falls back (name and path; the reserve probe and reader then see the default file), a wrong digest is refused for a name and for a path (message carries the actual digest; no reserve size is -reported), a matching digest reads the selected ids and the probe sees their size (the digest of another recorded subset does not satisfy a name), malformed/odd/empty/directory/oversized files refused, symlink refused, -subset row -> full id -> subset row round trip and the ids a restricted subset can no longer propose. With `LELEKA_TEST_DRAFT_VOCAB_DIR` pointing at the four upstream files the real-file test also checks the four digests, the -id counts, no duplicates, every id inside 248,320 rows, `en` ascending and inside the default list, and 65,774 rows fewer (passed on the laptop 2026-10-30). - -## 4. What is expected, and what can go wrong - -* Lossless against verification in principle: the draft only proposes, the verifier checks every token by equality with its own greedy or sampled pick. -* Not bitwise in practice: a different draft changes which windows are accepted and what the rejected suffix of a window holds, so batched kernels may round a verified row differently with different companion rows. Hence a - q_pair gate with an A/A control and a window-shape control (section 5), not an assumption. The earlier upstream-review note said the same ("rounding class changes"). -* Acceptance can only drop for tokens outside the subset (CJK, most Cyrillic) and for English tokens the English subset left out; the A/B reports tokens per round and the accepted-length histogram per arm, so a - draft-step gain bought with acceptance is visible. Our workload (Rust source of the frozen corpus, English prompts, `--max-output 300`) is the favourable case; a Chinese or Russian session would lose. -* Our draft step costs 1.7 ms against vanilla's 0.9 ms (`draft-tail-5090.md`). How much of that is the draft head GEMV over 106k rows is not measured here; the saving scales with the row count (106k -> 40k) and is - bounded by that share. For scale: 1 % of a ~15 ms round is 0.15 ms, so upstream's +2.7-3.1 % would be ~0.4-0.45 ms per round (upstream hardware, upstream workload). - -## 5. Jobs (written, not run) - -Both need a build of this branch (code commit 4232adaf plus the scripts commit): `dt/bin-draftvocab` (leleka-inference, leleka-daemon, leleka-cli, strata-next; `dt/BUILD.md`) and `dt/rt-draftvocab` (leleka-runtime lib test -binary). The jobs create `/data/leleka-e2e/decode/assets/draft_vocab_en.bin` from the vanilla install copy when it is missing and refuse a digest other than `369151522...fb25`. - -* `scripts/e2e/decode/draftvocab-ab.sh`: paired 5-turn ~245k, seed off, frozen corpus, product budget 32,819,404,800, same binary in all arms, counterbalanced order `base en | en base | base en`. Arms `dv-base-noseed`, - `dv-en-noseed` (EXPERT_SLOTS=auto, product effect), `dv-en-eqslots-noseed` (the base arm's slot count, isolates the draft step and acceptance). `LELEKA_SPEC_STATS=1` gives tokens per round, accepted/offered and the - accepted-length histogram per request. Validity rejects an en arm without `subset=en ids=40525`, any FALLBACK, a base arm that logged a draft-vocab line, fewer than 5 spec-stats lines, a failed turn, a short - corpus, turn-5 PLE >= 5 ms. About 13 min an arm, 6 arms, about 80 min (+13 per `eqslots` arm). -* `scripts/e2e/decode/draftvocab-id.sh`: teacher-forced replay of `night5-long-256k`, fixed 8000 slots, `LELEKA_SPEC=4`, `LELEKA_ORIGINAL_SERVE_RT_DIR` set in every process, one test binary. Processes: `idBase`, `idEn` - (two arms each: the A/A floor and the pair), optional `idSpec3` (`WITH_CONTROL=1`: a window-shape change without any weight change, the yardstick for what a different mix of windows does to the rounding class). - `q_pair` compares every forced row whose context is common (identical top-16 rows or d_top1 and argmax flips); `q_tail_gate` gives p99 / max / flip rate against the recorded tail. Pass: 0 argmax flips; identical rows, - or differences no larger than the control's; any flip is a finding. About 8 GPU-min a process, 2 (3) processes, about 20 (30) min. - -Not covered: sampled (non-greedy) quality, non-English sessions, the laptop 3080, the Windows path, and any end-to-end agent task completion with the English subset (the tool-call integrity gate of the charter -applies before this goes into a profile; it stays opt-in until then). diff --git a/docs/experiments/acceptance-knobs-5090.md b/docs/experiments/acceptance-knobs-5090.md deleted file mode 100644 index a403b258..00000000 --- a/docs/experiments/acceptance-knobs-5090.md +++ /dev/null @@ -1,56 +0,0 @@ -# Stage 6d: tokens per round and the drafter on the RTX 5090 (2026-11-12) - -Status: analysis done (no GPU); the knob measurements are queued (section 5) and their numbers are NOT in this file yet. -Labels: M measured, E estimate. - -## 1. Vanilla against Leleka: tokens per round - -Method: vanilla logs `generated N ... drafts accepted a of b` per request, so rounds = generated - accepted (one bonus token a window); Leleka logs `rounds` itself. Requests of 100+ tokens. - -| arm | requests | tok/round | ms/round | decode tok/s | source | -| --- | ---: | ---: | ---: | ---: | --- | -| VAN (vanilla 0.2.6, shipped defaults) | 258 | 2.960 | 12.42 | 238.3 | `codex-compare/runs/main/VAN/*/engine-slice.log` | -| VANL (vanilla 0.2.6, lossy defaults off) | 240 | 2.959 | 13.65 | 216.8 | same, VANL | -| LEL release 17e372944279 | 227 | 3.337 | 18.75 | 178.0 | same, LEL | -| LEL release 83bdd85bb482 (owner default) | 259 | 3.194 | 16.41 | 194.6 | `prefill-latency/runs/e2e-codex-ttt-and-crm-release-83bdd85bb482-owner-default` | - -**Vanilla's accept length is NOT higher; ours is 8-13 % higher.** The gap to vanilla is the round time (16.4 against 12.4-13.7 ms), not acceptance. Tokens per round in the replays: 3.30 (243k), 3.58 (110k), 3.19-3.47 (cap-s3 / 67k). The same finding was made at 245k in 2026-11 (ours 2.05-2.13, vanilla 1.79-1.88, `docs/upstream-review/decode.md`). - -## 2. What upstream changed (pin 41cf05a0 / engine 0.1.50 to `strata-upstream/main` 504b14334 / engine 0.1.59), local git only - -| upstream change | applies to us? | -| --- | --- | -| `6ec4d68ab`, `a04860fad` DFlash2 per-device defaults: Blackwell cc 12.0 conf 0.35 to 0.55, window 6 to 8 | **No.** They configure the DFlash2 block drafter (we run the MTP chain + suffix drafter), only on cc 12.0 cards with >= 48 GB (RTX PRO 5000 72 GB, set IQ3_S, every expert resident, +2.4 %, output identical). The code says explicitly that consumer cards under 48 GB (the RTX 5090 has 32 GB) keep conf 0.35 and window 6 (`strata_control/drafting.py` `big_blackwell`, `window_for`). | -| DFlash2 is the Auto drafter on CUDA IQ3_S (`13edeb7f8`, CLASS_DEFAULTS: MTP only on the 12 GB streaming class) | Means a new-base vanilla on the 5090 will run DFlash2 (slots >= 12,000 give conf 0.35, window 6, tuned pack), not the MTP of our VAN/VANL. Upstream measures DFlash2 +2..+14 % per text kind over MTP on resident cards, +6.5 % on one streaming set, and the MTP wins by 12-44 % where the experts stream from file. Its accept length is not published in the repo (`phaseA-tests/` is not in it). Porting it is a drafter port (5 transformer layers, Q8_0/Q4_0 pack, selector), not a knob. Not started. | -| `cc703b5e4`, `03627326d` (#4040) `--lookup-max-t 12` on by default: prompt-lookup windows up to 12 rows, run as two groups of 8 | The one change that targets accept length. Upstream: file rewrites and agent edit turns +11..+14 % (A6000, resident), prose and code within 1 %. Our `kVerifyMaxT` is 8 (compiled into the sealed PTX). See section 4. | -| `STRATA_SPEC_PROB`, `STRATA_DF2_GATE` (retired later), `STRATA_WINDOW_MAX_T=12/16` | sampled-request or other-drafter features; wide-window build: upstream says it gains less than the two-group form. Not applicable to greedy MTP serving. | -| MTP drafter code (`mtp.cpp`, +292 lines) | plumbing only (prompt room, KVA floor, Pascal Q8, DFlash2 head sharing); the draft numerics and the draft attention window (32768 cells, same constant in ours) are unchanged. | -| `draft_vocab_en.bin` (release notes 0.2.7: +2.7..+3.1 % decode English text) | already ported opt-in (`LELEKA_DRAFT_VOCAB`, `2026-10-30-draft-vocab-en.md`); its A/B never ran. Queued, section 5. | -| `MMQ_KQ` default for cc >= 8.0 | K-quant matmul default for prompt paths; our model is IQ3_S, no draft effect. | - -## 3. Knobs that exist in our port - -`LELEKA_SPEC_ARMS` per-arm policy constants (`explore margin min_p_lo step alpha decay bias ceil rowq smooth measured`, floor ceiling = `adaptive@P`), process level `LELEKA_SPEC_SUFFIX` (suffix minimum match, 3), `LELEKA_SPEC_ADAPTIVE_MAX_T` (8, the compiled ceiling), `LELEKA_SPEC_MTP_MAX_T`, `LELEKA_DRAFT_VOCAB`. The draft attention window (32768) and the suffix index (trigram, 4 candidates) are constants. The window policy landscape was measured flat (+-1.2 %) at 245k on 2026-11-03 (`window-policy-5090.md`); a faster round has since moved the optimum only slightly. - -## 4. Offline estimates (CPU only, M for the counts, E for the conclusions) - -Round cost by width (a request of the 67k replay, `ms_by_T`): T1..T8 = 9.0, 10.1, 11.4, 13.5, 16.1, 19.1, 22.8, 24.1 ms: a base of about 7-9 ms plus 2.2 ms a row. Rounds by accepted drafts (share of rounds, `spec-stats` of the owner-default A/B): 24 % accept nothing; 10 % (67k) and 3-4 % (243k) accept all 7 drafts of a full 8-row window. - -Suffix drafter simulated on the real Codex session cap-s3 (33 requests, 10,414 positions, teacher-forced text, history = prompt + reply; `scripts/e2e/decode/accept-knobs-suffix-sim.py`): a proposal of match length >= 3 exists at 56.5 % of positions; mean accepted 3.81 of 7 per proposal with the 4-candidate index, 3.85 / 3.88 / 3.92 with 8 / 16 / all candidates (+1..+3 % of accepted tokens: too small to pay). If the window allowed 11 drafts: mean accepted 5.29 per proposal and 34.7 % of proposals are fully matched. - -E for a 12-row window (single window, slope 2.2 ms a row): a fully copied stretch costs 24.1 + 4 x 2.2 = 32.9 ms for 12 tokens = 2.74 ms a token against 3.0 at 8 rows (-9 %); full-accept rounds carry roughly a quarter of the tokens, so **at most +2 % end to end** (+1 % at 243k), and only if one 12-row window is built. Upstream's two-group form in our regime would add a second pass with its own base (a 4-row window costs 13.5 ms): 37.6 ms for 12 tokens = 3.1 ms a token, worse than 8 rows. Cost of the port: window kernels and sealed PTX for T=12, GDN commit of 12 rows, drafter catch-up. **Not worth it for 220 tok/s** (needs +20 %). - -Arithmetic of the target: tok/s = tokens per round / round ms. 220 tok/s at 3.3 tokens a round needs a 15.0 ms round; at the current 16.4-17.9 ms it needs 3.6-3.9 tokens a round (+13..+22 %), which no policy knob delivers (all measured within +-1.5 %); the remaining lever is the round time (stages 6c, 6e, 6f). - -## 5. Measurements queued (server, `/data/leleka-e2e/prefill-latency/accept-knobs`, inputs frozen by `MANIFEST.sha256`) - -Instrument: `scripts/e2e/decode/accept-knobs-replay.sh`: the real Codex session cap-s3 (33 requests of 177k-232k tokens, replies capped at 400) teacher-forced in ONE test-binary process (main code of release bcbfa2c99422, sha in the manifest), release profile `rtx5090-32g` engine_env read from the frozen json, several policies as `LELEKA_SPEC_ARMS` on identical text, 5 repetitions with rotated order, base arm and its twin (A/A floor). Summary: `accept-knobs-summary.py` (paired percent against the base, 95 % interval, n of N). - -| job (stub in `~/work/gpu-runs/holder2/jobs`) | content | -| --- | --- | -| `acceptance-replay-harness-smoke-two-arms-three-requests` | harness smoke | -| `acceptance-draft-vocabulary-en-identity-fixed-window-top16-rows` | fixed window 4, suffix off, night5, top-16 rows, default vs English draft vocabulary, A/A inside each process | -| `acceptance-policy-knobs-codex-session-teacher-forced-ceiling-explore-rowq-margin-and-vanilla-window` | base, twin, fixed4@0.5 (vanilla window), ceiling 0.5 / 0.7, explore=0, rowq=0.75, margin=0.05 | -| `acceptance-draft-vocabulary-en-vs-default-codex-session-teacher-forced` | two processes (default vocabulary control, English subset), base + twin each | - -Results directories `/data/leleka-e2e/prefill-latency/runs//`. Identity reading for adaptive-window knobs: the policy changes which window widths run, so rows differ within the batch-rounding envelope (`window-policy-5090.md` section 5); the forced text makes equal output true by construction, and the fixed-window gate above is the bitwise one for the drafter knob. Nothing is defaulted until a knob beats the twin floor and passes its gate. diff --git a/docs/experiments/async-park-compression-and-orchestrator-bench.md b/docs/experiments/async-park-compression-and-orchestrator-bench.md deleted file mode 100644 index 6ee961f7..00000000 --- a/docs/experiments/async-park-compression-and-orchestrator-bench.md +++ /dev/null @@ -1,258 +0,0 @@ -# Plan 6g, owner ideas 2026-11-12: asynchronous compression of parked blocks, and an orchestrator-mode benchmark - -Analysis only: code and docs read, one small synthetic experiment, no GPU, no queue stub, no engine change. Companion of `docs/experiments/multiplexing-feasibility.md` -(numbers from it are quoted, not re-derived) and of `docs/design/memory-single-copy-and-elastic-state.md` C.4-C.6 / T8-T9, which already analysed compression of parked state -in November; this page adds the code-level payload formats, a measured codec test on a synthetic block, the switch-path decomposition and the benchmark design. - -Labels: **M** = measured, source named; **C** = read from code; **E** = estimate by arithmetic from M numbers (arithmetic shown); **S** = measured on SYNTHETIC data (not the model); **U** = unknown. - -## 0. Result - -| Question | Answer | -|---|---| -| (A) Lossless ratio of a parked block | **E: 1.06x pessimistic, 1.17x central, 1.29x optimistic** (S: 1.05x / 1.17x / 1.23x on the K/V codes alone). Not measured on the model: no real parked block exists anywhere (searched the server). | -| (A) Time saved on a session switch | **None.** The switch copy is a host memcpy into the pinned K/V image at 13-14 GB/s (C, M), not a PCIe copy; PCIe carries only the 12 % index rows (about 6 ms at 180k). Decompression at 2.4-2.9 GB/s per core (S) needs about 8 threads to match the one-thread memcpy it replaces. | -| (A) RAM gained | One parked session shrinks by 5 % / 14 % / 22 % (180k: 2.81 -> 2.67 / 2.42 / 2.19 GB). Whole sessions kept (raw -> pessimistic / central / optimistic): 243k at 8 GiB 2 -> 2/2/2, at 13 GiB 3 -> 3/4/4; 180k at 8 GiB 3 -> 3/3/3, at 13 GiB 4 -> 5/5/6 (section A.5). About **+0.4 to +0.8 session**, i.e. +1 session at best. | -| (A) Recommendation | **MEASURE-FIRST, then probably NO-GO as a stand-alone feature.** Cost of the measurement: a 40-line logging hook, 0 extra GPU time when piggy-backed on a 243k run (about 0.4 GPU-h alone). Build the codec only if the measured K/V ratio is at least 1.3x (the T8 gate of the design doc). Cheaper levers first: lazy parking (T6/T7, about -3.2 GiB per live session), the cache budget itself, a parallel import memcpy (saves about 0.1 s per switch). | -| (B) Can Codex be made to fan out | Yes: Codex CLI 0.163.0 advertises the `multi_agent_v1` tool namespace in every request (M, `docs/e2e-run.md` 7); public docs: sub-agents are spawned by the model on request in the prompt, each child makes its own model requests in parallel, `[agents] max_threads` (default 6). Whether the Qwen3.5 IQ3 model calls the spawn tool reliably is **U** and is the first thing to test (step P0/P1). Fallback: N parallel `codex exec` sessions started by the harness. | -| (B) Cost | **about 3-3.5 GPU-hours** for the Leleka-only matrix (pilot 0.7 h + 3 repetitions x 43 min), about 5 GPU-hours with the vanilla `--parallel 1` / `--parallel 2 --batch-mtp` arms (needs the owner's word). Merge with step 1 of `multiplexing-feasibility.md` (2-3 GPU-h): the combined bill is about 4 h, not 6. | -| (B) Expected aggregate effect through today's time-sliced queue | **E: 0.97-1.18x of the same work done one session after another, central 1.03-1.08x**; against ONE agent doing the whole task alone about 0.95-1.08x (the orchestrator's serial plan/wait/merge requests eat the overlap). Not "several times". The benchmark's value is the switch cost, the tier penalty and the real overlap, with numbers instead of E. | - -## A. Asynchronous compression of parked blocks - -### A.1 What is parked, and in which format (C unless marked) - -Code path: `QwenSession` park -> `ResidentQsaLayer::export_span` (`crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/prompt_device/resident_device/span_transfer.rs`) -fills one `ParkedLayerSpan { first_token, tokens, kv: Vec, index: Vec }` per QSA layer; a `ParkedBlock` (`session_original_prompt.rs`) is 12 spans; a `ParkedSession` -(node) holds the GDN and PLE priors, the index checkpoint tails and the draft-ring snapshot. The store (`engine-core::prefix_cache`) is model-free and keeps them as plain host heap bytes. - -| Component | Format | Bytes | Share of a block | Source | -|---|---|---:|---:|---| -| K codes | **int8**, symmetric, `clamp(rint(x/scale), -127, 127)`, 2 KV heads x 256 dims, one scale per 64 values | 512 B per cell and layer | 43.2 % | `crates/experimental-ref/src/kv_q8.rs`, `crates/context/src/geometry.rs` | -| V codes | int8, same | 512 B | 43.2 % | same | -| K / V scales | **fp16**, 8 per cell and layer (2 heads x 4 groups) | 16 B + 16 B | 2.7 % | same | -| pooled index rows | **fp32**, 128 values per 4-cell row (sum of four fp16-rounded keys, RMS-normalised, gamma, RoPE) | 512 B per 4 cells = 128 B per cell and layer | 10.8 % | `qsa_prompt_indexer.cu::pooled_value`, `OriginalQsaResidentIndex::ROW_BYTES` | -| **block total** | host layout is run-major per 4-cell page (K codes 2048 B, V codes 2048 B, K scales 64 B, V scales 64 B = 4224 B), index rows separate | **1,184 B per cell and layer, 14,208 B per token (12 layers)** | 100 % | `PAGE`, `prefix-cache.md` | -| node: GDN recurrent state | **fp32**, 36 layers, constant 112.2 MiB (117,669,888 B) plus a history window (`host_bytes = (values + history) x 4`) | about 127 MB per node with PLE history (fp32, 360 KiB), 12 index tails of 2,564 B and the draft-ring snapshot | n/a (constant per node) | `gdn_state.rs`, `memory-single-copy...md` C.1 | - -There is no bf16/fp8 anywhere in a parked block: the "bf16 weight/KV" literature ratios do not transfer. K/V are already 8-bit, so the exponent-splitting tricks (ZipNN, DFloat11) have -nothing to split except the fp16 scales and the fp32 index rows, which are 14 % of the bytes. Other K/V formats exist (`Q4_0` 576 B, `K8V4` 816 B, keyless 528 B per cell); parking them -would be a lossy re-quantisation of an INT8 image and is out of scope (needs its own quality gate; not default). - -### A.2 Lossless ratio - -**No real parked block exists to measure.** Searched `/data/leleka-e2e` (read-only, files above 50 MB and `*.bin`/`*.raw`/`*.img`, names with kv/park/dump/ckpt): only model assets, build output and profiler -`sync.bin`. `LELEKA_ORIGINAL_SERVE_DUMP_ROUTING` dumps expert routing only. The T8 hook of the design doc was never built. - -What is known without the model: - -* **S, order-0 entropy and `zstd` on synthetic blocks** (script `scripts/memory/kv_block_compress_sim.py`, one 2048-token block of one layer in the real layout; three activation models; `zstd` 1.5.7 on the 9950X3D, - one thread, `nice 19`, the box was loaded by a running GPU job (load 15), 2 MiB inputs, 2-3 iterations each, so the speeds are indicative, not benchmarks): - - | synthetic K/V model | entropy of codes | ideal x | zstd -1 / -3 x | zstd -19 x | zstd -1 compress, decompress (MB/s) | - |---|---:|---:|---:|---:|---:| - | Gaussian, no outliers (worst case) | 7.62 bit/B | 1.05 | 1.047 / 1.046 | n/a | 858 / 2413 | - | per-channel outliers (log-normal scale sigma 0.7) | 6.79 | 1.18 | 1.171 / 1.171 | 1.170 (11-14 MB/s) | 880 / 2638 | - | outliers + Student-t(4) tails | 6.49 | 1.23 | 1.226 / 1.226 | n/a | 884 / 2894 | - | fp16 scales plane (K and V) | 5.85-6.58 | 1.22-1.37 | 1.24-1.36 | | 880-950 / 2330-2750 | - | fp32 pooled index rows, raw | 6.67 (byte-plane mean) | 1.20 | **1.079** | | 929 / 2340 | - | fp32 pooled index rows, byte-shuffled | | | **1.135-1.144** | | 1300 / 3880 | - - Reading: zstd at level 1 already reaches the order-0 entropy of the codes (levels 3 and 19 add nothing; -19 is 70x slower); LZ matching finds nothing in quantised activations, so `lz4` (not installed - on the server) would sit at about 1.0x; the entropy stage is the whole gain. The index rows need the byte shuffle. The earlier `scripts/memory/entropy_bound.py` gave 1.06 / 1.14 / 1.20 for Gaussian / Laplace / Student-t vectors of width 128 and 1.20 (shuffled 1.16) for fp32 states; the two syntheses agree. -* **Real activations are probably better than Gaussian** (U): keys have outlier channels, which make the per-64 absmax large and leave the other channels on few levels; this is what the second and third rows model. Whether the - real distribution is closer to row 1 or row 3 decides 1.05 against 1.23; the model itself must tell. -* **Literature, other dtypes**: Bf16 caches carry about 11 bits of entropy per scalar (about 30 % smaller, speculative-KV-coding blog), FP8 weights compress to about 83 % (Heilper and Singer, lossless compression of low-precision tensors), - and the slack "collapses as the bit width falls" (same blog); that is consistent with 1.05-1.25 for int8 codes. Entropy-coded KV in KVComp is lossy end to end (quantisation first). - -Estimate for a whole block and node (E; weights 1024 / 32 / 128 of 1184 B; codes, scales, index ratios per column; node = 112 MiB fp32 GDN state at 1.0 / 1.12 / 1.2 from `entropy_bound.py`): - -| scenario | codes | scales | index | block ratio | node ratio | -|---|---:|---:|---:|---:|---:| -| pessimistic | 1.05 | 1.20 | 1.08 | **1.057** | 1.0 | -| central | 1.17 | 1.25 | 1.14 | **1.169** | 1.12 | -| optimistic | 1.30 | 1.35 | 1.20 | **1.290** | 1.2 | - -### A.3 Where the time goes on a switch, and what compression does to it - -Decomposition of the restore (C for the path, M for the totals from `prefix-cache.md` sections 2-3): - -* K/V pages: `OriginalQsaMappedJournal::import_pages` -> `write_import_spans` -> `m.write(...)` into the **pinned mapped host image** (the authority for every cell; the 20-32k-cell VRAM window is - refilled on demand after the resolver reset). This is a **host-to-host memcpy**, one thread, plus `context.synchronize()` before it. 180k tokens x 12 layers x 1056 B = 2.28 GB; measured 175-194 ms for 2.4-2.6 GB = **13-14 GB/s** (M). -* Pooled index rows: `OriginalQsaResidentIndex::import` writes into the **device** image: 180k x 12 x 128 B = 0.28 GB over PCIe at 45 GB/s = **about 6 ms** (E). -* So the owner's picture ("dominated by the PCIe copy; 2.6 GB = 60 ms at 45 GB/s") is not what runs: 60 ms is what the same bytes would cost over PCIe, the restore takes 3x that because it is - a single-thread host memcpy. **The cheapest switch speed-up is a parallel memcpy**: 4 threads over the 12 layers x blocks would approach the DRAM limit (read 2.3 GB + write 2.3 GB at 74.5 GB/s - shared = about 62 ms floor, E), saving about 100-130 ms per full switch at 180k, bitwise identical by construction. Not measured; it is a candidate row, not a result. - -Effect of compression on that path (E, decompress 2.4 GB/s per thread from the S measurement, writing straight into the pinned image instead of memcpy): - -| threads on the switch | decompress 180k (2.28 GB raw) | 243k | note | -|---|---:|---:|---| -| 1 | 950 ms | 1.2 s | 5x slower than today's 190 ms | -| 4 | 240 ms | 320 ms | about today's | -| 8 | 120 ms | 160 ms | about 0.6x of today; the same as a parallel memcpy would give without compression | -| GPU (nvCOMP-class) | does not apply | | see below | - -So compression never makes the switch faster than an uncompressed parallel import; at best it hides inside it, and it takes up to 8 hardware threads at the one moment the engine thread is waiting. The switch is 0.07-0.3 s of an 8 s request (1-4 %); there -is no meaningful time to win there. **Where time can be won is eviction:** a session evicted for lack of RAM costs a cold prefill (28-31 s at 100k, 51-55 s at 180k, M) instead of 0.2 s, so the value of -extra capacity is about 250x the cost of the copy, but it only exists when the working set falls into the band between the raw and the compressed capacity (about 14 % of the budget wide). - -**GPU-side decode (nvCOMP-style) is the wrong shape here.** The project links only the CUDA Driver API and loads sealed PTX built offline (no cuBLAS/nvCOMP dependency; `AGENTS.md`, `crates/cuda-driver`). A hand-written -GPU entropy decoder (Huffman/tANS LUT kernel, about 500-800 lines CUDA plus a seal cycle for sm_120 and sm_86) is possible, but the destination of 89 % of the bytes is the **host** K/V image: GPU decode would mean -compressed bytes up (2.0 GB), decode, raw bytes down (2.3 GB), both over the PCIe the prefill expert ring is using (44.6 GB/s measured over the copies, ledger U6). That is about 100 ms of PCIe plus the decode, no better than the 190 ms memcpy it replaces, and it -competes with the prefill that follows. Only the index rows (device-resident, 11 %) would benefit. No-go. - -### A.4 Async compression: CPU budget (C/E) - -* Hardware (M): the server is a Ryzen 9 9950X3D, 16 cores / 32 threads, 128 MiB L3; the engine takes **15 expert workers** (`docs/deploy.md`; `min(cores - 2, 15)`), one engine thread and the draft/stager threads. The design doc's note - (C.5) says the 15 workers sit on 15 physical cores and the CPU leg is about 3.9 ms of a 15-18 ms round, so the spare capacity is **one physical core plus the SMT siblings (about 14-16 logical threads that share execution units with busy workers)** (U for the pinning layout). Decode is bound by host DRAM (CPU leg + PCIe reach 74.5 GB/s together, `roofline.md`), so a compressor competes for the scarce resource even when cores are free. -* The load is small if blocks are compressed **once, when they become cold**, not as a stream of whole sessions: a block is immutable; a request adds about one block (1.6-2.7k tokens = 23-39 MB raw, `prefix-cache.md`). At 0.85 GB/s per thread that is **about 30-45 ms of ONE thread per 8 s request (0.4-0.6 % of a thread)** and 1.2 GB/s of DRAM traffic for 30 ms. A cold 180k build (55 s of prefill) adds - 3.0 s of one thread (2.8 GB at 0.85 GB/s). Both are negligible next to 15 busy workers, but "negligible" for decode is exactly what the paired A/B must show (deploy.md measured: removing 7 of the 15 workers costs -2.4 %; a pure DRAM-bound neighbour at 1-2 % of 74.5 GB/s is expected to cost under 1 %, U). -* "Idle only" (the design doc's rule) is hard to meet for an agent: the gap between requests is 56-448 ms (M) and with several sessions there is no idle at all, so the compressor must run at idle priority beside the decode, with a cap of 1-2 threads. -* Policy that makes the whole thing small: compress only blocks of sessions that are **not the live one** (the live session's buffer holds its prefix; the same session continuing never reads its blocks, which is why lazy parking T6 saves 100 % of them for a single agent), and decompress on switch only the blocks the other session overwrote. - -### A.5 RAM capacity (E) - -Per session = blocks (14,208 B x tokens) + 2 nodes of 127 MB (a thinned session keeps its frontier and one previous node). Budgets: 8 GiB and 13 GiB are the measured `auto` values on the 5090 server with the 53.5 GiB engine footprint (`deploy.md`, `prefix-cache.md`); 27 GiB is what a 41 GB `MemAvailable` (observed on the server 2026-11-12 with a job running) would give at 75 %. - -Parked size of one session, raw -> pessimistic / central / optimistic: - -| tokens | raw | pessimistic | central | optimistic | -|---|---:|---:|---:|---:| -| 30k | 0.68 GB | 0.66 | 0.59 | 0.54 | -| 70k | 1.25 | 1.20 | 1.08 | 0.98 | -| 100k | 1.67 | 1.60 | 1.44 | 1.31 | -| 180k | 2.81 | 2.67 | 2.42 | 2.19 | -| 243k | 3.71 | 3.52 | 3.18 | 2.89 | - -Sessions that fit (fractional; the integer part is what is kept): - -| budget | tokens | raw | pessimistic | central | optimistic | -|---|---|---:|---:|---:|---:| -| 8 GiB | 70k | 6.88 | 7.19 | 7.97 | 8.74 | -| 8 GiB | 180k | 3.06 | 3.21 | 3.56 | 3.91 | -| 8 GiB | 243k | 2.32 | 2.44 | 2.70 | 2.97 | -| 13 GiB | 70k | 11.18 | 11.68 | 12.95 | 14.20 | -| 13 GiB | 180k | 4.96 | 5.22 | 5.78 | 6.36 | -| 13 GiB | 243k | 3.77 | 3.96 | 4.39 | 4.83 | -| 27 GiB | 70k | 23.2 | 24.3 | 26.9 | 29.5 | -| 27 GiB | 180k | 10.3 | 10.8 | 12.0 | 13.2 | -| 27 GiB | 243k | 7.8 | 8.2 | 9.1 | 10.0 | - -In whole sessions the central scenario gains: 8 GiB 70k 6 -> 7, 180k 3 -> 3, 243k 2 -> 2; 13 GiB 70k 11 -> 12, 180k 4 -> 5, 243k 3 -> 4; 27 GiB 180k 10 -> 11-12, 243k 7 -> 9. **At the budgets that matter for 243k sessions -the gain is zero or one session**, and in the pessimistic case it is zero everywhere but 70k. - -Comparison with the other levers (E): lazy parking removes the live session's blocks (3.2 GiB at 245k) = one full session at 8-13 GiB, more than the central compression gain, and costs 0.27 s on a switch (the same memcpy); raising the budget from -8 to 27 GiB (the single-copy work freed about 42 GB) = 3.4x capacity, 20x the central compression gain. Compression multiplies what is left after those, ~1.17x. - -### A.6 Exactness - -Lossless coding is exact if the round trip is checked: store `{codec, raw_len, crc}` per span, decompress straight into the destination, verify the crc, and on any mismatch drop the node (a miss, never wrong state). The existing -byte-for-byte parked tests (`parked_tests`: write back, export, compare) and the `prefix_bypass` equality check (restored vs full read) keep their meaning; the lossless class needs no quality gate beyond them. **Any lossy variant** (re-quantising to Q4/K8V4, fp16 GDN -state) changes numerics and stays an experimental mode behind its own gate (`AGENTS.md`); not proposed here. - -### A.7 Recommendation: measure-first, expected NO-GO as a stand-alone feature - -1. **The minimal hook (T8), cost about 40 lines, no behaviour change**: in `ResidentQsaLayer::export_span` (K/V and index vectors are in hand) and where the node's GDN image is cloned (`session_park_and_qsa_owners.rs`), behind - `LELEKA_PREFIX_DUMP_STATS=1`, log per block and layer the 256-bin histogram entropy of the K codes, V codes, K scales, V scales, index byte-planes, and for nodes of the GDN byte-planes; optionally `LELEKA_PREFIX_DUMP_DIR=/data/leleka-e2e/prefill-latency//` writing 3 blocks (early, middle, late of one 243k replay; at the 2048 grid a block is 29 MB over the 12 layers, 87 MB in all; at the 8192 grid 116 MB each) and one node (127 MB) for `zstd -1/-3`, the byte shuffle and the speed test on the real bytes (about 215 MB at the 2048 grid). Entropy lines cost nothing and prove the ideal ratio (zstd reached the order-0 bound on every synthetic plane). It rides on any job that already replays a 243k session - (the `q245`/`fixbug-ledger` replays); alone, one 243k replay is about 0.4 GPU-h. `/data` has about 2 GB free, so dump only the sub-samples and move them to `garbage/` afterwards. -2. **Gate (from the design doc):** build the codec only if the measured K/V ratio is at least **1.3x** or the GDN ratio at least 1.3x. On the S data only the optimistic column reaches it. -3. If it passes: compress once per cold block with `zstd` level 1 (a Rust port or a vendored decoder, since the production binary may not link a library: a Huffman/FSE encoder is about 600 lines; this is a new dependency decision for the owner), 1-2 idle-priority threads, decompress on 4-8 threads straight into the pinned image on a switch; acceptance = bytes equal (property tests + `prefix_bypass`), paired A/B of decode tok/s with the compressor running against not running (A/A floor +-1-2 %), RAM series. -4. **Do first, in this order** (all cheaper and larger): T6/T7 lazy parking, a decision on the budget cap (T2/T11), a parallel import memcpy (candidate, E -100..-130 ms per switch at 180k), then T8. - -## B. Orchestrator-mode benchmark (design, not run) - -### B.1 Why this benchmark - -The earlier analysis found no overlapping requests in 4 recorded sessions (227 requests, 0 negative gaps) and no `multi_agent_v1` call in 750 recorded rounds. With a Codex that orchestrates sub-agents, concurrent requests to the gateway are guaranteed, so what Leleka does with them -(FIFO queue, one generation at a time, cache switch per request) becomes the product behaviour, not an edge case. - -### B.2 What Leleka and vanilla Strata do with concurrent requests today - -| | Leleka (this repo) | vanilla Strata `--parallel 1` (our compare arms) | vanilla `--parallel N` / `--batch-mtp` | -|---|---|---|---| -| Admission | gateway `max_in_flight_requests` 17 (429 beyond); `mpsc(16)`; one worker task | the server queue: "one request at a time, the others wait" (`BATCHING.md` line 3) | up to N slots decode together | -| Execution | strictly serial, FIFO, no preemption of a prefill (cancel takes up to one chunk, 1.6 s at 2048) | serial; conversation cache parks the other session's history (on by default with an auto budget) | every verify window carries one token of each slot; per-slot GDN/QSA/PLE state; a slot costs 0.56 GiB VRAM at 32K | -| Switch | prefix store restore: 1-3 ms no-copy, 0.07-0.3 s when blocks were overwritten (M/E, 101 ms at 98k, 175-194 ms at 172-180k) + 98-109 ms decode-graph re-record per request (with or without a switch) | 50-60 ms per short conversation restore (DETAILS/BATCHING); a long prompt gives way to a short one (`BYIELD`) | n/a | -| Their own gain from batching | none | none | 4 concurrent requests on a 12 GB card: 63.1 vs 70.7 tok/s one after another (-11 %); PRO 6000 Blackwell all-in-VRAM: 179 -> 268-312 tok/s at 4 (+50..74 %); 2x3080: +15 %; PRO 5000: +31..39 % at 2-4 clients (vendor numbers, BATCHING.md). Setup advice: only where the expert cache holds at least half the experts; our 5090 tier holds 49.6 % | - -### B.3 How to make Codex produce concurrent requests - -Facts: the harness uses `codex exec --json --skip-git-repo-check -C ""` with Codex CLI **0.163.0** (`run-codex.sh`; config rendered from `scripts/e2e/codex/config.toml.tmpl`: `approval_policy = "never"`, `sandbox_mode = "workspace-write"`, `wire_api = "responses"`, `stream_idle_timeout_ms = 900000`, `request_max_retries = 2`). Every request of this version already carries the `multi_agent_v1` namespace (10 KB) and `parallel_tool_calls: true` (M, `docs/e2e-run.md` 7), so the sub-agent tools exist and are on in the shipped version. Public documentation (OpenAI Codex docs, "Subagents") says: - -* sub-agents are spawned **by the model when the prompt asks for it** ("spawn two agents", "one agent per point", say how to split, whether to wait, what to return); built-in agents `default`, `worker`, `explorer`; children inherit the parent's model and reasoning effort; -* config under `[agents]`: `max_threads` (legacy alias, third-party docs: default 6) / `max_concurrent_threads_per_session`, `max_depth` (default 1: the root spawns children, no grandchildren), `job_max_runtime_seconds` (CSV jobs); a flag `multi_agent` can be set by `--enable multi_agent` or `[features] multi_agent = true` in builds where it is not yet default; -* "each child performs its own model inference and tool invocations" in parallel threads: that is the source of concurrent `POST /v1/responses`. -* Not in the public text, **U** until tried: that `codex exec` (non-interactive) runs the spawn tools to completion under `approval_policy = "never"`; that the Qwen3.5 IQ3 model calls them correctly (a 10 KB tool namespace is one more place for tool-call integrity to fail); the headers/instructions of a child's requests (whether its first 8192 tokens equal the parent's, which decides prefix-cache sharing). - -**Step P0, CPU only, about 1 hour:** run the real Codex binary (already installed on the server for the harness) against `scripts/e2e/codex/mock_responses.py` extended to script a `spawn_agent`-style call, record the `multi_agent_v1` schema (tool names, parameters), the number and timing of concurrent requests children issue, the per-request headers (`session_id`/thread id) and the common prefix length of parent and child requests. This answers the "can the CLI fan out" question without a GPU. - -**If the model will not spawn (Fallback H): N parallel Codex sessions from the harness.** `cell.py` already takes a free proxy port, a cell directory and `--active-dir` per cell (concurrency-safe, `multiplexing-feasibility.md` section 4): start the N cells of one boot together, each with its own sub-task prompt; the stack is shared. This does not test Codex's orchestrator, but it produces the same request pattern with controlled work. - -### B.4 Task and arms - -Task: **`nestng-crm`** (`scripts/e2e/codex/tasks/nestng-crm`, 56-check `accept.py`, 30-70 rounds, two disjoint trees `backend/` (NestJS) and `frontend/` (Angular 20)) is naturally parallel: backend API + its jest/e2e tests, frontend pages + build, then a short README and a verification pass. A multi-part refactor -(`refactor-shop`) is a second choice (parts are independent files but the shared seed makes conflicts likely). `ttt` is too small (14-21 rounds) for N>2 but works as a cheap stress (4 x ttt). -The split prompt is the task's own text cut at the Backend / Frontend boundary (same acceptance); the orchestrator prompt adds only: "Spawn one worker for `backend/` and one for `frontend/`, wait for both, then write README.md and run both builds and test commands yourself; do not spawn further agents." - -| Arm | What runs | Purpose | -|---|---|---| -| S1 | one session, the full prompt (the existing cell) | reference single-agent wall (LEL CRM M: 488 s, 54 rounds, 163 tok/s) | -| S2 | backend session, then frontend session, fresh contexts, strictly sequential (harness) | the correct sequential baseline for the same sub-tasks | -| H2 | the same two sub-task sessions started together (harness fan-out) | time-sliced queue with controlled work | -| O | one orchestrator prompt, Codex spawns 2 (and in a second variant 3-4) sub-agents | the real orchestrator mode (if P0 passes) | -| H4 (optional) | 4 x `ttt` started together | queue depth 4, switch and tier penalty | -| V1 / V2 / V4 (optional, owner's word) | vanilla `--parallel 1`, `--parallel 2 --batch-mtp`, `--parallel 4 --batch-mtp`, arms S2/H2/O | what batching gives on this card; the reference of any "several times" claim | - -Quality: temperature 0 as in the existing cells; accepted by the same `accept.py` (strict) and the relaxed `reaccept-1` version, both reported (rule from the ledger, 2026-11-12); the workspace of parallel children must be disjoint, merge conflicts counted as failures. Paired reps: 3 blocks, arm order rotated, same boot per block (no cross-boot comparisons), release pinned by the PROVENANCE commit. - -### B.5 Metrics (from `requests.log`: admitted, engine_start, first_token, session id; `proxy/rounds.jsonl`; `mon.csv`) - -* **Wall to accepted result** per arm (primary, but CRM wall sd is 21-112 s on 430-540 s: effects below about 15-20 % cannot be resolved with n=3; this is why the other metrics matter). -* **Aggregate tok/s** = sum of committed output tokens / wall, and **engine duty cycle** = sum of engine-busy intervals / wall; **overlap recovered** = seconds in which the engine served request k while another session was in tool/think time. -* **Per-session tok/s** (decode tokens / decode time of its requests, expected unchanged) and **per-session pace** (tokens / wall, expected about 1/N). -* **TTFT** and **queue wait** (`engine_start - admitted`) per request, p50/p90, expected (N-1) x 8 s; **switch cost** per request (`prefix_import_ms`, `reused_tokens`, `prefix_hit`, graph re-record) and the **tier penalty** (VRAM expert share, hit share by request ordinal after a switch vs same session continuing). -* Rounds and requests per session (trajectory length differs between greedy runs), sub-agents actually spawned and their request counts, 429 or timeout events, tool-call failures. -* **VRAM min free** (rule: at least 315 MiB, M 338-340 MiB on the 243k runs), **RAM** `MemAvailable` min, prefix-store used/budget/evicted/rejected (extra sessions raise eviction). -* Acceptance: pass/total of both accept versions. - -### B.6 Expected effect: when the time-sliced queue helps and when not (E from M) - -Model for N sessions of equal work, per-request model time m, tool/think gap g (gamma = g/m = (wall - model)/model over a cell), switch overhead sigma per request (switch + unmeasured tier penalty, relative to m). Sequential = N m (1 + gamma). Queue (N large enough to keep the engine full, N >= 1 + gamma) = N m (1 + sigma) + a serial head and tail. So - - speed-up = (1 + gamma) / (1 + sigma), capped by the serial parts of the orchestrator. - -* M gamma from `docs/e2e-data/codex-compare/compare.csv` (3 reps each): LEL CRM **0.089** (0.067-0.117), LEL ttt 0.034, VAN CRM 0.194 (0.074-0.387), VANL CRM 0.224, VAN ttt 0.037. M trace gaps (4 recorded sessions): 1.0-2.0 % of wall (`docs/e2e-data/*-trace.csv`). -* M sigma pieces: switch 0.07-0.3 s on an 8.3-8.4 s request (CRM LEL 395.7 s / 47 rounds) = 0.8-3.6 %; tier penalty U (cold-tier hit gap 3.1 points = about 1.5 % of decode, E from 0.0021 point/slot and 0.67 %/192 slots); say sigma 1-6 %. - -| gamma | sigma 1 % | sigma 3.6 % | sigma 6 % | -|---|---:|---:|---:| -| 0.034 (LEL ttt) | 1.024 | 0.998 | 0.976 | -| 0.089 (LEL CRM) | 1.078 | 1.051 | 1.027 | -| 0.194 (vanilla-like waits) | 1.18 | 1.15 | 1.13 | - -* **Trace-driven check** (`scripts/memory/queue_gap_sim.py`, S/M: recorded service times and gaps of the four sessions, FIFO engine, pairs and all four together): concurrent makespan against the sum of solo walls = **0.993-1.010 with a 0.1-0.3 s switch at the recorded speeds; 0.98-1.025 if decode were 2.5x faster with the same gaps**. The recorded sessions have so little idle (1-2 %) that the queue cannot gain more than 1-2 %, and a 0.3 s switch erases it. -* **Orchestrator end to end (E):** CRM model time 448 s (LEL mean). Split into two children, the queue makespan is about 448 x (1 + 0.01..0.04) + serial plan/wait/merge requests (about 20 s, which do not overlap) = 472-486 s, against S1 488 s and S2 (sequential children plus the same serial parts) about 505-515 s: **O/S2 about 1.03-1.08, O/S1 about 1.00-1.03**, with the trajectory noise (wall sd 21-112 s) much larger than the effect. With vanilla-like waits (gamma 0.19) up to 1.1-1.15. -* **When the queue helps:** (1) long tool waits while other agents have work: builds, test suites (`ng build` 20-60 s, jest runs) in a child while another child decodes: this is the gamma term; (2) any cache-less alternative: against a single-slot engine that re-prefills on a switch the cache saves 3.5-5.5x at 70k (E, `multiplexing-feasibility.md` 2.4; M sum of TTFT 1,200 s -> 244 s on the 4-session trace); (3) fairness: a child's short request is not blocked behind the orchestrator for more than one request. -* **When it does not:** (1) tool time is small (gamma below sigma, ttt-like tasks): the queue is a wash or slightly negative; (2) the engine is the bottleneck with N >= 2: per-session pace is 1/N and the wall to the last result is the sum of model times, no matter how many agents; (3) a cold 180k prefill (55 s) blocks all (FIFO, no preemption); (4) more sessions than the RAM budget keeps (A.5) turn switches into cold prefills; (5) each child's first request is a cold prefill of its own context (1-9 s; 9.3k tokens of shared system+tools are cached only if the first 8192-token block is identical to the parent's, U). -* Simultaneous decode (not built) is a separate, later step: E 1.0-1.3x at N=2 on top (`multiplexing-feasibility.md` 3.2); vanilla already has it opt-in. - -### B.7 GPU cost - -| Step | Content | GPU | -|---|---|---:| -| P0 | mock-server run of the real Codex: tool schema, concurrency pattern, prefix overlap | 0 (CPU, about 1 h) | -| P1 pilot | one boot (about 6 min) + O prompt x1 + H2 x1: do children spawn, do 2 requests overlap, no 429/timeouts | 0.7 h | -| Main | per block: boot 6 + S1 8 + S2 9 + H2 9 + O 10 = 42 min, x3 blocks, order rotated | 2.1 h | -| H4 stress (optional) | 4 x ttt together, about 10 min per block | +0.5 h | -| Vanilla V1/V2/V4 (optional, owner's word) | boot 6 + S2 9 + H2 9 + O 10 = 34 min x3 | +1.7 h | -| Total | | **about 3-3.5 h Leleka-only; about 5 h with vanilla** | - -Shares the stack start and guards with `cmp_codex_job.sh`; a new stub only needs the concurrent launcher (the harness runs cells sequentially in `run_cells`). Merge with step 1 of the multiplexing plan (2-3 GPU-h) rather than running both. -The run holds `requests.log` per session id, so no new telemetry is needed for the first pass; the three numbers the multiplexing plan asks for (queue wait, import ms, tier VRAM share by ordinal after a switch) are the new fields to add if missing. - -## Sources - -* Repo: `docs/prefix-cache.md`, `docs/design/memory-single-copy-and-elastic-state.md` C.4-C.6, T8/T9, `docs/experiments/multiplexing-feasibility.md`, `docs/experiments/plan-faster-than-strata.md` (6g), `docs/e2e-run.md` 7, `docs/deploy.md` (workers), `docs/roofline.md`, `engine/strata/docs/BATCHING.md`, `docs/e2e-data/*-trace.csv`, `docs/e2e-data/codex-compare/compare.csv`, `scripts/e2e/codex/{run-codex.sh,config.toml.tmpl,mock_responses.py,tasks/nestng-crm/task.md,compare/cmp_codex_job.sh}`; code: `crates/context/src/geometry.rs`, `crates/experimental-ref/src/kv_q8.rs`, `crates/cuda-driver/src/{qsa_mapped_journal/original_qsa_mapped_journal.rs,qsa_resident_index/qsa_resident_index_checkpoint_restore.rs,qsa_prompt_indexer.cu}`, `crates/engine-qwen35-cuda/src/qwen_forward/{session_original_prompt.rs,qsa_resident_device.rs,qsa_resident_device/resident_qsa_span_export_and_seal.rs,gdn_state.rs}`. -* Scripts added: `scripts/memory/kv_block_compress_sim.py` (synthetic block, writes planes for `zstd`), `scripts/memory/queue_gap_sim.py` (trace-driven queue model). The synthetic planes were run on `rnr5090` under `/data/leleka-e2e/prefill-latency/async-park-compression/` (6.8 MB, moved to `garbage/` afterwards, see `garbage/LOG.txt`). -* Public: OpenAI Codex documentation, subagents page (learn.chatgpt.com/docs/agent-configuration/subagents, formerly developers.openai.com/codex/multi-agent); third-party Codex multi-agent notes for `max_threads` / `max_depth` defaults (codex.danielvaughan.com, March 2026); lossless low-precision compression (Heilper and Singer, arXiv 2508.19263); KVComp (arXiv 2509.00579); speculative KV coding blog (fergusfinn.com/blog/kv-entropy-coder). Public figures are secondary sources and unverified against Codex 0.163.0. diff --git a/docs/experiments/baseline-pair-5090.md b/docs/experiments/baseline-pair-5090.md deleted file mode 100644 index 8f81800e..00000000 --- a/docs/experiments/baseline-pair-5090.md +++ /dev/null @@ -1,220 +0,0 @@ -# Ours against vanilla Strata 0.2.6 on the RTX 5090: balanced paired runs with a machine-state record (claude/baseline-pair) - -Date 2026-10-31 to 2026-11-01. RTX 5090 server `rnr5090`, Ryzen 9 9950X3D, uptime 29.8-34.7 h during the runs, frozen corpus, ~245k context, 5 turns, `--max-output 300`, final-turn input 246,862-246,961 tokens. -Labels: M measured in the run named. All 69 runs of parts a-d are VALID (validity rules of `speedtrain3-ab.sh`; vanilla arms also checked against their engine log for the tail-skip / CPU-share lines). -Parts c and d (newer main binaries, PCIe 0.55/0.45 and 0.45) are in section 7; section 1 leads with the final pairing (part d). - -## 1. Result - -**Final pairing (part d, current main ffd9322c7, PCIe share 0.45 = product default, 6 balanced blocks, all valid): ours is ahead of vanilla v2 in 6 of 6 blocks.** - -| arm | n | all-turn tok/s mean (sd) | min..max | tokens/round | ms/round (sd) | -| --- | ---: | ---: | --- | ---: | ---: | -| ours (defaults) | 6 | 155.6 (1.6) | 153.1..157.2 | 2.11 | 13.57 (0.14) | -| ours, `LELEKA_HUGEPAGES=on` | 6 | 156.4 (2.0) | 152.4..158.0 | 2.11 | 13.49 (0.07) | -| vanilla v2 (tail skip off, CPU share 0) | 6 | 132.9 (5.5) | 126.4..142.3 | 1.88 | 14.23 (0.59) | - -Block-paired (same block): ours - v2 **+22.7 tok/s (+17.2 %)**, per block +24.0 +14.6 +24.0 +25.2 +21.6 +26.7, 95 % interval about +18..+27 tok/s; ours+hugepages - v2 +23.5 (+17.8 %); hugepages - defaults **+0.8 tok/s (+0.5 %)**, per block -0.5 +1.0 +0.7 +3.9 +0.7 -0.7, interval -0.9..+2.6: not distinguishable from zero here (the hugepages page measured +1.3 %). -Ours rounds are 0.66 ms shorter than this series' vanilla and carry 0.23 more tokens per round. - -**The vanilla state matters and I cannot call the +17 % "the" gap.** In part d five of the six vanilla runs were in the poor state (started after an ours run, 44.5-45.2 GiB of the arena as huge pages): 131.0 tok/s; the one full-coverage run was 142.3. Pooling all 34 vanilla runs of parts a-d (uptime 29.9-43.6 h): full-coverage n=14 **146.9 tok/s (sd 12.5, best runs 160-174)**, poor n=20 **136.8 (sd 11.6)**. Against those, current-main ours at 155.6-156.4 is **ahead by about 6 % of vanilla's good-state mean and 14 % of its poor-state mean**, and still **behind vanilla's best single runs** (160.3, 161.2, 162.4, 162.5, 174.2: 5 of 34 runs above 160 tok/s). The good-state comparison is across parts and uptimes (vanilla's good-state mean was 149.3 in part a, and one run at 142.3 in part d), so it carries the time confound of section 5; the within-block comparison above is the clean one. - -**Part e (section 10, one arm per fresh boot, page cache of the files read so far evicted per file, vanilla at full huge-page coverage in all 6 runs):** ours 155.4 tok/s (sd 2.4, n=3), v1 137.0 (sd 5.6), v2 144.7 (sd 23.0, one run at 171.2). Block-paired ours - v1 **+18.4 tok/s (+13.5 %)**, 3 of 3 blocks; ours - v2 **+10.7 (+9.2 %)**, 2 of 3 blocks (block 2: v2 171.2 against ours 152.6, ours 10.8 % behind). So: ahead of vanilla in vanilla's good THP state on average, behind its occasional fast mode; n=3 blocks and the fast mode is unexplained. - -**How ours moved over the work (same harness, ours only):** main e381c3082 (parts a, b) 143.4 (sd 2.0, n=11) at PCIe 0.55; main 11e021161 (part c) 151.5 at 0.55 and 148.4 at 0.45; main ffd9322c7 (part d) 155.6 at 0.45. Against vanilla in the same part: parts a-b e381c3082 level with v2/v1 (-0.9 % / +0.8 % paired, n=6); part c 11e021161 vs v2 +7.6 % (0.55) and +5.4 % (0.45), ahead in 5 of 6 and 4 of 6 blocks; part d +17.2 %. Part c's vanilla was also mostly poor-state (5 of 6), so its +5..8 % understates the good-state gap. - -**Vanilla is the unstable arm; ours is not.** Vanilla sd 11-17 tok/s per part (5.5 in part d), ours 1.6-2.5 in every part and arm. ms/round of ours has sd 0.07-0.17 ms, vanilla 1.0-1.2 ms. - -**Vanilla drift: partly explained, the rest not.** (a) Predecessor and huge-page coverage (section 5): a vanilla launch after an ours run gets 44.0-45.2 GiB of its 46.8 GiB arena as huge pages instead of 46.4-46.7; across 34 runs vanilla after ours is 10.8 tok/s (8 %) slower and 0.91 ms/round longer (Welch t -2.6 and +2.6, one of about 20 variables inspected). (b) A slow decline with uptime remains inside both classes (about -0.7 to -0.8 tok/s per hour over 30-43 h, pooled r -0.35, n=34); I cannot separate uptime from the number of vanilla launches since boot. CPU clocks, GPU clocks and temperature, PCIe probe, vanilla's PCIe share (0.35 in all runs), hit rates and page cache do not explain it. About two thirds of the remaining spread inside a class is round time, not acceptance, and nothing recorded correlates with it. - -## 2. Method - -* **Ours** = `dt/bin-footprint3b` (claude/slots-footprint3 9e13fc809). `git diff 9e13fc809 e381c3082` outside `docs/` and `scripts/` is empty, so this is the code of main e381c3082 (the task's minimum). Shipped lossless defaults: seed off, upstream ranked profile, auto slots (12,192), budget 31,300 MiB, spec-min-p 0, prefix cache auto, nothing experimental. The harness `run-e2e.sh` exports `LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55` when unset (the product default is 0.45; cpu-service found this): **every ours arm of parts a and b ran PCIe share 0.55**. Vanilla settles at 0.35 by itself in every run (M, CPU pool 42-44 us per expert, probe 49.8-51.0 GB/s). -* **v1** vanilla Strata 0.2.6 shipped defaults (route tail skip ON rank 7, prefill CPU share ON). **v2** `STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0` (lossless-comparable). Same launch line and client as `speedtrain3-ab.sh`. -* **Order.** Part a: 6 blocks of the three arms in the 6 permutations (three reversed pairs: every arm is first, second, last twice; ABBA generalised). A block is the unit of pairing. Part b: 5 x (v2 v2 ours), a predecessor test (vanilla directly after ours against vanilla directly after vanilla, interleaved in time). -* **Warm-up discipline.** Identical start procedure for every arm (no GPU process, load1 < 0.5, GPU <= 48 C, nothing dropped or pre-touched); the state is recorded, not normalised. Block 1 is not discarded. -* **State record** (`baseline-sampler.py`, read-only, pinned to CPU 31): `pre.jsonl` before an arm, `state.jsonl` during it (full sample every 15 s, per-CPU clocks and load every 2 s), `post.jsonl` after: per-CPU `scaling_cur_freq` and utilisation, governor / driver (powersave, amd-pstate-epp, balance_performance, boost 1), `/proc/meminfo` (AnonHugePages, HugePages_*, MemAvailable, Cached, Shmem), THP `enabled` (madvise) / `defrag` (madvise), `/proc/buddyinfo`, THP / compaction / allocstall counters of `/proc/vmstat`, uptime, loadavg, PSI, `nvidia-smi` (SM and memory clocks, temperature, power, P-state, throttle reasons), for the GPU process its `Cpus_allowed_list`, `smaps_rollup` (AnonHugePages, Rss), every thread (tid, name, last CPU, CPU ticks, affinity), and the top-5 other CPU consumers. Client lines are timestamped (`client.ts.log`) so decode windows can be joined to samples. -* **tokens/round, ms/round.** Ours: `produced / rounds` of the request outcome line and decode time = 300 / client tok/s. Vanilla: engine line "N generated in X ms, drafts accepted A of M": rounds = N - A. -* **Provenance and frozen inputs:** `/data/leleka-e2e/baseline-pair/MANIFEST.sha256` (tools, ours binaries, harness, profile, corpus manifest, vanilla launcher and engine 0.1.50, settings) is verified at every job start; `PROVENANCE.txt`. The tools were reinstalled three times between jobs (line endings, options); the sampler and job logic of part a are those of the first install apart from line endings and the later `SEQ`, `PRE_ARM_HOOK`, `ours45` additions. Part b's first launch failed in the first second (CRLF line endings my edit introduced, no GPU time used) and was re-queued as `bp-b2`. - -## 3. Part a: balanced blocks (M, `runs/baseline-pair`, uptime 29.8-31.3 h) - -| run | tok/s T1..T5 | all-turn | tok/round | ms/round | arena AnonHugePages GiB | thp fallback pages | -| --- | --- | ---: | ---: | ---: | ---: | ---: | -| b01 ours | 146.0 143.7 142.5 137.2 157.1 | 145.3 | 2.08 | 14.32 | 0 | 0 | -| b01 v1 | 128.9 177.9 162.6 154.2 155.8 | 155.9 | 1.76 | 11.43 | 44.6 | 1144 | -| b01 v2 | 136.7 149.7 146.0 134.4 137.1 | 140.8 | 1.81 | 12.89 | 46.6 | 145 | -| b02 v2 | 165.5 175.4 186.2 157.8 186.2 | 174.2 | 2.01 | 11.55 | 46.7 | 61 | -| b02 v1 | 146.6 158.9 158.7 172.0 169.7 | 161.2 | 1.82 | 11.32 | 46.6 | 143 | -| b02 ours | 139.9 144.8 137.0 148.5 151.7 | 144.4 | 2.04 | 14.14 | 0 | 0 | -| b03 v1 | 151.3 122.7 151.4 124.9 117.8 | 133.6 | 1.80 | 13.57 | 44.7 | 1102 | -| b03 v2 | 140.4 152.1 143.9 138.7 120.9 | 139.2 | 1.83 | 13.20 | 46.4 | 232 | -| b03 ours | 140.1 145.3 142.9 142.6 137.9 | 141.8 | 1.98 | 13.97 | 0 | 0 | -| b04 ours | 140.0 145.1 137.4 148.6 152.0 | 144.6 | 2.04 | 14.09 | 0 | 0 | -| b04 v2 | 157.5 144.0 172.0 123.0 121.7 | 143.6 | 1.89 | 13.27 | 44.7 | 1073 | -| b04 v1 | 136.8 135.2 165.8 137.3 155.6 | 146.1 | 1.89 | 12.99 | 46.5 | 187 | -| b05 v2 | 167.0 136.6 135.1 133.6 132.4 | 140.9 | 1.93 | 13.75 | 46.7 | 60 | -| b05 ours | 139.9 145.1 137.2 148.2 145.8 | 143.2 | 2.00 | 14.01 | 0 | 0 | -| b05 v1 | 134.0 135.7 147.1 120.7 124.2 | 132.3 | 1.86 | 14.04 | 44.7 | 1095 | -| b06 v1 | 159.6 139.3 142.0 138.1 136.2 | 143.0 | 1.87 | 13.05 | 46.5 | 157 | -| b06 ours | 140.1 145.0 136.5 140.6 142.5 | 140.9 | 1.95 | 13.87 | 0 | 0 | -| b06 v2 | 121.9 123.9 126.1 130.1 114.5 | 123.3 | 1.86 | 15.11 | 44.5 | 1194 | - -(Rows in run order within a block as executed; the block number is the pairing unit.) - -| arm | n | all-turn tok/s mean (sd) | min..max | tok/round | ms/round (sd) | -| --- | ---: | ---: | --- | ---: | ---: | -| ours | 6 | 143.4 (1.7) | 140.9..145.3 | 2.02 | 14.06 (0.15) | -| v1 | 6 | 145.4 (11.6) | 132.3..161.2 | 1.83 | 12.73 (1.12) | -| v2 | 6 | 143.7 (16.6) | 123.3..174.2 | 1.89 | 13.29 (1.16) | - -Block-paired differences (same block, a - b, all-turn mean tok/s): - -| pair | per block 1..6 | mean | pairs a faster | ms/round | tok/round | -| --- | --- | ---: | ---: | ---: | ---: | -| ours - v1 | -10.6 -16.8 +8.1 -1.5 +10.9 -2.1 | -2.0 (-0.9 %), se 4.3 | 2 of 6 | +1.33 | +0.18 | -| ours - v2 | +4.5 -29.8 +2.6 +1.0 +2.3 +17.6 | -0.3 (+0.8 %), se 6.4 | 5 of 6 | +0.77 | +0.13 | -| v1 - v2 | +15.1 -13.0 -5.6 +2.5 -8.6 +19.7 | +1.7 (+1.8 %), se 5.4 | 3 of 6 | -0.56 | -0.06 | - -v1 and v2 are not different; the lossy tail skip and the prefill CPU share buy nothing measurable on this card at this context. -Position in the block: ours 145.0 / 142.1 / 143.1 (first / second / third), v1 138.3 / 158.5 / 139.2, v2 157.6 / 141.4 / 132.0 (n=2 each; the vanilla pattern is the predecessor effect of section 5, not position). - -## 4. Part b: predecessor test (M, `runs/baseline-pair-b`, uptime 33.5-34.7 h) - -5 x (v2, v2, ours); the first v2 of a triple follows ours, the second follows v2. - -| run | tok/s T1..T5 | all-turn | tok/round | ms/round | AnonHugePages GiB | thp fallback | -| --- | --- | ---: | ---: | ---: | ---: | ---: | -| b01 v2 (after cpu-service jobs) | 160.0 171.4 164.3 137.2 127.8 | 152.1 | 1.90 | 12.59 | 44.4 | 1231 | -| b01 v2 | 140.1 152.4 140.4 125.1 134.1 | 138.4 | 1.84 | 13.30 | 46.4 | 213 | -| b01 ours | 139.8 145.0 142.6 147.8 148.3 | 144.7 | 2.05 | 14.19 | 0 | 0 | -| b02 v2 (after ours) | 113.6 151.8 115.9 113.5 122.2 | 123.4 | 1.74 | 14.25 | 45.1 | 905 | -| b02 v2 | 133.9 177.0 174.6 174.8 141.1 | 160.3 | 1.95 | 12.39 | 46.6 | 141 | -| b02 ours | 142.3 161.2 143.6 145.3 142.2 | 146.9 | 2.11 | 14.36 | 0 | 0 | -| b03 v2 (after ours) | 153.9 171.3 151.1 136.1 129.0 | 148.3 | 1.91 | 12.96 | 44.0 | 1453 | -| b03 v2 | 120.5 126.6 153.0 137.8 131.9 | 133.9 | 1.92 | 14.39 | 46.6 | 118 | -| b03 ours | 139.7 147.2 141.0 140.0 135.1 | 140.6 | 2.02 | 14.39 | 0 | 0 | -| b04 v2 (after ours) | 112.7 131.2 110.4 135.0 115.8 | 121.1 | 1.77 | 14.63 | 44.3 | 1297 | -| b04 v2 | 119.3 134.4 133.8 140.1 136.4 | 132.8 | 1.80 | 13.64 | 46.6 | 110 | -| b04 ours | 146.1 143.8 143.3 142.1 144.4 | 143.9 | 2.04 | 14.19 | 0 | 0 | -| b05 v2 (after ours) | 157.2 144.2 141.2 120.8 127.3 | 138.1 | 1.89 | 13.69 | 44.5 | 1204 | -| b05 v2 | 157.5 163.3 168.7 156.6 166.3 | 162.5 | 1.79 | 11.02 | 46.5 | 177 | -| b05 ours | 139.7 142.4 145.9 141.1 138.2 | 141.5 | 1.98 | 13.99 | 0 | 0 | - -Ours: 143.5 (sd 2.5, n=5). v2: 141.1 (sd 14.3, n=10). Vanilla after ours (4 runs here) 132.7 against after vanilla (5 runs) 145.6; the first v2 of block 1 followed cpu-service jobs and also got partial coverage. - -## 5. Drift analysis (parts a + b pooled, vanilla n=22, ours n=11) - -1. **Predecessor, huge pages and free 2 MiB blocks (M).** Vanilla requests `MADV_HUGEPAGE` for its 23,983 x 2 MiB (46.8 GiB) expert arena (`MAP_HUGETLB unavailable, vm.nr_hugepages=0`; THP is `madvise`, defrag `madvise`). Free memory in blocks of 2 MiB or more before the launch (buddyinfo) was 48.1-49.6 GiB after a vanilla run and 40.0-45.9 GiB after an ours run (ours holds 57 GiB in 4 KiB pages and exits leaving a fragmented free list; it uses no huge pages: AnonHugePages 0 in all 11 runs). With >= 48 GiB free the arena got 46.4-46.7 GiB of huge pages (fallback 60-232 pages of 2 MiB); with <= 46 GiB it got 44.0-45.1 GiB (fallback 905-1453 pages). The classification is perfect in 22 of 22 runs. Per class: full coverage n=12 147.8 tok/s, 12.79 ms/round; partial n=10 137.2, 13.55 ms/round. Vanilla after ours - after vanilla: -12.3 tok/s (-8 %), +0.87 ms/round (Welch t -2.2 and +1.9; I looked at about 20 variables, so read this as suggestive). The kernel does compact: `kcompactd0` burned 5-31 s of CPU per vanilla launch (ours 0.4-1.8 s), mostly before the first request; during the session itself it used 0-4.5 s and does not correlate with decode speed (r about +-0.4, n=12, mixed sign). -2. **Uptime.** Part a alone looked like a trend (vanilla ms/round +1.9 ms per hour over 29.9-31.3 h, r 0.79); part b, 3 hours later, has the same predecessor pattern and no trend (pooled +0.13 ms per hour over 29.8-34.7 h). The part-a trend was the predecessor pattern aliased with time. Uptime beyond that range (the 175 tok/s right after a reboot) is not covered; a freshly booted machine has unfragmented memory, which fits the mechanism but was not tested. -3. **Frequency.** Busy cores (utilisation > 40 %) averaged 5.43-5.52 GHz in the decode windows of 30 of 33 runs, all arms (max 5.756 GHz); three runs show lower means (5083 vanilla b06, 5215 vanilla b-b01, 4968 ours b-b01), which I read as a sample where a lightly loaded core sat at its 2.98 GHz idle clock but did not check per run. Correlation with tok/s or ms/round is not significant (r -0.34..+0.46, n=12-30) and flips sign between v1 and v2. Governor is `powersave` with amd-pstate-epp and EPP balance_performance, boost on; it did not limit the busy cores. -4. **GPU.** SM clock 2872-2917 MHz, temperature 56-66 C, power 304-458 W (full samples inside decode windows, runs that had one); the throttle-reason field was recorded but not analysed. Correlation with vanilla speed is confounded by time and not independent. -5. **Not explanatory:** PCIe probe (49.8-51.0 GB/s, r about 0), final `pcie_frac` (0.35 in all 22), CPU pool us per expert (42-44), decode VRAM hit rate (97.1-98.5 %; v1 98.4-98.5 vs v2 97.1-97.4 by construction of the tail skip), PCIe-read share, foreign process CPU (nothing but kernel threads, the agent daemons and the sampler), page cache (Cached 57.5 or 59.2 GiB before a run is the same predecessor pattern). -6. **Variance split (turn level, 30 turns per arm of part a):** ours' turn-to-turn spread is acceptance (tokens/round explains ~110 % of the log tok/s variance, round time ~-10 %); vanilla's is 62-78 % round time (ms/round) and 21-38 % acceptance. So vanilla's instability is mostly in how long its rounds take, and inside the full-coverage class (sd 13 tok/s) I have no explanatory variable. Ours is stable (sd 2.0, ms/round sd 0.17) in all three state classes. -7. **Does ours drift too?** Part a: all-turn 145.3, 144.4, 141.8, 144.6, 143.2, 140.9 over 1.6 h (r with uptime -0.77, n=6); part b 144.7, 146.9, 140.6, 143.9, 141.5. Pooled over 29.8-34.7 h r = -0.11 (slope -0.11 tok/s per hour). No drift established. Ours' predecessor does not matter (after vanilla 143.1, n=9; after ours 144.6, n=1). - -Limitations: the sampler runs on CPU 31, the SMT sibling of pool worker 15, for ~2 ms per 2 s plus ~100 ms per 15 s, in every arm alike; it was not switched off for a control. n is small (6 blocks); intervals are t-approximations. The harness gives ours PCIe share 0.55, vanilla self-tunes to 0.35. Vanilla runs at its shipped settings including its own pinned-memory behaviour; the 54 GiB `Shmem` of the KAR holder is present in all arms and leaves ~9-11 GiB MemAvailable during a vanilla run, which may be what makes huge-page availability matter. Nothing was changed on the machine. - -## 6. Owner-run test of the mechanism (not run by me) - -`scripts/e2e/decode/owner-compact-memory.sh` (root) asks the kernel to compact free memory once and prints free 2 MiB+ blocks before and after. Used through the job's `PRE_ARM_HOOK` with `SEQ="v2 ours v2 ours ..."` it tests whether "vanilla after ours" loses its penalty once memory is compacted before the launch. It changes no setting. Nothing else (THP knobs, governor) needs changing for the hypotheses above; I did not test any. - -## 7. Parts c and d (M) - -**Part c** (`runs/baseline-pair-c`, 2026-10-31 22:30Z to 2026-11-01 00:05Z, uptime about 36 h; ours = `dt/bin-cpuservice` = claude/cpu-service bba658f20, the same code as main 11e021161 outside docs/scripts; arms `ours` at PCIe 0.55 (the then harness default, `pcie-frac.txt`), `ours45` at the product default 0.45, vanilla v2; 6 balanced blocks, all valid): ours 151.5 (sd 1.9, 2.09 tok/round, 13.82 ms/round), ours45 148.4 (sd 0.5, 2.06, 13.90), v2 141.7 (sd 12.5, 1.88, 13.42). Paired: ours - v2 +9.8 tok/s (+7.6 %, per block -13.2 +12.7 +4.4 +22.4 +14.1 +18.5), ours45 - v2 +6.7 (+5.4 %, -14.3 +7.7 -0.5 +21.9 +11.2 +14.2), ours - ours45 +3.1 (+2.1 %, 6 of 6 blocks, se 0.8). The gain of 0.55 over 0.45 on this binary is the opposite of cpu-service2's end-to-end result (equal across 0.45-0.65, later binary); I did not investigate. In block 1 vanilla had its full-coverage run and was 13-14 tok/s ahead of ours. - -**Part d** (`runs/baseline-pair-d`, 2026-11-01 05:09Z to 06:48Z, uptime 42.0-43.6 h; ours = `dt/bin-main-ffd9322` = main ffd9322c7; PCIe share pinned to 0.45 in the job (`pcie-frac.txt`, `LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45` in `env-arm.txt`); arms `ours` and `ourshp` (`LELEKA_HUGEPAGES=on`: engine log "after collapse ... 46.78 GiB huge (99.9 %)", AnonHugePages 46.8 GiB in the process) against vanilla v2): - -| run | tok/s T1..T5 | all-turn | tok/round | ms/round | AnonHugePages GiB | thp fallback | -| --- | --- | ---: | ---: | ---: | ---: | ---: | -| b01 ours | 159.5 151.4 173.8 152.0 149.4 | 157.2 | 2.15 | 13.69 | 0 | 0 | -| b01 ourshp | 159.9 161.3 158.5 156.0 147.9 | 156.7 | 2.11 | 13.47 | 46.8 | 2186 | -| b01 v2 (after ourshp) | 139.5 134.1 130.8 137.1 124.9 | 133.3 | 1.89 | 14.19 | 44.7 | 1090 | -| b02 v2 (after v2) | 141.9 149.3 147.7 141.7 130.9 | 142.3 | 1.89 | 13.28 | 46.7 | 77 | -| b02 ourshp | 160.1 161.8 161.9 146.3 159.2 | 157.9 | 2.14 | 13.51 | 46.8 | 2381 | -| b02 ours | 159.3 151.0 173.7 151.4 149.1 | 156.9 | 2.15 | 13.72 | 0 | 0 | -| b03 ourshp | 161.0 155.4 154.6 142.1 171.5 | 156.9 | 2.10 | 13.37 | 46.8 | 2164 | -| b03 v2 (after ourshp) | 127.8 164.8 121.5 123.2 124.0 | 132.3 | 1.84 | 14.02 | 44.8 | 1066 | -| b03 ours | 159.8 151.4 174.9 149.2 145.9 | 156.2 | 2.10 | 13.42 | 0 | 0 | -| b04 ours | 159.7 157.4 165.8 144.6 142.9 | 154.1 | 2.11 | 13.65 | 0 | 0 | -| b04 v2 (after ours) | 127.0 134.1 136.3 119.6 127.3 | 128.9 | 1.88 | 14.61 | 44.7 | 1089 | -| b04 ourshp | 160.1 159.7 163.4 148.8 158.0 | 158.0 | 2.14 | 13.52 | 46.8 | 2945 | -| b05 v2 (after ourshp) | 119.4 140.6 161.7 120.3 129.9 | 134.4 | 1.91 | 14.24 | 44.5 | 1200 | -| b05 ours | 159.7 153.3 171.7 144.5 150.7 | 156.0 | 2.10 | 13.46 | 0 | 0 | -| b05 ourshp | 160.0 161.6 158.6 155.3 147.8 | 156.7 | 2.11 | 13.47 | 46.8 | 2854 | -| b06 ourshp | 150.1 156.6 153.5 152.4 149.5 | 152.4 | 2.07 | 13.59 | 46.8 | 2225 | -| b06 ours | 159.6 154.0 158.1 144.0 149.9 | 153.1 | 2.06 | 13.46 | 0 | 0 | -| b06 v2 (after ours) | 127.1 128.5 125.5 127.7 123.2 | 126.4 | 1.90 | 15.02 | 45.2 | 859 | - -(Rows in the order they ran.) Observations: turn 1 of ours is 159-161 in all but one run, higher than in any earlier ours series (newer code; not investigated). A `LELEKA_HUGEPAGES=on` process does not leave memory in a better state for the next vanilla launch: all three vanilla runs that followed an ourshp arm (b01, b03, b05) got partial coverage. - -Caveats of part d: the first build of this binary came from a CRLF checkout and was 9 MB smaller than every earlier binary; it was discarded and rebuilt from a worktree re-checked out with LF endings (74.56 MB like the others), and only that one was run. The server copy of `run-e2e.sh` still defaults to PCIe 0.55; the job pins 0.45 explicitly. Vanilla ran at 42-43.6 h uptime with the partial-coverage penalty in 5 of 6 runs because the balanced design puts it after an ours arm in most blocks. Pooled predecessor analysis of parts a-d: `analysis/bp-abcd-pred.txt`. - -## 8. Reproduce - -`scripts/e2e/decode/baseline-install.sh` (on the server) installs the tools; stubs `bp-a.sh`, `bp-b2.sh`, `bp-c.sh`, `bp-d2.sh` in `~/work/gpu-runs/holder2/jobs/` hold the environment of each part (`BLOCKS`, `SEQ`, `OUTR`, `BINDIR`, `SUBST_V1`). Analysis: `baseline-analyze.py`, `baseline-turns.py`, `baseline-compact.py`, `baseline-pred.py` (outputs in `/data/leleka-e2e/baseline-pair/analysis/`). Data: `/data/leleka-e2e/runs/baseline-pair{,-b,-c,-d}//` (`long-session.json`, `client.ts.log`, `engine.log` or `inference.log`, `pre/state/post.jsonl`, `startup.txt`, `VALIDITY.txt`). - -## 9. Part e, first attempt (owner-authorised reboots, 2026-11-01/02): stopped after cycle 1, cost problem; completed in section 10 - -Driver: `scripts/e2e/decode/baseline-reboot-series.sh` (runs on the laptop; per cycle: wait until no foreign job, `sync`, `sudo -n systemctl reboot`, wait for a new boot id, check the safety net, pre-read the KAR file, restart the holder the way `notes.md` did after the boot of 2026-10-29, pre-read the model shard / MTP / pack, queue one holder job with `ENTRIES`, wait for it). Arms: ours = `dt/bin-main-ffd9322` (main d29e3dba2 has the same code outside docs/scripts), PCIe 0.45 pinned, defaults; v1; v2. Per run the job also writes `hook.txt` (boot id and time, uptime at the hook, rescue sshd :2222, `/dev/watchdog0`, `hung_task_panic`, swap, NVMe dmesg hits, holder pid and READY time, buddyinfo) next to the usual `pre/state/post.jsonl`. - -What happened (M): - -* Safety net after every boot checked: rescue sshd on :2222 up, `/dev/watchdog0` present, `kernel.hung_task_panic=1`, swap off, no NVMe timeout / reset / abort / error line in dmesg. Boots took 253-255 s to ssh, no hang, no rescue needed. -* **A cold start is dominated by reading the 55 GB KAR file into the holder memfd.** The holder reads with plain buffered `read()`: on this NVMe that runs at 8-35 MB/s (iostat r_await 4-15 ms, 112-128 KiB requests, queue depth 1-2): 2003.8 s (33 min) for the first holder after the first reboot. The same drive does 600 MB/s with 32 MiB `O_DIRECT` reads and 0.6-2.4 GB/s with `posix_fadvise(WILLNEED)` readahead. The pre-read (`baseline-prefetch.py`) helped in one cycle (holder READY about 8 min after start) and not in the next (the unread tail of the file was not resident; holder still at 8-25 MB/s after 26 minutes); I did not find out why. -* Cycle durations: cycle 1 (reboot, pre-read, holder, run) 25 min; cycle 2 more than 45 min and stopped by my own 15-minute holder timeout (raised to 90 min). At that pace 18 cycles take 10-14 h, so I stopped the series after cycle 1 and did not resume it. -* Owner option (not done by me, it is a runtime sysfs setting): `scripts/e2e/decode/owner-readahead.sh set 4096` raises the device readahead from 128 KiB; expected to bring holder and model loads down to minutes, which would make a cycle about 15 min. Resume with `START_CYCLE=2 bash scripts/e2e/decode/baseline-reboot-series.sh "1 2 3 4 5 6"` on the laptop after it (the stop file is `baseline-reboot-series.STOP`). - -Results so far (only ours ran on fresh boots): - -| run | boot age at start | tok/s T1..T5 | all-turn | tok/round | ms/round | state | -| --- | ---: | --- | ---: | ---: | ---: | --- | -| pilot (pipeline test, `runs/baseline-pair-e-pilot/b00p1-ours`) | 0.6 h | 157.7 153.9 178.0 148.8 150.7 | 157.8 | 2.16 | 13.70 | valid | -| cycle 1 (`runs/baseline-pair-e/b01p1-ours`) | 0.3 h | 159.9 151.1 173.8 151.7 148.9 | 157.1 | 2.15 | 13.71 | valid, hook.txt in the run dir | - -Ours on a fresh boot is 157.1-157.8 against 155.6 (sd 1.6, n=6) at 42-44 h uptime in part d: boot state moves ours by about 1 %, inside its own spread. The vanilla arms, which are the ones that depend on the boot state (section 5), have not been run on fresh boots, so the question "is fresh-boot vanilla in its good state (arena THP >= 46.4 GiB)" is **not answered here**: on the fresh boots the free memory in 2 MiB+ blocks was recorded in `pre.jsonl` / `hook.txt` but no vanilla launch followed. Cycle 2's boot was not used. - -**One vanilla run on a fresh boot (`runs/baseline-pair-e/b01p2-v1`, boot age 0.74 h, same boot as cycle 1, holder up, model shard pre-read; the cycle-2 slot, not a clean cycle):** valid, **130.6 tok/s** (113.9 147.9 138.1 125.9 127.4; 1.84 tokens/round, 14.13 ms/round). Its engine log says "expert arena: ... transparent huge pages NOT requested: only 0 GiB of free 2 MiB blocks for a 46 GiB arena": vanilla checks the free 2 MiB blocks before asking for huge pages, and with the holder's 55 GB memfd plus the page cache that the KAR read and the pre-read leave behind (Cached 115 GB, MemFree 10 GB, buddyinfo order 9+ about 8 GiB) there were none. AnonHugePages of the process was 0 (Rss 65.7 GiB), the worst vanilla state seen in 36 runs. So **fresh-boot vanilla is not in its good state when the holder has just been loaded**: a fresh boot is not an unfragmented machine, it is a machine whose RAM is full of page cache. This also reads back on the partial-coverage class of section 5: that class is vanilla's own guard (huge pages only where free 2 MiB blocks exist) meeting the page-cache and 4 KiB-page footprint an ours run leaves behind, not a defect of the launch. I did not test dropping the cache of the KAR file after the holder load (a read-only `posix_fadvise(DONTNEED)` on that one file would be the obvious next step) and did not run vanilla on a boot without the pre-read. - -## 10. Part e completed: one arm per fresh boot, page cache evicted, vanilla in its good THP state (M, `runs/baseline-pair-e`, 2026-11-02 00:29Z to 06:28Z) - -Resumed after section 9 with three changes: 3 blocks (9 cycles, permutations 1-3: ours v1 v2 / v2 v1 ours / v1 v2 ours), per-file `posix_fadvise(DONTNEED)` (`baseline-evict.py`; not `drop_caches`) of the KAR file, both model shards, the MTP files and the vanilla pack after the holder load and before every arm (the holder's read otherwise leaves ~50 GB of page cache and vanilla found "only 0 GiB of free 2 MiB blocks" and ran without huge pages), and a THP gate for vanilla arms (`baseline-thpcheck.py`: AnonHugePages >= 46.4 GiB, else the run is moved to `_poor/` and the cycle repeated once). Holder-load timeout 90 min. No sysfs, readahead or other setting changed; the only privileged call was `sudo -n systemctl reboot` (and read-only `sudo -n dmesg`). Ours = `dt/bin-main-ffd9322` (code of main d29e3dba2), PCIe 0.45 pinned. - -All 9 runs VALID on the first attempt; no run was repeated, no poor state occurred. Every boot: ssh back in 255-257 s, rescue sshd :2222 up, `/dev/watchdog0`, `hung_task_panic=1`, swap off, no NVMe error lines in dmesg. Cycles took 23-55 min (the cold holder load of the 55 GB KAR file, 10-39 min, dominates). After eviction every cycle showed MemFree 68.0-68.3 GiB, Cached 52.0-52.2 GiB (the holder's 51.5 GiB memfd), free 2 MiB+ blocks 54.0-55.3 GiB (`_cycles/series.log`). - -| run (block, position) | boot age at start | tok/s T1..T5 | all-turn | tok/round | ms/round | AnonHugePages GiB | THP fallback pages | note | -| --- | ---: | --- | ---: | ---: | ---: | ---: | ---: | --- | -| b01p1 ours | 0.8 h | 159.8 151.4 173.9 153.9 144.2 | 156.6 | 2.11 | 13.44 | 0 | 0 | | -| b01p2 v1 | 0.3 h | 142.8 136.7 129.4 131.2 162.8 | 140.6 | 2.00 | 14.29 | 46.5 | 158 | | -| b01p3 v2 | 0.5 h | 127.3 137.2 132.8 120.0 132.1 | 129.9 | 1.95 | 15.05 | 46.7 | 77 | pcie_frac retuned 0.35 -> 0.30 mid-run | -| b02p1 v2 | 0.3 h | 176.5 174.5 174.1 153.7 177.0 | **171.2** | 1.94 | **11.38** | 46.7 | 66 | engine ready in 76 s (others 102-132 s) | -| b02p2 v1 | 0.8 h | 139.7 122.3 135.6 132.2 123.0 | 130.6 | 1.92 | 14.68 | 46.6 | 105 | | -| b02p3 ours | 0.8 h | 158.5 155.2 149.5 153.2 146.6 | 152.6 | 2.07 | 13.54 | 0 | 0 | | -| b03p1 v1 | 0.8 h | 143.9 146.1 135.1 126.5 147.7 | 139.9 | 1.95 | 13.92 | 46.7 | 65 | | -| b03p2 v2 | 0.4 h | 136.9 117.6 139.7 133.9 137.4 | 133.1 | 1.92 | 14.41 | 46.7 | 66 | | -| b03p3 ours | 0.3 h | 159.7 151.3 173.7 151.1 149.1 | 157.0 | 2.15 | 13.72 | 0 | 0 | | - -THP per vanilla run: 46.5, 46.7, 46.7, 46.6, 46.7, 46.7 GiB of the 46.8 GiB arena, fallback 65-158 pages (the engine log says "transparent huge pages requested (MADV_HUGEPAGE)" in all six). Fresh-boot vanilla with the page cache evicted is in its good state every time, so the 130-171 tok/s spread below is not the huge-page coverage of section 5. - -| arm | n | all-turn tok/s mean (sd) | min..max | tokens/round | ms/round (sd) | -| --- | ---: | ---: | --- | ---: | ---: | -| ours | 3 | 155.4 (2.4) | 152.6..157.0 | 2.11 | 13.57 (0.14) | -| v1 | 3 | 137.0 (5.6) | 130.6..140.6 | 1.95 | 14.30 (0.38) | -| v2 | 3 | 144.7 (23.0) | 129.9..171.2 | 1.94 | 13.61 (1.96) | - -Block-paired differences (same block, a - b): - -| pair | block 1 | block 2 | block 3 | mean | blocks a faster | ms/round | tok/round | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| ours - v1 | +16.1 | +22.0 | +17.1 | **+18.4 tok/s (+13.5 %)**, se 1.8 | 3 of 3 | -0.73 | +0.15 | -| ours - v2 | +26.8 | -18.6 | +23.9 | **+10.7 tok/s (+9.2 %)**, se 14.6 | 2 of 3 | -0.04 | +0.17 | -| v1 - v2 | +10.7 | -40.6 | +6.8 | -7.7 tok/s (-3.5 %), se 16.5 | 2 of 3 | +0.68 | +0.02 | - -Reading (n=3 blocks, intervals wide): - -* **Ours is ahead of vanilla in vanilla's good state, with one exception.** Against v1 in 3 of 3 blocks (+13.5 %, tight: se 1.8). Against v2 in 2 of 3 blocks; in block 2 vanilla v2 ran 171.2 tok/s (11.38 ms/round) and ours 152.6, ours 10.8 % behind. Ours itself did not move (152.6-157.0, sd 2.4; 155.6 at 42 h uptime in part d, 143.4 on the older main of parts a-b). -* **Vanilla has two speeds that nothing recorded separates.** v2 b02p1 (171.2, ready in 76 s, boot age 0.3 h, full huge pages, free 2 MiB blocks 55.0 GiB, PCIe probe 49.4 GB/s) and the other five (130-141) have the same huge-page coverage, memory state, CPU clocks (5.49-5.53 GHz busy cores) and PCIe probe (46.4-50.7 GB/s). The pooled record has the same shape: 5 of 34 earlier vanilla runs were above 160 tok/s. I cannot say what puts vanilla into its fast mode; a fresh boot does not (5 of 6 fresh-boot vanilla runs were slow). -* **v1 against v2** is noise again (-3.5 %, signs split), as in part a. -* Fresh-boot vanilla is slower on average (140.9, n=6, sd 15.5) than the 146.9 of the good-THP class pooled over uptimes 30-43 h in section 1 (n=14): within the noise of both. - -What the series does not show: whether eviction itself changes vanilla (the pre-eviction state was measured only once, 130.6 tok/s with 0 huge pages, section 9). Statements about the earlier poor-state class (section 5) rest on that one fresh-boot run plus the predecessor analysis of parts a-d. diff --git a/docs/experiments/codex-compare-5090-results.md b/docs/experiments/codex-compare-5090-results.md deleted file mode 100644 index 4e6fe3fb..00000000 --- a/docs/experiments/codex-compare-5090-results.md +++ /dev/null @@ -1,63 +0,0 @@ -# Codex + runtime + model: vanilla Strata against Leleka, results (RTX 5090, 2026-11-05) - -Design: [codex-compare-5090.md](codex-compare-5090.md). Tables: `docs/e2e-data/codex-compare/` (`compare.md`, `compare.csv`, `index.md`, `rounds.csv`). 18 cells = 3 arms x 2 tasks x 3 repetitions, all finished, every one accepted. -This page states what the data shows and what it cannot resolve. It claims nothing as a performance improvement (AGENTS.md): the one clear signal below is **against** Leleka on speed. - -## 1. What was run - -* Arms: **LEL** = Leleka release package `leleka-0.1.0-17e372944279-5090-linux-x86_64.tar.xz` (sha256 `c4bbee3f...d356d69`), KAR, shipped configuration. **VANL** = vanilla Strata 0.2.6 with both lossy defaults off, the **reference** (owner). - **VAN** = vanilla Strata 0.2.6 with its shipped defaults (route tail skip and CPU prefill share ON; the stack log of `VAN/stack-r1` shows both). Same machine, model files and Codex CLI 0.163.0 (sha256 `399ff69c...c4215`), Node 22.23.4. - Temperature 0 injected for every arm; no AGENTS.md pad; limits 3000 s and 150 requests per cell (none reached). -* Tasks: `ttt` (three.js tic-tac-toe, the earlier prompt) and `nestng-crm` (new: NestJS REST + Angular 20 CRM, no network, Node on PATH, no browser). Repetition order per arm: r1 LEL, VAN, VANL; r2 VANL, VAN, LEL; r3 LEL, VANL, VAN. -* Tools: commit `42dcceff2` of branch `claude/codex-compare`; task manifest sha256 `246ccf203ddd69f3...`. - -### Deviations (all recorded in `decode/notes.md`) - -1. First pass: the NestJS dependency setup failed twice (`npm` needs `node` on PATH; then `cp -al` of a read-only tree), so `nestng-crm` was dropped everywhere; fixed, and a second pass ran only the missing cells. -2. The restarted lab holder passed the window's `CMP_*` variables on, so the first-pass `VAN` r2 and r3 blocks ran as `VANL` (their cells were skipped as finished; the `VANL` data is genuine). `VAN` r2 and r3 were rerun in the second pass. Fixed in `cmp_window.sh`; stubs now set every variable. -3. Blocks of the second pass have no warm-up cell (the warm-up cells of the first pass exist and are skipped); the first cell of those blocks therefore ran on a cold stack. The `nestng-crm` cells of a block follow the `ttt` cell, which is itself a warm-up. -4. **Post-hoc acceptance fix.** The static check "a board with one column per stage" required the five stages and the loop in one file and failed identically in all nine `nestng-crm` cells (55 of 56); every model keeps the stage list in `models.ts`. The check now looks across files; the nine cells were re-accepted offline (old logs kept as `acceptance.log.prev`). The failure was the same in all arms, so it cannot favour one; the real board is present (read in the sources). -5. The Codex sandbox (default, no network) refuses `listen` even on 127.0.0.1 (EPERM). The agents could not start the server and tested with in-process shims or supertest-free scripts. Same for all arms, but it changes what "verify your work" can mean. - -## 2. Results - -### Quality -* Objective acceptance: 18 of 18 accepted, 0 failed requests, no round cap, no wall limit. `nestng-crm` 56/56 in all nine cells, `ttt` 14/14 in all nine. The acceptance saturates: it cannot rank the arms. -* Browser checks of the nine `ttt` pages (six real-mouse checks, Chromium on the laptop, software GL): LEL r1 6/6, **LEL r2 2/6**, LEL r3 6/6; VAN r1 6/6, VAN r2 6/6, VAN r3 5/6; VANL r1 6/6, r2 6/6, r3 6/6. - * **LEL r2 is a real defect**: the `#hud` (with the Restart button) and the full-screen canvas are both `position: fixed` with no `z-index`, and the canvas comes later in the DOM, so the canvas covers the button; a mouse cannot press Restart (Playwright: "canvas intercepts pointer events"). The game otherwise runs. The static acceptance cannot see this. - * VAN r1 and r3 first failed the draw step because the probe that locates the nine cells splits the perspective board into thirds of the clickable range; a screenshot showed marks in the wrong rows. With a probe that clusters by gaps VAN r1 is 6/6 and VAN r2, LEL r1 stay 6/6. **VAN r3 still fails the draw step ("X wins")** with the new probe; its win and draw logic is present in the source and the probe geometry is the likely cause, but this is **not established**. Count it as 5/6 inconclusive. -* Code metrics of the nine `nestng-crm` projects (read blind, labels shuffled; not a code review): backend 789-1,310 lines, 39-78 test cases, README about 2.3-3.2 kB, class-validator used in 8 of 9. No pattern by arm; the spread inside an arm is as large as between arms. I did **not** read the nine codebases in full, so "equal quality" is not claimed, only "no difference visible in these measures". - -### Iterations (model requests per cell, mean ± sd over 3 repetitions) - -| task | LEL | VAN | VANL (reference) | -| --- | --- | --- | --- | -| ttt rounds | 17.7 ± 3.8 | 12.7 ± 3.2 | 19.0 ± 4.6 | -| ttt tool calls | 19.7 ± 5.0 | 13.7 ± 2.3 | 18.3 ± 4.2 | -| nestng-crm rounds | 54.0 ± 7.5 | 71.3 ± 18.5 | 62.0 ± 19.0 | -| nestng-crm tool calls | 58.7 ± 7.5 | 58.0 ± 25.5 | 54.3 ± 11.7 | - -The repetition-to-repetition spread inside one arm (up to 19 rounds, CV 25-30 %) is larger than the differences between arms, so **no arm is shown to need fewer or more iterations**. Paired by repetition, LEL minus VANL on `nestng-crm`: rounds -8 (pairs -20, +21, -25). `VAN` needing fewer rounds on `ttt` (9, 15, 14 against 15-24) is consistent over the three pairs but three pairs of a greedy, non-reproducible session are thin evidence. - -### Speed -The metric: output tokens (including reasoning) divided by the time of each model request, summed over the cell. The proxy's first-byte time is the response header, so the time **includes preparing the request (prefill of the new tokens)**; it is request throughput, not pure decode. - -| task | LEL tok/s | VAN tok/s | VANL tok/s | LEL minus VANL, per pair | -| --- | --- | --- | --- | --- | -| ttt | 164.3 ± 2.7 | 225.7 ± 0.6 | 202.0 ± 1.7 | -39.8, -40.5, -32.7 | -| nestng-crm | 163.1 ± 1.3 | 221.4 ± 5.7 | 202.1 ± 3.8 | -36.8, -44.1, -36.0 | - -* **Leleka is about 19 % slower than the reference and about 26 % slower than vanilla's shipped defaults on this workload** (contexts 30-120k, prefix-cache hit 98-99 % in both stacks, 1-2k uncached input tokens per request). The six pairs are consistent with a tiny spread; this is not noise. Vanilla's lossy defaults buy about 10 % (VAN against VANL, +19 to +24 tok/s). -* Model time per `nestng-crm` cell: LEL 396, 468, 480 s; VAN 382, 393, 309 s; VANL 388, 318, 420 s, for similar token totals (LEL 65-78k output tokens, VAN 70-85k, VANL 65-83k). Wall time per cell does not separate the arms (LEL 488 ± 59 s, VAN 434 ± 99 s, VANL 462 ± 106 s) because the number of rounds varies more than the speed. -* This contradicts the earlier agent-workload numbers of `docs/e2e-run.md` (Leleka ahead of an older vanilla). Different vanilla version and shape, different tasks; not reconciled here. **The cause is not investigated**: the per-request engine logs (`stack-r*/engine.log`, `requests.log`) hold the split between prefill, decode and the speculative-decode statistics and were not read. That is the next step before any statement about why. - -## 3. What the data cannot resolve - -* Quality or iteration differences below roughly the run-to-run spread (rounds CV 20-30 % with n = 3): not resolvable here; 20+ repetitions per cell would be needed for a 10 % round difference. -* Whether the Leleka `ttt` r2 Restart defect is Leleka-specific: one of three pages, same prompt; the other 14 pages of the other arms did not show it. Greedy sessions are not reproducible, so one defect in nine pages is an observation, not a rate. -* Quality on long, real tasks: both tasks end within ~125k tokens of context. -* Arm order effects: the blocks of one repetition ran within about two hours; server drift (clocks, temperature) is in `stack-r*/mon.csv` and was not analysed. - -## 4. Files - -Server `/data/leleka-e2e/codex-compare/`: `runs/main/{LEL,VAN,VANL}/-r/` (cell.json, proxy/, transcript.md, workspace), `runs/main/_compare`, `_index`, `results-20261105-0558/`, `reaccept-1/reaccept.out`, `window-*.out`, job logs `runs/main/job-*.log`. Laptop scratch (not kept in Git): workspaces without `node_modules`, the Playwright 1.49.1 install, probe variants (`check_ttt_v2.mjs`: gap clustering). Evidence tables in this repository: `docs/e2e-data/codex-compare/`. diff --git a/docs/experiments/codex-compare-5090.md b/docs/experiments/codex-compare-5090.md deleted file mode 100644 index 47839cfd..00000000 --- a/docs/experiments/codex-compare-5090.md +++ /dev/null @@ -1,54 +0,0 @@ -# Codex + runtime + model: vanilla Strata against Leleka on two real tasks (RTX 5090) - -Branch `claude/codex-compare` (from `claude/quality-245k`, which carries the `--agents-md` option of `cell.py`). Owner request (2026-11-05): test the model and the runtime, KAR included, the way it is used, -with Codex CLI + runtime + model, on two tasks, handed out to the vanilla build (Strata) and to ours in turn, and compare **relative quality, number of iterations and speed**. -This page fixes the design before the first run; it contains no result. Numbers go to `codex-compare/runs/main/_compare/` on the server and are quoted here after the runs. - -## 1. Arms - -| id | stack | configuration | -| --- | --- | --- | -| LEL | Leleka release package `leleka-0.1.0-17e372944279-5090-linux-x86_64.tar.xz` (tag `leleka-5090-v0.1` plus the deploy-only follow-up commits), `leleka up --foreground --kar-fd` from the holder's sealed memfd | shipped: profile `rtx5090-32g`, KAR level-2 PLE, prefix cache auto, tail `reply`, greedy | -| VAN | vanilla Strata 0.2.6 (launcher `~/work/vanilla-strata/control`, engine 0.1.50), `launch --model iq3_s --context 256k --kv int8 --vision off --parallel 1 --tune skip` | **shipped defaults** (route tail skip ON, CPU prefill share auto); default GGUF PLE | -| **VANL = the reference** (owner, 2026-11-05: "in principle this is the reference") | same, `STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0` | lossy defaults off, the Original of the 245k study; LEL is judged against it first, VAN shows what vanilla's lossy defaults cost | - -Same machine, same model files, same Codex CLI 0.163.0 (`~/work/codex-e2e/bin/codex`), same `config.toml.tmpl` (reasoning effort medium, context window 262144, no web search, workspace-write sandbox, no network). -The logging proxy injects `temperature: 0` into every request of every arm (Codex sends none; vanilla would otherwise sample), so both are greedy. Greedy agent sessions are still not reproducible run to run -(adaptive expert tier, prefix cache), which is why every cell is repeated. No AGENTS.md pad: the sessions are what a user gets, contexts grow naturally (tens of thousands of tokens). - -## 2. Tasks (frozen in `scripts/e2e/codex/tasks/`, installed read-only on the server) - -* `ttt`: three.js tic-tac-toe in one `index.html` (prompt of the earlier jobs 943*, unchanged; the vendored `three.module.min.js` is an external seed file). Acceptance: static checks on the server; - the six real-mouse browser checks (`hidden/check_ttt.mjs`, Playwright) run afterwards on the laptop over the stored workspaces (`delta/browser_check_ttt.sh`) and go into `_compare/browser.json`. -* `nestng-crm`: a simple NestJS REST API + Angular front-end CRM (companies, contacts, deals with stages, search, pipeline). New task, authored for this study: seed = scaffolded Nest and Angular projects with - pinned dependencies and `package-lock.json`; `node_modules` are not in the seed: the runner hard-links two shared, read-only trees (`codex-compare/nm/backend`, `nm/frontend`) into the workspace (`cell.py --link-tree`), - so the agent has Node 22 + the real dependency set and no network, and no bulk data is written per cell. No browser on the server: verification is the Nest tests, a started server and `npm run build` of the Angular app. - Acceptance (`accept.py`, variant-blind): black-box REST checks, the agent's own backend tests, production build of both projects, static checks of the Angular sources. -* `smoke-mini` runs first in every block as the warm-up cell (identical for both arms; not compared). - -Limits, identical for both arms: cell wall limit 3000 s, 150 model requests (the proxy answers 503 beyond it: recorded `round_cap`), Codex medium reasoning. A cell that hits a limit is not completed. - -## 3. Protocol - -One **block** = one stack start of one arm (LEL load about 7-8 min, VAN about 5 min) running the warm-up cell and the tasks of one repetition. Three repetitions per arm and task, balanced against drift: -rep 1 LEL, VAN, VANL; rep 2 VANL, VAN, LEL; rep 3 LEL, VANL, VAN (9 blocks); the task order inside a block alternates with the repetition. Both arms run on the same server state otherwise (the lab holder is stopped for VAN by the usual -holder-free window and restarted afterwards). Server drift (uptime, GPU clocks, temperature) is recorded per block (`stack-r/mon.csv`, `host-r.txt`). -Stage 1 (queued behind the window-policy batch 2): `ttt` repetition 1 for LEL and VAN, which also shakes out the harness. Stage 2: the remaining repetitions and `nestng-crm` once its task is frozen and its dependencies are installed. - -## 4. What is compared - -* **Quality (relative):** objective acceptance (pass / fail and checks passed of N), the browser checks of `ttt`, failed or malformed model requests and tool-call errors, termination reason; then a blinded read of the final - workspaces and sessions against a fixed rubric (correct behaviour, completeness against the prompt, code structure, tests written and run, how the agent used its feedback), with the arm hidden from the reader, done after all cells exist. -* **Iterations:** model requests per cell (rounds), Codex tool calls, rounds that ended in an error, input tokens re-read in total. -* **Speed:** wall time to completion, decode tok/s (output tokens over decode time), time to first byte, seconds per request. Speed is only comparable between completed cells of the same task; a longer session is not slower. - -`scripts/e2e/codex/compare/cmp_report.py RUNS_ROOT` prints per task and arm every repetition, mean and sd, and the paired difference LEL minus VAN by repetition. With three repetitions per cell it cannot resolve small differences (the -lossy-delta study measured the run-to-run CV of rounds; see `codex-lossy-delta.md` section 6); the report states the spread, not a verdict. - -## 5. Provenance and rules kept - -Test tooling only, never in serving. Server work folder `/data/leleka-e2e/codex-compare/` (tasks, delta, tools read-only with `INSTALL.sha256`; `toolchain/` Node.js with the tarball sha256 in the notes; `nm/` shared dependencies; `runs/main/`). -Every run is a GPU-queue stub; jobs append to `decode/notes.md`. Nothing is claimed as a performance improvement from this study: it compares products on two workloads, and a faster or slower arm -is reported with its quality and its iteration count beside it (AGENTS.md rule on A/B claims). - -Results: [codex-compare-5090-results.md](codex-compare-5090-results.md). diff --git a/docs/experiments/codex-compare-nestng-task-notes.md b/docs/experiments/codex-compare-nestng-task-notes.md deleted file mode 100644 index a6a0bdaf..00000000 --- a/docs/experiments/codex-compare-nestng-task-notes.md +++ /dev/null @@ -1,71 +0,0 @@ -# nestng-crm: notes for the orchestrator (never sent to Codex) - -Written 2026-11-05 on the laptop (Windows 11, Node 22.16.0, npm 10.9.2, Python 3.9.13). Nothing here was run on the server. - -## Pinned versions (exact, `package.json` and `package-lock.json` are in `seed/`) - -backend (`seed/backend/package.json`): @nestjs/common, core, platform-express, testing 11.2.8; @nestjs/cli 11.0.24; @nestjs/schematics 11.1.0; class-validator 0.15.1; -class-transformer 0.5.1; reflect-metadata 0.2.2; rxjs 7.8.2; jest 29.7.0; ts-jest 29.4.15; supertest 7.3.1; typescript 5.9.3; @types/express 5.0.6, jest 29.5.14, -node 22.20.5, supertest 6.0.3. 579 packages after `npm ci`, node_modules about 214 MB, about 28,000 files. -Scaffold is hand-made (no `nest new`, so no git init and no eslint/prettier): classic CommonJS tsconfig (no `module: nodenext`/`isolatedModules`, which make decorator -metadata imports awkward), `nest build` to `dist/main.js`, no `incremental`. The seed has an EMPTY `AppModule`, a `main.ts` that listens on 3000 (the agent must add PORT and -127.0.0.1), the jest config for unit tests (in package.json, `src/**/*.spec.ts`) and `test/jest-e2e.json` (`*.e2e-spec.ts`), and no tests. - -frontend (`seed/frontend/package.json`): @angular/common, compiler, core, forms, platform-browser, router 20.3.35; @angular/build, cli 20.3.42; @angular/compiler-cli 20.3.35; -rxjs 7.8.2; tslib 2.8.1; zone.js 0.15.1; typescript 5.9.3. 410 packages, node_modules about 218 MB, about 19,000 files. -Angular 20, not the 22.x that is current on the registry (22.x needs Node >= 22.22.3; the laptop has 22.16 and Angular 20 accepts ^22.12). Standalone components, esbuild -`@angular/build:application`, strict TS and strict templates, the dev server target exists, no `test` target (Karma/Jasmine removed), `cli.analytics=false`. - -Lockfile digests (sha256): `seed/backend/package-lock.json` 23a3084dc848bf127f97696563cab0ec113358585df6245d270b1f123c7fd533, -`seed/frontend/package-lock.json` 87f8dc2edd3bb892330bb23ea3675dc2e173cbafbd35865fccc9168a58bca72c (the manifest records them with the other seed files). -`npm ci` on both from a clean directory works and the reference then passes 56/56 (checked 2026-11-05). - -## Installing node_modules on the server (once, by the main session, network is available there) - -One shared tree per project outside any workspace, for example `/data/leleka-e2e/codex-compare/node_modules-nestng/{backend,frontend}/node_modules`. Install from the -frozen seed lockfiles, low priority, because the root NVMe stalls under sustained writes (about 430 MB, 47,000 small files, about 45 s on the laptop): - -```sh -for d in backend frontend; do - mkdir -p $NM/$d && cp $TASKS/nestng-crm/seed/$d/package.json $TASKS/nestng-crm/seed/$d/package-lock.json $NM/$d/ - ( cd $NM/$d && nice -n 19 ionice -c3 npm ci --ignore-scripts=false --no-audit --no-fund ) -done -``` - -then `chmod -R a-w $NM` and record `find $NM -type f | sort | sha256sum`-style digest in the run metadata (it is not part of the task manifest). Node 22 itself: a pinned -tarball (the version and its sha256 recorded) in the same directory, put on PATH for Codex's shell and for `accept.py` (`NESTNG_NODE_BIN=`). -Angular 20 needs Node >= 20.19 or >= 22.12; any 22.x LTS from this year is fine. - -## What accept.py needs - -* `python3 accept.py WORKSPACE`, stdlib only, 56 checks, prints `PASS`/`FAIL name :: detail` and `SUMMARY n/m`. Nothing in WORKSPACE is modified (the self-test confirms it). -* node_modules: `WORKSPACE//node_modules` if present, else `$NESTNG_NM_ROOT//node_modules` (a directory holding `backend/node_modules` and `frontend/node_modules`). - It symlinks them (junction on Windows) into a temp copy that excludes node_modules, dist, .angular, coverage, out-tsc, *.tsbuildinfo and .git. The runner's workspace copy of - node_modules is therefore never copied or written. -* Node and npm from PATH, or `$NESTNG_NODE_BIN`. It sets CI=1, NG_CLI_ANALYTICS=false, NG_DISABLE_VERSION_CHECK=1 for its own children. -* The backend is started with `node dist/main.js` on a free port in `PORT`; a server that ignores PORT fails the whole REST group (35 checks). -* Time on the laptop: reference 22-24 s; bare seed 79 s (30 s of waiting for a server that never listens on `PORT`). Worst case with a slow agent solution well below 300 s. - On the server expect 2-3x the CPU-bound parts (ng build, tsc, jest). -* Groups: 7 structure, 2 backend build/listen, 35 REST, 3 own tests (npm test, npm run test:e2e, >= 15 cases in total), 1 frontend build, 9 static frontend checks. -* Does NOT check the UI in a browser (none on the server). A later laptop check with Playwright over the stored workspaces is possible (serve `frontend/dist/frontend/browser` - with the backend on 3000 and a proxy), not written. - -## Laptop timings (reference solution) - -`npm run build` backend 3.7 s; `npm test` 5.9 s (15 tests); `npm run test:e2e` 5.4 s (15 tests); `ng build` production 5.4 s; whole accept.py 22 s (seed + overlay self-test: seed -rc=1 79 s, overlay rc=0 22 s). - -## Gotchas for the server and the Codex sandbox - -* The runner must copy the seed FIRST, check SEEDTREE (`taskfile.workspace_lines`) and only then add the hard-linked node_modules; `workspace_lines` would otherwise hash 47,000 - files of node_modules (`cell.py` does it again after the run for `workspace.sha256`: exclude `node_modules`, `dist`, `.angular` there, or it reads 430 MB per cell). -* Hard-linked files are shared: make the shared tree read-only (`chmod -R a-w`) so an agent cannot edit a package of every later cell. `cp -al` (hard links) writes no data. - A symlinked node_modules also works with `accept.py`, but Angular/Jest under a symlink inside a Codex sandbox was not tried; hard links are what the prompt promises. -* esbuild and the Angular CLI fetch platform-specific optional dependencies (`@esbuild/linux-x64`, `@parcel/watcher-linux-x64-glibc`, `lmdb` prebuilds for the Angular cache) at - `npm ci` time from the registry. Install on the server (linux-x64), never copy the laptop's tree. Check `npm ls @esbuild/linux-x64` after the install. -* The agent's `ng build` writes `frontend/.angular/cache` into its workspace (fine); jest/ts-jest write a cache under the OS temp dir: the Codex workspace-write sandbox allows - the temp dir, but confirm once with a smoke cell. If `HOME` is not writable, `ng` may try to write `~/.angular-config.json` (analytics is disabled in the seed `angular.json`). -* `ng serve` and `nest start --watch` need a listening port and file watching; Codex may start them. `cell.py` kills the process group at the end, accept.py uses a random port, - so a leftover server on 3000 does not disturb the acceptance, but check that 3000 is free before the first cell (the agent's own tests use supertest, no port). -* Round estimate 30-70 is the author's guess; the prompt is a single phase and the seed has no tests, so the agent must create about 15+ test cases. -* After the main session freezes `MANIFEST.sha256` do not edit any file in this directory (including this one): `TASK`/`SEEDTREE` digests cover it. diff --git a/docs/experiments/codex-compare-speed-gap.md b/docs/experiments/codex-compare-speed-gap.md deleted file mode 100644 index f15d45a0..00000000 --- a/docs/experiments/codex-compare-speed-gap.md +++ /dev/null @@ -1,429 +0,0 @@ -# Codex compare: why Leleka decodes slower than vanilla Strata, and the ranked levers (RTX 5090, 2026-11-07) - -Branch `claude/speed-vs-strata-08143a`. Phase 1 = analysis of existing logs, **no new GPU run, no performance claim**. Phase 2 (measurements) is in section 6 once it has data. -Sources (server `/data/leleka-e2e/`): `codex-compare/runs/main/{LEL,VAN,VANL}/stack-r{1,2,3}/engine.log` (LEL: JSON `request` events of the engine; VAN/VANL: `strata serve: prompt ... generated ... drafts accepted a of b` lines), -`spd-gap/runs/main/{A,B,E,K*,KA*,KS*,P,T*,VANLP,VANL-noprof}` (replay of the recorded VANL `nestng-crm-r2` prompts), `docs/ledger.md`, `docs/roofline.md`, `docs/experiments/codex-compare-5090-results.md` (branch `claude/codex-compare`). -Arms: LEL = release package `leleka-0.1.0-17e372944279`, VANL = vanilla 0.2.6 with route tail skip and CPU prefill share off (reference), VAN = vanilla shipped defaults (both on). -Analysis scripts are not kept in Git (run over ssh from stdin; formulas below). - -## 1. Where the time goes (all requests with prompt > 200 tokens of the 9 `stack` logs per arm, ttt + nestng-crm together) - -Rounds of vanilla are estimated as `generated - drafts accepted` (one bonus token per window); LEL logs `rounds` itself. - -| metric | LEL | VANL (reference) | VAN | LEL vs VANL | -| --- | ---: | ---: | ---: | ---: | -| requests (3 stacks) | 531 | 246 | 271 | | -| decode tok/s (sum output / sum decode ms) | 177.5 | 217 | 238 | **-18 %** | -| tokens per round | 3.22-3.34 | 2.92-3.00 | 2.91-3.02 | **+12 %** (adaptive window) | -| ms per round | 18.1-18.8 | 13.5-13.9 | 12.3-12.5 | **+36 %** | -| prefill tok/s over uncached tokens | 930-1050 | 1460-1560 | 1320-1660 | -35 % | -| prefill share of request time | 9.5 % | 7.1 % | 7.3 % | +2.4 points | -| request time per output token, prefill + decode (ms) | 0.59 + 5.63 = 6.22 | 0.36 + 4.61 = 4.97 | 0.33 + 4.20 = 4.53 | gap 1.25 ms: **decode 82 %, prefill 18 %** | - -Reading: Leleka gets more tokens per round than vanilla (+12 %), but a round costs +5 ms. With vanilla's round time Leleka would be ~10 % *faster* than VANL. The whole gap is the time per round, plus a smaller prefill share. - -Prefill latency by size of the uncached part (median ms): the fixed cost per request is about +200-300 ms, and large reads are 2x slower. - -| uncached tokens | LEL | VANL | VAN | share of LEL requests | -| --- | ---: | ---: | ---: | ---: | -| < 64 | 430 | 268 | 210 | 19 % | -| 64-256 | 530 | 292 | 251 | 31 % | -| 256-1024 | 722 | 435 | 397 | 35 % | -| 1024-4096 | 1002 | 715 | 695 | 11 % | -| >= 4096 | 4405 | 2184 | 2044 | 4 % (19 % of LEL prefill time) | - -## 2. Same prompts replayed (spd-gap; `nestng-crm-r2` of VANL, first 30 requests, requests are identical across variants; dec_tps = output tokens / decode ms) - -| variant | what | dec tok/s | tok/round | ms/round | VRAM / PCIe / CPU % of routed | -| --- | --- | ---: | ---: | ---: | --- | -| VANL (vanilla, lossless) | `--spec 4 --spec-min-p 0.5` | **208.3** (2 runs equal) | 2.95 | 14.2 | hit 92.8 / 2.0 / 5.2 | -| A | ours shipped (adaptive window, floor 0) | 183.8 | 3.55 | 19.3 | 90.2 / 3.0 / 6.7 | -| B | ours with vanilla's window (fixed 4, floor 0.5) | 178.8 | 2.90 | 16.2 | 90.8 / 2.7 / 6.6 | -| E | A + our lossy tail skip | 206.7 | 3.58 | 17.3 | 93.7 / 1.7 / 4.6 | -| T45 | E, repeat | 205.8 | 3.59 | 17.4 | 94.0 / 1.6 / 4.4 | -| KAa | E + sm_120 `ATTN_DAILY` + `GU_SWIGLU` | 209.7 | 3.51 | 16.7 | 93.6 / 1.7 / 4.7 | - -Over requests 4-30 only (whole runs of 27 requests, n = 1-4 per variant, not a paired design): T45 family 207.8 / 210.1 / 213.3 / 209.0 (mean 210.1), K (all three sm_120 sets) 214.0 / 215.8 / 218.3 (216.0), KA 212.0 / 217.6 (214.8), KS (side mixer only) 208.3 / 210.5 (209.4), T30/T35/T40 (PCIe fraction) 204.0 / 206.8 / 207.2. -So: `ATTN_DAILY + GU_SWIGLU` ~ +2.3 %; the side mixer adds nothing; the PCIe fraction 0.45 is not worse than 0.30-0.40. Run-to-run spread inside one variant is +-1.5 %: these are indications, not A/B results. - -Step profile (`P` = ours with `LELEKA_SERVE_PROFILE=1`, vanilla `STRATA_DECODE_TIMING=1`; ms per window, GDN layers + QSA layers, 30 profile lines each): - -| step (ms/window) | ours, miss-heavy (lines 1, 2, 7, 8, 26) | vanilla, miss-heavy (lines 8, 9, 12, 22, 27) | ours, quiet (16, 17) | vanilla, quiet (17, 18) | -| --- | ---: | ---: | ---: | ---: | -| total per window | 21-26 | 16-17 | 12.0 | 10.7 | -| waitB (GDN + QSA) | 4.3-5.9 | 3.9-4.6 | 0.45 | 0.5 | -| **waitCPU (GDN + QSA)** | **3.1-4.0** | **0.4-1.3** | **0.8** | **0.2** | -| **PCIe group** | **0.6-0.9** | **0.3** | **0.4** | **0.1** | -| VRAM hits | 1.7-2.8 | 1.4-1.9 | 1.5 | 1.4 | - -The windows differ by 5-9 ms only in states with misses, and almost all of it is `waitCPU` + `PCIe group` (+2.5 ms of 21 in a miss-heavy window, +0.6 ms in a quiet one) and a hit rate that is lower in ours (90.2 % against 92.8 % of the routed experts). -Cache size: ours 12,192 expert slots (23.24 GiB), vanilla 12,575 (23.87 GiB, +3.1 %), vanilla leaves 389 MiB VRAM free (and warns); vanilla draft head over 106,299 tokens (212.9 MiB), ours the full 248,320-row head (ledger section 5). -Draft + commit outside the window: ours about 2.5 ms/round (`draft.finish` 1.7, `apply_pending` 0.6, commit 0.4), vanilla 1.2 (`draft` 1.17 in its timing line); ledger section 5 measured +1.5 ms/round. -The vanilla server drifts with uptime: 13.5-16 ms/round at 11-13 h, 10.1-11.7 after a fresh boot (`codex-lossy-delta.md`); every A/B must alternate inside one boot. - -## 3. Ranked levers - -Gain = estimated change of end-to-end tok/s on the Codex workload (contexts 30-120k), **E** = estimate from the numbers above, not measured as an A/B. Lossy = changes output; "placement-class" = changes which experts run on the GPU (GPU and CPU round differently), so output differs slightly without being a bug. - -| # | lever | expected gain | risk | class | evidence | -| --- | --- | ---: | --- | --- | --- | -| 1 | sm_120 sets `ATTN_DAILY` + `GU_SWIGLU` default on (the vanilla 0.1.50 defaults) | +2-3 % (E from KA vs T45: 214.8 vs 210.1) | low | non-lossy: byte-identical in the probe and 243-row replay | section 2 | -| 2 | Remove the CPU/PCIe wait of the miss leg (`waitCPU` + `PCIe group`: why is the CPU-expert result late: pool wake/hand-off, per-layer dispatch, split rule with `pcie_frac`, CPU kernel speed per expert) | +4-10 % (E: 1.0-3.1 ms of 19 ms/round; the quiet-state excess is already 0.6 ms) | medium (host threading) | non-lossy if the numerics of each expert stay (same device decides the rounding) | step profile | -| 3 | Fewer misses: slots 12,192 -> 12,575 (headroom policy), adaptive tier timing, draft-head VRAM | +2-6 % (E: miss rate 9.8 % -> 7.2 % removes up to a quarter of the miss leg) | medium: VRAM headroom (vanilla warns at 389 MiB), OOM/paging risk | placement-class (quality gate against control placement) | slots, hit rates | -| 4 | Per-round draft + commit overhead (merge small graphs, fewer launches, cheaper chain step: 0.68 vs 0.42 ms, `mtp_original_finite` guards) | +3-6 % (E: -1.3 ms of 19) | medium | non-lossy, bitwise (same kernels; draft vocabulary subset is a separate sub-lever, ledger: prompt-dependent -4 %..+19 %) | ledger 5, profile | -| 5 | Prefill fixed latency per request (+200-300 ms per small tail; vanilla reads <= 64 tokens through verify windows) and 2x slower large reads | +2-3 % (E: prefill share 9.5 % -> 7.1 %) | medium | tail through windows is a different kernel path: placement-class numerics; faster large chunks are bitwise | section 1 | -| 6 | Adaptive window policy: A vs B is +2.8 % net (+0.65 tokens per round for +3.1 ms); tune floor / ceiling (variants C, D of `spd_replay_job` never ran) | +1-3 % (E) | low | non-lossy (exact speculative decoding) | section 2 | -| 7 | Route tail skip (lossy): E vs A +12.5 % (206.7 vs 183.8), vanilla VAN vs VANL +9.7 % real | +10-12 %, shrinks lever 2 and 3 | quality: rounds growth unknown (codex-compare rounds CV 20-30 %) | **lossy, experimental, stays off** until the owner gate | section 2 | -| 8 | CPU prefill share (vanilla default, KL ~0.004) | ~0 (VAN prefill share 7.3 % vs VANL 7.1 %) | | lossy | section 1 - do not pursue | - -Total of the non-lossy levers 1, 2, 4, 5, 6 if additive: about +12-25 %; the gap to VANL is +22 % (217 / 177.5), to VAN +34 %. Lever 3 and 7 are the way past parity with vanilla's shipped defaults. -The levers interact: tail skip removes most of the miss leg, so lever 2 and 3 are measured with tail skip off (the default). - -## 4. Gates, per lever (AGENTS.md; nothing changes a default before its gate) - -| lever | A/B | quality / identity gate | -| --- | --- | --- | -| 1 | switch on/off, same boot | byte-identical outputs and R hashes on a **full** replay of a Codex session (all 56 requests of `nestng-crm-r2`, plus the earlier 243-row replay); then default on | -| 2 | switch on/off | per-step output identical on a frozen tier (`--adapt-every 0` and a frozen placement, because the adaptive tier is not reproducible run to run); a distribution comparison of the adaptive runs | -| 3 | slots / headroom / profile variants | placement-class gate: deviation against the control placement not worse than between two control placements (>= 1000 rows), zero OOM/paging in the 256k run, VRAM free >= the policy floor | -| 4 | switch on/off | greedy output and tensor identity (the kernels are the same); chain graph timing in the model-free probe first | -| 5 | switch on/off, tails of 1-64 / 64-256 tokens | R hash identity for the unchanged path; the window-tail path under the placement-class gate | -| 6 | variants of floor/ceiling on the same replay | identical greedy output (speculation is exact); tokens/round and ms/round reported | -| 7 | E against A on the replay + real Codex sessions | the **owner criterion**: rounds growth <= speed gain in %, game playable, CRM 56/56; stays experimental until it passes | - -## 5. Measurement protocol for phase 2 - -* Workload: the recorded VANL `nestng-crm-r2` requests (`proxy/rounds/NNNN.fwd.json.gz`) through `scripts/e2e/codex/compare/spd_replay_job.sh` (server copy `spd-gap/tools/spd_replay_job7.sh`), whole cell (56 requests); requests 1-3 are warm-up and dropped. -* Design: blocks of `leleka up` per variant, order A B B A A B ..., **n >= 10 blocks per variant** in one boot (uptime drift above), GPU lock and holder queue as for all jobs; the metric per block: dec tok/s, tok/round, ms/round, end-to-end tok/s (`otok / (pf + dec)`), tier %; paired difference per adjacent block pair with a 95 % CI. -* Record per run: GPU, driver, CUDA, host, model digest (`8f59b4aa...` profile, model files), binary sha256 and commit, the switches, cache state (prefix cache and expert tier start state: engine restarted per block, prefix cache empty at start), token counts and the distributions (per-request dec tok/s). -* Binary: lever 1 is a pure switch (`LELEKA_SM120_ATTN_DAILY`, `LELEKA_SM120_GU_SWIGLU`), so its paired A/B runs the same codex-compare release package on and off (sha256 in the job log); the default flip itself is a commit on the hexagonal head `e4993d151` and needs one confirmation block pair on that head. Levers that change code (2, 4, 5) are measured as head build against head build with the same switch off. -* Tools (this branch, `scripts/e2e/codex/speed/`): `spd_ab_job.sh` (holder job; variant names `NAME.BLOCK`, new variant `L`), `replay_hash.py` (adds `out_sha` per request), `ab_report.py RUN_DIR BASE VAR` (paired differences with 95 % t intervals and the identity count). Copies live in `/data/leleka-e2e/spd-gap/tools/`. - -## 6. Phase 2 results - -Not run yet: the GPU queue holds the hexagonal identity/A-B jobs (`hx-abg1` running, `hx-abc3..5`, `hx-id6`, `hx-abd1..5` behind it, ~30 min each) ahead of this program. -Queued at the end of `PRIORITY` (2026-11-07 18:30 UTC): `spd-l1a` (blocks 1-5) and `spd-l1b` (blocks 6-10) = lever 1, A (shipped lossless) against L (A + `ATTN_DAILY` + `GU_SWIGLU`), 10 blocks per arm, 30 requests of the recorded cell per block, ~12 min per block. -Read the result with `python3 -I - RUN_DIR A L < scripts/e2e/codex/speed/ab_report.py` on `/data/leleka-e2e/spd-gap/runs/ab-l1`. Smoke test of the report on three old block pairs (tail skip on, no hashes): L +1.9 % decode tok/s, CI -2.1..+6.0 % (n = 3, which is why n >= 10). -Entries are added below, one per lever, as each paired A/B finishes. - -### Lever 1, interim (blocks 1-5 of 10, `spd-l1a`; `spd-l1b` was running, so no final numbers yet) - -| metric | A | L | L - A (95 % CI) | -| --- | ---: | ---: | --- | -| decode tok/s | 187.10 | 190.05 | +1.6 % (-0.3..+3.4 %) | -| end-to-end tok/s | 170.18 | 169.67 | -0.3 % (-3.2..+2.6 %) | -| ms/round | 19.60 | 19.21 | -2.0 % (-6.6..+2.6 %) | - -n = 5 pairs: not significant, gain below the +2-3 % of the estimate. **Identity gate cannot use two boots**: `out_sha` is equal for only 2 of 30 requests even between two runs of the *same* arm (A.1 vs A.2, A.2 vs A.3; L.1 vs L.2: 3 of 30), because the adaptive tier / placement is not reproducible run to run (as `codex-lossy-delta.md` noted). So the byte-identity of lever 1 must be shown on a frozen placement (`--adapt-every 0`, static tier, one boot, switch toggled per request or two boots with the same frozen tier), not by this A/B; the A/B above is the speed record only. -Queue order (orchestrator request 2026-11-07): `hx-abg2..5` (cumulative refactor A/B) are on top of `PRIORITY`; the running `spd-l1b` was left to finish. - - -### Lever 1, final speed result (10 pairs, `spd-l1a` + `spd-l1b`, 2026-11-08) - -Release package `leleka-0.1.0-17e372944279-5090`, RTX 5090, VANL `nestng-crm-r2`, 30 requests per block (27 after the 3-request warm-up skip), engine restarted per block, order alternated, only the switch differs. - -| metric | A (shipped lossless) | L (+ ATTN_DAILY + GU_SWIGLU) | L - A (95 % CI) | -| --- | ---: | ---: | --- | -| decode tok/s | 186.58 | 190.03 | **+1.85 % (+0.97..+2.73 %)** | -| end-to-end tok/s | 168.87 | 170.07 | +0.71 % (-1.01..+2.44 %) | -| tokens/round | 3.66 | 3.63 | -0.66 % (-3.13..+1.82 %) | -| ms/round | 19.61 | 19.13 | -2.46 % (-4.47..-0.46 %) | -| VRAM % of routed | 90.37 | 90.34 | -0.03 % (-0.27..+0.21 %) | - -Decode gain is real and small (+1.85 %, CI excludes zero), inside the +2-3 % estimate's lower end; it does not reach the end-to-end number (prefill is untouched; CI crosses zero). The cross-boot `out_sha` identity is 22 of 300 and is **not** the gate (A against A is as low, adaptive tier and window). Default stays off until the frozen-placement gate passes: `spd-l1id` (variants `FA`/`FL` = tier swaps off + fixed window 4, with and without the two sets; `FA.1` vs `FA.2` is the A/A floor, then `FA.n` vs `FL.n` must be byte-identical), output `/data/leleka-e2e/spd-gap/runs/id-l1`, queued on top of `PRIORITY`. - -### Lever 1, identity gate: HTTP replay cannot decide, teacher-forced harness used (2026-11-08) - -`spd-l1id` (release package, `leleka up`, tier swaps off, fixed window 4, 30 requests, 4 boots FA.1 FL.1 FA.2 FL.2): `out_sha` equal for 10/30 (FA.1 vs FA.2), 10/30 (FL.1 vs FL.2), 11/30 (FA.1 vs FL.1), 9/30 (FA.2 vs FL.2). The A/A floor is as low as the A-vs-L pairs, so the live HTTP replay is not a deterministic probe even on a frozen tier and window (the remaining sources are not isolated: host-thread timing of the CPU/PCIe split, the persisted prefix-cache state between boots; the frozen tier also runs at 63 % VRAM hits, ~104 tok/s, so these four boots say nothing about speed). The gate is therefore the repository's teacher-forced harness (`scripts/e2e/decode/draftround-id.sh`, the 256k-class capture `night5-long-256k`, top-16 logprob rows, A/A floor inside each process): `spd-l1id2`, P1 = release kernels, P2 = P1 + `ATTN_DAILY` + `GU_SWIGLU`, test binary `rt-dr2`, output `/data/leleka-e2e/spd-gap/runs/id-l1-tf`. - -### Lever 1, verdict: default ON for the 5090 profiles (2026-11-08) - -`spd-l1id2` (teacher-forced, `rt-dr2`, five requests of `night5-long-256k` up to 243k prompt, 240 forced tokens each, `ADAPT=4`): reference process A/A floor 2057 of 2057 top-16 rows identical; P2 (`ATTN_DAILY` + `GU_SWIGLU`) against the reference, both arms: 2057 of 2057 identical, 0 argmax flips; draft trace 1036 of 1036 lines identical (**IDENTICAL**); `q_tail_gate` PASS in both processes. So the two sets are bitwise identical to the shipped kernels on this gate and the paired decode gain is +1.85 % (CI +0.97..+2.73 %), end-to-end +0.71 % (not significant). Caveats: the gate binary `rt-dr2` (draft-round `28d74a2ef`) is older than the release package `17e372944279`, and the live HTTP replay cannot serve as an identity probe (floor 10/30). The three 5090 profiles (`rtx5090-32g`, `-file`, `-gguf-ple`) now set `LELEKA_SM120_ATTN_DAILY=1` and `LELEKA_SM120_GU_SWIGLU=1`; the laptop profile (sm_86) does not; an operator's `engine_env` still wins. Rollback: set both to `0` in `engine_env`. - -Confirmation on the product tree (2026-11-08, jobs `spd-l1id4-c9`, `spd-l1id4-main`): the same teacher-forced gate on the hexagonal test binaries `rt-c9` (refactored product tree) and `rt-main` (its base). Both: A/A floor 2057 of 2057 top-16 rows identical, P2 (`ATTN_DAILY` + `GU_SWIGLU`) against the reference 2057 of 2057 in both arms, 0 argmax flips, draft trace 1036 of 1036 identical, `q_tail_gate` PASS. The release package itself cannot run the replay smoke (it is a lib test), and a test binary of exactly `17e372944279` does not exist on the server (not built: 41 GiB free on `/data`); the kernels are the same PTX. The server copy of `draftround-id.sh` hardcodes the binary directory, so these two jobs use the repository version (`D` override) installed as `spd-gap/tools/draftround-id.sh`. The decision to keep the sets on stands; the paired A/B of the release package (10 pairs above) is the switch these profiles now set, so no further A/B was run. - -### Levers 2 and 4: what the existing evidence says before any code (2026-11-08, no GPU run) - -* Vanilla and ours run the same CPU leg shape: 15 workers on logical processors 1-15, host on 0 (vanilla engine.log, ours `cpu_workers=15`), `LELEKA_POOL_TASKS_PER_THREAD` 2/4/6 within +-2 us per expert (`docs/experiments/cpu-service2-5090.md`), PCIe fraction 0.30-0.40 not better than 0.45 (section 2 above). -* The step-profile columns are not comparable one to one: vanilla books the CPU wait inside `waitB` (GDN layers waitB 4.87, waitCPU 0.22, PCIe group 0.36 = 5.45 ms/window) where ours splits it (waitB 3.74, waitCPU 2.36, PCIe group 0.57 = 6.67 ms/window). The wait group of the GDN layers is ~1.2 ms/window longer in ours, the QSA layers ~0.2 ms/window shorter in ours: a net ~1.0 ms of ~19 ms/window (~5 %), and it moves with the miss count (hit rate 90.2 % against 92.8 %, 12,192 against 12,575 slots), so lever 2 and lever 3 are one effect until a per-miss cost is measured. -* The fused verifier commit graph (`LELEKA_DRAFT_FUSED_COMMIT=on`, bitwise, `docs/experiments/draft-round-5090.md`) measured -0.024 +- 0.046 ms per round: neutral, not worth an A/B here. -* Consequence: a code change for lever 2 needs a per-miss timing (CPU compute against late start) from an instrumented build before it is worth an A/B; the cheap config knobs are already flat. Not started; the next measured lever is 7 (tail skip, experimental, lossy): `spd-l7a`/`spd-l7b` queued, 10 paired blocks A against E, speed and rounds growth only (the owner gate also needs real Codex sessions and CRM 56/56), output `/data/leleka-e2e/spd-gap/runs/ab-l7`. - -### Lever 7 (route tail skip, EXPERIMENTAL, lossy), interim: blocks 1-5 of 10 (`spd-l7a`; `spd-l7b` running), 2026-11-08 - -Release package `17e372944279`, same replay as lever 1, A (shipped) against E (`LELEKA_ROUTE_TAIL_SKIP=7`, `..._MAX_CACHED=100`), 27 requests per block after warm-up, order alternated. - -| metric | A | E | E - A (95 % CI) | -| --- | ---: | ---: | --- | -| decode tok/s | 185.84 | 210.30 | **+13.16 % (+11.80..+14.53 %)** | -| end-to-end tok/s | 168.49 | 186.95 | +10.95 % (+8.47..+13.44 %) | -| tokens/round | 3.59 | 3.79 | +5.45 % (+0.07..+10.83 %) | -| ms/round | 19.31 | 18.00 | -6.81 % (-10.67..-2.96 %) | -| VRAM % of routed | 90.42 | 93.89 | +3.48 % (+3.09..+4.59 %) | - -The gain is large and the CI is far from zero; rounds per token did not grow in this replay (tokens/round +5.5 %), but the replay sends recorded prompts, so the replies differ from E's own (the task trajectory is not followed) and this says nothing about the owner criterion on real sessions. The output is not identical (lossy by definition). **Stays off by default.** The owner gate (rounds growth <= speed gain in %, game playable, CRM 56/56) runs on real Codex sessions: `spd-g1..3` (the codex-compare ours arm with the two tail-skip variables exported, tasks `ttt` + `nestng-crm`, repetitions 1-3, output `/data/leleka-e2e/spd-gap/runs/codex-tail`), queued behind `spd-l7b`; compare with the shipped `LEL` and `VANL` runs of `codex-compare/runs/main`. - -### Lever 7, final speed result (10 pairs, `spd-l7a` + `spd-l7b`, 2026-11-08) - -Same replay and arms as the interim table (27 requests per block after warm-up, 10 block pairs, order alternated): decode tok/s A 186.40, E 209.81, **+12.56 % (95 % CI +11.50..+13.62 %)**; end-to-end +11.00 % (+9.75..+12.25 %); tokens/round 3.65 against 3.77 (+3.30 %, CI -0.21..+6.80 %, includes zero); ms/round 19.57 against 17.96 (-8.24 %, -10.71..-5.77 %); VRAM share of routed 90.32 -> 93.76 %. `out_sha` identical in 4 of 300 requests: it is a lossy mode, and the HTTP replay floor is about 10 of 30 anyway, so this number decides nothing. - -### Lever 7, owner gate on real Codex sessions (jobs `spd-g1..3`, 2026-11-08) - the table below used the OLD accept.py, see the correction after it - -Release package `17e372944279`, `LELEKA_ROUTE_TAIL_SKIP=7`, `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100`, real Codex CLI 0.163.0, temperature 0, three repetitions of `ttt` and `nestng-crm`, run by `cmp_codex_job.sh` on the 5090 (`/data/leleka-e2e/spd-gap/runs/codex-tail`, report `_compare/compare.md`). Baseline is the shipped LEL of `codex-compare/runs/main` (same tools, same Codex, same tasks). - -| task | arm | accepted | rounds (mean +- sd) | wall s | decode tok/s | -| --- | --- | --- | --- | ---: | ---: | -| nestng-crm | LEL shipped | 3/3 (56/56 each) | 54.0 +- 7.5 | 488.4 | 163.1 | -| nestng-crm | LEL + tail skip | **0/3 (55/56, 55/56, 54/56)** | 55.0 +- 17.4 | 468.3 | 183.2 | -| ttt | LEL shipped | 3/3 (14/14) | 17.7 (15, 22, 16) | 177.9 | 164.3 | -| ttt | LEL + tail skip | 3/3 (14/14) | 18.0 +- 7.0 | 155.5 | 184.6 | - -* Speed: decode tok/s +12.3 % (crm) and +12.4 % (ttt); the engine's own per-round view over the CRM requests is 17.4 ms/round against 19.4 (-10 %) at an equal 3.47 tokens/round. -* Rounds: CRM +1.9 % and ttt +1.7 % (both far inside the sd): the growth of rounds is below the speed gain (+12 %) in both tasks (greedy sessions are not reproducible run to run, n = 3). -* Game: `ttt` accepted 3/3. -* **CRM 56/56 is not met in any of the three runs.** The failing check is `frontend src: a board with one column per stage (all five stages and a loop)` in r1, r2 and r3 (`no file with all five stages and a loop`), plus one backend e2e test in r3 (`deals.e2e-spec.ts`, passed=41 failed=1). All nine baseline sessions (LEL, VAN, VANL, three each) passed 56/56. Three of three against zero of nine is not noise at this size; the lossy skip changes what the model writes on this task, and the gate in AGENTS.md ("do not enable lossy optimizations by default until their separate quality gate passes") is not passed. - -Verdict: the route tail skip stays **experimental and off by default**; no default or profile was changed for it. The logit gate (`q_tail_gate`, teacher-forced `night5-long-256k`, `rt-c10`) is queued as `spd-l7id` for the record; it cannot overturn the CRM failure above. - -### Lever 2 (waitCPU / PCIe), decision after re-reading `cpu-service2-5090.md` (2026-11-08, no new GPU run) - -The CPU leg already costs what vanilla's costs per expert: the server bench of the dispatch gives 41-51 us per CPU expert (15 workers, 54-57 GB/s of expert bytes, near this host's DRAM bandwidth) and vanilla's PcieAuto line reports 44 us; the host-callback stages are 0.06-1.08 ms/round each and already trimmed (eager admission +4.24 %, AVX2 `q8_k`); pool tasks per thread, PCIe share 0.45-0.65 and the fused commit graph are flat or neutral. What remains of the `waitCPU` + `PCIe group` excess (about 1 ms of ~19 ms per window) scales with the number of misses per window, i.e. it is lever 3 (hit rate 90.2 % against 92.8 %), not a separate host-side defect. A per-miss instrumented build would only re-split a quantity that the miss count already explains, so none is built. Lever 2 is closed with **no change**; the remaining miss-leg work moves to lever 3 (placement-class gate) and, lossy, lever 7. - -Queued next: lever 6 (`spd-l6a`, `spd-l6b`: D = adaptive window at floor 0.5 against shipped A, 10 block pairs, exact speculative decoding) and the lever 7 logit gate `spd-l7id`. - -#### Correction: the `spd-g1..3` cells were accepted by the pre-fix `accept.py` (2026-11-08) - -`cmp_codex_job.sh` ran the frozen `codex-compare/tasks/nestng-crm/accept.py` (sha256 `db1b7095...`), whose check "a board with one column per stage" needs the five stages and the loop in ONE file and failed in all nine baseline cells too (`codex-compare-5090-results.md`, Deviations 4); the baseline 56/56 come from the fixed `reaccept-1/tasks/nestng-crm/accept.py` (sha256 `b2e6c690...`). The 0/3 above therefore compared unlike checkers. Re-accepted offline with the fixed script (copy at `/data/leleka-e2e/spd-gap/runs/codex-tail-reaccept/accept-task`, logs `r1.log r2.log r3.log`, original cell logs untouched): - -| cell | fixed accept.py | detail | -| --- | --- | --- | -| nestng-crm r1 | **56/56** | board: `@for (stage of stages ...)` in `deals.component.html` | -| nestng-crm r2 | **56/56** | board: `@for (stage of stages ...)` in `deals-page.html` | -| nestng-crm r3 | 55/56 (reproduced 3 of 3 runs) | `backend tests: npm run test:e2e passes`: 41 of 42 pass | - -* The board is present in all three (a column per stage over the five stages, read in the sources), so the static failure was the checker artifact, not a model defect. -* r3: the failing test is the agent's OWN `deals.e2e-spec.ts:176` ("searches deals by title ... combines with stage"): it expects one deal for `?stage=won&q=software`, but its own fixture creates two won deals with "software" in the title ("Alpha software" and "Beta software"), so the API correctly returns two. Deterministic (3 of 3 reruns), a wrong assertion written by the model, not environment noise, and not a defect of the service. It still fails the acceptance rule "the agent's tests pass". The baselines have 0 such cases in 9 sessions; 1 in 3 with tail skip is a small-n signal, not proof (an own-test slip of this kind can occur without tail skip, and greedy sessions are not reproducible). -* Gate re-assessed: rounds growth below the speed gain (yes, +1.9 % / +1.7 % against +12 %); game playable (ttt 3/3, 14/14); CRM 56/56: **2 of 3** (r3 55/56 through its own wrong test). Not passed in full; with n = 3 per arm I do not call it a quality regression either. Tail skip stays experimental and off. To settle it, run 3 more repetitions of `nestng-crm` with the fixed `accept.py` (and the first three re-run under it); needs the owner's go on the cost (about 8 GPU-min each). - -### Lever 7, owner gate on n = 7 CRM and 5 ttt (`spd-g1..3` re-accepted + `spd-g4..g9`, fixed `accept.py` b2e6c690, 2026-11-08): NOT passed on rounds - -Real Codex CLI 0.163.0, release package `17e372944279` with `LELEKA_ROUTE_TAIL_SKIP=7`, `..._MAX_CACHED=100`. Baseline = shipped LEL of `codex-compare/runs/main` (n = 3, same fixed accept.py). New cells in `/data/leleka-e2e/spd-gap/runs/codex-tail2` (job copy `tools/cmp_codex_job_fixed.sh`: `TASKS_ROOT=reaccept-1/tasks`, manifest-checked). - -| nestng-crm | tail skip n = 7 | shipped LEL n = 3 | difference | -| --- | --- | --- | --- | -| accepted (fixed accept.py) | 6 of 7 (r3: own e2e test wrong) | 3 of 3 | | -| rounds (requests), each | 75, 43, 47, 98, 94, 87, 52 | 47, 62, 53 | | -| rounds mean +- sd | 70.9 +- 23.3 | 54.0 +- 7.5 | **+31 %** (Welch t = 1.7, df 7.9: not significant) | -| wall s mean +- sd | 539.0 +- 118.5 | 488.4 +- 59.4 | **+10 %** (t = 0.9) | -| decode tok/s | 179.4 +- 5.1 | 163.1 +- 1.3 | **+10.0 %** (t = 7.8) | - -Against the pooled nine shipped baselines of the three arms (LEL, VAN, VANL: rounds 62.4 +- 15.7, wall 461 s) the tail-skip rounds are +13.5 % and wall +16.8 %. The four new cells are the long ones (98, 94, 87 requests at 1.9-2.2 requests per tool call, against about 1.0 before); the early sessions (r1-r3) were short, so the order of runs, not only the mode, differs between the groups. - -`ttt` (static 14/14; the six-click browser check is not available on the server or in this work folder, so it is NOT done): 5 of 5 accepted, rounds 17.6 against 17.7 (-0.4 %), wall 161.5 s against 177.9 s, decode 178.5 against 164.3 tok/s (+8.6 %). - -Owner criterion "rounds growth must not exceed the speed gain in %": the point estimate fails on CRM (+31 % rounds, and wall time +10 % longer, against +10 % decode speed); the difference is within the noise of n = 3 against n = 7 (t = 1.7), so it is neither proven nor refuted. Game playable: statically yes, in a browser unchecked. CRM works: 6 of 7. Verdict: **not passed**, tail skip stays experimental and off. - -Teacher-forced logit check (`spd-l7id`, `rt-c10`, 5 requests of `night5-long-256k`, 240 forced tokens each): the A/A floor in the reference process is bit-identical (2057 of 2057 rows). Tail skip against the reference: 1687 common top-16 rows, 0 identical, **60 argmax flips = 3.6 %** (the Original's envelope in `q_tail_gate` is flips <= 2.8 %), and the draft traces differ in every line (1036 compared, 0 identical). `q_tail_gate` itself prints PASS only for the in-process arm pair (A/A), not for this cross-process comparison. - -### Lever 6 (adaptive window floor), result: no gain (`spd-l6a`, `spd-l6b`, 10 pairs, 2026-11-08) - -D (adaptive window with `spec_min_p` floor 0.5, `leleka reconfigure`) against shipped A (floor 0), same replay, 27 requests per block after warm-up: decode tok/s A 185.77, D 185.25, **-0.28 % (95 % CI -1.13..+0.57 %)**; end-to-end -0.13 % (-0.96..+0.70 %); tokens/round +2.72 % (-0.74..+6.19 %); ms/round 19.48 against 20.07 (+3.0 %, CI +0.18..+5.86 %). The extra tokens per round cost as much in round time. No default change; the shipped adaptive policy stays. - -### Lever 3 (fewer misses), plan (2026-11-08) - -`docs/experiments/vram-footprint-5090.md` already holds the footprint work (dense slab default on; decode reserve 130 MiB and the prompt-embedding alias are opt-in, about +250 slots together, against vanilla's 12,575; our 12,192 now). Free VRAM at idle after load is about 1,040 MiB. The paired test queued here (`spd-l3a`, `spd-l3b`, variant `G` = `leleka up --gpu-budget-gib 31`, +0.43 GiB, about +190 slots, free VRAM after load about 600 MiB against vanilla's 389) measures the upper bound of what ~+200 slots are worth without any code change. If the gain is under 1 % the slot route is closed except for the larger prompt-buffer carve-out (+250..450 slots, needs code). - -### Where the real-session gap goes, per request (existing cells only, no new run; `scripts/e2e/codex/speed/session_split.py`, 2026-11-08) - -Source: `codex-compare/runs/main/{LEL,VANL,VAN}/{nestng-crm,ttt}-r1..3`. Proxy time per request (`proxy/rounds.jsonl`, `t_end - t_start`) joined by order with the engine's own prefill and decode milliseconds (the cell's `engine_log_start_offset` slice of the stack `engine.log`; join checked: request counts equal in all 6 cells per arm, 3 per task). Proxy "tok/s" = output tokens / proxy time = the `decode tok/s` of `compare.md`. - -| nestng-crm (3 cells per arm) | LEL | VANL | VAN | LEL - VANL | -| --- | ---: | ---: | ---: | ---: | -| requests | 162 | 186 | 214 | | -| output tokens per request | 1,351 | 1,217 | 1,114 | | -| uncached prompt tokens per request | 583 | 609 | 441 | | -| proxy time per request, ms | 8,297 | 6,055 | 5,064 | | -| of it engine prefill, ms | 726 | 431 | 354 | **+295** | -| of it engine decode, ms | 7,549 | 5,592 | 4,674 | | -| of it rest (gateway, tokenizer, HTTP, SSE, prefix-cache work), ms | 22 | 32 | 36 | **-10** | -| pause between requests (tool run + Codex), ms | 713 | 1,405 | 1,013 | trajectory, not engine | -| ms per output token, proxy | 6.14 | 4.97 | 4.54 | **+1.17** | -| ... prefill / decode / rest | 0.54 / 5.59 / 0.02 | 0.35 / 4.59 / 0.03 | 0.32 / 4.19 / 0.03 | **+0.19 / +1.00 / -0.01** | -| proxy tok/s (the 163 vs 201 of `compare.md`) | 162.8 | 201.0 | 220.1 | -19.0 % | -| engine decode tok/s | 178.9 | 217.7 | 238.4 | -17.8 % | - -At LEL's own 1,351 output tokens per request the 1.17 ms/token gap is **about 1,580 ms per request: decode 1,350 ms (85 %), prefill 257 ms (16 %), gateway and the rest -13 ms (0 %)**. `ttt` is the same: 6.10 against 4.96 ms/token (+1.14 = prefill +0.13, decode +1.01, rest 0). The wall-clock of a cell also contains the pauses (LEL 38 s, VANL 86 s per CRM cell: the vanilla sessions ran heavier tool commands), which differ with the trajectory and are not the engine. - -So the 19 % (proxy) against the replay's 11-12 % (`dec tok/s` 183.8 against 208.3) is not a gateway, proxy, prefix-cache, tokenizer or serialization cost: the "rest" is 22 ms per request against 32 for vanilla. Two things make the gap look smaller in the replay: it counts decode only (the real-session proxy number adds the prefill gap, 0.19 of 1.17 ms/token, about 3 points), and the replay's two arms differ from the sessions by +-4 % each (LEL 186 in the replay against 178.9 in the sessions; VANL 208 against 217.7), i.e. a different text and a vanilla that ran at a different uptime. The decode gap itself is flat over the context: engine decode tok/s by prompt size (LEL / VANL): 0-20k 178.4 / 218.3 (-18.3 %), 20-40k 183.3 / 221.1 (-17.1 %), 40-70k 177.8 / 214.1 (-17.0 %), 70-100k 173.5 / 215.0 (-19.3 %), > 100k 155.8 / 206.7 (-24.6 %, 9 requests). - -Where the decode time goes (ms per round, phase 1): LEL 18.1-18.8, VANL 13.5-13.9: **+4.7 ms**. Our adaptive window pays +3.1 ms for +0.65 tokens per round (net +2.8 %, kept); the step-profile excess is `waitCPU` + `PCIe group` (+2.5 ms in miss-heavy windows, +0.6 in quiet ones, tied to the hit rate 90.2 % against 92.8 %), draft + commit outside the window +1.3 ms (full 248,320-row draft head against vanilla's 106,299-token subset), and +1.3 ms in quiet windows (12.0 against 10.7: kernels; the sm_120 sets of lever 1 took a part of it, +1.85 %). - -Prefill: +295 ms per request at equal uncached tokens (726 against 431); by size: < 64 tokens 430 against 268 ms, 64-256 530 against 292, >= 4096 4,405 against 2,184 (4 % of requests, 19 % of the prefill time). The known cause is old code work, not a switch: `docs/prefill-throughput.md` "Remaining gap" (8192-token chunks 2,830-2,930 tok/s against the Original's 5,400-5,900; tails of <= 64 tokens read through verify windows in the Original). - -What is available without lossy (E, none measured as an A/B yet beyond lever 1): lever 1 done (+1.85 % decode); lever 3 upper bound queued (`spd-l3a/b`: +190 slots); lever 4 (draft + commit, up to -1.3 ms of 18 = up to +7 % decode if all of it went, but the fused-commit graph measured neutral and the draft-vocabulary route is prompt-dependent and not bitwise); lever 5 (prefill: up to 16 % of the gap, code-level, placement-class numerics for the window tails). Nothing identified so far closes the 18 % without the lossy tail skip (+12.6 % decode, gate not passed). - -## Levers 4 and 5 after the base moved to hexagonal-finish (b686f6ab7), 2026-11-08 - -### Lever 4, draft head 248k against 106k: the premise was wrong for the shipped product - -* What the Original does: a **static** subset file, not a prompt-dependent or frequency-ranked choice at run time. `rt/draft_vocab.bin` (106,299 int32 ids, 425,196 bytes, sha256 `b1e1d3a7…cb91`) is copied by setup from `data/draft_vocab*.bin`, built offline by `tools/draft_vocab.py` (base list + whole scripts `--add han,kana,hangul,cjk_punct,cyrillic` or a language corpus by token frequency `--corpus --coverage 0.99`). The engine computes draft logits over those rows only (`MtpDrafter::bind`, `src/core/mtp.cpp`). -* What the product does: `leleka-deploy` always passes `--mtp-rt-dir ` (`crates/deploy/src/config/engine_launch.rs`), so the engine drafts over the same file. Checked on the running 5090 engine: argv has `--mtp-rt-dir /data/leleka-e2e/codex-compare/ours-assets/data/mtp-rt`, and that directory's `draft_vocab.bin` has sha256 `b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91`, the Original's default. The "248,320-row head" in section 2 and in the ledger (section 5) described the model-free smokes and the daemon without `--mtp-rt-dir`, **not** the release package that the A/B and the Codex cells ran. There is no subset sub-lever to take: ours already equals vanilla there. (The opt-in `LELEKA_DRAFT_VOCAB=en|cyrillic|fr` exists, is not bitwise and is prompt-dependent: unchanged, see `2026-10-30-draft-vocab-en.md`.) -* What is left of "draft + commit +1.3 ms/round": `draft.finish` 1.7 against vanilla's `draft` 1.17, `apply_pending` 0.6 and commit 0.4. The ledger's own split of the chain step with the subset bound is 0.466 ms against 0.421 (about 0.2 ms per round over 3.9 chain steps) plus launch calls of 100-200 us against 55-125 us. That is at most about 0.5 ms of 18.5 (2.7 %), spread over many small items; no single switch, nothing started. - -### Lever 5, prefill: the fixed cost per request, from the product's own profile lines (`runs/main/P/engine.log`, 30 replayed requests, `LELEKA_SERVE_PROFILE=1`) - -Per request, ms: `prefill.read` (the batched read of the uncached tokens), `prefill.refill` (the lent expert slots refilled after the read: 2,226 copy spans, constant), `decode.assemble` (host assembly and re-recording the window graphs: capture 54-62, instantiate 27-30, charged to the decode time). - -| uncached tokens | prefill.read | prefill.refill | decode.assemble | -| ---: | ---: | ---: | ---: | -| 239 | 485 | 139 | 109 | -| 266 | 486 | 136 | 106 | -| 536 | 582 | 140 | 104 | -| 1223 | 668 | 140 | 105 | -| 2453 | 1013 | 140 | 101 | -| 5440 | 1229 | 136 | 108 | - -A least-squares line through the 29 post-warm-up requests gives 581 ms plus 0.134 ms per token for the read; the smallest tails (239-266 tokens) read in 485 ms, where vanilla's whole prefill for the same size class is 292 ms. Fixed per request: about 490 (read of a small tail) + 139 (refill) + 105 (assemble, inside decode) = about 730 ms, 9 % of a 8.3 s request. Two of the three have a known non-lossy handle: - -* `prefill.refill` (139 ms): `LELEKA_REFILL_DEFER=on` (opt-in, never measured: "no GPU result yet (job 904)") queues the same copies inside the decode assembly, after its uploads and before the graph capture. Same bytes, other time; `spd-l5a/b` run it as variant R against A, 10 pairs. -* the read's ~490 ms fixed part: no per-stage split of a small tail exists for the 5090 (`docs/prefill-throughput.md` only has 8192-token chunks and an 80-token laptop run: GDN 1.3 s). `spd-l5q` is a single profiled replay (variant Q: `LELEKA_BRINGUP_TRACE=1`, `LELEKA_PREFILL_PROFILE_SYNC=1`) to get `PREFILL-PROFILE` lines per chunk; its sync drains make it a diagnosis run, never an A/B arm. - -### Lever 3, first attempt (variant G, `--gpu-budget-gib 31`): invalid, the arm opened the same cache - -`ab-l3`, 10 pairs, G against A: decode +0.58 % (CI -0.15..+1.31 %), end-to-end +0.07 %, tokens/round +1.71 %, ms/round +1.10 %, VRAM share 90.33 -> 90.28 %. **Both arms logged `expert cache 12192 slots`**: the cache is sized against `min(card free, context budget - allocated)` (`usable_room`, `original_cache_startup.rs`); on the 32 GiB card the card binds, so a larger declared budget adds no slot (the engine saw +177 MiB available for the prefix cache only). The result is a null experiment, not evidence about slots. - -Second attempt (`ab-l3h`, jobs `spd-l3c/d`): variant H = `LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130` (opt-in of `vram-footprint-5090.md`, bitwise: it moves only the cache size) and `LELEKA_ORIGINAL_SERVE_VRAM_RESERVE_MIB=500` (from 700): 370 MiB less reserve = about +190 slots, placement class, an upper bound of what ~+200 slots are worth. The slot count has to be read from the H log before the pairs are used. - -### Lever 5 first A/B (R = `LELEKA_REFILL_DEFER=on`) and lever 3 H: both invalid, the job script leaked their variables - -`ab-l5` (10 pairs): decode -0.65 % (CI -1.60..+0.30 %), end-to-end -0.26 % (-1.52..+0.99 %), `pf_ms` per request 866 -> 870 (mean paired difference +6.9 ms, sd 17.6): **no change in the prefill time at all**. Cause found afterwards: `spd_ab_job.sh` unset a fixed list of variables between blocks and the list did not contain `LELEKA_REFILL_DEFER`, so every A block after the first R block ran with the deferral on (the pair order `A R R A A R R A` makes half of the A blocks contaminated). The same hole applied to the lever 3 variable pair of H (`DECODE_RESERVE_MIB`, `VRAM_RESERVE_MIB`) and to Q. Levers 1, 3-G, 6 and 7 were not affected (their variables, `FLOOR` and `UPX` were reset per block). The script now unsets all of them (commit of this section); the contaminated outputs are kept as `runs/ab-l5-contaminated` and `runs/ab-l3h-contaminated` and are not evidence. `spd-l3e/f` (H against A) and `spd-l5c/d` (R against A) rerun the pairs into `runs/ab-l3v2` and `runs/ab-l5v2`. - -### Lever 5, where a small tail's prefill goes (`prof-l5/Q.1`, `PREFILL-PROFILE` per chunk, `PREFILL_PROFILE_SYNC=1`, 31 chunks; ms) - -| tokens in chunk | total | moe | moe.ring | gdn | qsa | input | -| ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| 238 | 492 | 374 | 355 | 52 | 46 | 3 | -| 278 | 558 | 424 | 404 | 66 | 42 | 8 | -| 541 | 696 | 546 | 522 | 74 | 46 | 7 | -| 1,242 | 738 | 516 | 475 | 108 | 56 | 18 | -| 1,416 | 861 | 601 | 565 | 120 | 83 | 14 | - -For a tail under about 1,500 tokens **72-80 % of the chunk is `moe.ring`**: the per-layer expert copy ring (48 layers, about 7.4 ms per layer even for 238 tokens, 355 ms in all). It barely grows with the tokens (238 -> 1,416 tokens: +210 ms), which is the fixed cost found in the product's profile lines (about 490 ms of read). GDN, QSA and the input stage together are under 120 ms. The prompt stream (`STRATA_PREFILL_STREAM_MIN`, 4096 rows) is off for these chunks. Whether the ring is bandwidth-bound (bytes of the non-resident routed experts at 36-47 GB/s) or latency-bound (48 synchronous per-layer round trips) is not known from the existing counters: `PREFILL-COPY` is only printed for streamed chunks. Code proposal (needs the orchestrator's word): see the report of 2026-11-08. - -### Graph re-recording per request (`decode.assemble`, 2026-11-08): what it would take - -Per request (product profile lines, 30 replayed requests): `decode.assemble` 98-109 ms, of which `assemble.record_all` 83 ms (capture 54-62, instantiate 27-30; nine graphs: windows T = 1..8 and the commit graph, about 6 ms capture + 3 ms instantiate each); `assemble.prepare` 12, `assemble.verifier_new` 2, `assemble.aggregates` 0.75. The decode phase uses every width up to 8 in a long request (`T_hist` of a 2,444-round request: 187/681/635/523/235/85/56/42 for T = 1..8), so recording only the widths used saves little. - -Why the graphs are not kept: a recorded graph holds device pointers, and four things behind them are made per request in `AssembleInputs::assemble` (`original_serve_verifier.rs`): the canonical GDN image (`original_verify_canonical_gdn(states, histories)` allocates and seeds from the session's priors), the verifier bank and its GDN journal (`OriginalVerifier::new`, `bank().gdn_journal`), the per-width head/embedding row views and window resources, and the QSA journal that takes the twelve resident index and mapped K/V owners **by value** from the prompt executor (`take_qsa_owners`) and gives them back in `disassemble`. Keeping the verifier between requests therefore needs (1) a persistent, re-seedable canonical GDN image and bank (seed = upload, no allocation), (2) the QSA owners staying with the journal while the prompt path appends to the same buffers, (3) the `'a` borrows of `DecodeResources` (dense and MoE weight caches) to outlive a request, which is a self-referential shape in the present `OriginalServeStack`, and (4) invalidation when any pointer changes (prefix-cache switch, window-cap fallback, tier reconfigure). Expected gain at best -60..-80 ms per request of about 8,300 (under 1 % end to end); it is a cross-crate ownership change (`cuda-driver` verifier/bank and `engine-qwen35-cuda` stack), not a switch. - -### Decode miss leg, draft + commit, quiet windows: what the P profile lines say (2026-11-08, no new GPU run) - -Per round and per group (48 groups per round), from `runs/main/P/engine.log` (30 profile lines): - -| window kind | rounds' T | window.verifier | doorbell wait (GPU mixers) | pool.cpu (CPU leg on the critical path) | cpu.compute per group | draft.finish | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | -| miss-heavy (lines 2, 7, 26) | 4.5-7.0 | 23.3-26.0 ms | 8.8-10.4 ms | 12.0-14.1 ms | 233-272 us | 1.5-2.6 ms | -| quiet (lines 16, 17) | 3.0-3.2 | 12.1-12.2 ms | 8.7-8.9 ms | 2.5-2.6 ms | 45-47 us | 0.93-0.97 ms | - -* The CPU leg is serial with the GPU mixers of the next layer (the layer output needs every expert): window time = doorbell wait + pool time + 0.5-0.7 ms sync. It is DRAM-bound (about 39 us per 2 MB expert = 52 GB/s, equal to vanilla's 44 us), so the miss leg is proportional to the number of CPU-computed experts; nothing in the host path adds to it: the fixed host work around a group (split 3, spans 2, publish plan 6, open + zero 5 us) is about 16 us x 48 = 0.8 ms per round and is already small. -* `draft.finish` follows the window width (0.93 ms at T 3.0, 2.5 ms at T 6.2): the chain has more steps in a wider window. It is not a per-round defect; the "+1.3 ms" is the width of the adaptive window, the same cost as the "+3.1 ms for +0.65 tokens" of the window price. -* Same speculation, ours against vanilla (B 178.8 against VANL 208.3 tok/s at 2.90 against 2.95 tokens/round): +2.0 ms per round (+14 %). The largest identified part is the miss count: hit rate 90.8 % against 92.8 % (28 % more misses, about +1.4 ms of CPU leg). Per request, vanilla's hit rate is higher in nearly every request, by up to 7 points in short ones (request 12: 93.2 against 86.4 at 276 tokens; request 26: 87.6 against 78.4), i.e. mostly at the start of a request. -* The tier policy is the same as the Original's (decay 0.7, margin 1.5, min count 2.0, `adapt_every` 4, 96 swaps, candidates and victims paired per layer; counts survive across requests; the lent slots are refilled with their own previous experts, so the prefill borrow does not lose learned placement). The differences left are +3 % slots (12,575 against 12,192), the window width and whatever the first rounds of a request see. `spd-w1..5` (tier knobs) and `spd-l3e/f` (slots) measure how much each of them moves the hit rate. - -### Real-session weighting of the hit-rate gap and the gap by context (owner rule 2026-11-08: weigh by time in the real session, ignore short-request-only gains) - -Tools: `scripts/e2e/codex/speed/session_hit.py` and `session_ctx_gap.py` (run on the server with `python3 -I`; read the `engine-slice.log` of the `runs/main/{LEL,VANL}` cells, three repetitions each). - -* **VRAM hit share weighted by decode time**: nestng-crm LEL 91.38 % against VANL 92.41 % (-1.03 points), ttt 92.68 % against 93.38 % (-0.70). By output length of the request (share of decode time in brackets), nestng-crm LEL/VANL: < 600 tokens (10 %/12 %) 86.9/89.9, 600-2000 (33 %/34 %) 90.5/91.6, >= 2000 (58 %/54 %) 92.7/93.5 (-0.9). The 3-8 point gaps of the replay are in the short requests, which carry 10 % of the decode time; in the long ones the gap is about 0.9 point. -* **Price of a point**: lever 7 raised the VRAM share by 3.5 points and took 2.0 ms off a round (19.3 -> 17.3) at equal tokens per round, so at most 0.57 ms per round per point (that figure also contains the skipped entries). One point of hit share is therefore at most 0.57 / 3.55 = 0.16 ms per output token: 2.6 % of nestng-crm's 6.14 ms request time per token (1.0 point), 1.8 % of ttt's (0.7 point). That is the ceiling for everything done about the hit rate together (tie order, tier knobs, slots). -* **Gap by context** (decode tok/s LEL against VANL, same cells): nestng-crm 0-30k -18.2 %, 30-60k -16.6 %, 60-100k -18.7 %, 100-160k -24.6 % (3 % of the time); ttt 0-30k -16.8 %, 30-60k -20.0 %. The sessions never pass 160k; the gap is flat in context, so there is no long-context hot spot in these two tasks (a 245k session is not in the cells). - -### Kernel level: what vanilla has on by default and the release does not (2026-11-08; the measured per-kernel table is queued) - -Vanilla `sm120_series.hpp` turns five bitwise switches on for a 12.0 card (`SIDE_MIXER=2`, `ATTN_DAILY`, `GR_UP75`, `GR_DOWN_TG=1`, `GU_SWIGLU`) and its tables add the interleaved MMVQ (`MMVQ_IL`, 2-4 columns, 5-8 on sm_120). Upstream's own number for the set is 13.70 -> 12.23 ms per 4-token round on an RTX PRO 5000 (other hardware). Status in the release: `ATTN_DAILY` and `GU_SWIGLU` on since lever 1 (+1.85 % decode paired, bitwise); `SIDE_MIXER` exists (`LELEKA_SM120_SIDE_MIXER`), off, measured no gain (KS variants 209.4 against 209.1 tok/s); `GR_DOWN_TG` we have and better (`chain_gr_down_t2w8_nb4` 9.7 us against 18.4 us); `GR_UP75` partial; the rest below is missing. The remaining estimates are those of `docs/upstream-port-plan.md` rows 2.1/2.2 (estimates from our microseconds, not measurements), ms per round of about 18: - -| item | estimate ms/round | effort | numerics | -| --- | ---: | --- | --- | -| `COMMIT_BATCH` + state-only GDN commit (commit graph 158 kernels, 0.463 ms) | 0.25-0.35 | M, seal | bitwise (`gdn_parity`) | -| `GU_SWIGLU` sub16 expert kernels beyond the fused launch (`window_moe_gu_*` are warp-per-row) | 0.20-0.35 | L, seal | bitwise (claimed) | -| `MMVQ_IL` interleaved MMVQ 2-4 and 5-8 columns (we run the old `head_n*_t*`; dense 2.25 ms against a floor of ~2.0) | 0.10-0.40 | L, seal | bitwise (claimed) | -| `HEAD_MIX_MULTI` (one multi-token head mix) | 0.06-0.10 | S | bitwise | -| `GR_UP75` delta, batched K/V and indexer append, float4 combine, fused norm+rope | 0.05-0.10 each | S-M, seal | bitwise | - -Their sum is 1.0-1.4 ms per round, i.e. the "+1.3 ms in quiet windows" of the step profile; none is a single big defect. `spd-cuo` (ours, shipped package with the lever 1 switches) and `spd-cuv` (vanilla VANL) take one 15 s CUPTI window each over request 29 of the replay (67k context, 4,741 output tokens), `decode_rounds.py --tsv` per arm gives the measured per-kernel table. - -## Lever 5, variant R (`LELEKA_REFILL_DEFER=on`), clean paired result, 10 blocks (2026-11-08) - -Run `ab-l5v2` (server `/data/leleka-e2e/spd-gap/runs/`), A = release package, R = A + refill deferred into the decode assembly, 27 requests per block after the 3-request warm-up, 10 block pairs, `ab_report.py`: - -| metric | A | R | diff | 95 % CI | -|---|---:|---:|---:|---| -| decode tok/s | 180.19 | 178.53 | -0.92 % | -1.63..-0.21 % | -| end-to-end tok/s | 162.93 | 163.84 | +0.56 % | -0.15..+1.27 % | -| ms/round | 19.95 | 20.31 | +1.80 % | -1.26..+4.87 % | -| tokens/round | 3.59 | 3.63 | +0.87 % | -2.69..+4.43 % | - -Reading: the deferred refill moves prefill time into decode (decode slower by about 0.9 %, significant), the end-to-end gain is +0.56 % and not significant. Not a lever by itself; stays an opt-in, off by default. `out_sha` identity is not usable in live replay (A/A floor about 10/30), so no identity claim from this run. - -## Lever 3, variant H (larger VRAM reserves → slot count), clean paired result, 10 blocks (2026-11-09) - -Run `ab-l3v2`, A = release package, H = A with the reserve settings of variant H, 27 requests per block after warm-up, 10 block pairs, `ab_report.py`: - -| metric | A | H | diff | 95 % CI | -|---|---:|---:|---:|---| -| decode tok/s | 181.00 | 181.91 | +0.51 % | -0.19..+1.20 % | -| end-to-end tok/s | 163.07 | 164.79 | +1.06 % | -0.38..+2.50 % | -| ms/round | 20.23 | 19.79 | -2.19 % | -3.55..-0.83 % | -| tokens/round | 3.66 | 3.60 | -1.69 % | -3.33..-0.05 % | -| VRAM % of routed | 90.31 | 90.75 | +0.44 pp | +0.19..+0.79 pp | - -Reading: the extra resident share (+0.44 pp) makes the round shorter (significant), but tokens per round fall by a similar amount (the tier placement differs, accept changes), so decode and end-to-end gains are not significant. Placement-class change: would need a quality gate against the control placement before any default. Not a lever on this evidence. - -## Kernel level: one CUPTI window of request 29 (67k context), LEL against VANL (2026-11-09) - -Runs `cupti/CL.1` (release package + lever 1 switches) and `cupti/VANL` (vanilla 0.2.6, tail skip and CPU prefill share off, no engine-side profile), 15 s over the same replay request (`/data/leleka-e2e/spd-gap/runs/cupti/*/win-r29.lct`); analysis `decode_rounds.py --tsv`, `scripts/e2e/codex/speed/{cupti_verify_graph,cupti_stream_overlap,kernel_roles}.py`. One window per arm, greedy trajectories differ a little: shapes, not CIs. - -Round (graph start to start): LEL 17.86 ms, VANL 15.89 ms (-1.98). Verify graph GPU span 13.56 against 11.75 (-1.81); after the verify graph to the next start (draft, commit, host, CPU-leg join) 4.30 against 4.14 (-0.16). Kernels per verify graph 2061 against 2098; idle inside the graph 0.21 against 0.12 ms (launch gaps are negligible). Outside the verify graph: 630 against 147 kernels per round, 5.38 against 4.47 graph executions, 207 against 20 API calls, 121 against 12 copies (71.5 against 23.6 MB), 27.8 against 89 syncs (2.47 against 0.93 ms) per round; the tail they feed is only 0.16 ms longer. - -Structure: in LEL the verify graph is on ONE stream (714; kernel sum 13.35 ms = span 13.56 ms, zero overlap). In VANL it forks over 11 streams (kernel sum 13.73 ms, span 11.75 ms): wall time with two or more streams active is 2.03 ms per graph (1.52 expert/shared-expert branches against the main stream, 0.51 the QSA mixer branch: `native_mmvq_il` + `norm_rope` on side streams). That 2.03 ms is the verify gap (1.81 ms). - -Matched kernels are not slower in LEL: attention `leleka_qsa_decode_chunk_daily` 18.3 us against `attn_chunk_kernel_pre75` 17.1, topk 17.3 against 18.0, scores 14.2 against 17.1; draft chain `chain_gr_down` 11.1 against `gr_down_staged` 11.5, `chain_gr_split` 3.1 against 2.9; GDN equal; dense (`head_n*`, mmvf) 3.9 against 4.6 ms (LEL faster); routed experts at equal entry count: `window_moe_down_20` with 40 entries 13.6 us against `native_down_multi<20>` 17.4 us, `sm120_moe_gu_swiglu_22` with 50 entries 12.3 us against vanilla 26 us (with 40). Mean-per-kernel comparisons are distorted by the entry mix (vanilla has many empty 0.7 us launches). CPU/PCIe leg handling in total (flag waits + doorbell + mapped copies + `fetch_blobs`) 3.25 ms in LEL against 3.08 ms in VANL. - -Conclusion: no single kernel explains the gap; the verify graph has no parallel branches. Candidate steps in order: (1) measure the existing GDN `SIDE_MIXER` at this context (CUPTI window overlap + paired A/B), then port the QSA part (indexer/queries chain, about 0.5 ms of overlap in VANL), then the routed/shared-expert branch (about 1.5 ms of overlap); bitwise (only graph edges change). (2) the draft/commit tail: 0.16 ms. - -### Lever 7 gate on the owner-default release 83bdd85bb482 (2026-11-13, plan stage 6f), n = 3 CRM + 3 ttt - -Jobs `e2e-codex-ttt-and-crm-release-83bdd85bb482-route-tail-skip-7-experimental-lel-r{1,2,3}` and `-report` (stubs `scripts/e2e/codex/prefill/e2e-release/`, evidence `/data/leleka-e2e/prefill-latency/runs/e2e-codex-ttt-and-crm-release-83bdd85bb482-route-tail-skip-7-experimental/`). Tarball sha256 3837a32b..., PROVENANCE git_commit 83bdd85bb482, `LELEKA_ROUTE_TAIL_SKIP=7`, `..._MAX_CACHED=100` exported in the job shell (the profile key allow-list has no `LELEKA_ROUTE_` prefix); the engine log of all three blocks has `EXPERIMENTAL route tail skip is ON (... 49.9% of the experts in VRAM)`. Baseline = the stored owner-default series of the same release (CRM rounds 62/43/74, decode 184.2, wall 539.1; ttt rounds 27/24/13, decode 181.7, wall 170.5), vanilla cells not re-run (VANL 202.1 / 462 s, VAN 221.4 / 434 s; ttt VANL 202, VAN 226). - -| cell set | tail skip 7 | owner default | change | -| --- | --- | --- | --- | -| CRM decode tok/s | 211.1 / 212.4 / 209.5 = 211.0 | 184.2 | +14.5 % (VAN 221.4, VANL 202.1) | -| CRM rounds | 56 / 48 / 55 = 53.0 | 59.7 | -11 % | -| CRM wall s | 499 / 493 / 385 = 458.8 | 539.1 | -15 % | -| CRM tool calls | 56 / 51 / 64 | 66 / 47 / 79 | | -| CRM accepted, RELAXED (gate) | 56/56, 56/56, 55/56 (r3: only the literal `/api/` check) | 55/56 (same check), 56/56, 56/56 | 2 of 3 in both | -| CRM accepted, STRICT | 56/56, 55/56, 54/56 | 54/56, 55/56, 55/56 | 1 of 3 vs 0 of 3 | -| ttt decode tok/s | 196.4 / 203.9 / 207.4 = 202.6 | 181.7 | +11.5 % (VAN 226, VANL 202) | -| ttt rounds | 49 / 16 / 24 = 29.7 | 21.3 | +39 % (median 24 vs 24) | -| ttt wall s | 327 / 127 / 203 = 218.9 | 170.5 | +28 % | -| ttt checks | 14/14 x 3 (static; no browser) | 14/14 x 3 | | - -Owner criterion (rounds growth <= decode gain in %): CRM passes (-11 % against +14.5 %); ttt fails on the point estimate (+39 % against +11.5 %), driven by one 49-round session (r1: the agent wrote its own test harness and fixed two bugs; the median equals the baseline). n = 3 per arm with a CV of 20-30 % cannot separate these; the earlier n = 7 series on release 17e372944279 had CRM rounds +31 % (not significant). Both acceptance versions were applied to every cell (`cmp_accept_both.py`, relaxed `reaccept-1` is the gate): CRM 56/56 is NOT reached in 3 of 3 under either, but neither is the stored owner default without tail skip (2 of 3 relaxed). The logit gate stays failed (60 argmax flips = 3.6 % against the 2.8 % envelope, `spd-l7id`). Verdict: the speed gain is real and large (CRM 184 -> 211 tok/s, 4.7 % below VAN), the quality gate is not shown to pass; not enabled by default, decision with the owner (more repetitions or an explicit opt-in flag). - -### Lever 7 as the 5090 default: confirmation on package 945fc44f32fb (2026-11-13, plan stage 6f, ledger H9) - -Owner decision 2026-11-13: the lossy route tail skip (`LELEKA_ROUTE_TAIL_SKIP=7`, `..._MAX_CACHED=100`) is ON in the three 5090 profiles (the two exact keys are on the profile allow-list; `docs/deploy.md` section 4). Package `leleka-0.1.0-945fc44f32fb-linux-x86_64.tar.xz` (sha256 5f5479151620b9b5cb3f5d86a32e228858544411bfad30f48ff24853e9503a67; built in WSL from `git archive` of main 945fc44f3 with `LELEKA_GIT_COMMIT` set, PROVENANCE git_commit 945fc44f32fb9f58..., clean; contains the CPU expert kernel 0c48c823e, the tail skip profile keys and the owner-default PCIe 0.65; on the server `release-tail-skip-default/`). Jobs `e2e-codex-ttt-and-crm-release-945fc44f32fb-owner-default-tail-skip-lel-r{1,2,3}` and `-report` (stubs `scripts/e2e/codex/prefill/e2e-release/`, evidence `/data/leleka-e2e/prefill-latency/runs/e2e-codex-ttt-and-crm-release-945fc44f32fb-owner-default-tail-skip/`). The job unsets every route/placement variable of the shell: nothing is exported. Proof in all three blocks: engine log `EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP=7, 49.9% of the experts in VRAM)`, the `engine environment` line of `leleka up` lists `LELEKA_ROUTE_TAIL_SKIP=7` and `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED=100`, meta config `expert_per_layer=0 pcie_frac=0.65`, 12,254 expert slots (global fill). (The watcher of repetition 1 raised a false alarm, `watcher-false-alarm-r1-missing-argument.txt`: `tsd_proof_lines` was called without the repetition argument; fixed for r2 and r3, the proof of r1 was written from the same logs by hand.) - -| cell set | default profile (tail skip from the profile) | gate series (83bdd85bb482, variables exported) | owner default before (83bdd85bb482) | VANL | VAN | -| --- | --- | --- | --- | --- | --- | -| CRM decode tok/s | 216.7 / 218.1 / 207.7 = 214.2 | 211.0 | 184.2 | 202.1 | 221.4 | -| CRM wall s | 394.6 / 428.1 / 397.6 = 406.8 | 458.8 | 539.1 | 461.8 | 434.0 | -| CRM rounds | 48 / 52 / 59 = 53.0 | 53.0 | 59.7 | 62.0 | 71.3 | -| CRM accepted, RELAXED | 56/56, 56/56, 56/56 | 56, 56, 55 | 55, 56, 56 | 3/3 | 3/3 | -| CRM accepted, STRICT | 55/56, 55/56, 55/56 | 56, 55, 54 | 54, 55, 55 | | | -| ttt decode tok/s | 206.1 / 222.8 / 204.7 = 211.2 | 202.6 | 181.7 | 202.0 | 225.7 | -| ttt rounds | 15 / 18 / 34 = 22.3 | 29.7 | 21.3 | 19.0 | 12.7 | -| ttt wall s | 143.5 / 184.5 / 234.0 = 187.3 | 218.9 | 170.5 | 136.7 | 99.3 | -| ttt checks | 14/14 x3 (both checkers) | 14/14 x3 | 14/14 x3 | 14/14 x3 | 14/14 x3 | - -Reading: against the owner default of the same release the default-on tail skip gives CRM decode +16.3 % and wall -24.5 %, ttt decode +16.2 %; ttt rounds 22.3 against 21.3 (+5 %) and wall +10 % (n = 3, CV 20-45 %: not resolved, the 34-round session of r3 drives both). CRM decode is 3.3 % below VAN and 6.0 % above VANL; CRM wall 407 s is below VAN (434 s) and VANL (462 s). Acceptance: the CRM failures are the same static board check as before (`no file with all five stages and a loop`), 55/56 in every strict cell and none in the relaxed one, so the relaxed gate reads 3 of 3 (gate series 2 of 3, owner default 2 of 3); no tool-call defect, 0 failed rounds. The result is within the earlier gate series; the lossy status and the open logit point (3.6 % flips against the Original's 2.8 %) are unchanged and were accepted by the owner. diff --git a/docs/experiments/codex-lossy-delta.md b/docs/experiments/codex-lossy-delta.md deleted file mode 100644 index c16a0a12..00000000 --- a/docs/experiments/codex-lossy-delta.md +++ /dev/null @@ -1,93 +0,0 @@ -# Codex lossy-vs-lossless delta study (vanilla Strata 0.2.6 and our port, RTX 5090) - -Branch `claude/codex-lossy-delta` (from main `e1bd61f5`). Question of the owner: with the real Codex CLI on realistic tasks, how much worse is the -lossy mode (route tail skip) than the lossless one, for vanilla and for our port. The orchestrator judges the DELTA by re-reading the sessions: -"small" = the task still completes with less than 5 % extra agent rounds (rounds = model requests), "large" = 5 % or more extra rounds, or the -task fails where the lossless variant completes it. This page fixes the design; it contains no result. Numbers go to `runs/codex-lossy-delta/_index/`. - -## 1. Variants (same machine `rnr5090`, RTX 5090, 256k context, same model files, Codex CLI 0.163.0 sha256 `399ff69c...c4215`) - -| id | stack | setting | check before the first cell | -| --- | --- | --- | --- | -| V1 | vanilla Strata 0.2.6 (launcher `~/work/vanilla-strata/control`, engine 0.1.50 `ae49d5da...4776`, `launch --model iq3_s --context 256k --kv int8 --vision off --parallel 1 --tune skip`) | shipped defaults: `STRATA_ROUTE_TAIL_SKIP=7` ON by default, `STRATA_PREFILL_CPU_SHARE=auto` | engine.log has `STRATA_ROUTE_TAIL_SKIP=7 is ON (default)` (block.py stops the block otherwise) | -| V2 | same vanilla | `STRATA_ROUTE_TAIL_SKIP=0 STRATA_PREFILL_CPU_SHARE=0` (both lossy defaults off, recorded in `stack.json`) | no `is ON` line; no `CPU share` line | -| V3 | our port, binaries `bin-main` = main `e1bd61f5` built in WSL (sha256 in `bin-main/COMMIT.txt`), `rtx5090-32g` profile shape (expert slots auto, GPU budget 32,819,404,800, spec-min-p 0, prefix cache auto/reply/8192, chain kernels, prompt-routing seed OFF, MTP draft vocabulary, ranked upstream expert profile `8f59b4aa...`) | `LELEKA_ROUTE_TAIL_SKIP=7` (EXPERIMENTAL, changes the output) | engine log (first decode) has `EXPERIMENTAL route tail skip is ON` | -| V4 | same binaries and shape | skip off (main default) | no such line | - -Vanilla runs untraced (no `STRATA_DECODE_TIMING`), ours with `LELEKA_SERVE_PROFILE=1` only (the per-request `expert tier ... route tail skip` line carries our skip counters). The ours shape is the one of the paired A/B jobs -(`decode/dt/jobs/speedtrain3-ab.sh`, `ours()`), run through the same `run-e2e.sh` as the earlier Codex jobs 943d/945d (copy in `run-e2e/`, state dir `codex-lossy-delta/w`). - -Sampling: Codex sends none. Vanilla would then use the model card's sampling (thinking: T 1.0, top_p 0.95, top_k 20) and ours is greedy. The logging proxy therefore -injects `"temperature": 0` into every `/v1/responses` request for ALL variants (greedy on both; recorded per request in `proxy/rounds.jsonl` as `fwd_sampling`). The proxy also maps the model name Codex sees (`qwen-local`, -identical in every variant, so Codex builds identical requests) to the engine's own id. The adaptive expert tier and the prefix cache are not bit-exact run to run, so greedy does not mean reproducible (measured by the pilot). - -## 2. What is captured, identically for the four stacks - -`scripts/e2e/codex/delta/logproxy.py` sits between Codex and the Responses endpoint of either stack. Per cell it writes `proxy/rounds.jsonl` (one line per HTTP request: timings, sizes, sha256, usage, output item summary) and, gzip-ed, every request body exactly as Codex -sent it, the forwarded body when the proxy changed it, and every response body exactly as received (`rounds/NNNN.{req.json,fwd.json,resp.sse}.gz`). Beside it: Codex's own rollout -(`codex-home/sessions/**/rollout-*.jsonl`), `codex-events.jsonl` (`codex exec --json` with arrival times), `codex.err`, the engine-log slice of the cell (`engine-slice.log`), the final workspace, `acceptance.log`, `cell.json`. The block directory -`V?/_stack-/` holds `inference.log` or `engine.log`, `strata-next.log`, `stack.json` (versions, env, warm-up, skip-state check, uptime, boot id), `mon.csv` (GPU temperature, clocks, power every 10 s), `memsample.txt`. -`delta/index.py` renders every session into `transcript.md` (round by round: new tool outputs, reasoning, calls, messages) and builds `_index/{index.csv,rounds.csv,index.md}`. - -Round = one POST `/responses` (counted by the proxy, retries and failed attempts included; completed and failed ones are listed separately). Codex's own tool-call count is in the index too. - -## 3. Tasks (`scripts/e2e/codex/tasks/`, frozen with `MANIFEST.sha256`, read-only on the server) - -| id | kind | what the agent does | acceptance (`accept.py`, exit 0 = done) | author's round estimate | -| --- | --- | --- | --- | --- | -| ttt | create | Three.js tic-tac-toe in one file (prompt of jobs 943*, unchanged) | STATIC checks on the server (file, relative import of the vendored three, WebGL renderer, raycaster, `#status`, `#restart`, win/draw logic, no network). The six real-click browser checks (`hidden/check_ttt.mjs`) need Node + Playwright, which the server lacks: run later over the stored workspaces and reported separately | 15-60 | -| crm | create | CRM web app, two phases (prompt of jobs 945*, unchanged) | 21 REST checks + the app's own tests (`hidden/crm_acceptance.py` on a copy) | 60-110 | -| fixbug-ledger | bugfix | 6 seeded bugs in a 12-module bookkeeping library, 133 tests, 13 fail | pristine tests untouched and green + 34 hidden behaviour tests | 15-40 | -| feature-query | feature | implement the `where` query language of `SPEC.md` for a small table store, CLI flag, tests, README | existing tests, ~250 hidden spec cases, the agent's >= 25 tests pass, README | 20-45 | -| refactor-shop | refactor | 8-step refactor of a 22-module legacy shop library by `REFACTOR.md`, 119 tests stay green | pristine tests (with the `Cust` rename) + 26 static and behaviour checks | 35-60 | -| debuglog-sched | debug | find the id-reuse bug of a job scheduler from a 4,730-line (417 KB) log, fix, regression test, `FINDINGS.md` | visible + regression tests, two hidden stress simulations (zero lost jobs), `FINDINGS.md` content | 20-50 | -| smoke-mini | bugfix | 2 bugs in a 120-line package; pipeline smoke only, not in the matrix | pristine tests + hidden cases | 6-14 | - -Every task has an exact prompt (between the marker lines of `task.md`), a seed workspace (copied byte for byte, digest `SEEDTREE` in the manifest, checked by `cell.py` before Codex starts), an acceptance script that does not know the variant, hidden files that never enter the workspace, and a reference -solution used only by `tasks/selftest.py` (acceptance FAILS on the bare seed and PASSES on seed + reference; verified for all 7 on Python 3.9 and 3.12, and it never modifies the workspace). The reference solutions are NOT installed on the server. The workspace Codex works in lives in -`codex-lossy-delta/_active/ws`, away from earlier results, and is moved into the cell afterwards. The Codex sandbox is `workspace-write` without network (`approval_policy = never`), as in the earlier jobs; it can still read the file system, which is a residual risk shared by all variants. -The Rust-crate idea of the owner's list was replaced by Python (the server has no Rust toolchain and the agent could not build); `gcc`/`make` exist but no C task was written. - -Limits, identical for all variants and cells: wall limit 2,400 s per cell, cap 150 model requests (the proxy answers 503 beyond it and the runner stops Codex; the cell is recorded as `round_cap`), Codex `model_reasoning_effort = medium`, `model_context_window = 262144`. -A cell that hits a limit counts as not completed, its rounds are the rounds it used. - -## 4. Order, repeats and the stack life - -One block = one stack start of one variant (model load: ours about 7-8 min, vanilla about 4-5 min) followed by several cells, so a cell does not pay a load. The engine therefore carries its expert-tier history and its prefix cache from one cell to the next -(Codex's first ~9k tokens are common to all tasks); this is identical for the four variants but means cells are not independent. The warm-up request before the first cell is the same for all. -Block order per repetition is a small balanced design that keeps the lossy/lossless pair of an engine adjacent and alternates which comes first: rep 1 V1 V2 V3 V4, rep 2 V2 V1 V4 V3, rep 3 V3 V4 V1 V2, rep 4 V4 V3 V2 V1; the task order inside a block rotates with the repetition. -Server drift (vanilla was 13.5-16 ms/round at uptime 11-13 h on 2026-10-29 and 10.1-11.7 ms/round after fresh boots) is recorded per block (`uptime_s_at_block`, `boot_id`, GPU clocks), not removed. - -## 5. GPU-hour estimate and the cut - -Per cell (lossless, 130 tok/s): ttt 4-15 min (943d: 203 s), crm 15-25 min (945d: 871 s), the four new tasks 6-20 min each (author estimates, unmeasured on this model). Per block: model load 5-8 min, shutdown 1 min, warm-up 1 min. - -| design | blocks | cell time per block | total | -| --- | --- | --- | --- | -| full: 6 tasks x 3 repeats x 4 variants | 12 | 65-130 min | 14-27 GPU-h | -| pilot + smoke (queued first): smoke-mini x1 + fixbug-ledger x2 per variant | 4 | 20-30 min | about 2 GPU-h | - -The full design exceeds the 10 h budget, so the matrix is cut AFTER the pilot, from measured cell times, by this rule: keep every task but give each cell the n that fits 8 GPU-h (pilot excluded): first drop CRM to n=1 per variant, then the long tasks to n=2, never below n=3 for the -short tasks (fixbug-ledger, ttt, feature-query) unless the pilot shows bit-identical repeats. What was cut is stated in the second report. - -## 6. What delta the data can resolve - -A 5 % difference of the mean round count is not resolvable with 2-3 repeats of agent sessions unless the sessions are reproducible. The index prints the measured run-to-run CV of the round count (same variant, same task) and the relative difference two cell means of n repeats can resolve -(`2.8 * CV * sqrt(2/n)`, two-sided alpha 0.05, power 0.8). With a CV of 25 % that is about 57 % at n=3 for one task, about 23 % when the six tasks are pooled; with sessions that repeat exactly the per-cell delta is exact but is a statement about one trajectory. The index therefore reports, for each task, the lossy -and lossless round counts of every repeat, the paired difference by repeat, the completion counts, and the first round where the lossy and lossless sessions differ (with transcript line numbers), so the orchestrator can read both the numbers and the sessions. No quality verdict is computed. - -## 7. How to run and read - -```sh -bash scripts/e2e/codex/delta/install.sh # laptop: freeze + check + install on the server (read-only), nothing is hard-deleted -# server: stub ~/work/gpu-runs/holder2/jobs/.sh = `exec bash /data/leleka-e2e/codex-lossy-delta/delta/jobs/.sh`, add to jobs/PRIORITY -python3 -I ~/work/leleka/codex-lossy-delta/delta/index.py ~/work/leleka/runs/codex-lossy-delta # index.csv, rounds.csv, index.md, transcripts -``` - -Layout: `~/work/leleka/runs/codex-lossy-delta//-r/` (matrix cells), `_smoke/V?/...` (smoke), `V?/_stack-/` (stack logs), `_index/`. Incomplete cells are renamed `*.incomplete-