Move the notes and evidence out of docs/ (MCP is the store; STRA-338 follow-up)

This commit is contained in:
Pavlo Ratushnyi
2026-11-23 09:34:21 +01:00
parent 5819a26f75
commit deae0aa6ba
249 changed files with 9 additions and 39103 deletions
@@ -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
+1 -1
View File
@@ -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.
@@ -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 -- <model.gguf> 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)
@@ -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
@@ -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
@@ -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
+1 -1
View File
@@ -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.
-146
View File
@@ -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<t} prod_{i<=j} a_i
* `a_i` is the **calibrated** probability that draft i is accepted given drafts 1..i-1 were: for the MTP a table indexed by
(depth, bucket of the draft's own probability), shrunk toward a depth-free table per probability bucket, shrunk toward a prior
from the bucket centre; for the suffix the first row and the continuation rows by match-length bucket, separately when the suffix
agrees with the MTP and when it does not. Counts are decayed (0.995 per sample). A scalar logit bias per source moves fast
(rate 0.06 per tested row, fading) so a change of content (code to prose, JSON, a pasted file) is followed in tens of rounds
without waiting for the tables.
* The learning signal is exact: of `t-1` offered rows, rows 1..min(accepted+1, t-1) were tested (row j counts as a hit when
j <= accepted), the rest were censored by the first rejection.
* `T(t)` is the measured round time of a t-row window minus the draft chain (0.45 ms per chain step), kept as a decayed mean per
width (winsorised) blended with a fit `a + c (t-1)` over the recent rounds (forgetting 0.97 per round, slope pulled toward 15 %
of the level per row). The fit is what predicts widths not run lately: it carries the current tier / CPU / PCIe state. A width's own mean is trusted less as
it ages. Every observation also moves the other widths a part of the way (a state change is mostly common to all widths).
* Hysteresis: the previous round's (source, width) is kept unless another candidate is better by `LELEKA_SPEC_MARGIN` (2 %).
* Exploration is deterministic (no RNG, traces are reproducible): every `LELEKA_SPEC_EXPLORE` rounds (32; 8 for the first 24
rounds) a neighbouring width (+-1) whose model rate is within 12 % of the best and which has not been measured for 48 rounds is
run instead. Verification keeps the result exact; only one round's speed is at stake.
* **Next chain plan** (`draft_plan`): chain length = peak-held recent width (decays 8 % per round) capped by `max_t - 1`; confidence
floor = the smallest draft probability whose calibrated acceptance clears `rate * (row slope + chain step ms) / survival`, i.e.
a lower floor when rows are cheap, clamped to `[LELEKA_SPEC_MIN_P_LO, request spec_min_p]` (the operator's value stays the upper
bound; 0 means the policy's default ceiling, 0.6 since claude/window-policy, 0.9 before and with `LELEKA_SPEC_POLICY=legacy`, docs/experiments/window-policy-5090.md). The plan is applied to the MTP actor per round (`set_draft_plan`; the actor's `max_drafts` is set from it).
Verification is untouched. The controller still checks every offered row against the target's own output, commits the accepted
prefix and the bonus token. Sampled requests use the existing sampled verification path unchanged (acceptance is equality with the
sampled target token; the policy only chooses how many rows to offer).
## Knobs
| variable | default | meaning |
| --- | --- | --- |
| `LELEKA_SPEC_ADAPTIVE` | on | `off`: the fixed mode17 window; adaptive = 8-row verifier, MTP chain up to 7 drafts, suffix 3 |
| `LELEKA_SPEC_ADAPTIVE_MAX_T` | 8 | widest window (rows); the Original's constant `kVerifyMaxT` is 8 |
| `LELEKA_SPEC` / `_MTP_MAX_T` / `_SUFFIX` | unset / spec / 3 | the Original's `--spec`, `--mtp-max-t`, `--suffix-draft`; setting `LELEKA_SPEC` selects the fixed window |
| `LELEKA_SPEC_ARMS` | - | `fixed3@0.5,fixed4@0,adaptive@0`: policies one process switches between per request (A/B in one load); `@P` pins the arm's request floor (`spec_min_p`) |
| `LELEKA_SPEC_EXPLORE`, `_MARGIN`, `_MIN_P_LO`, `_DRAFT_STEP_MS`, `_COST_ALPHA`, `_DECAY`, `_BIAS_RATE` | 32, 0.02, 0.10, 0.45, 0.12, 0.995, 0.06 | policy constants |
| `LELEKA_SPEC_FLOOR_CEILING` | 0.60 | the chain floor's ceiling when the request carries `spec_min_p` 0 (a request value above 0 is the ceiling itself) |
| `LELEKA_SPEC_POLICY` | current | `legacy` (or `v1`): the constants of the policy before claude/window-policy (ceiling 0.9) |
| `LELEKA_SPEC_ARMS` suffix `~key=value` | - | per-arm policy constants for replays: `adaptive@0.6~step=0.3~explore=0` (keys step explore margin min_p_lo alpha decay bias ceil rowq smooth measured) |
| `LELEKA_SPEC_STATS=1` | off | one `DBG spec-stats` line per request: rounds, tokens per round, width and accepted histograms, mean ms per width |
| `LELEKA_SPEC_TRACE=1` | off | one `DBG spec-trace` line per timed round (width, source, accepted, round ms, expected tokens, next chain plan, the bar a further draft must clear and the row slope in ms) |
| smoke: `@file:PATH` lines in `LELEKA_SMOKE_PROMPTS` | - | a whole file as one prompt (code with its newlines); with `LELEKA_SPEC_ARMS` pass p of prompt i uses arm (p+i) mod arms |
## Wider windows than 6
`kVerifyMaxT = 8` is compiled into the window kernels (`acc[kVerifyMaxT]` register arrays, the grouped-expert `GMAX >= 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.
-995
View File
@@ -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":"<normalized text>","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 `</think>` 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</think>\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 `<server>__<tool>`, 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 <n>` and `REUSED <n>` 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 `</think>` 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 `<tool_call>`, `<function=NAME>`, one `<parameter=P>` ... `</parameter>` per argument,
`</function>`, `</tool_call>`. `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 `</parameter>` that is followed by the next
`<parameter=` or by `</function>` and that does not belong to a call the value itself quotes (the quoted `<function=NAME>`
openers before it, each followed by `<parameter=` or `</function>`, must not outnumber the `</function>` 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 (`</parameter></function>` with no opener) still ends there; and a
value that reopens its own parameter (`</parameter><parameter=content>` 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.
* `</function>` left out: `</parameter>` followed by `</tool_call>` ends the value and the call, but only when no `</parameter>`
followed by `<parameter=` or `</function>` ends the value (so a value that quotes `</parameter></tool_call>` and has a real
close later is read whole). A streamed response delivers such a call when the generation ends, not when its `</tool_call>`
arrives, because only the end of the generation can tell the two readings apart.
* `</tool_call>` left out: the call is whole when the next `<tool_call><function=NAME>` follows its `</function>`, or when its
`</function>` 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 `</think>` 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 </think>`) stands; so does a `</think>` 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
`<tool_call>` 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:
* `<parameter=NAME>` where `<function=NAME>` belongs (after `<tool_call>`);
* `<tool_call>` followed by `<=NAME>`, `<function:NAME>`, `<function =NAME>` or `<NAME>`;
* a JSON object `{"name": NAME, "arguments": {...}}` inside `<tool_call>` (also in a Markdown fence; `arguments` may be a JSON string);
* a bare `<function=NAME>` ... `</function>` with no `<tool_call>`, only at the start of a line outside a code fence and outside
inline code (a stray `</tool_call>` after it is dropped);
* a second call in the same `<tool_call>` (opened by `<function=` or `<parameter=NAME>` after the first `</function>`);
* 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
`</tool_call>` 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 `<function=NAME>` 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.
-157
View File
@@ -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 <ids>` / `T <id>` / `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.
-106
View File
@@ -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<dyn Port>` (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<AppState> ----+--- 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).
-238
View File
@@ -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<br/>gateway root]
dcore[leleka-engine-host<br/>engine process root]
rt[leleka-runtime<br/>facade]
end
subgraph L3[L3 adapters]
q35[engine-qwen35-cuda]
fake[engine-fake]
cuda[cuda-driver]
mfmt[model-format<br/>WeightSource]
cpux[native-cpu-expert]
rtc[runtime-client<br/>gRPC]
end
subgraph L2[L2 domain]
core[engine-core<br/>EngineFamily, run_request,<br/>prefix cache, conversation]
gdom[gateway-domain]
end
subgraph L1[L1 leaf libraries]
obs[obs<br/>Clock]
mem[leleka-memory<br/>MemoryPressure]
gtext[gateway-text, harmony,<br/>tokenizer, ...]
cudam[cuda-model<br/>Error, shapes, schedules]
end
subgraph L0[L0 contract]
api[backend-api<br/>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<C>` (`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<S>`, `ScriptedPressure`; Windows adapter `leleka_memory_os::WindowsProc` | `Arc<dyn MemoryPressure>` 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<dyn PageLocking>`) 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<E>, admit}` | generic, no trait object | admission, reset or resume, prefill, decode, finish: the order and the failure classes run over any owners |
| EngineFamily + `spawn::<F>` | `leleka_engine_core::family::{EngineFamily, spawn}`; families `Qwen35Cuda` and `EngineFake` | `F` is generic; the result is `Box<dyn Backend>` | 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<dyn Backend>` 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<dyn Port>` 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::<Qwen35Cuda>` 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-<family>-<device>` (package `leleka-engine-<family>-<device>`), 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<Box<dyn Backend>, 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::<Family>(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::<Family>` 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 <crate>`, 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`, `*_<N>.rs` / `*_<N>_<M>.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_<method>`) 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<E>`, `run_request` over `Lifecycle` to `engine-core::request` |
| S20 | `e049e24fe` | `EngineFamily` and `spawn::<F>`, `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 |
@@ -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<Admission, InsufficientMemory>`: 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<BackendEvent>`: 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.
-212
View File
@@ -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<Self>`)
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 `<file>` 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 `<file>` 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`).
-70
View File
@@ -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, <https://rust-lang.github.io/api-guidelines/naming.html>); John Ousterhout, *A Philosophy of Software Design*,
ch. 14 "Choosing Names" (<https://lamb.github.io/a-philosophy-of-software-design/choosing-names.html>); the SSW rule "avoid generic
names" (<https://www.ssw.com.au/rules/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_<what>`, `from_<what>`; 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 `*_<N>.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_<method>`); a taken name gets a word (`_more`), never a number.
* After `scripts/dev/rustsplit`, run `python scripts/dev/explicit_imports.py <worktree> <crate dir> <package>`: 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`).
-207
View File
@@ -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 `<think>` (effort other than `none`); the model closes with `</think>` | always: the analysis channel becomes the text before `</think>` |
| Tool calls | `<tool_call><function=NAME><parameter=P>..` 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 `</think>` | 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 (`</think>`, `<tool_call>`) 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 `</think>` and `<tool_call>` 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 `</function>` 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 `</think>` 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::<family>` and
`AtEndDecoder::<family>`, 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 `<kind>_ID<k>` by order of first
appearance and **keeps its numeric suffix** (`call_ID3_1`), so the index inside `call_<response>_<n>` 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 `</think>` 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
`</think>` 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_<response>_<n>` 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 `</think>` (for gpt-oss, the one that closed the analysis).
* gpt-oss: a literal `</think>` 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 `</think>` and `<tool_call>` text, and the shared cut and parse read that. Reading the channels directly
would change two corners that the golden pins: the `</think>` 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.
-188
View File
@@ -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.
@@ -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 `<module path>::<test name>`. 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/<name>.rs` became `tests/<name>/main.rs`, which Cargo discovers under the
same target name.
* Two families of tests start themselves as a child process with `--exact <id>`. `credential_child("<name>")` in
`runtime_gateway_sdet` and `native_tools_retry_sdet` now names `"<module>::<name>"`; 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 (`<module>/tests.rs` becomes `<module>/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/<name>.rs` becomes `tests/<name>/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_<rpc>` 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.
-86
View File
@@ -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 `<module path>::<test name>`. 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 (`<module>/tests.rs` or an inline `mod tests` becomes `<module>/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::<name>` 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`).
-69
View File
@@ -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 `<module path>::<test name>`. A split changes the module path and nothing else:
* `cargo test -p <crate> --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/<name>.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.
-816
View File
@@ -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<dyn PageLocking>`),
`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(<the declaration's 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<bool>` 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<Vec<f32>>`, 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<bool>` 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 `<parent>/<name>.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<dyn Error>` 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::<u64>("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<String>` (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 | <!-- old-names -->
| 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 | <!-- old-names -->
| 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) | <!-- old-names -->
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<dyn Backend>` 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<dyn Backend>` 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<Settings>`: 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<C>` (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<C = SystemClock>` (`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<C = SystemClock>` | 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<AnyClock>`) | the retention scale (`wall_ms`, now milliseconds since the cache was built instead of a process `OnceLock<Instant>`: 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<S: ProcSource>` 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<dyn ProcSource>)` 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<Instant>` 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<u64>; // 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<D: PromptDevice>(
dev: &mut D, prefix: Option<&mut PrefixServe<D::State, D::Block>>, 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<Self::Port, SpecError>;
fn close(&mut self, port: Self::Port, result: &Result<ServeOutcome, SpecError>, want_tail: bool);
}
pub(crate) fn decode_request<D: DecodeDevice>(
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<ServeOutcome, SpecError>; // 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<u64>) -> Result<Region<'_>, WeightError>;
fn len(&self) -> u64; fn live_len(&self) -> Result<u64, WeightError>; // 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<S: WeightSource + ?Sized>(source: &S, scratch: &mut [u8]) -> Result<[u8; 32], WeightError>;
```
`BackingKind` is `Memory | HugePages | MappedFile | File | SealedMemfd`; `Verification` is `Unverified | FullPass | Stamp |
AttestedMemfd | SparseExtents` (`From<KarTrust>`). 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<u8>`, `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<F: Borrow<File>>` | 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<S: WeightSource + ?Sized>`; 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<E>`, `Lifecycle`, `run_request`) | `RequestOwners` and the `Owners` wrapper that implements `Lifecycle` over them |
| S20 | `e049e24fe` | `family` (`EngineFamily`, `spawn::<F>`) | `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<Settings>` 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<dyn Backend>` 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<F>` 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::<EngineFake>`); that is a size entry, not a `dyn` count. `Backend`
is the trait object the process already had at its boundary: `RuntimeServer` holds `Box<dyn api::Backend>` (`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-<hash>`; 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
`</think>` 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 `</think>` 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
`<file>` 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.
-11
View File
@@ -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.
-959
View File
@@ -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 -- <external-sample-gguf> 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 <digest>` 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 `<tool_call><function=...><parameter=...>` 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 `<tool_call>` 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.
-116
View File
@@ -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.
-356
View File
@@ -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
<think>
</think>
<|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 <worktree>/target/stra157-sdet && mount -t tmpfs tmpfs <worktree>/target/stra169-mtp-binder &&
exec setpriv --inh-caps=-all --bounding-set=-all --ambient-caps=-all "$@"' sh <command>`.
-193
View File
@@ -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`.
-192
View File
@@ -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 `<tool_response>` 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 <name> <ms> t_unix_ms=<end>` 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`.
-273
View File
@@ -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 <gguf> [--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 <ctx> stop`
after loading (and, unless `--no-warm`, reading every page of the model once), then per request:
`PP <done> <total>` after every prefill chunk, `REUSED <n>`, `T <id>` per generated token, and one
`DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> stop|length|cancel 0 0 <reused> 0 0` (or `ERR`).
Input: `GEN <max_new> [temperature=] [top_p=] [seed=] <ids>`, `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", "<gpt-oss-20b-MXFP4.gguf>", "--ctx", "8192", "--threads", "10"],
"gptoss_gguf": "<gpt-oss-20b-MXFP4.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 <gguf>` 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.
-598
View File
@@ -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 <source>
strata model prepare <model> --quality preserve
strata run <model> --device auto
strata jobs watch <id>
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:<local-port>`. Перевірка зайнятого порту;
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 не встановлено.
-168
View File
@@ -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.
-501
View File
@@ -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<Option<FixedKernel>>` 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.
-238
View File
@@ -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.
@@ -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
}
]
}
-286
View File
@@ -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<false> (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."
}
}
-325
View File
@@ -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<false>",
"required": "--use_fast_math"
},
{
"cu": "mtp_original_session_native_rope.cu",
"original": "native_rope.cu apply<TAB>",
"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"
}
}
-114
View File
@@ -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.
-182
View File
@@ -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 <token ids>`/`T <id>`/`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 |
-436
View File
@@ -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.
@@ -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.
-81
View File
@@ -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.
-310
View File
@@ -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: <client-visible message>` 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):
* `<function=shell>` with `<command>["ls"]</command>` instead of `<parameter=command>` -> `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 <<EOF`), not a Lark custom tool. Nothing else had to be added to the Responses surface.
| | tic-tac-toe 943b (default conversation cache) | CRM 945 (prefix cache `--prefix-cache-mib auto`) |
| --- | --- | --- |
| first attempt | job 943 ended after 4 min: defect 7 below | none |
| outcome | Codex exit 0 after **918 s**, 51 requests, `index.html` 10,778 bytes sha256 `8f3e24b0a3fc6018607b93b584cf8d1b2e29df4a330121fd5d65dbffea76aaff` | Codex exit 0 after **1,526 s**, 84 requests, 2,391 lines of Python in 8 modules, 139 tests (green), README, CODE_REVIEW.md |
| functional verdict | **6/6** shared browser checks (laptop, real mouse clicks, software GL): loads without page error, visible WebGL canvas, row win, moves blocked after the win, restart to empty board, draw; the agent's own `check_game.py` passed 64 checks | acceptance script `crm_acceptance.py` **21/21** (server and laptop): CRUD, search, stage filter, notes, pipeline, 400/404, SET NULL on delete, its own `unittest` suite |
| Codex tokens (events) | input 2,474,932 / cached 2,392,367 (96.7 %) / output 56,553 (reasoning 32,835) | input 6,016,105 / cached 5,801,984 (96.4 %) / output 96,081 |
| context reached | 82,315 tokens | **123,239 tokens** (not the typical 180k) |
| **weighted decode tok/s** (tokens after the first / decode time) | **71.7** (56,502 tokens / 788 s); per-request median 68.5 | **74.8** (95,997 tokens / 1,283 s); median 73.6 |
| reference (earlier vanilla Strata, same host and task shape) | native 115.7, KAR PLE 150.1-150.3 | same |
| wall-time shares | time to first text 12.1 % (111 s), decode 85.9 %, agent+tools between requests 2.0 % (18 s, of which commands 12 s), queue 0 | 14.9 % (228 s), 84.1 %, 1.0 % (15 s), 0 |
| tokens per verify round (accepted drafts + 1) | 2.92 (median 2.96) | 3.36 (median 3.50) |
| expert entries per request: VRAM / PCIe / CPU | 49 % / 23 % / 28 % (median) | 43 % / 27 % / 30 % |
| decode tok/s by context (median) | 66 (4-16k), 71 (16-48k), 67 (48-96k) | 65 (4-16k), 79 (16-48k), 74 (48-96k), 68 (96k+) |
| re-prefilled tokens (total / per request) | 82,565 of 2,474,932 / median about 1.1k | 214,121 of 6,016,105 / median about 2.2k |
| ideal (only the new suffix re-read) | 26.4k tokens: prefill about 24 s instead of 75 s | 28.4k tokens: about 27 s instead of 202 s |
| engine prefill rate | 388 (64-512 tokens) / 873 (512-2k) / 1,158 (2k-8k) tok/s | 995 / 1,038 / 1,140 tok/s |
| memory | engine RSS 53.6 -> 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 <mtp pack>` 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`.
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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.
@@ -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.

Some files were not shown because too many files have changed in this diff Show More