gpu-head-to-head
aien-dev/gpu-head-to-head
Brought by drakestapleton
GitHub aien-dev/gpu-head-to-head#8 (code only)
Apply it
git checkout -b patch-cf265253a79106d5 557d050e7be5885bb3ae231df5cff98495109d5f curl -fsSL https://interplane.io/drakestapleton/gpu-head-to-head/patches/cf265253a79106d5.patch | git am
Provenance
github-import 1
aien-dev/gpu-head-to-head
8
3bf02917ccf5eb179cb82a20e39b1a6e4de66852
{"kind":"github-import","owner":"aien-dev","repo":"gpu-head-to-head","number":8,"url":"https://github.com/aien-dev/gpu-head-to-head/pull/8","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:58Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/PROTOCOL.md b/PROTOCOL.md index 8ab4b84..343b713 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -367,3 +367,100 @@ children, sampler identity and parent-versus-child lock ownership. No GPU, real container is used by these controls. The active frozen 9B campaign is unchanged. Source and runtime pins, the shared-service controller, unload/memory evidence and full 35B execution remain separate requirements before this runner is used for the larger-model comparison. + +### A10 (2026-10-31, before DRA-74 35B timing): comparator arms, TTFT rows, window sessions + +Arms. `bench/arms.conf` declares every comparator arm; `run_arm.sh` hashes it into +`driver-sha256.txt`, so the record carries the exact hooks. + +- OURS: the prebuilt `aien-serve-http` of bin-19173f9e, sha256 `19173f9e…f22b3aeb`, checked before + launch (`--max-context 49152 --batch-slots 8 --thinking off`, port 18190). The variable + `AIEN_OMEGA_FP8_GROUPED_WAVE` is passed explicitly and recorded as 0. That binary has no reader for + it (`grep -c GROUPED_WAVE` = 0 on `aien-serve-http` and `libomega_gpu.a`). The 0 therefore records + the binary's behaviour; it is not a setting. +- VLLM_FP8, VLLM_FP8_MTP (MTP, 3 speculative tokens), VLLM_FP8_MTP2 (MTP, 2): checkpoint + `qwen3.6-35b-a3b-fp8-95a723d0`, KV dtype auto, FLASH_ATTN, DeepGEMM MoE, prefix caching off. +- VLLM_NVFP4, VLLM_NVFP4_MTP (MTP 3, draft MoE on Triton), VLLM_NVFP4_NSYS: checkpoint + `nvidia/Qwen3.6-35B-A3B-NVFP4@1355db6a`, quantization modelopt, KV fp8, FLASHINFER, Marlin MoE, + prefix caching off. VLLM_NVFP4 supersedes the legacy A3 VLLM4 arm. +- All vLLM arms use image `nvcr.io/nvidia/vllm@sha256:55774733…02c2` (release 26.09, image id + `8ec4dbb7a3d1`, vLLM 0.29.0) with `--max-model-len 49152 --max-num-seqs 32 + --gpu-memory-utilization 0.50 --language-model-only` before the per-arm hooks. +- KV-dtype confound: the FP8 arms run KV auto (bf16) and the NVFP4 arms run KV fp8, as each checkpoint + declares. A FP8-vs-NVFP4 difference therefore includes the KV dtype and is reported as such, not + as a weight-format effect alone. + +Cell sets. `H2H_CELLS` is a comma list without duplicates, so one model load can serve several +sets: + +- `full`: the 14 A3 cells. +- `dra74`: 7 cells. Decode at c1/c4/c8/c16 with `max_tokens` 256, plus prefill p256/p2k/p8k with the + per-request nonce. +- `nsys-c8`: one c8 decode cell. It runs alone, only on an `ARM_PROFILE=nsys` arm. nsys starts with + `--capture-range=cudaProfilerApi`, and the capture opens and closes through vLLM's + `/start_profile` and `/stop_profile`. `bench/nsys_classify.py` classifies its kernels. + `extract.py` excludes every `*_NSYS` row from timing results. +- `ttft-fresh`: one cell per item of `H2H_TTFT_PROMPTS` (distinct, from t2k, t8k, t32k), named + `ttft-fresh-2k/8k/32k`. Each cell runs 1 warmup on t2k, then `H2H_TTFT_REPS` (1-9) measured reps + numbered from `H2H_TTFT_REP_BASE` (0-99). Reps can therefore be split across sessions without + reusing a nonce. Prefix caching must be off. +- `ttft-turn2`: one cell. OURS has no prompt cache (L375 is not in bin-19173f9e), so its row is + `ttft-turn2-reread`. On a VLLM_* arm the row is `ttft-turn2-cached` and needs `H2H_PREFIX=on`. + `H2H_PREFIX=on` is accepted only for a VLLM_* arm whose `H2H_CELLS` is exactly `ttft-turn2`. + +TTFT rows. `prompts/ttft.jsonl` (sha256 `348c36ec…2f0e59`) is generated by +`bench/make_ttft_prompts.py`. The generator pins its sources by sha256 and exits 2 on a mismatch. + +- Sources: judge checkout b129e1ea `long-2048.txt` (`26a44c50…`), `long-8192.txt` (`2bcc84b2…`) and + `long-256.txt` (`153a5f88…`); DRA-85 `long-32768.txt` (`791ef12b…`, which is long-8192 ×3 + + long-2048 ×3 + long-256 ×2, 32771 raw-text tokens as measured by DRA-85). +- Prompts: t2k, t8k and t32k are the fresh prompts. Turn 2 is t32k, a fixed short assistant reply, + then `turn2-new` (long-256 ×4). +- Nonce: every request starts with a nonce line, the first 16 hex digits of + `sha256("h2h-ttft|<id>|<w|r><rep>")`. It contains no arm and no clock. Request bodies are + therefore byte-identical across arms, while no two reps share a prefix. Each row records + `messages_sha256`. +- Turn 2, per rep: a priming request (the turn-1 conversation, metric suffix `-prime`), then the + 3-message conversation, whose first message is byte-identical to the primed prompt + (`prefix_sha256`). For vLLM the runner records the `/metrics` prefix-cache lines before and after + each turn-2 request, so a cache hit or miss is observed, not assumed. +- Token counts come from `usage.prompt_tokens` under each server's own tokenizer. They are recorded, + not asserted. +- M1 TTFT is `t_first - t_send` (section 6). TPOT is `(t_last - t_first)/(completion_tokens - 1)` from + the usage counts (the M2 rule). All derived values are computed from the `h2hRows` that + `extract.py` emits. + +Session control. + +- Core 17 is excluded from every role. This supersedes A4(e); the kthread-core fallback is 18. +- In a chip slice the client runs on core 5 at nice 19 (`H2H_CLIENT_CPUS`, `H2H_CLIENT_NICE`, + checked by `cpu_guard`). +- Inside an exclusive spark-window, `AIEN_GB10_LOCK_HELD=1` is accepted only when `SPARK_WINDOW`, + `SPARK_WINDOW_DIR`, `spark-window id` and `$SPARK_WINDOW_DIR/gb10 = exclusive` all agree. +- `H2H_DEADLINE_EPOCH` must lie more than 600 s ahead. Request execution stops at + min(lock + 3540 s, deadline − 60 s). +- Defect fix: the `mark_complete` call that writes DONE had been lost. Before the fix every session + ended INCOMPLETE. It is restored and covered by `bench/test-run-arm-dra74.py`. + +These numbers are HTTP-only (client-side `t_send`, `t_first`, `t_last`) and are never placed beside +chip-only measurements. + +Named limit: DRAM GB/s. The DRA-74 acceptance item "DRAM GB/s per arm" is NOT_RUN-able on this +host as configured. + +- nsys 2025.3.2 has no DRAM-throughput metric for this GPU: `GpuMetrics/gb20b.config` lists only + NVENC/OFA counters, and SocMetrics ships only `t234.config`. +- The driver runs with `RmProfilingAdminOnly: 1` (`/proc/driver/nvidia/params`), which restricts + hardware counters to root. +- Changing that parameter needs root and an nvidia module reload, which takes down the live servers. + It is Drake's decision. The runner does not change it and does not work around it. +- The available substitute is MODELED: bytes read per decoded token, multiplied by measured tok/s. + It is labelled MODELED and reported in a separate table, never as a measured DRAM rate. + +Not yet verified on the chip: whether vLLM prefix caching hits on this hybrid DeltaNet model (the +`/metrics` capture will show it), and whether OURS accepts a multi-turn chat that includes an +assistant message. + +CPU-only controls: `python3 bench/test-run-arm-dra74.py`, `python3 bench/test-ttft.py`, +`python3 bench/test-nsys-classify.py` and `node bench/test-bench-node.mjs`, plus the A8 and A9 controls. +They use fake servers and fixtures and never touch a GPU, model or container. diff --git a/README.md b/README.md index 6af1142..21b9efe 100644 --- a/README.md +++ b/README.md @@ -46,11 +46,17 @@ python3 bench/test-shared-model-guard.py python3 bench/test-shared-window.py python3 bench/test-bench-python.py python3 bench/test-extract-admission.py +python3 bench/test-run-arm-dra74.py +python3 bench/test-ttft.py +python3 bench/test-nsys-classify.py +node bench/test-bench-node.mjs bash -n bench/run_arm.sh ``` Protocol amendments A8 and A9 describe owned-process cleanup, per-cell admission records, failed-stream detection and refusal to -overwrite previous evidence. Passing these CPU-only controls does not qualify a model or complete +overwrite previous evidence. A10 adds the DRA-74 comparator arms, the TTFT rows (`prompts/ttft.jsonl`, +generated by `bench/make_ttft_prompts.py`), comma-list cell sets and in-window sessions. +Passing these CPU-only controls does not qualify a model or complete the GPU benchmark. Historical rows without an admission ledger retain their original limitations. The separate `shared-model-guard.py` checks the saved executable, arguments, working directory, diff --git a/bench/arms.conf b/bench/arms.conf new file mode 100644 index 0000000..09e7c59 --- /dev/null +++ b/bench/arms.conf @@ -0,0 +1,38 @@ +# Sourced by bench/run_arm.sh (bash). PROTOCOL.md A3 (4-bit arms) and A10 (DRA-74 comparator arms). +# Every value here is part of the result record: run_arm.sh hashes this file into driver-sha256.txt. + +# A3: empty -> the arm is recorded NOT_RUN. A10: VLLM_NVFP4 below supersedes the legacy VLLM4 arm. +SGLANG_IMG= +MODEL4= +GGUF4= + +# OURS (A10): prebuilt server, checked by sha256 before launch; AIEN_OMEGA_FP8_GROUPED_WAVE is passed +# explicitly. bin-19173f9e carries no reader of that variable (grep -c GROUPED_WAVE = 0 on its +# aien-serve-http and libomega_gpu.a), so 0 records the behaviour it has, not a lever setting. +OURS_BIN_DIR=${OURS_BIN_DIR:-/home/drakestapleton/.local/state/aien-q36/bin-19173f9e} +OURS_BIN_SHA256=${OURS_BIN_SHA256:-19173f9ec3b609fe79af644f84741d8808b92ea8eb3ecec4bc945af6f22b3aeb} +OURS_WAVE=${OURS_WAVE:-0} + +# nvidia/Qwen3.6-35B-A3B-NVFP4@1355db6a052410cfd62085d94b58866fd0f2c3c5 (hf_quant_config MIXED_PRECISION: +# W4A16 NVFP4 experts, FP8 linear attention, FP8 KV cache, bf16 MTP head); sha list verified 15/15. +MODEL_NVFP4=/home/drakestapleton/models/qwen3.6-35b-a3b-nvfp4-1355db6a +NSYS_DIR=/opt/nvidia/nsight-systems/2025.3.2 + +# FP8: the backends vLLM chose by itself in the A1 session (DeepGEMM MoE, FlashAttention), pinned so a +# version default cannot drift; KV dtype auto as in A1 (the FP8-vs-NVFP4 KV dtype confound is in A10). +for a in VLLM_FP8 VLLM_FP8_MTP VLLM_FP8_MTP2; do + ARM_MODEL[$a]=$MODEL; ARM_UTIL[$a]=0.50; ARM_KV[$a]=auto + ARM_ATTN[$a]=FLASH_ATTN; ARM_MOE[$a]=deep_gemm; ARM_PREFIX[$a]=off +done +ARM_SPEC[VLLM_FP8_MTP]='{"method":"mtp","num_speculative_tokens":3}' +ARM_SPEC[VLLM_FP8_MTP2]='{"method":"mtp","num_speculative_tokens":2}' + +# NVFP4: modelopt (resolves to modelopt_mixed on this checkpoint), FP8 KV as the checkpoint declares, +# FlashInfer attention (FP8 KV), Marlin W4A16 MoE. The MTP draft is bf16, so its MoE runs on Triton. +for a in VLLM_NVFP4 VLLM_NVFP4_MTP VLLM_NVFP4_NSYS; do + ARM_MODEL[$a]=$MODEL_NVFP4; ARM_UTIL[$a]=0.50; ARM_QUANT[$a]=modelopt; ARM_KV[$a]=fp8 + ARM_ATTN[$a]=FLASHINFER; ARM_MOE[$a]=marlin; ARM_PREFIX[$a]=off +done +ARM_SPEC[VLLM_NVFP4_MTP]='{"method":"mtp","num_speculative_tokens":3,"moe_backend":"triton"}' +ARM_PROFILE[VLLM_NVFP4_NSYS]=nsys +unset a diff --git a/bench/bench.py b/bench/bench.py index 478b9f7..a392faf 100755 --- a/bench/bench.py +++ b/bench/bench.py @@ -7,6 +7,7 @@ One JSON row per request is appended to --out. Nothing is aggregated here; aggre Wolfram (see PROTOCOL.md section 7) so that the raw rows stay the evidence. """ import argparse +import hashlib import http.client import json import os @@ -21,10 +22,10 @@ def load1(): return float(f.read().split()[0]) -def one_request(host, port, model, prompt, max_tokens, timeout=1800): +def one_request(host, port, model, prompt, max_tokens, timeout=1800, messages=None): body = { "model": model, - "messages": [{"role": "user", "content": prompt}], + "messages": messages if messages is not None else [{"role": "user", "content": prompt}], "stream": True, "stream_options": {"include_usage": True}, "temperature": 0, @@ -107,6 +108,83 @@ def one_request(host, port, model, prompt, max_tokens, timeout=1800): return row +# PROTOCOL A10 TTFT rows. The nonce depends only on the prompt id, the repetition and whether the +# request is a warmup, never on the arm or the clock: every arm receives byte-identical requests, +# and no prefix cache can carry one repetition into the next. +NONCE_LINE = "Request id %s. Ignore this line.\n" + + +def ttft_nonce(prompt_id, rep, warm): + key = "h2h-ttft|%s|%s%d" % (prompt_id, "w" if warm else "r", rep) + return hashlib.sha256(key.encode()).hexdigest()[:16] + + +def ttft_requests(kind, byid, prompt_id, nonce): + """[(phase, messages)] for one repetition: fresh -> one request; turn2 -> prime, then turn 2.""" + first = {"role": "user", "content": NONCE_LINE % nonce + byid[prompt_id]["text"]} + if kind == "fresh": + return [("fresh", [first])] + full = [dict(first), {"role": "assistant", "content": byid["turn2-assistant"]["text"]}, + {"role": "user", "content": byid["turn2-new"]["text"]}] + return [("prime", [first]), ("turn2", full)] + + +def messages_sha256(messages): + return hashlib.sha256(json.dumps(messages, sort_keys=True).encode()).hexdigest() + + +def prefix_cache_lines(host, port): + """vLLM /metrics prefix-cache counter lines (raw text; deltas are taken in Wolfram).""" + try: + conn = http.client.HTTPConnection(host, port, timeout=10) + conn.request("GET", "/metrics") + resp = conn.getresponse() + text = resp.read().decode(errors="replace") + conn.close() + if resp.status != 200: + return {"error": "HTTP %d" % resp.status} + return {"lines": [l for l in text.splitlines() if "prefix_cache" in l and not l.startswith("#")]} + except Exception as e: # recorded, never hidden + return {"error": repr(e)} + + +def run_ttft(args, byid, f): + """One request at a time; rows carry phase, nonce and the sha256 of the exact message list.""" + failed = False + for k in range(args.warmup + args.reps): + warm = k < args.warmup + rep = args.rep_base + (k if warm else k - args.warmup) + # a warmup may use a cheaper prompt (--warm-select) and is always a single fresh request + pid = (args.warm_select or args.select) if warm else args.select + nonce = ttft_nonce(pid, rep, warm) + for phase, messages in ttft_requests("fresh" if warm else args.ttft, byid, pid, nonce): + before = prefix_cache_lines(args.host, args.port) if args.ttft == "turn2" else None + l1 = load1() + ts = time.time() + r = one_request(args.host, args.port, args.model, None, args.max_tokens, messages=messages) + r.update({"arm": args.arm, "round": args.round, + "metric": args.metric + ("-prime" if phase == "prime" else ""), "rep": rep, + "warmup": warm, "concurrency": 1, "stream_index": 0, + "batch_id": uuid.uuid4().hex[:12], "load1_start": l1, "load1_end": load1(), + "wall_utc": ts, "max_tokens": args.max_tokens, "prompt_id": pid, + "cell_run": args.cell_run, "ttft_phase": phase, "nonce": nonce, + "messages_sha256": messages_sha256(messages), + "prefix_sha256": messages_sha256(messages[:1]), + "server_cpus": os.environ.get("H2H_SRV_CPUS"), + "client_cpus": os.environ.get("H2H_CLI_CPUS")}) + if before is not None: + r["prefix_cache_before"] = before + r["prefix_cache_after"] = prefix_cache_lines(args.host, args.port) + f.write(json.dumps(r) + "\n") + f.flush() + failed = failed or bool(r["error"]) + u = r["usage"] or {} + print("%s %s %s %s rep=%d warm=%s pt=%s ct=%s err=%s" % ( + args.arm, args.round, r["metric"], phase, rep, warm, u.get("prompt_tokens"), + u.get("completion_tokens"), (r["error"] or "")[:120]), file=sys.stderr) + return failed + + def run_batch(args, prompts, rep, warm): rows = [None] * len(prompts) barrier = threading.Barrier(len(prompts)) @@ -153,11 +231,27 @@ def main(): ap.add_argument("--reps", type=int, default=3) ap.add_argument("--nonce", action="store_true", help="prefix each prompt with a unique nonce line so no prefix cache can hit") + ap.add_argument("--ttft", choices=["fresh", "turn2"], + help="A10 TTFT rows: one --select id, deterministic per-rep nonce, concurrency 1") + ap.add_argument("--rep-base", type=int, default=0, help="first repetition number (--ttft only)") + ap.add_argument("--warm-select", default="", help="prompt id for --ttft warmup requests") ap.add_argument("--out", required=True) ap.add_argument("--cell-run", default="", help="id of this cell invocation (voiding unit, A2)") args = ap.parse_args() if args.concurrency < 1 or args.reps < 1 or args.warmup < 0 or args.max_tokens < 1: ap.error("concurrency, reps and max-tokens must be positive; warmup must be nonnegative") + if args.ttft: + byid = {p["id"]: p for p in (json.loads(l) for l in open(args.prompts) if l.strip())} + need = [args.select] + (["turn2-assistant", "turn2-new"] if args.ttft == "turn2" else []) + need += [args.warm_select] if args.warm_select else [] + if (args.nonce or args.concurrency != 1 or args.rep_base < 0 or "," in args.select + or not all(n in byid for n in need)): + ap.error("--ttft takes exactly one --select id present in --prompts (turn2 also needs " + "turn2-assistant and turn2-new), concurrency 1, no --nonce, rep-base >= 0") + with open(args.out, "a") as f: + return 1 if run_ttft(args, byid, f) else 0 + if args.rep_base or args.warm_select: + ap.error("--rep-base and --warm-select need --ttft") allp = [json.loads(l) for l in open(args.prompts) if l.strip()] if args.select: @@ -178,7 +272,7 @@ def main(): for p in sel: t = p["text"] if args.nonce: - t = "Request id %s. Ignore this line.\n" % uuid.uuid4().hex + t + t = NONCE_LINE % uuid.uuid4().hex + t texts.append(t) args.prompt_ids = [p["id"] for p in sel] for r in run_batch(args, texts, rep, warm): diff --git a/bench/extract.py b/bench/extract.py index aca5347..199e009 100755 --- a/bench/extract.py +++ b/bench/extract.py @@ -47,7 +47,9 @@ for r in raw: rows = [] for r in raw: cr = r.get("cell_run") - if r["warmup"] or r["arm"] == "STUB" or cr in void or (admission is not None and admission.get(cr) != "PASS"): + # A10: rows of a profiled arm (*_NSYS) carry tracer overhead and never enter timing results + if (r["warmup"] or r["arm"] == "STUB" or r["arm"].endswith("_NSYS") or cr in void + or (admission is not None and admission.get(cr) != "PASS")): continue if cr: cell, _, n = cr.rpartition("-t") diff --git a/bench/make_ttft_prompts.py b/bench/make_ttft_prompts.py new file mode 100755 index 0000000..9cdeb1e --- /dev/null +++ b/bench/make_ttft_prompts.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Generate prompts/ttft.jsonl (PROTOCOL.md A10 TTFT rows) from pinned source texts; stdlib only. + +usage: bench/make_ttft_prompts.py LONG2048 LONG8192 LONG32768 LONG256 OUT + +The sources are the PrefillGate long prompts (sovereign evidence/merge-train/l369/long-{2048,8192,256}.txt +@ b129e1ea) and the DRA-85 32k prompt (long-8192 x3 + long-2048 x3 + long-256 x2). Every source is +checked against the sha256 below before anything is written; a mismatch exits 2 and writes nothing. +Token counts depend on each server's tokenizer and chat template, so none is claimed here: the run +records usage.prompt_tokens for every request. +""" +import hashlib +import json +import sys + +SOURCES = { # id -> (argv index, sha256 of the source file) + "t2k": (1, "26a44c508412e213de876eb54bb90390426b086c887a68b90fa78f7470425ee3"), + "t8k": (2, "2bcc84b25c418cba83df9546344fd4ae28962c314e03defe2aab62a8e6c8abb9"), + "t32k": (3, "791ef12bc33c74cb23f3318e1543def0a07e6008aa38e8d815381687dd5098b2"), + "turn2-new": (4, "153a5f88932393b2be56fd81f8914d44218169c614ebc5b2753069c9a09bc3a1"), +} +# The assistant turn between the primed 32k user turn and the new 1k user turn. It is a fixed text, +# not the model's own reply, so the second request is byte-identical across arms. +TURN2_ASSISTANT = "I have read the whole document above and I am ready for your question about it." +TURN2_NEW_REPEAT = 4 # four copies of the 256-token PrefillGate text: about 1k new tokens + + +def main(argv): + if len(argv) != 6: + print(__doc__.strip().splitlines()[2], file=sys.stderr) + return 2 + rows = [] + for pid, (i, want) in SOURCES.items(): + data = open(argv[i], "rb").read() + got = hashlib.sha256(data).hexdigest() + if got != want: + print("%s: %s sha256 %s is not %s" % (pid, argv[i], got, want), file=sys.stderr) + return 2 + text = data.decode("utf-8") + if pid == "turn2-new": + text = "\n".join([text.rstrip("\n")] * TURN2_NEW_REPEAT) + "\n" + rows.append({"id": pid, "text": text, "source_sha256": want}) + rows.append({"id": "turn2-assistant", "text": TURN2_ASSISTANT, "source_sha256": None}) + with open(argv[5], "w") as f: + for r in rows: + f.write(json.dumps(r) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/bench/nsys_classify.py b/bench/nsys_classify.py new file mode 100755 index 0000000..4717745 --- /dev/null +++ b/bench/nsys_classify.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""PROTOCOL.md A10/A8: classify the kernels of one vLLM decode trace into the l2 timeline buckets. + +External test equipment, not part of any arm. Input: the CSV of + nsys stats -r cuda_gpu_trace -f csv <report>.nsys-rep +(columns "Start (ns)", "Duration (ns)", "Name"). Output: integer nanosecond sums and kernel counts per +bucket as JSON on stdout plus a Wolfram association on the last line; every ratio is taken in Wolfram. +Exit 0 = classified, 2 = INCONCLUSIVE (unclassified time > 10 % of total), 1 = unusable input. + +Kernel names are matched case-insensitively, first rule wins. Dense GEMMs carry no role in their +names, so their role comes from the position inside a layer: + before the token mixer -> mix (QKV / in_proj), after the mixer -> o_proj, after the post-mixer norm + -> router (gate linear), inside the MoE phase -> shared_gate_up / shared_down alternately; + any GEMM of >= 1 ms is lm_head, and steps = number of lm_head kernels. Prefill steps inside the + captured range are counted the same way; the trace covers one decode-c8 cell (A10). +""" +import csv +import json +import sys + +BUCKETS = ['gate_up', 'down', 'lm_head', 'gdn', 'mix', 'attn', 'res', 'o_proj', 'router', 'perm', + 'shared_gate_up', 'shared_down', 'act', 'sample', 'copy', 'other'] +RULES = [ # (bucket, substrings); first match wins + ('copy', ['memcpy', 'memset']), + ('moe', ['marlin_moe', 'moe_wna16', 'fused_moe', 'cutlass_moe', 'grouped']), + ('router', ['topk', 'gating', 'routing']), + ('perm', ['moe_align', 'moe_sum', 'permute', 'sort', 'count_and_sort', 'scatter', 'gather']), + ('gdn', ['gated_delta', 'recurrent', 'causal_conv1d', 'gdn', 'l2norm', 'fused_sigmoid_gating']), + ('attn', ['flashinfer', 'batchdecode', 'batchprefill', 'flash_fwd', 'fmha', 'reshape_and_cache', 'rotary']), + ('res', ['rms_norm', 'rmsnorm', 'fused_add', 'layernorm']), + ('act', ['silu', 'act_and_mul']), + ('sample', ['argmax', 'sampl', 'softmax', 'logits']), + ('gemm', ['gemm', 'gemv', 'cutlass', 'nvjet', 'cublas', 'matmul', 'splitk', 'scaled_mm', 'marlin', 'sm90_', 'sm100_']), +] +LM_HEAD_NS = 1_000_000 + + +def rule(name): + low = name.lower() + for bucket, keys in RULES: + if any(k in low for k in keys): + return bucket + return 'other' + + +def classify(rows): + ns = dict.fromkeys(BUCKETS, 0) + count = dict.fromkeys(BUCKETS, 0) + other = {} + phase, moe_gemms, shared = 'pre', 0, 0 + for start, dur, name in rows: + kind = rule(name) + if kind == 'moe': + if phase != 'moe': + phase, moe_gemms, shared = 'moe', 0, 0 + bucket = 'gate_up' if moe_gemms % 2 == 0 else 'down' + moe_gemms += 1 + elif kind == 'router': + bucket, phase = 'router', 'moe' + elif kind in ('gdn', 'attn'): + bucket, phase = kind, 'core' + elif kind == 'res': + bucket = 'res' + if phase == 'moe': + phase = 'pre' + elif kind == 'gemm': + if dur >= LM_HEAD_NS: + bucket, phase = 'lm_head', 'pre' + elif phase == 'pre': + bucket = 'mix' + elif phase == 'core': + bucket, phase = 'o_proj', 'post' + elif phase == 'post': + bucket = 'router' + else: + bucket = 'shared_gate_up' if shared % 2 == 0 else 'shared_down' + shared += 1 + else: + bucket = kind + if kind == 'other': + other[name] = other.get(name, 0) + dur + ns[bucket] += dur + count[bucket] += 1 + return ns, count, other + + +def read(path): + with open(path, newline='') as f: + reader = csv.DictReader(f) + need = {'Start (ns)', 'Duration (ns)', 'Name'} + if not reader.fieldnames or not need <= set(reader.fieldnames): + raise ValueError('missing columns %s' % sorted(need - set(reader.fieldnames or []))) + rows = [(int(r['Start (ns)']), int(r['Duration (ns)']), r['Name']) for r in reader] + rows.sort() + if not rows: + raise ValueError('no kernels') + return rows + + +def main(argv): + if len(argv) != 2: + print('usage: nsys_classify.py cuda_gpu_trace.csv', file=sys.stderr) + return 1 + try: + rows = read(argv[1]) + except (OSError, ValueError, KeyError) as e: + print('unusable input: %s' % e, file=sys.stderr) + return 1 + ns, count, other = classify(rows) + total = sum(ns.values()) + top = sorted(other.items(), key=lambda kv: -kv[1])[:10] + verdict = 'INCONCLUSIVE' if ns['other'] * 10 > total else 'CLASSIFIED' + out = dict(verdict=verdict, kernels=len(rows), total_ns=total, steps=count['lm_head'], + ns=ns, count=count, other_top=[dict(name=n, ns=v) for n, v in top]) + print(json.dumps(out, indent=1)) + assoc = ', '.join('"%s" -> %d' % (b, ns[b]) for b in BUCKETS) + print('h2hNsys = <|"total_ns" -> %d, "steps" -> %d, "ns" -> <|%s|>|>;' % (total, count['lm_head'], assoc)) + return 2 if verdict == 'INCONCLUSIVE' else 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/bench/run_arm.sh b/bench/run_arm.sh index 891112f..6b1be51 100755 --- a/bench/run_arm.sh +++ b/bench/run_arm.sh @@ -1,9 +1,12 @@ #!/usr/bin/env bash -# One arm session of the head-to-head (PROTOCOL.md sections 6-8, amendments A1-A3). -# usage: bench/run_arm.sh OURS|VLLM|SGLANG|LLAMA|LLAMA16|VLLM4|SGLANG4|LLAMA4 R1|R2 -# Holds /tmp/aien-gb10.lock for the whole session (at most 60 min), writes BOARD lines, -# starts exactly one server, runs every cell, stops the server and checks the unload. +# One arm session of the head-to-head (PROTOCOL.md sections 6-8, amendments A1-A10). +# usage: bench/run_arm.sh OURS|VLLM|SGLANG|LLAMA|LLAMA16|VLLM4|SGLANG4|LLAMA4|VLLM_<conf arm> ROUND +# VLLM_<conf arm>: any arm declared in bench/arms.conf (ARM_MODEL[...]), PROTOCOL A10. +# Holds the GB10 lock for the whole session (at most 60 min; less with H2H_DEADLINE_EPOCH), or runs +# inside the caller's exclusive spark-window (A10), writes BOARD lines, starts exactly one server, +# runs the declared cell sets (H2H_CELLS, comma list), stops the server and checks the unload. # Ends with results/logs/<ARM>-<ROUND>/DONE, or NOT_RUN (with the reason) if the arm cannot start. +# H2H_PRINT_LAUNCH=1 prints the server launch argv (one item per line) and exits with no side effect. set -u ARM=$1; ROUND=$2 REPO=${H2H_REPO:-$(cd "$(dirname "$0")/.." && pwd)} @@ -18,20 +21,36 @@ GGUF=$H2H/gguf/q36-35b-a3b-q8_0.gguf GGUF16=$H2H/gguf/q36-35b-a3b-bf16.gguf # A3 arms: SGLANG_IMG (image@digest), MODEL4 (vLLM/SGLang 4-bit checkpoint dir), GGUF4 (llama.cpp # 4-bit GGUF) are set in bench/arms.conf once verified; unset -> the arm is recorded NOT_RUN. +# A10: bench/arms.conf also declares the per-arm vLLM hooks (ARM_* arrays) and the OURS binary. SGLANG_IMG=; MODEL4=; GGUF4= +declare -A ARM_MODEL=() ARM_IMG=() ARM_UTIL=() ARM_QUANT=() ARM_KV=() ARM_ATTN=() ARM_MOE=() \ + ARM_SPEC=() ARM_PREFIX=() ARM_PROFILE=() +OURS_BIN_DIR=${OURS_BIN_DIR:-/home/drakestapleton/.local/state/aien-q36/bin-19173f9e} +OURS_BIN_SHA256=${OURS_BIN_SHA256:-19173f9ec3b609fe79af644f84741d8808b92ea8eb3ecec4bc945af6f22b3aeb} +OURS_WAVE=${OURS_WAVE:-0} # A10: AIEN_OMEGA_FP8_GROUPED_WAVE recorded and passed explicitly to OURS +NSYS_DIR=/opt/nvidia/nsight-systems/2025.3.2 [ -f "$REPO/bench/arms.conf" ] && . "$REPO/bench/arms.conf" -BOARD=/home/drakestapleton/handoffs/BOARD.md +BOARD=${H2H_BOARD:-/home/drakestapleton/handoffs/BOARD.md} VLLM_UTIL=${VLLM_UTIL:-0.50} SGLANG_MEM=${SGLANG_MEM:-0.50} RESULTS=${H2H_RESULTS:-$REPO/results} OUT=$RESULTS/raw/$ARM-$ROUND.jsonl LOGD=$RESULTS/logs/$ARM-$ROUND -if [ -e "$OUT" ] || [ -e "$LOGD" ]; then - echo "refusing to overwrite an existing session: $LOGD or $OUT" >&2 - exit 2 +DEADLINE=${H2H_DEADLINE_EPOCH:-} # A10: absolute epoch by which the whole session must have stopped +CELLSET=${H2H_CELLS:-full} # A10: comma list of full (14 cells, A3) | dra74 (7) | nsys-c8 (1) + # | ttft-fresh (1 per H2H_TTFT_PROMPTS item) | ttft-turn2 (1) +TTFT_PROMPTS=${H2H_TTFT_PROMPTS:-t2k,t8k,t32k} # A10: ttft-fresh prompts, in order +TTFT_REPS=${H2H_TTFT_REPS:-3}; TTFT_REP_BASE=${H2H_TTFT_REP_BASE:-0} # A10: reps split across slices +PREFIX_OVERRIDE=${H2H_PREFIX:-} # A10: "on" enables vLLM prefix caching for a ttft-turn2-only session +[ "$PREFIX_OVERRIDE" = on ] && ARM_PREFIX[$ARM]=on # validated in arm_preconditions before any launch +if [ "${H2H_PRINT_LAUNCH:-0}" != 1 ]; then + if [ -e "$OUT" ] || [ -e "$LOGD" ]; then + echo "refusing to overwrite an existing session: $LOGD or $OUT" >&2 + exit 2 + fi + mkdir -p "$LOGD" "$(dirname "$OUT")" + touch "$RESULTS/cell-status.jsonl" || exit 2 fi -mkdir -p "$LOGD" "$(dirname "$OUT")" -touch "$RESULTS/cell-status.jsonl" || exit 2 ts() { date -u +%Y-%m-%dT%H:%M:%SZ; } board() { echo "$(ts) HeadToHead: $*" >> "$BOARD"; echo "$(ts) $*" >> "$LOGD/session.log"; } notrun() { board "$ARM $ROUND NOT_RUN: $*"; echo "$*" > "$LOGD/NOT_RUN"; exit 4; } @@ -46,25 +65,57 @@ case $ARM in LLAMA) PORT=18192; PAT='llama-server.*--port 18192'; MID=q36; G=$GGUF; MMAP= ;; LLAMA16) PORT=18193; PAT='llama-server.*--port 18193'; MID=q36; G=$GGUF16; MMAP=--no-mmap ;; LLAMA4) PORT=18192; PAT='llama-server.*--port 18192'; MID=q36; G=$GGUF4; MMAP= ;; + VLLM_*) + [ -n "${ARM_MODEL[$ARM]:-}" ] || { echo "bad arm: $ARM is not declared in bench/arms.conf"; exit 2; } + PORT=18191; PAT='vllm serve|VLLM::|EngineCore'; MID=q36; CTR=stack-h2h-$RUN_ID; MDIR=${ARM_MODEL[$ARM]} + VLLM_IMG=${ARM_IMG[$ARM]:-$VLLM_IMG}; VLLM_UTIL=${ARM_UTIL[$ARM]:-$VLLM_UTIL} ;; *) echo "bad arm"; exit 2 ;; esac # A2: cpus 5-9,15-19 are Cortex-X925 (CPU part 0xd85), 0-4,10-14 Cortex-A725 (0xd87). -# Every server gets 9 of the 10 X925 cores; the client runs on two A725 cores. -# A4(e): the excluded X925 core is the one the nvidia-modeset kthread is on when the session takes -# the GPU lock (core 18 if it is on an A725 core), chosen by pick_srv before the server starts. +# A10 (supersedes A4(e)): the server gets the X925 cores minus core 17, minus the client and monitor +# cores, minus the core the nvidia-modeset kthread is on when the session takes the GPU lock (core 18 +# when that core is on an A725 core or already excluded, so the count is constant). Default client +# 0-1 and monitor 2 leave 8 server cores; the DRA-74 slices put the client on X925 core 5 at nice 19. X925=" 5 6 7 8 9 15 16 17 18 19 " +cpus_expand() { # "0-1,5" -> " 0 1 5 " + local IFS=, p out=" " + for p in $1; do + if [[ "$p" =~ ^([0-9]+)-([0-9]+)$ ]]; then out="$out$(seq -s ' ' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}") " + elif [[ "$p" =~ ^[0-9]+$ ]]; then out="$out$p " + else return 1; fi + done + echo "$out" +} +cpu_guard() { # A10: fail closed unless the client and monitor cores are valid and disjoint + local cli c + cli=$(cpus_expand "$CLI_CPUS") && [ "$cli" != " " ] || { echo "client cpu list '$CLI_CPUS' is invalid"; return 1; } + [[ "$MON_CPU" =~ ^[0-9]+$ ]] || { echo "MON_CPU '$MON_CPU' must be one core number"; return 1; } + for c in $cli $MON_CPU; do + [ "$c" -le 19 ] || { echo "core $c does not exist"; return 1; } + [ "$c" -lt 10 ] || [ "$c" -gt 14 ] || { echo "core $c is in the 10-14 build set other lanes use"; return 1; } + [ "$c" != 17 ] || { echo "core 17 is excluded from every session role"; return 1; } + done + case $cli in *" $MON_CPU "*) echo "MON_CPU $MON_CPU overlaps the client cores $CLI_CPUS"; return 1 ;; esac + [[ "$CLI_NICE" =~ ^[0-9]+$ ]] && [ "$CLI_NICE" -le 19 ] || { echo "client nice '$CLI_NICE' must be 0-19"; return 1; } +} pick_srv() { - local k=$(ktpsr) c + local k=$(ktpsr) c excl + cpu_guard >/dev/null || return 1 + excl=" 17$(cpus_expand "$CLI_CPUS")$MON_CPU " case $X925 in *" $k "*) ;; *) k=18 ;; esac - SRV_LIST=" "; for c in $X925; do [ "$c" = "$k" ] || SRV_LIST="$SRV_LIST$c "; done + case $excl in *" $k "*) k=18 ;; esac + excl="$excl$k " + SRV_LIST=" "; for c in $X925; do case $excl in *" $c "*) ;; *) SRV_LIST="$SRV_LIST$c " ;; esac; done + case $SRV_LIST in *" 17 "*|*" $MON_CPU "*|" ") return 1 ;; esac SRV_CPUS=$(echo $SRV_LIST | tr ' ' ',') export H2H_SRV_CPUS=$SRV_CPUS } -SRV_CPUS=5-9,15-17,19 -SRV_LIST=" 5 6 7 8 9 15 16 17 19 " -CLI_CPUS=0-1 # A5(d): A725 cores outside the 10-14 build set other lanes use -MON_CPU=2 # coremon.py (A4), an A725 core outside the server and client sets +SRV_CPUS=5-9,15-16,18-19 +SRV_LIST=" 5 6 7 8 9 15 16 18 19 " +CLI_CPUS=${H2H_CLIENT_CPUS:-0-1} # A5(d): A725 cores outside the 10-14 build set; A10: slices use 5 +CLI_NICE=${H2H_CLIENT_NICE:-0} # A10: slices run the client at nice 19 +MON_CPU=${H2H_MON_CPU:-2} # coremon.py (A4), outside the server and client sets (cpu_guard) export H2H_SRV_CPUS=$SRV_CPUS H2H_CLI_CPUS=$CLI_CPUS KT=1671 # nvidia-modeset kthread; never reniced or pinned during the study (A2) ktpsr() { awk '{print $39}' /proc/$KT/stat 2>/dev/null || echo NA; } @@ -79,7 +130,7 @@ wait_quiet() { # PROTOCOL A2: before each cell, no foreign process >20% CPU ove if python3 "$REPO/bench/quiet.py" --window 10 --max-load 0 --exclude-tree $(mytree) >> "$LOGD/quiet.jsonl"; then return 0 fi - if [ $SECONDS -ge 3000 ]; then echo "$(ts) quiet gate timeout" >> "$LOGD/session.log"; return 1; fi + if [ "$(date +%s)" -ge "$QUIET_AT" ]; then echo "$(ts) quiet gate timeout" >> "$LOGD/session.log"; return 1; fi done } @@ -110,18 +161,19 @@ server_pids() { start_server() { case $ARM in OURS) - ( cd /home/drakestapleton/.local/state/aien-q36/bin-19173f9e && \ - exec env AIEN_Q36_STROKE=1 Q36_BATCH_BIN=bin-19173f9e AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-18190.lock \ - AIEN_GB10_LOCK_HELD=1 \ + ( cd "$OURS_BIN_DIR" && \ + exec env AIEN_Q36_STROKE=1 Q36_BATCH_BIN="$(basename "$OURS_BIN_DIR")" AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-18190.lock \ + AIEN_GB10_LOCK_HELD=1 AIEN_OMEGA_FP8_GROUPED_WAVE="$OURS_WAVE" \ taskset -c $SRV_CPUS ./aien-serve-http --engine omega --model-dir "$MODEL" --bind 127.0.0.1 --port 18190 --max-context 49152 \ --max-tokens-cap 16384 --thinking off --batch-slots 8 ) < /dev/null > "$LOGD/server.log" 2>&1 & SPID=$! ;; - VLLM|VLLM4) + VLLM|VLLM4|VLLM_*) + vllm_argv || return 1 + [ "${#DARGV[@]}" -eq 0 ] || mkdir -p "$LOGD/nsys" || return 1 # only the nsys arm mounts docker extras + printf '%s\n' "${DARGV[@]}" -v "$MDIR:/model:ro" "$VLLM_IMG" "${VARGV[@]}" > "$LOGD/launch.txt" timeout 30 docker create --pull never --rm --name "$CTR" --label "aien.stack-comparison.run=$RUN_ID" --runtime nvidia --gpus all --ipc host --network host \ - --cpuset-cpus $SRV_CPUS -v "$MDIR":/model:ro "$VLLM_IMG" vllm serve /model --served-model-name q36 \ - --host 127.0.0.1 --port 18191 \ - --max-model-len 49152 --max-num-seqs 32 --gpu-memory-utilization "$VLLM_UTIL" \ - --language-model-only < /dev/null > "$LOGD/container-id.txt" 2> "$LOGD/server.log" || return 1 + --cpuset-cpus $SRV_CPUS "${DARGV[@]}" -v "$MDIR":/model:ro "$VLLM_IMG" "${VARGV[@]}" \ + < /dev/null > "$LOGD/container-id.txt" 2> "$LOGD/server.log" || return 1 docker start --attach "$CTR" < /dev/null >> "$LOGD/server.log" 2>&1 & SPID=$! ;; SGLANG|SGLANG4) @@ -141,6 +193,33 @@ start_server() { printf '%s %s\n' "$SPID" "${H2H_PID_START[$SPID]}" > "$LOGD/server-identity.txt" } +vllm_argv() { # A10: VARGV = argv inside the container, DARGV = extra docker create options + VARGV=(vllm serve /model --served-model-name q36 --host 127.0.0.1 --port 18191 --max-model-len 49152 + --max-num-seqs 32 --gpu-memory-utilization "$VLLM_UTIL" --language-model-only) + DARGV=() + case $ARM in VLLM|VLLM4) return 0 ;; esac # A1/A3 arms: argv unchanged + [ -z "${ARM_QUANT[$ARM]:-}" ] || VARGV+=(--quantization "${ARM_QUANT[$ARM]}") + [ -z "${ARM_KV[$ARM]:-}" ] || VARGV+=(--kv-cache-dtype "${ARM_KV[$ARM]}") + [ -z "${ARM_ATTN[$ARM]:-}" ] || VARGV+=(--attention-backend "${ARM_ATTN[$ARM]}") + [ -z "${ARM_MOE[$ARM]:-}" ] || VARGV+=(--moe-backend "${ARM_MOE[$ARM]}") + [ -z "${ARM_SPEC[$ARM]:-}" ] || VARGV+=(--speculative-config "${ARM_SPEC[$ARM]}") + case ${ARM_PREFIX[$ARM]:-} in + off) VARGV+=(--no-enable-prefix-caching) ;; + on) VARGV+=(--enable-prefix-caching) ;; + '') ;; + *) echo "ARM_PREFIX[$ARM]='${ARM_PREFIX[$ARM]}' must be on, off or empty" >&2; return 1 ;; + esac + case ${ARM_PROFILE[$ARM]:-} in + '') ;; + nsys) # A10: kernel timeline of the cudaProfilerApi range opened by POST /start_profile + DARGV=(-v "$NSYS_DIR:/nsys:ro" -v "$LOGD/nsys:/nsys-out") + VARGV=(/nsys/bin/nsys profile -t cuda,nvtx --cuda-graph-trace=node --capture-range=cudaProfilerApi + --capture-range-end=repeat -f true -o "/nsys-out/$ARM-$ROUND" "${VARGV[@]}" + --profiler-config '{"profiler":"cuda"}') ;; + *) echo "ARM_PROFILE[$ARM]='${ARM_PROFILE[$ARM]}' must be nsys or empty" >&2; return 1 ;; + esac +} + stop_server() { if [ -n "$CTR" ] && docker inspect "$CTR" >/dev/null 2>&1; then local owner @@ -170,6 +249,69 @@ loopback_only() { # A5(f): every listener on the test port must be 127.0.0.1, e [ -s "$LOGD/listen.txt" ] && ! awk '{print $4}' "$LOGD/listen.txt" | grep -qv '^127\.0\.0\.1:' } +window_held() { # A10: inside the runner's exclusive spark-window, the window holds the GB10 lock + local id + [ "${AIEN_GB10_LOCK_HELD:-}" = 1 ] && [ -n "${SPARK_WINDOW:-}" ] && [ -n "${SPARK_WINDOW_DIR:-}" ] \ + || { echo "AIEN_GB10_LOCK_HELD/SPARK_WINDOW/SPARK_WINDOW_DIR incomplete"; return 1; } + id=$(timeout 10 "${SPARK_WINDOW_BIN:-spark-window}" id 2>/dev/null) || { echo "spark-window id failed"; return 1; } + [ "$id" = "$SPARK_WINDOW" ] || { echo "held window '$id' is not SPARK_WINDOW '$SPARK_WINDOW'"; return 1; } + [ "$(cat "$SPARK_WINDOW_DIR/gb10" 2>/dev/null)" = exclusive ] || { echo "window $id does not hold the GB10 exclusively"; return 1; } +} + +arm_preconditions() { # prints the NOT_RUN reason and returns 1; no side effects + case $ARM in + SGLANG*) [ -n "$SGLANG_IMG" ] || { echo "no SGLang image verified for aarch64/sm_121 (bench/arms.conf)"; return 1; } ;; + esac + case $ARM in + VLLM4|SGLANG4) [ -n "$MODEL4" ] && [ -f "$MODEL4/config.json" ] || { echo "no 4-bit checkpoint (bench/arms.conf MODEL4)"; return 1; } ;; + LLAMA4) [ -n "$GGUF4" ] && [ -f "$GGUF4" ] || { echo "no 4-bit GGUF (bench/arms.conf GGUF4)"; return 1; } ;; + VLLM_*) [ -f "$MDIR/config.json" ] || { echo "$ARM model dir $MDIR has no config.json"; return 1; } ;; + OURS) + local sha + sha=$(sha256sum "$OURS_BIN_DIR/aien-serve-http" 2>/dev/null | cut -d' ' -f1) + [ "$sha" = "$OURS_BIN_SHA256" ] || { echo "OURS binary $OURS_BIN_DIR/aien-serve-http sha256 '${sha:-missing}' is not $OURS_BIN_SHA256"; return 1; } + [[ "$OURS_WAVE" =~ ^[01]$ ]] || { echo "OURS_WAVE must be 0 or 1"; return 1; } ;; + esac + cpu_guard || return 1 + if [ -n "$DEADLINE" ]; then + [[ "$DEADLINE" =~ ^[0-9]+$ ]] && [ "$DEADLINE" -gt $(( $(date +%s) + 600 )) ] \ + || { echo "H2H_DEADLINE_EPOCH '$DEADLINE' must be an epoch more than 600 s ahead"; return 1; } + fi + if [ -n "$PREFIX_OVERRIDE" ]; then + [ "$PREFIX_OVERRIDE" = on ] && [[ $ARM == VLLM_* ]] && [ "$CELLSET" = ttft-turn2 ] \ + || { echo "H2H_PREFIX=on applies only to a VLLM_* arm running H2H_CELLS=ttft-turn2 alone"; return 1; } + fi + [[ "$TTFT_REPS" =~ ^[1-9]$ && "$TTFT_REP_BASE" =~ ^[0-9]{1,2}$ ]] \ + || { echo "H2H_TTFT_REPS must be 1-9 and H2H_TTFT_REP_BASE 0-99"; return 1; } + local set seen=, + for set in ${CELLSET//,/ }; do + [[ $seen != *",$set,"* ]] || { echo "H2H_CELLS '$CELLSET' names $set twice"; return 1; } + seen=$seen$set, + case $set in + full|dra74) [ "${ARM_PROFILE[$ARM]:-}" = "" ] || { echo "$ARM is a profiling arm; it runs only cell set nsys-c8"; return 1; } ;; + nsys-c8) [ "${ARM_PROFILE[$ARM]:-}" = nsys ] && [ -x "$NSYS_DIR/bin/nsys" ] \ + || { echo "cell set nsys-c8 needs an ARM_PROFILE=nsys arm and $NSYS_DIR/bin/nsys"; return 1; } + [ "$CELLSET" = nsys-c8 ] || { echo "cell set nsys-c8 runs alone"; return 1; } ;; + ttft-fresh|ttft-turn2) + [[ $ARM == OURS || $ARM == VLLM_* ]] && [ "${ARM_PROFILE[$ARM]:-}" = "" ] \ + || { echo "TTFT cell sets run on OURS and unprofiled VLLM_* arms only"; return 1; } ;;& + ttft-fresh) + [ "${ARM_PREFIX[$ARM]:-}" != on ] || { echo "ttft-fresh needs prefix caching off"; return 1; } + local p pseen=, + for p in ${TTFT_PROMPTS//,/ }; do + [[ $p =~ ^t(2|8|32)k$ && $pseen != *",$p,"* ]] || { echo "H2H_TTFT_PROMPTS '$TTFT_PROMPTS' must list distinct t2k, t8k, t32k"; return 1; } + pseen=$pseen$p, + done + [ "$pseen" != , ] || { echo "H2H_TTFT_PROMPTS is empty"; return 1; } ;; + ttft-turn2) + [[ $ARM != VLLM_* ]] || [ "$PREFIX_OVERRIDE" = on ] \ + || { echo "ttft-turn2 on a vLLM arm needs H2H_PREFIX=on (the cached row)"; return 1; } ;; + *) echo "H2H_CELLS '$CELLSET': each item must be full, dra74, nsys-c8, ttft-fresh or ttft-turn2"; return 1 ;; + esac + done + [ "$seen" != , ] || { echo "H2H_CELLS is empty"; return 1; } +} + cell_status() { python3 -c 'import json,sys; print(json.dumps({"cell_run":sys.argv[1],"status":sys.argv[2]}))' \ "$1" "$2" >> "$RESULTS/cell-status.jsonl" @@ -190,7 +332,7 @@ cell() { # metric concurrency max_tokens promptfile [extra] CMON_PID=$cm h2h_track "$cm" || return 1 t0=$(date +%s) - taskset -c $CLI_CPUS python3 "$REPO/bench/bench.py" --port $PORT --model $MID --arm $ARM --round $ROUND --metric "$metric" \ + taskset -c $CLI_CPUS nice -n "$CLI_NICE" python3 "$REPO/bench/bench.py" --port $PORT --model $MID --arm $ARM --round $ROUND --metric "$metric" \ --prompts "$REPO/prompts/$pf" --concurrency $c --max-tokens $mt --out "$OUT" --cell-run "$id" "$@" 2>> "$LOGD/client.log" & CPID=$! h2h_track "$CPID" || return 1 wait "$CPID"; clientrc=$? @@ -246,8 +388,8 @@ else: } mark_complete() { - if [ "$CELLS_COMPLETED" -ne 14 ] || [ -e "$LOGD/TIMEOUT" ]; then - echo "incomplete: $CELLS_COMPLETED/14 accepted cells; see session.log" > "$LOGD/INCOMPLETE" + if [ "$CELLS_COMPLETED" -ne "${EXPECTED_CELLS:-14}" ] || [ -e "$LOGD/TIMEOUT" ]; then + echo "incomplete: $CELLS_COMPLETED/${EXPECTED_CELLS:-14} accepted cells; see session.log" > "$LOGD/INCOMPLETE" return 1 fi touch "$LOGD/DONE" @@ -256,12 +398,12 @@ mark_complete() { start_watchdog() { ( if [ "$#" -ge 1 ]; then sleep "$1"; - else delay=$((3300 - SECONDS)); [ "$delay" -le 0 ] || sleep "$delay"; fi - board "T-5 $ARM $ROUND: cleanup reserved within 60-minute limit" + else delay=$((WARN_AT - $(date +%s))); [ "$delay" -le 0 ] || sleep "$delay"; fi + board "T-$(( (${STOP_AT:-0} - ${WARN_AT:-0}) / 60 )) $ARM $ROUND: cleanup reserved before the session stop time" if [ "$#" -ge 2 ]; then sleep "$2"; - else delay=$((3540 - SECONDS)); [ "$delay" -le 0 ] || sleep "$delay"; fi + else delay=$((STOP_AT - $(date +%s))); [ "$delay" -le 0 ] || sleep "$delay"; fi touch "$LOGD/TIMEOUT" - board "$ARM $ROUND reached 59 min; stopping own session with cleanup time reserved" + board "$ARM $ROUND reached its stop time; stopping own session with cleanup time reserved" kill -TERM $$ ) & WD=$! h2h_track "$WD" @@ -319,19 +461,26 @@ cleanup_session() { # PROTOCOL A2 (Main's gate): start only when no foreign process used >20% CPU for 60 s and load1 < 6, # before taking the lock, so the 60-min hold is not spent waiting SPID= CPID= CMON_PID= WD= SAMP= VMS= BASE= GPU_LOCK_HELD=0 GPU_LOCK_RELEASE=1 +if [ "${H2H_PRINT_LAUNCH:-0}" = 1 ]; then # A10: show the launch, touch nothing + why=$(arm_preconditions) || { echo "NOT_RUN: $why" >&2; exit 4; } + pick_srv || { echo "NOT_RUN: core guard" >&2; exit 4; } + echo "server_cpus $SRV_CPUS client_cpus $CLI_CPUS client_nice $CLI_NICE monitor_cpu $MON_CPU" >&2 + case $ARM in + VLLM|VLLM4|VLLM_*) vllm_argv || exit 4; printf '%s\n' "${DARGV[@]}" -v "$MDIR:/model:ro" "$VLLM_IMG" "${VARGV[@]}" ;; + OURS) printf '%s\n' "AIEN_OMEGA_FP8_GROUPED_WAVE=$OURS_WAVE" "$OURS_BIN_DIR/aien-serve-http" ;; + *) echo "print mode covers the OURS and vLLM arms" >&2 ;; + esac + exit 0 +fi trap cleanup_session EXIT trap 'exit 130' INT trap 'exit 143' TERM CELLS_COMPLETED=0 SESSION_RC=1 -case $ARM in - SGLANG*) [ -n "$SGLANG_IMG" ] || notrun "no SGLang image verified for aarch64/sm_121 (bench/arms.conf)" ;; -esac -case $ARM in - VLLM4|SGLANG4) [ -n "$MODEL4" ] && [ -f "$MODEL4/config.json" ] || notrun "no 4-bit checkpoint (bench/arms.conf MODEL4)" ;; - LLAMA4) [ -n "$GGUF4" ] && [ -f "$GGUF4" ] || notrun "no 4-bit GGUF (bench/arms.conf GGUF4)" ;; -esac -until python3 "$REPO/bench/quiet.py" --window 60 --max-load 6 --exclude-tree $$ >> "$LOGD/quiet.jsonl"; do :; done +why=$(arm_preconditions) || notrun "$why" +until python3 "$REPO/bench/quiet.py" --window 60 --max-load 6 --exclude-tree $$ >> "$LOGD/quiet.jsonl"; do + [ -z "$DEADLINE" ] || [ "$(date +%s)" -lt $((DEADLINE - 600)) ] || notrun "no quiet 60 s window before deadline - 600 s" +done for pair in LLAMA:convert.log LLAMA16:convert-bf16.log; do # the GGUF must be fully written [ "$ARM" = "${pair%%:*}" ] || continue CL=$H2H/gguf/${pair#*:} @@ -340,7 +489,12 @@ for pair in LLAMA:convert.log LLAMA16:convert-bf16.log; do # the GGUF must be f sleep 30 done done -if [ "${H2H_GPU_LOCK_FD:-}" = 9 ]; then +if [ "${AIEN_GB10_LOCK_HELD:-}" = 1 ] || [ -n "${SPARK_WINDOW:-}" ]; then + # A10: the runner's spark-window holds /tmp/aien-gb10.lock; waiting on it here would deadlock + why=$(window_held) || notrun "in-window lock check failed: $why" + GPU_LOCK_RELEASE=0 + echo "$(ts) in spark-window $SPARK_WINDOW (gb10 exclusive); no flock taken" >> "$LOGD/session.log" +elif [ "${H2H_GPU_LOCK_FD:-}" = 9 ]; then GPU_LOCK_RELEASE=0 [ "$(readlink /proc/$$/fd/9)" = /tmp/aien-gb10.lock ] || notrun "inherited GPU-lock descriptor names another file" flock -n 9 || notrun "inherited GPU-lock descriptor cannot acquire the lock" @@ -351,14 +505,25 @@ else fi GPU_LOCK_HELD=1 SECONDS=0 +LOCK_EPOCH=$(date +%s); STOP_AT=$((LOCK_EPOCH + 3540)); WARN_AT=$((LOCK_EPOCH + 3300)); QUIET_AT=$((LOCK_EPOCH + 3000)) +if [ -n "$DEADLINE" ] && [ $((DEADLINE - 60)) -lt "$STOP_AT" ]; then # A10 deadline mode + STOP_AT=$((DEADLINE - 60)); WARN_AT=$((STOP_AT - 120)); QUIET_AT=$((STOP_AT - 120)) +fi +echo "lock_epoch $LOCK_EPOCH warn_at $WARN_AT stop_at $STOP_AT quiet_at $QUIET_AT cells $CELLSET" >> "$LOGD/session.log" board "START $ARM $ROUND gpu lock held (<=60 min; test port $PORT; live 18091 untouched)" echo "kthread_psr_start $(ktpsr)" >> "$LOGD/session.log" -pick_srv +pick_srv || notrun "core guard: $(cpu_guard || true)" echo "server_cpus $SRV_CPUS client_cpus $CLI_CPUS monitor_cpu $MON_CPU" >> "$LOGD/session.log" timeout 5 nvidia-smi --query-compute-apps=pid,name,used_memory --format=csv > "$LOGD/gpu-before.csv" 2>&1 || notrun "GPU process inventory failed" GPU_ROWS=$(timeout 5 nvidia-smi --query-compute-apps=pid --format=csv,noheader,nounits) || notrun "GPU process inventory failed" [ -z "$GPU_ROWS" ] || notrun "another model/process is resident; shared-service window must be coordinated before launch" BASE=$(memavail); echo "baseline_memavail_kB $BASE" > "$LOGD/mem-baseline.txt" +sha256sum "$0" "$REPO/bench/bench.py" "$REPO/bench/arms.conf" "$REPO/bench/session-lifecycle.sh" \ + "$REPO/prompts/"*.jsonl > "$LOGD/driver-sha256.txt" 2>&1 +case $ARM in + OURS) printf 'bin_dir %s\nsha256 %s\nAIEN_OMEGA_FP8_GROUPED_WAVE=%s\n' "$OURS_BIN_DIR" "$OURS_BIN_SHA256" "$OURS_WAVE" > "$LOGD/ours-bin.txt" ;; + VLLM*) docker image inspect -f '{{.Id}} {{json .RepoDigests}}' "$VLLM_IMG" > "$LOGD/image.txt" 2>&1 || notrun "vLLM image $VLLM_IMG not present locally" ;; +esac sampler > "$LOGD/mem.tsv" & SAMP=$! h2h_track "$SAMP" || exit 1 vmstat -t 1 > "$LOGD/vmstat.txt" & VMS=$! @@ -370,25 +535,76 @@ if ready && loopback_only; then echo "load_seconds $(echo "$(date +%s.%N) - $T0" | bc)" >> "$LOGD/session.log" case $ARM in LLAMA*) LD_LIBRARY_PATH=$CUDART_DIR:$LLAMA_DIR "$LLAMA_DIR/llama-server" --version > "$LOGD/version.txt" 2>&1 ;; esac [ -n "$CTR" ] && docker exec $CTR pip list 2>/dev/null | grep -i -E '^(vllm|sglang|torch|transformers|flashinfer)' > "$LOGD/version.txt" - for c in 1 4 8 16; do + EXPECTED_CELLS=0 + for set in ${CELLSET//,/ }; do [ -e "$LOGD/TIMEOUT" ] && break - cell decode-c$c $c 256 decode.jsonl --warmup 2 --reps 3 || break - done - for p in p256 p2k p8k; do - [ "$CELLS_COMPLETED" -ge 4 ] || break - [ -e "$LOGD/TIMEOUT" ] && break - cell prefill-$p 1 1 prefill.jsonl --select $p --warmup 2 --reps 3 --nonce || break - done - if [ "$CELLS_COMPLETED" -eq 7 ] && [ ! -e "$LOGD/TIMEOUT" ]; then - cell agree 1 128 decode.jsonl --warmup 0 --reps 16 || true - fi - # A3 grid: N = 1, 8, 32 streams x prompt 512 / 8k tokens, 256 new tokens, 1 warmup + 3 runs - for p in p512 p8k; do - [ "$CELLS_COMPLETED" -ge 8 ] || break - for n in 1 8 32; do - [ -e "$LOGD/TIMEOUT" ] && break - cell grid-$p-n$n $n 256 prefill.jsonl --select $p --warmup 1 --reps 3 --nonce || break 2 - done + SET0=$CELLS_COMPLETED + case $set in + full) + n=14 + for c in 1 4 8 16; do + [ -e "$LOGD/TIMEOUT" ] && break + cell decode-c$c $c 256 decode.jsonl --warmup 2 --reps 3 || break + done + for p in p256 p2k p8k; do + [ $((CELLS_COMPLETED - SET0)) -ge 4 ] || break + [ -e "$LOGD/TIMEOUT" ] && break + cell prefill-$p 1 1 prefill.jsonl --select $p --warmup 2 --reps 3 --nonce || break + done + if [ $((CELLS_COMPLETED - SET0)) -eq 7 ] && [ ! -e "$LOGD/TIMEOUT" ]; then + cell agree 1 128 decode.jsonl --warmup 0 --reps 16 || true + fi + # A3 grid: N = 1, 8, 32 streams x prompt 512 / 8k tokens, 256 new tokens, 1 warmup + 3 runs + for p in p512 p8k; do + [ $((CELLS_COMPLETED - SET0)) -ge 8 ] || break + for n2 in 1 8 32; do + [ -e "$LOGD/TIMEOUT" ] && break + cell grid-$p-n$n2 $n2 256 prefill.jsonl --select $p --warmup 1 --reps 3 --nonce || break 2 + done + done ;; + dra74) # A10: the DRA-74 decode ladder and prefill cells, one arm per chip slice + n=7 + for c in 1 4 8 16; do + [ -e "$LOGD/TIMEOUT" ] && break + cell decode-c$c $c 256 decode.jsonl --warmup 2 --reps 3 || break + done + for p in p256 p2k p8k; do + [ $((CELLS_COMPLETED - SET0)) -ge 4 ] || break + [ -e "$LOGD/TIMEOUT" ] && break + cell prefill-$p 1 1 prefill.jsonl --select $p --warmup 2 --reps 3 --nonce || break + done ;; + nsys-c8) # A10: one profiled decode-c8 cell; its rows never enter timing results (extract.py) + n=1 + if curl -sf -X POST "http://127.0.0.1:$PORT/start_profile" > /dev/null; then + cell decode-c8 8 256 decode.jsonl --warmup 1 --reps 1 || true + curl -sf -X POST "http://127.0.0.1:$PORT/stop_profile" > /dev/null || echo "$(ts) stop_profile failed" >> "$LOGD/session.log" + last=-1 + for i in $(seq 1 36); do # the report is written after the range ends; wait for a stable size + sleep 5 + size=$(cat "$LOGD"/nsys/*.nsys-rep 2>/dev/null | wc -c) + [ "$size" -gt 0 ] && [ "$size" = "$last" ] && break + last=$size + done + if [ "$size" -gt 0 ] && [ "$size" = "$last" ]; then echo "nsys_report_bytes $size" >> "$LOGD/session.log" + else echo "$(ts) nsys report missing or still growing after 180 s" >> "$LOGD/session.log"; CELLS_COMPLETED=$SET0; fi + else + echo "$(ts) start_profile failed; no profiled cell" >> "$LOGD/session.log" + fi ;; + ttft-fresh) # A10: fresh-prompt TTFT; per-rep nonce, byte-identical requests on every arm + n=$(echo ${TTFT_PROMPTS//,/ } | wc -w) + for p in ${TTFT_PROMPTS//,/ }; do + [ -e "$LOGD/TIMEOUT" ] && break + cell ttft-fresh-${p#t} 1 1 ttft.jsonl --select $p --ttft fresh --warmup 1 --warm-select t2k \ + --reps $TTFT_REPS --rep-base $TTFT_REP_BASE || break + done ;; + ttft-turn2) # A10: prime the 32k turn, then the conversation + ~1k new tokens; OURS re-reads it + n=1 + case $ARM in OURS) t2=reread ;; *) t2=cached ;; esac + cell ttft-turn2-$t2 1 1 ttft.jsonl --select t32k --ttft turn2 --warmup 1 --warm-select t2k \ + --reps $TTFT_REPS --rep-base $TTFT_REP_BASE ;; + esac + EXPECTED_CELLS=$((EXPECTED_CELLS + n)) + [ $((CELLS_COMPLETED - SET0)) -eq "$n" ] || break # a short cell set ends the session INCOMPLETE done board "$ARM $ROUND cells done at $SECONDS s" if mark_complete; then SESSION_RC=0; fi diff --git a/bench/test-extract-admission.py b/bench/test-extract-admission.py index 0a5661f..5936ee1 100644 --- a/bench/test-extract-admission.py +++ b/bench/test-extract-admission.py @@ -11,22 +11,24 @@ import unittest HERE = Path(__file__).resolve().parent class AdmissionTests(unittest.TestCase): - def extract(self, statuses): + def extract(self, statuses, arm='CONTROL', chunks=None, completion_tokens=2, stdout=False): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) raw = root / 'results/raw' raw.mkdir(parents=True) - row = dict(cell_run='CONTROL-R0-decode-t1', warmup=False, arm='CONTROL', + row = dict(cell_run=arm + '-R0-decode-t1', warmup=False, arm=arm, round='R0', metric='decode', rep=0, batch_id='fixture', stream_index=0, load1_start=0, t_send=1, t_first=2, t_last=3, error=None, http_status=200, - usage=dict(prompt_tokens=5, completion_tokens=2)) - (raw / 'CONTROL-R0.jsonl').write_text(json.dumps(row) + '\n') + usage=dict(prompt_tokens=5, completion_tokens=completion_tokens)) + if chunks is not None: + row['chunks'] = chunks + (raw / (arm + '-R0.jsonl')).write_text(json.dumps(row) + '\n') if statuses is not None: entries = [dict(cell_run=row['cell_run'], status=status) for status in statuses] (root / 'results/cell-status.jsonl').write_text(''.join(json.dumps(x)+'\n' for x in entries)) result = subprocess.run([sys.executable, os.environ.get('H2H_EXTRACT_SCRIPT', str(HERE / 'extract.py')), tmp], text=True, capture_output=True, timeout=5, check=True) - return '"CONTROL"' in result.stdout + return result.stdout if stdout else json.dumps(arm) in result.stdout def test_only_single_pass_is_admitted(self): self.assertTrue(self.extract(['PASS'])) @@ -40,6 +42,15 @@ class AdmissionTests(unittest.TestCase): self.assertFalse(self.extract(statuses)) def test_historical_runs_keep_explicit_legacy_behavior(self): self.assertTrue(self.extract(None)) + def test_profiled_arm_rows_never_enter_timing(self): + # A10: *_NSYS rows are excluded; the same row under the unprofiled arm name is the control + self.assertFalse(self.extract(['PASS'], arm='VLLM_NVFP4_NSYS')) + self.assertTrue(self.extract(['PASS'], arm='VLLM_NVFP4')) + def test_mtp_rows_count_usage_tokens_not_stream_chunks(self): + # A10: an MTP stream delivers several tokens per chunk; the row carries usage.completion_tokens + out = self.extract(['PASS'], arm='VLLM_FP8_MTP', chunks=3, completion_tokens=9, stdout=True) + fields = out[out.index('{"VLLM_FP8_MTP"'):].split('}')[0].split(', ') + self.assertEqual(fields[11], '9') if __name__ == '__main__': unittest.main() diff --git a/bench/test-nsys-classify.py b/bench/test-nsys-classify.py new file mode 100755 index 0000000..cafe6e7 --- /dev/null +++ b/bench/test-nsys-classify.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""PROTOCOL.md A10: nsys_classify.py on a synthetic decode step, with a negative control.""" +import csv +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent + +# One synthetic step: a GDN layer, an attention layer, final norm, lm_head, sampling. +LAYER_GDN = [('fused_add_rms_norm_kernel', 100), ('cutlass_scaled_mm_sm100', 300), + ('causal_conv1d_update_kernel', 50), ('fused_recurrent_gated_delta_rule_fwd', 400), + ('rms_norm_kernel', 30), ('cutlass_scaled_mm_sm100', 200), + ('fused_add_rms_norm_kernel', 100), ('cutlass_scaled_mm_sm100', 40), + ('topkGatingSoftmax', 60), ('moe_align_block_size_kernel', 20), + ('marlin_moe_wna16::Marlin<4>', 2000), ('act_and_mul_kernel', 30), ('marlin_moe_wna16::Marlin<4>', 1500), + ('cutlass_scaled_mm_sm100', 120), ('cutlass_scaled_mm_sm100', 90), ('moe_sum_kernel', 10)] +LAYER_ATTN = [('fused_add_rms_norm_kernel', 100), ('cutlass_scaled_mm_sm100', 250), + ('rotary_embedding_kernel', 20), ('reshape_and_cache_flash_kernel', 15), + ('BatchDecodeWithPagedKVCacheKernel', 500), ('cutlass_scaled_mm_sm100', 210), + ('fused_add_rms_norm_kernel', 100), ('cutlass_scaled_mm_sm100', 40), + ('topkGatingSoftmax', 60), ('marlin_moe_wna16::Marlin<4>', 2100), + ('marlin_moe_wna16::Marlin<4>', 1600), ('cutlass_scaled_mm_sm100', 130), ('cutlass_scaled_mm_sm100', 95)] +TAIL = [('rms_norm_kernel', 40), ('nvjet_tst_bf16_gemm', 4_000_000), ('argmax_kernel', 25), + ('Memcpy DtoH (Device -> Pageable)', 8)] + + +def run(kernels): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp, 'trace.csv') + with open(path, 'w', newline='') as f: + w = csv.writer(f) + w.writerow(['Start (ns)', 'Duration (ns)', 'CorrId', 'Name']) + t = 1000 + for i, (name, dur) in enumerate(kernels): + w.writerow([t, dur, i, name]) + t += dur + 5 + r = subprocess.run([sys.executable, str(HERE / 'nsys_classify.py'), str(path)], + capture_output=True, text=True, timeout=10) + out = json.loads(r.stdout[:r.stdout.rindex('}') + 1]) if r.stdout.strip() else None + return r.returncode, out, r.stdout + + +class ClassifyTests(unittest.TestCase): + def test_synthetic_step(self): + rc, out, stdout = run(LAYER_GDN + LAYER_ATTN + TAIL) + self.assertEqual(rc, 0, stdout) + ns = out['ns'] + self.assertEqual(out['steps'], 1) + self.assertEqual(ns['gate_up'], 2000 + 2100) + self.assertEqual(ns['down'], 1500 + 1600) + self.assertEqual(ns['lm_head'], 4_000_000) + self.assertEqual(ns['gdn'], 450) + self.assertEqual(ns['attn'], 535) + self.assertEqual(ns['mix'], 300 + 250) + self.assertEqual(ns['o_proj'], 200 + 210) + self.assertEqual(ns['router'], 40 + 60 + 40 + 60) + self.assertEqual(ns['shared_gate_up'], 120 + 130) + self.assertEqual(ns['shared_down'], 90 + 95) + self.assertEqual(ns['perm'], 30) + self.assertEqual(ns['other'], 0) + self.assertEqual(out['total_ns'], sum(d for _, d in LAYER_GDN + LAYER_ATTN + TAIL)) + self.assertIn('h2hNsys = <|"total_ns" -> %d' % out['total_ns'], stdout.splitlines()[-1]) + + def test_unknown_kernels_are_inconclusive(self): + # negative control: same step with most time in kernels the rules do not know + rc, out, _ = run(LAYER_GDN + [('mystery_kernel_a', 9_000_000), ('mystery_kernel_b', 10)] + TAIL) + self.assertEqual(rc, 2) + self.assertEqual(out['verdict'], 'INCONCLUSIVE') + self.assertEqual(out['other_top'][0], dict(name='mystery_kernel_a', ns=9_000_000)) + + def test_missing_columns_are_unusable(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp, 'bad.csv') + path.write_text('Start,Name\n1,x\n') + r = subprocess.run([sys.executable, str(HERE / 'nsys_classify.py'), str(path)], + capture_output=True, text=True, timeout=10) + self.assertEqual(r.returncode, 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/bench/test-run-arm-dra74.py b/bench/test-run-arm-dra74.py new file mode 100755 index 0000000..8737248 --- /dev/null +++ b/bench/test-run-arm-dra74.py @@ -0,0 +1,277 @@ +#!/usr/bin/env python3 +"""PROTOCOL.md A10 (DRA-74): print-launch argv, OURS binary pin, in-window lock, deadline, cell sets, +TTFT cell sets, the turn-2 prefix-cache override and the session completion (DONE) path.""" +import hashlib +import os +from pathlib import Path +import shlex +import subprocess +import tempfile +import time +import unittest + +HERE = Path(__file__).resolve().parent +SOURCE = (HERE / 'run_arm.sh').read_text() +LEGACY_VARGV = ['vllm', 'serve', '/model', '--served-model-name', 'q36', '--host', '127.0.0.1', '--port', '18191', + '--max-model-len', '49152', '--max-num-seqs', '32', '--gpu-memory-utilization', '0.50', + '--language-model-only'] + + +def piece(start, end): + return SOURCE[SOURCE.index(start):SOURCE.index(end)] + + +def print_launch(arm, **env): + with tempfile.TemporaryDirectory() as tmp: + full = dict(os.environ, H2H_PRINT_LAUNCH='1', H2H_RESULTS=tmp + '/results', H2H_BOARD=tmp + '/BOARD') + full.update(env) + r = subprocess.run(['bash', str(HERE / 'run_arm.sh'), arm, 'D1'], env=full, capture_output=True, + text=True, timeout=30) + touched = os.listdir(tmp) + return r, touched + + +class PrintLaunchTests(unittest.TestCase): + def test_legacy_vllm_argv_is_unchanged(self): + r, touched = print_launch('VLLM') + self.assertEqual(r.returncode, 0, r.stderr) + lines = r.stdout.splitlines() + self.assertEqual(lines[0:2], ['-v', '/home/drakestapleton/models/qwen3.6-35b-a3b-fp8-95a723d0:/model:ro']) + self.assertEqual(lines[3:], LEGACY_VARGV) + self.assertEqual(touched, [], 'print mode must not create the session') + + def test_comparator_arms_append_their_hooks(self): + cases = { + 'VLLM_FP8': ['--kv-cache-dtype', 'auto', '--attention-backend', 'FLASH_ATTN', '--moe-backend', 'deep_gemm', + '--no-enable-prefix-caching'], + 'VLLM_FP8_MTP': ['--kv-cache-dtype', 'auto', '--attention-backend', 'FLASH_ATTN', '--moe-backend', 'deep_gemm', + '--speculative-config', '{"method":"mtp","num_speculative_tokens":3}', + '--no-enable-prefix-caching'], + 'VLLM_NVFP4': ['--quantization', 'modelopt', '--kv-cache-dtype', 'fp8', '--attention-backend', 'FLASHINFER', + '--moe-backend', 'marlin', '--no-enable-prefix-caching'], + } + for arm, tail in cases.items(): + with self.subTest(arm=arm): + r, _ = print_launch(arm) + self.assertEqual(r.returncode, 0, r.stderr) + lines = r.stdout.splitlines() + self.assertEqual(lines[3:3 + len(LEGACY_VARGV)], LEGACY_VARGV) + self.assertEqual(lines[3 + len(LEGACY_VARGV):], tail) + + def test_profile_arm_runs_only_its_cell_set(self): + r, _ = print_launch('VLLM_NVFP4_NSYS', H2H_CELLS='dra74') + self.assertEqual(r.returncode, 4) + r, _ = print_launch('VLLM_NVFP4_NSYS', H2H_CELLS='nsys-c8') + self.assertEqual(r.returncode, 0, r.stderr) + lines = r.stdout.splitlines() + self.assertIn('/nsys/bin/nsys', lines) + self.assertIn('--capture-range=cudaProfilerApi', lines) + self.assertEqual(lines[-2:], ['--profiler-config', '{"profiler":"cuda"}']) + r, _ = print_launch('VLLM_FP8', H2H_CELLS='nsys-c8') + self.assertEqual(r.returncode, 4, 'an unprofiled arm must refuse the profile cell set') + + def test_ours_binary_pin(self): + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, 'aien-serve-http').write_bytes(b'fixture server\n') + sha = hashlib.sha256(b'fixture server\n').hexdigest() + r, _ = print_launch('OURS', OURS_BIN_DIR=tmp, OURS_BIN_SHA256=sha) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.splitlines(), ['AIEN_OMEGA_FP8_GROUPED_WAVE=0', tmp + '/aien-serve-http']) + r, _ = print_launch('OURS', OURS_BIN_DIR=tmp, OURS_BIN_SHA256='0' * 64) + self.assertEqual(r.returncode, 4) + self.assertIn('sha256', r.stderr) + r, _ = print_launch('OURS', OURS_BIN_DIR=tmp, OURS_BIN_SHA256=sha, OURS_WAVE='2') + self.assertEqual(r.returncode, 4) + + def test_deadline_and_cell_set_are_checked(self): + now = int(time.time()) + self.assertEqual(print_launch('VLLM_FP8', H2H_DEADLINE_EPOCH=str(now + 2000))[0].returncode, 0) + for bad in [str(now + 100), 'soon']: + with self.subTest(deadline=bad): + self.assertEqual(print_launch('VLLM_FP8', H2H_DEADLINE_EPOCH=bad)[0].returncode, 4) + self.assertEqual(print_launch('VLLM_FP8', H2H_CELLS='bogus')[0].returncode, 4) + + def test_client_core_guard(self): + r, _ = print_launch('VLLM_FP8', H2H_CLIENT_CPUS='5', H2H_CLIENT_NICE='19') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('client_cpus 5 client_nice 19', r.stderr) + self.assertNotIn(',5,', ',' + r.stderr.split()[1] + ',') + self.assertEqual(print_launch('VLLM_FP8', H2H_CLIENT_CPUS='12')[0].returncode, 4) + + def ours(self, **env): + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, 'aien-serve-http').write_bytes(b'fixture server\n') + sha = hashlib.sha256(b'fixture server\n').hexdigest() + return print_launch('OURS', OURS_BIN_DIR=tmp, OURS_BIN_SHA256=sha, **env)[0] + + def test_turn2_prefix_override(self): + r, touched = print_launch('VLLM_FP8', H2H_CELLS='ttft-turn2', H2H_PREFIX='on') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(touched, []) + lines = r.stdout.splitlines() + self.assertEqual(lines[-1], '--enable-prefix-caching') + self.assertNotIn('--no-enable-prefix-caching', lines) + self.assertEqual(self.ours(H2H_CELLS='ttft-turn2').returncode, 0, 'OURS turn 2 is a labelled re-read') + + def test_turn2_prefix_override_negative_controls(self): + for arm, env in [('VLLM_FP8', dict(H2H_CELLS='ttft-turn2')), # cached row needs the cache + ('VLLM_FP8', dict(H2H_CELLS='dra74', H2H_PREFIX='on')), # never on timing cells + ('VLLM_FP8', dict(H2H_CELLS='ttft-turn2,ttft-fresh', H2H_PREFIX='on')), + ('VLLM_FP8', dict(H2H_CELLS='ttft-turn2', H2H_PREFIX='yes')), + ('VLLM_NVFP4_NSYS', dict(H2H_CELLS='ttft-turn2', H2H_PREFIX='on'))]: + with self.subTest(arm=arm, **env): + self.assertEqual(print_launch(arm, **env)[0].returncode, 4) + self.assertEqual(self.ours(H2H_CELLS='ttft-turn2', H2H_PREFIX='on').returncode, 4) + + def test_cell_set_lists(self): + for env in [dict(H2H_CELLS='dra74,ttft-fresh'), dict(H2H_CELLS='ttft-fresh', H2H_TTFT_PROMPTS='t32k'), + dict(H2H_CELLS='ttft-fresh', H2H_TTFT_REPS='1', H2H_TTFT_REP_BASE='2')]: + with self.subTest(**env): + r = print_launch('VLLM_NVFP4', **env)[0] + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.splitlines()[-1], '--no-enable-prefix-caching') + self.assertEqual(self.ours(H2H_CELLS='ttft-fresh,ttft-turn2').returncode, 0) + for arm, env in [('VLLM_FP8', dict(H2H_CELLS='dra74,dra74')), ('VLLM_FP8', dict(H2H_CELLS=',')), + ('VLLM_FP8', dict(H2H_CELLS='ttft-fresh', H2H_TTFT_PROMPTS='t4k')), + ('VLLM_FP8', dict(H2H_CELLS='ttft-fresh', H2H_TTFT_PROMPTS='t2k,t2k')), + ('VLLM_FP8', dict(H2H_CELLS='ttft-fresh', H2H_TTFT_REPS='0')), + ('VLLM_FP8', dict(H2H_CELLS='ttft-fresh', H2H_TTFT_REP_BASE='x')), + ('VLLM_NVFP4_NSYS', dict(H2H_CELLS='nsys-c8,dra74')), + ('VLLM_NVFP4_NSYS', dict(H2H_CELLS='ttft-fresh')), + ('VLLM', dict(H2H_CELLS='ttft-fresh'))]: + with self.subTest(arm=arm, **env): + self.assertEqual(print_launch(arm, **env)[0].returncode, 4) + + +class VllmArgvTests(unittest.TestCase): + def argv(self, prefix): + script = ('declare -A ARM_QUANT ARM_KV ARM_ATTN ARM_MOE ARM_SPEC ARM_PREFIX ARM_PROFILE\n' + 'ARM=VLLM_X VLLM_UTIL=0.50 ARM_PREFIX[VLLM_X]=%s\n' % shlex.quote(prefix) + + piece('vllm_argv() {', 'stop_server() {') + '\nvllm_argv && printf "%s\\n" "${VARGV[@]}"\n') + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, timeout=5) + + def test_prefix_values(self): + self.assertEqual(self.argv('on').stdout.splitlines()[-1], '--enable-prefix-caching') + self.assertEqual(self.argv('').stdout.splitlines(), LEGACY_VARGV) + bad = self.argv('maybe') + self.assertEqual(bad.returncode, 1) + self.assertIn('must be on, off or empty', bad.stderr) + + +class WindowLockTests(unittest.TestCase): + def held(self, *, held_id='w1', env_id='w1', gb10='exclusive', lock_held='1'): + with tempfile.TemporaryDirectory() as tmp: + sw = Path(tmp, 'spark-window') + sw.write_text('#!/bin/sh\n[ "$1" = id ] && echo %s\n' % held_id) + sw.chmod(0o755) + Path(tmp, 'gb10').write_text(gb10 + '\n') + env = dict(os.environ, SPARK_WINDOW_BIN=str(sw), SPARK_WINDOW=env_id, SPARK_WINDOW_DIR=tmp, + AIEN_GB10_LOCK_HELD=lock_held) + script = piece('window_held() {', 'arm_preconditions() {') + '\nwindow_held\n' + return subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=15) + + def test_exclusive_window_is_accepted(self): + self.assertEqual(self.held().returncode, 0) + + def test_negative_controls_refuse(self): + for kw, why in [(dict(held_id='w2'), 'is not SPARK_WINDOW'), (dict(gb10='shared'), 'exclusively'), + (dict(lock_held=''), 'incomplete')]: + with self.subTest(**kw): + r = self.held(**kw) + self.assertEqual(r.returncode, 1) + self.assertIn(why, r.stdout) + + def test_window_mode_never_waits_on_flock(self): + block = piece('if [ "${AIEN_GB10_LOCK_HELD:-}" = 1 ] || [ -n "${SPARK_WINDOW:-}" ]; then', 'GPU_LOCK_HELD=1') + window_branch = block[:block.index('elif')] + self.assertNotIn('flock', window_branch.replace('no flock taken', '')) + self.assertIn('GPU_LOCK_RELEASE=0', window_branch) + self.assertIn('flock -w 900 9', block[block.index('else'):]) + + +class DeadlineAndCellSetTests(unittest.TestCase): + def epochs(self, deadline): + block = piece('LOCK_EPOCH=$(date +%s)', 'echo "lock_epoch') + script = 'date() { echo 1000; }\nDEADLINE=%s\n%s\necho $STOP_AT $WARN_AT $QUIET_AT\n' % (deadline, block) + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, timeout=5).stdout.split() + + def test_epochs(self): + self.assertEqual(self.epochs(''), ['4540', '4300', '4000']) # no deadline: the 60-min hold + self.assertEqual(self.epochs('2140'), ['2080', '1960', '1960']) # slice deadline wins + self.assertEqual(self.epochs('9999'), ['4540', '4300', '4000']) # later deadline never extends + + def cells(self, cellset, arm='VLLM_FP8', fail='', prompts='t2k,t8k,t32k'): + """Run the session's cell-set block with a stub cell(); the real mark_complete decides DONE.""" + block = piece(' EXPECTED_CELLS=0\n for set in', 'else\n if [ -s "$LOGD/listen.txt" ]') + complete = piece('mark_complete() {', 'start_watchdog() {') + with tempfile.TemporaryDirectory() as tmp: + script = ('LOGD=%s PORT=1 ARM=%s CELLSET=%s FAIL=%s TTFT_PROMPTS=%s TTFT_REPS=3 TTFT_REP_BASE=0\n' + 'CELLS_COMPLETED=0 SESSION_RC=1\n' + 'cell() { echo "$*" >> "$LOGD/cells"; [ "$1" = "$FAIL" ] && return 1;' + ' CELLS_COMPLETED=$((CELLS_COMPLETED+1)); }\n' + 'curl() { echo "$@" >> "$LOGD/curl"; }\nsleep() { :; }\nboard() { :; }\n' + 'ts() { echo T; }\n%s\n%s\necho "$EXPECTED_CELLS $SESSION_RC"\n') % ( + shlex.quote(tmp), arm, cellset, fail, prompts, complete, block) + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True, timeout=10) + lines = Path(tmp, 'cells').read_text().splitlines() if Path(tmp, 'cells').exists() else [] + curls = Path(tmp, 'curl').read_text() if Path(tmp, 'curl').exists() else '' + expected, rc = r.stdout.split()[-2:] + done = Path(tmp, 'DONE').exists() + incomplete = Path(tmp, 'INCOMPLETE').read_text() if Path(tmp, 'INCOMPLETE').exists() else '' + return dict(expected=expected, rc=rc, cells=[l.split()[0] for l in lines], lines=lines, curls=curls, + done=done, incomplete=incomplete) + + def test_dra74_set(self): + s = self.cells('dra74') + self.assertEqual(s['expected'], '7') + self.assertEqual(s['cells'], ['decode-c1', 'decode-c4', 'decode-c8', 'decode-c16', + 'prefill-p256', 'prefill-p2k', 'prefill-p8k']) + + def test_complete_session_marks_done(self): + # regression: the session must call mark_complete after its cells, or every run ends INCOMPLETE + s = self.cells('dra74') + self.assertEqual((s['rc'], s['done'], s['incomplete']), ('0', True, '')) + + def test_short_session_is_incomplete(self): + s = self.cells('dra74', fail='prefill-p2k') + self.assertEqual((s['rc'], s['done']), ('1', False)) + self.assertIn('5/7', s['incomplete']) + self.assertNotIn('prefill-p8k', s['cells']) + + def test_full_set_unchanged(self): + s = self.cells('full') + self.assertEqual((s['expected'], len(s['cells']), s['rc']), ('14', 14, '0')) + + def test_nsys_set_brackets_one_cell_with_the_profiler(self): + s = self.cells('nsys-c8') + self.assertEqual((s['expected'], s['cells']), ('1', ['decode-c8'])) + self.assertEqual([l.split()[-1].rsplit('/', 1)[-1] for l in s['curls'].splitlines()], + ['start_profile', 'stop_profile']) + + def test_ttft_fresh_cells(self): + s = self.cells('ttft-fresh') + self.assertEqual((s['expected'], s['rc']), ('3', '0')) + self.assertEqual(s['cells'], ['ttft-fresh-2k', 'ttft-fresh-8k', 'ttft-fresh-32k']) + self.assertEqual(s['lines'][2], 'ttft-fresh-32k 1 1 ttft.jsonl --select t32k --ttft fresh --warmup 1 ' + '--warm-select t2k --reps 3 --rep-base 0') + self.assertEqual(self.cells('ttft-fresh', prompts='t32k')['cells'], ['ttft-fresh-32k']) + + def test_turn2_label_follows_the_arm(self): + self.assertEqual(self.cells('ttft-turn2', arm='OURS')['cells'], ['ttft-turn2-reread']) + s = self.cells('ttft-turn2', arm='VLLM_FP8') + self.assertEqual((s['cells'], s['expected'], s['rc']), (['ttft-turn2-cached'], '1', '0')) + self.assertIn('--select t32k --ttft turn2', s['lines'][0]) + + def test_cell_set_list_sums_and_stops_on_a_short_set(self): + s = self.cells('dra74,ttft-fresh') + self.assertEqual((s['expected'], len(s['cells']), s['rc'], s['done']), ('10', 10, '0', True)) + s = self.cells('dra74,ttft-fresh', fail='decode-c4') + self.assertEqual(s['cells'], ['decode-c1', 'decode-c4']) + self.assertEqual((s['rc'], s['done']), ('1', False)) + s = self.cells('ttft-fresh,ttft-turn2', arm='OURS', fail='ttft-turn2-reread') + self.assertEqual((s['expected'], s['rc']), ('4', '1')) + self.assertIn('3/4', s['incomplete']) + + +if __name__ == '__main__': + unittest.main() diff --git a/bench/test-run-arm.py b/bench/test-run-arm.py index 459e5ce..3dbe767 100644 --- a/bench/test-run-arm.py +++ b/bench/test-run-arm.py @@ -27,7 +27,7 @@ class CellGateTests(unittest.TestCase): ROOT=%s LOGD=$ROOT REPO=$ROOT RESULTS=$ROOT OUT=$ROOT/rows.jsonl ARM=CONTROL ROUND=R0 PORT=1 MID=fixture -MON_CPU=2 CLI_CPUS=0-1 SRV_CPUS=5 SRV_LIST=' 5 ' +MON_CPU=2 CLI_CPUS=0-1 CLI_NICE=0 SRV_CPUS=5 SRV_LIST=' 5 ' CELLS_COMPLETED=0 wait_quiet() { return %d; } mytree() { echo $$; } diff --git a/bench/test-ttft.py b/bench/test-ttft.py new file mode 100755 index 0000000..2bcc831 --- /dev/null +++ b/bench/test-ttft.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""PROTOCOL.md A10 TTFT rows: identical requests across arms, per-rep nonce, turn-2 prefix identity. + +Local synthetic HTTP only; no model, no GPU.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import unittest + +sys.dont_write_bytecode = True +HERE = Path(__file__).resolve().parent +PROMPTS = HERE.parent / 'prompts' / 'ttft.jsonl' +spec = importlib.util.spec_from_file_location('bench_client', HERE / 'bench.py') +bench = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bench) +gspec = importlib.util.spec_from_file_location('make_ttft', HERE / 'make_ttft_prompts.py') +make_ttft = importlib.util.module_from_spec(gspec) +gspec.loader.exec_module(make_ttft) + + +def event(value): + return 'data: ' + json.dumps(value) + '\n\n' + + +STREAM = (event({'choices': [{'delta': {'content': 'x'}}]}) + + event({'choices': [{'finish_reason': 'length'}], 'usage': {'prompt_tokens': 7, 'completion_tokens': 1}}) + + 'data: [DONE]\n\n') +METRICS = ('# HELP vllm:prefix_cache_hits_total hits\n' + 'vllm:prefix_cache_queries_total{model_name="q36"} 10.0\n' + 'vllm:prefix_cache_hits_total{model_name="q36"} 4.0\nvllm:other_total 1.0\n') + + +class FakeServer: + """Records every request body in arrival order; answers /metrics and the chat stream.""" + def __enter__(self): + bodies, gets = self.bodies, self.gets = [], [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_GET(self): + gets.append(self.path) + self.send_response(200) + self.end_headers() + self.wfile.write(METRICS.encode()) + + def do_POST(self): + bodies.append(self.rfile.read(int(self.headers['Content-Length']))) + self.send_response(200) + self.send_header('Content-Type', 'text/event-stream') + self.end_headers() + self.wfile.write(STREAM.encode()) + self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + return self + + def __exit__(self, *_): + self.server.shutdown() + self.thread.join() + self.server.server_close() + + +def run_bench(arm, *extra, prompts=PROMPTS): + """Run bench.py against a fresh fake server; returns (rc, raw request bodies, rows, GET paths, stderr).""" + with FakeServer() as srv, tempfile.TemporaryDirectory() as tmp: + out = Path(tmp, 'rows.jsonl') + r = subprocess.run([sys.executable, str(HERE / 'bench.py'), '--port', str(srv.server.server_port), + '--model', 'q36', '--arm', arm, '--round', 'T1', '--metric', 'ttft-x', + '--prompts', str(prompts), '--max-tokens', '1', '--out', str(out)] + list(extra), + capture_output=True, text=True, timeout=60, env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1')) + rows = [json.loads(l) for l in out.read_text().splitlines()] if out.exists() else [] + return r.returncode, list(srv.bodies), rows, list(srv.gets), r.stderr + + +def first_user(body): + return json.loads(body)['messages'][0] + + +class NonceTests(unittest.TestCase): + def test_nonce_is_deterministic_and_arm_free(self): + self.assertEqual(bench.ttft_nonce('t2k', 0, False), bench.ttft_nonce('t2k', 0, False)) + self.assertEqual(bench.ttft_nonce('t2k', 0, False), + hashlib.sha256(b'h2h-ttft|t2k|r0').hexdigest()[:16]) + + def test_nonce_changes_per_rep_warmup_and_prompt(self): + seen = {bench.ttft_nonce(p, rep, w) for p in ('t2k', 't8k', 't32k') for rep in range(4) for w in (False, True)} + self.assertEqual(len(seen), 3 * 4 * 2) + + +class FreshRowTests(unittest.TestCase): + ARGS = ('--ttft', 'fresh', '--select', 't8k', '--warmup', '1', '--warm-select', 't2k', '--reps', '3') + + def test_requests_are_byte_identical_across_arms(self): + rc_a, bodies_a, rows_a, _, err = run_bench('OURS', *self.ARGS) + self.assertEqual(rc_a, 0, err) + rc_b, bodies_b, rows_b, _, err = run_bench('VLLM_FP8', *self.ARGS) + self.assertEqual(rc_b, 0, err) + self.assertEqual(len(bodies_a), 4) + self.assertEqual(bodies_a, bodies_b) + self.assertEqual([r['messages_sha256'] for r in rows_a], [r['messages_sha256'] for r in rows_b]) + + def test_nonce_changes_per_rep_and_text_is_the_pinned_prompt(self): + rc, bodies, rows, gets, err = run_bench('OURS', *self.ARGS) + self.assertEqual(rc, 0, err) + byid = {p['id']: p for p in map(json.loads, PROMPTS.read_text().splitlines())} + users = [first_user(b)['content'] for b in bodies] + self.assertEqual(len(set(u.split('\n', 1)[0] for u in users)), 4) # 1 warmup + 3 reps + self.assertTrue(users[0].endswith(byid['t2k']['text'])) # cheap warmup prompt + for u, row in zip(users[1:], rows[1:]): + self.assertEqual(u, bench.NONCE_LINE % row['nonce'] + byid['t8k']['text']) + self.assertEqual(row['nonce'], bench.ttft_nonce('t8k', row['rep'], False)) + self.assertEqual([(r['warmup'], r['rep'], r['prompt_id']) for r in rows], + [(True, 0, 't2k'), (False, 0, 't8k'), (False, 1, 't8k'), (False, 2, 't8k')]) + self.assertEqual(gets, [], 'fresh rows never read /metrics') + + def test_rep_base_continues_the_nonce_sequence(self): + _, one, _, _, _ = run_bench('OURS', '--ttft', 'fresh', '--select', 't2k', '--warmup', '0', '--reps', '3') + _, split, _, _, _ = run_bench('OURS', '--ttft', 'fresh', '--select', 't2k', '--warmup', '0', '--reps', '2', + '--rep-base', '1') + self.assertEqual(one[1:], split) + + def test_negative_control_random_nonce_differs_across_arms(self): + # the legacy prefill path (uuid nonce) must fail the same identity comparison + a = run_bench('OURS', '--select', 't2k', '--warmup', '0', '--reps', '1', '--nonce')[1] + b = run_bench('VLLM_FP8', '--select', 't2k', '--warmup', '0', '--reps', '1', '--nonce')[1] + self.assertEqual((len(a), len(b)), (1, 1)) + self.assertNotEqual(a, b) + + +class TurnTwoTests(unittest.TestCase): + ARGS = ('--ttft', 'turn2', '--select', 't32k', '--warmup', '1', '--warm-select', 't2k', '--reps', '2') + + def test_turn2_prefix_is_byte_identical_to_the_primed_prompt(self): + rc, bodies, rows, gets, err = run_bench('VLLM_FP8', *self.ARGS) + self.assertEqual(rc, 0, err) + self.assertEqual([r['ttft_phase'] for r in rows], ['fresh', 'prime', 'turn2', 'prime', 'turn2']) + self.assertEqual([r['metric'] for r in rows[1:3]], ['ttft-x-prime', 'ttft-x']) + byid = {p['id']: p for p in map(json.loads, PROMPTS.read_text().splitlines())} + for prime, full in ((bodies[1], bodies[2]), (bodies[3], bodies[4])): + pm, fm = json.loads(prime)['messages'], json.loads(full)['messages'] + self.assertEqual(len(pm), 1) + self.assertEqual(json.dumps(pm[0]).encode(), json.dumps(fm[0]).encode()) + self.assertEqual([m['role'] for m in fm], ['user', 'assistant', 'user']) + self.assertEqual(fm[1]['content'], byid['turn2-assistant']['text']) + self.assertEqual(fm[2]['content'], byid['turn2-new']['text']) + self.assertTrue(pm[0]['content'].endswith(byid['t32k']['text'])) + self.assertNotEqual(first_user(bodies[1]), first_user(bodies[3]), 'nonce must change per rep') + self.assertEqual(rows[1]['prefix_sha256'], rows[2]['prefix_sha256']) + self.assertNotEqual(rows[1]['prefix_sha256'], rows[3]['prefix_sha256']) + + def test_turn2_requests_identical_across_arms(self): + a = run_bench('OURS', *self.ARGS) + b = run_bench('VLLM_NVFP4', *self.ARGS) + self.assertEqual((a[0], b[0]), (0, 0)) + self.assertEqual(a[1], b[1]) + + def test_prefix_cache_counters_are_recorded_around_each_request(self): + rc, _, rows, gets, err = run_bench('VLLM_FP8', *self.ARGS) + self.assertEqual(rc, 0, err) + self.assertEqual(gets, ['/metrics'] * 10) + want = ['vllm:prefix_cache_queries_total{model_name="q36"} 10.0', 'vllm:prefix_cache_hits_total{model_name="q36"} 4.0'] + self.assertEqual(rows[2]['prefix_cache_before'], {'lines': want}) + self.assertEqual(rows[2]['prefix_cache_after'], {'lines': want}) + + def test_negative_control_tampered_prefix_is_detected(self): + byid = {p['id']: p for p in map(json.loads, PROMPTS.read_text().splitlines())} + prime = bench.ttft_requests('turn2', byid, 't32k', bench.ttft_nonce('t32k', 0, False))[0][1] + other = bench.ttft_requests('turn2', byid, 't32k', bench.ttft_nonce('t32k', 1, False))[1][1] + self.assertNotEqual(bench.messages_sha256(prime[:1]), bench.messages_sha256(other[:1])) + + +class ArgumentTests(unittest.TestCase): + def test_refusals(self): + for extra in (('--ttft', 'fresh', '--select', 't2k', '--nonce'), + ('--ttft', 'fresh', '--select', 't2k,t8k'), + ('--ttft', 'fresh', '--select', 'p2k'), + ('--ttft', 'fresh', '--select', 't2k', '--concurrency', '2'), + ('--ttft', 'fresh', '--select', 't2k', '--warm-select', 'nope'), + ('--select', 't2k', '--rep-base', '1'), + ('--select', 't2k', '--warm-select', 't2k')): + with self.subTest(extra=extra): + rc, bodies, _, _, _ = run_bench('OURS', *extra) + self.assertEqual((rc, bodies), (2, [])) + + def test_turn2_needs_its_conversation_texts(self): + with tempfile.TemporaryDirectory() as tmp: + p = Path(tmp, 'p.jsonl') + p.write_text(json.dumps({'id': 't32k', 'text': 'x'}) + '\n') + rc, bodies, _, _, _ = run_bench('OURS', '--ttft', 'turn2', '--select', 't32k', prompts=p) + self.assertEqual((rc, bodies), (2, [])) + + +class PromptFileTests(unittest.TestCase): + def test_committed_prompts_carry_the_pinned_source_shas(self): + rows = {r['id']: r for r in map(json.loads, PROMPTS.read_text().splitlines())} + self.assertEqual(sorted(rows), ['t2k', 't32k', 't8k', 'turn2-assistant', 'turn2-new']) + for pid, (_, sha) in make_ttft.SOURCES.items(): + self.assertEqual(rows[pid]['source_sha256'], sha) + if pid != 'turn2-new': + self.assertEqual(hashlib.sha256(rows[pid]['text'].encode()).hexdigest(), sha) + self.assertEqual(rows['turn2-assistant']['text'], make_ttft.TURN2_ASSISTANT) + + def test_generator_refuses_a_wrong_source(self): + with tempfile.TemporaryDirectory() as tmp: + src = [Path(tmp, n) for n in ('a', 'b', 'c', 'd')] + for s in src: + s.write_text('wrong\n') + out = Path(tmp, 'out.jsonl') + self.assertEqual(make_ttft.main(['x'] + [str(s) for s in src] + [str(out)]), 2) + self.assertFalse(out.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/prompts/ttft.jsonl b/prompts/ttft.jsonl new file mode 100644 index 0000000..64d1545 --- /dev/null +++ b/prompts/ttft.jsonl @@ -0,0 +1,5 @@ +{"id": "t2k", "text": "ne 503-511, VERIFIED), so an unseen file is free until found. 23. FS adapter: reversible filename from the key, `.tmp` suffix + `os.replace`, unlink of the temp on failure; no `fsync` anywhere in the file (fs_l2_adapter.py:99-135, 518-532, 640-662, VERIFIED; absence of `fsync` VERIFIED by grep). 24. Tests adapted (test_nixl_store_dynamic_l2_adapter.py): `test_salted_objects_recover_independently_after_restart` (745), `test_store_rejected_when_capacity_exceeded` (985), `test_batched_store_reports_failure_when_capacity_exceeded` (1034), `test_secondary_lookup_finds_key` (1113), `test_secondary_lookup_and_load_data` (1138), `test_load_partial_failure_marks_only_successful` (561), `test_delete_skips_pinned_key` (887). Each is re-expressed as a Rust test; none is copied. Attribution: an Apache-2.0 header on `crates/aien-kv-store/src/identity.rs` (the prefix-chain idea) and the test file that adapts the cases, plus a THIRD_PARTY.md row (\"LMCache, Apache-2.0, ideas adapted: deterministic rolling prefix keys, completed-object publication by temp+rename, lazy disk recovery; no code copied\"). The LMCache clone has a LICENSE and no NOTICE file (VERIFIED by `ls`). ### Prior art in this repository (not depended on) 25. OWN-30B serve branch `own30b/serve` (sc-own30b, unmerged, pinned at commit 69459db): in-memory prefix reuse for one conversation, `reused = common.min(prompt.len() - 1)` so at least the last prompt token is always recomputed to produce logits (crates/aien-inference-abi/src/qwen3_moe_omega.rs:2163 at 69459db, VERIFIED), test `prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run` (fn at 2421 at 69459db, VERIFIED). Line numbers move on that branch; the pin is the commit. This ADR adopts the same \"never restore the last prompt token\" rule (section 6.5) and the same warm-equals-cold test shape. Nothing else overlaps: that branch has no disk, no identity, no sharing across requests. ## Decision drivers 1. Correctness before speed: no byte is reused unless its identity proves compatibility, and validation happens before any allocation or copy. 2. The runtime mutex and the KV lock are never held across storage I/O. 3. Everything is bounded: queue depth, bytes in flight, recovery memory, disk quota including objects never looked up. 4. One record header for host and native, so tooling and tests read both; payloads differ by backend format and are never cross-loaded. 5. The native side keeps the single-command, bounce-buffered NVMe contract and the freestanding no_std rule. 6. Conversation history stays authoritative; the KV store is a cache that may be dropped at any time. ## 1. Versioned chunk identity ### 1.1 Units - A **chunk** is `chunk_tokens = chunk_blocks * block_size` consecutive positions of one sequence, aligned to a multiple of `chunk_tokens`. `chunk_blocks` is a setting fixed into the namespace (default 16 blocks; with the 16-token blocks of `model_dir.rs` that is 256 tokens (calc:ceaa1589), LMCache's default). A chunk is **full** when it holds `chunk_tokens` positions. The last chunk of a parked sequence may be **partial** (`token_count < chunk_tokens`); partial chunks are keyed with their exact token count and therefore only ever match an identical prefix of identical length. Only full chunks are prefix-share candidates. - Hash everywhere is SHA-256 (host: `sha2`, already in the lockfile; native: argus `sha256.h`, used by `store_v1.h`). blake3 is not used because native has no blake3. ### 1.2 Namespace id (binds everything that must be equal for bytes to be reusable) `namespace_id = SHA-256( \"AIEN-PKV-NS-V2\\0\" || fields )` (V1 until sc#504; the domain moved when field 14 started to bind the engine, section 1.2.2, so no V1 namespace can match) where `fields`, in this order, little-endian: | # | field | type | source | |---|---|---|---| | 1 | format_version | u16 = 1 | this ADR | | 2 | model_sha256 | [u8;32] | `ModelIdentity.model_sha256` decoded from hex (generation.rs:25) | | 3 | model_digest_kind | u8 len + bytes | `ModelIdentity.model_digest_kind` (generation.rs:26) | | 4 | model_id | u16 len + bytes | `ModelConfig.model_id` | | 5 | num_layers, num_kv_heads, head_dim, block_size | 4 x u32 | `ModelConfig` | | 6 | rope_theta | u32 (f32 bits) | `ModelConfig.rope_theta` | | 7 | rope_scaling | u8 tag (0 none, 1 llama3) then, if 1: factor f64 bits, low_freq_factor f64 bits, high_freq_factor f64 bits, original_max_position_embeddings u64 | `Llama3RopeScaling` (abi-core lib.rs:45-50) | | 8 | qk_norm | u8 | `ModelConfig.qk_norm` | | 9 | dtype | u8 (1 Fp4, 2 Fp8, 3 Bf16, 4 Fp16, 5 Fp32) | `KvDType` | | 10 | layout | 5 x u64 strides (head, token, kv_plane, layer, block) + u64 element_bytes | `KvLayout` (lib.rs:143-156) | | 11 | backend_format | u8 (1 = host paged pool v1; 2 = native f32 decode state v1) | section 2.3 | | 12 | chunk_tokens | u32 | setting | | 13 | sharing_namespace | u16 len + bytes | setting `AIEN_KV_STORE_NAMESPACE` (host); sealed Store uuid + identity class + subject id (native, section 9) | | 14 | compute_config_digest | [u8;32] | `ComputeConfig::digest_with_engine(engine)`, sections 1.2.1 and 1.2.2 (added by the review, C1 delta in section 12; binds the engine since sc#504) | Rationale: fields 2-8 cover \"which weights, which geometry, which RoPE\"; 9-11 cover \"which bytes\"; 13 is the authorization scope; 14 covers every other number that changes what the forward pass computes. Two runtimes with different `block_size` or `chunk_tokens` cannot share objects, by design: positions and chunk boundaries are part of identity. #### 1.2.1 Compute configuration digest (review finding 1) The review showed (VERIFIED by the orchestrator) that two model directories with the same weights digest and the same fields 1-13 but a different `rms_norm_eps` in `config.json` produce different K/V: the backend reads `weights.config.rms_norm_eps` for every RMSNorm (transformer_backend.rs:738, 1111, 1391, 1760) and the value comes from `config.json` (model_dir.rs:112, 239). The weights digest covers the safetensors bytes only, not `config.json`. `ComputeConfig::digest() = SHA-256(\"AIEN-PKV-CFG-V1\\0\" || ComputeConfig)` (namespace field 14 until sc#504; field 14 is now the V2 digest of section 1.2.2, which hashes the same nine fields first) where `ComputeConfig` is, little-endian and in this order: | # | field | type | source | |---|---|---|---| | 1 | num_heads | u32 | `ModelConfig.num_heads` | | 2 | hidden_dim | u64 | `ModelConfig.hidden_dim` | | 3 | intermediate_dim | u64 | `ModelConfig.intermediate_dim` | | 4 | vocab_size | u64 | `ModelConfig.vocab_size` | | 5 | rms_norm_eps | u32 (f32 bits) | `ModelConfig.rms_norm_eps` | | 6 | tie_word_embeddings | u8 | `ModelConfig.tie_word_embeddings` | | 7 | hidden_act | u8 (1 = silu) | `config.json` `hidden_act`; the loader refuses everything but silu (model_dir.rs:198-199, VERIFIED), so the byte is a constant today and exists so a future activation cannot alias | | 8 | arith_id | u8 len + bytes | `TensorBackend::name()` (backend.rs:131, VERIFIED trait method; implementations return `\"ReferenceCpuBackend\"` at backend.rs:509-511, `\"NativeCpuBackend (Rayon Multi-Core)\"` at mojo_backend.rs:242-244, and an availability-dependent string at omega_backend.rs:815-820, all VERIFIED) | | 9 | arith_epoch | u32 | a constant `KV_ARITH_EPOCH` in `aien-inference-abi`, bumped by any change that alters numeric results of the forward pass | Fields not listed and why (each is a decision, not an omission): `model_id` (field 4 of the namespace), `num_layers`, `num_kv_heads`, `head_dim`, `block_size`, `rope_theta`, `rope_scaling`, `qk_norm` (namespace fields 5-8), `max_sequence_length` (caps context, does not change a K/V value; the cap is applied to the restorable prefix, section 6.3), `eos_token_ids` (decides when to stop, not what is computed), `attention_bias` and `mlp_bias` (the loader refuses true, model_dir.rs:201-203, so they cannot vary). **Why the resolved `ModelConfig` and not a digest of the raw `config.json`** (INFERRED, decision): (a) the raw file carries fields that cannot change a K/V value (`torch_dtype`, `transformers_version`, `use_cache`, `initializer_range`; model_dir.rs:22-52 lists the\n\nIn one sentence, what is the text above about?", "source_sha256": "26a44c508412e213de876eb54bb90390426b086c887a68b90fa78f7470425ee3"} +{"id": "t8k", "text": " frees the sequence after publication (section 6), so there is no resident-but-parked state to track. `Failed` is sticky per request until the request's recompute path has started, then it is cleared; it exists so a stale completion cannot flip a request back. `Draining` is new (review finding 5): a restore that has a failed chunk still owns its destinations until every sibling job has produced its terminal completion. ### 5.2 Storage references reuse the fork refcount The storage worker never holds a raw block id. A **holder** is a real block table in `AienKvManager` whose id lives in the reserved slot `u32::MAX` (`SequenceId { slot: u32::MAX, generation: job_id as u32 }`, generation nonzero). Arena slot indices start at 0 and grow by one per new slot (`allocate_slot` pushes when `free_slots` is empty, sequence.rs:382-399, VERIFIED), so slot `u32::MAX` is unreachable in practice but not refused today; C3 adds the refusal in `allocate_slot` (slot index must stay below `u32::MAX`) so the reservation is a rule, not an assumption. **One holder per chunk**, both directions: - Park: a new primitive `fork_range(seq, holder, block_range)` takes one reference on exactly the blocks of that chunk (C3). `fork_sequence(seq, holder)` is not used: it copies the parent's whole table (lib.rs:1165-1210, VERIFIED), so a per-chunk holder built with it would pin every block of the sequence. - Restore: `allocate_sequence(holder, tokens)` allocates zeroed blocks owned by that chunk's holder. - Assembly: `assemble_table(seq, holders)` (C3) builds the request's own table from the holders' block lists, adding one reference per block and marking the table `PrefillPending`. It refuses a `seq` that already has a table (unlike `fork_sequence`, which frees a live child id's blocks, lib.rs:1181-1184, VERIFIED) and refuses any holder that is not complete. - Release: `free_sequence(holder)`. Consequences, all from existing code paths: - A block reaches `free_blocks` only when its refcount hits zero (lib.rs:1419-1425), so a slot is reused only after the sequence tables and the storage holders are all done. No new free-list logic. - Shared-prefix owners stay valid when another owner parks or cancels: the holder is one more sharer; the existing COW tests already cover the invariants (`crates/aien-kv-cache/tests/cow_branching_tests.rs`). - A parked sequence that resumes while its park is in flight copies on write only on a partial last block (lib.rs:1234-1255): the worker keeps reading the frozen original. - `fork_range` leaves the parent's state alone; `fork_sequence` sets the parent to `SharedFrozen` (lib.rs:1192-1197), which is the intended meaning for a fully ready parent. ### 5.3 Incarnation checks Every job carries `Incarnation = (seq_id u64 as issued by the arena, residency_epoch u32)`; the spine bumps `residency_epoch` on every state transition of that sequence. A completion is committed only if the sequence still exists with the same `seq_id` (its generation makes a reused slot a different id, sequence.rs:7-50) **and** the same epoch. Anything else is counted `kv_store_stale_completions` and its holder is freed after the terminal completion. A reused sequence id can therefore never be mutated by an old job. ### 5.4 Short critical sections (the only places the KV lock is taken for storage) | name | lock | work | bound | |---|---|---|---| | S1 finish-fork | KV write, **inside the scheduler's finish transaction, before `free_sequence`** (section 6.1) | `fork_range(seq, holder_i, range_i)` per chunk; push a `ParkIntent` to a lock-free outbox | O(blocks) | | S2 restore-alloc | KV write | `allocate_sequence(holder_i, tokens_i)` per chunk; refuse if `free < watermark + needed` | O(blocks) | | S3 restore-commit | KV write, **on the spine thread** while it handles polled completions, never on the storage worker (review 2, new finding 2) | verify incarnation and that **every** job of the txn is `Completed`; `assemble_table(seq, holders)`; scheduler `admit_restored_prefix` (section 6.3) | O(blocks) | | S4 holder-release | KV write | `free_sequence(holder_i)`, only when the txn has no non-terminal job | O(blocks) | | S5 queue | store index mutex | push/pop/complete | O(1) | The segment hashes on load are verified over the destination blocks *before* S3 (they are holder-owned and invisible to the scheduler until assembled), so no copy to a staging buffer is needed on the host. ### 5.5 Cancellation and restore transactions - A **restore transaction** (`RestoreTxn`) owns all of one request's chunk holders and the list of its submitted job ids. It is the unit of ownership: no holder of a txn is freed, reused or handed to prefill while any job of the txn is non-terminal (review finding 5). When chunk A fails while chunk B is mid-transfer: the txn moves to `Draining`, `cancel(job)` is issued for every non-terminal sibling, and the txn waits for each sibling's terminal completion (`Done`, `Failed` or `Cancelled`); only then S4 frees the holders and the request goes to plain prefill. `TooLate` siblings simply finish, their bytes are discarded. - Cancel own waiter only: a request that is cancelled (`CancelSwarm`, `Aborted`, client gone) cancels its own txn the same way. Shared work (a same-key load another request is waiting on) is never cancelled: the coalescing table keeps the job alive while any waiter remains; cancelling removes the waiter only. - Mid-transfer cancel of a store: the worker checks the cancel flag between segment writes (bounded granularity = one block); the temp is unlinked; nothing was published. - The worker never writes into a freed holder: the free happens in S4 only after the terminal completion of every job that targets it, so there is no use-after-free of pool blocks, including on the multi-chunk failure path. ## 6. Park and restore in the runtime ### 6.1 Boundary (review finding 2) The earlier text parked in `AienRuntimeSpine::step` when it processed `DecodeOutput::Finished` (spine.rs:198-230). That is too late (VERIFIED by the review and by reading the scheduler): `AienScheduler::step` frees the sequence's block table inside its own finish handling, `free_sequence(request_id)` at aien-scheduler/src/lib.rs:1106 for a normal finish and at 1152 for a backend-originated `Finished`, before it returns the `Finished` output (lib.rs:1111, 1172). By the time the spine sees `Finished`, the blocks are gone; what remains there is `backend.release_sequence` (spine.rs:225), which only drops backend state. Design: ownership transfer happens **inside the scheduler's finish transaction**. The scheduler gets an optional `FinishHook` (a trait object set by the spine; absent means today's behaviour exactly). At each of the two finish sites, for any finish reason except `Preempted`, in this order and inside one KV write guard: 1. `prefix = backend.computed_prefix(request_id)` (section 6.2), read while the backend still holds the sequence (the backend call happens before the guard is taken, the backend is not touched under the guard). 2. `hook.on_finish(&mut kv, request_id, prefix)`: `fork_range` into per-chunk holders (S1), a `ParkIntent { holders, keys, headers, incarnation }` pushed to an outbox (a `Mutex<Vec>` with O(1) push; no I/O, no store call). 3. The existing `free_sequence(request_id)`. The spine drains the outbox right after `step` returns and calls `submit_store` for each intent; a refused submit frees that holder (S4) and counts `kv_park_failed_total`. Because the fork happens before the free, the blocks have refcount at least 1 at every instant; the window the review found does not exist. Active decode KV stays resident: nothing parks a running sequence (milestone rule). A `Preempted` finish is not parked (its K/V is incomplete by definition). ### 6.2 Park 1. **Computed prefix, not the token list** (review finding 3). The backend exposes `computed_prefix(seq_id) -> Option<Vec<u32>>`, the tokens whose K/V is actually in the pool. VERIFIED facts it rests on: decode reads `pos = tokens.len() - 1` and computes K/V for the last token (transformer_backend.rs:1776-1782), then appends the newly sampled token (2158), so after any decode step the last token in `tokens` has no K/V; after prefill, `tokens.len()` equals the cached positions and the sample is held apart in `pending_prefill_token` (transformer_backend.rs:136-143), also with no K/V. So `computed = tokens.len()` when a pending prefill token exists and no decode has run, otherwise `tokens.len() - 1`. The earlier rule \"tokens plus the pending token\" would have labelled an unwritten position as valid and let a longer later prompt restore it. Nothing beyond `computed` is ever hashed, keyed or written. The mapping is asserted by a red test that reads the pool and shows position `computed` is unwritten. 2. Compute the key chain for full chunks of `computed` and the partial tail (`token_count = computed mod chunk_tokens`). Skip chunks whose keys `lookup` already finds or that are in flight (same-key publication dedup). 3. S1 inside the finish transaction (section 6.1), one holder per chunk. The writer applies the tail-row zeroing of section 2.2 to the last partial block. The stores are low priority (section 7.2). 4. The sequence's own references are dropped as today; the holders keep the blocks until each job is terminal, then S4. ### 6.3 Restore 1. On `submit_request` in the spine, compute the key chain of the prompt, walk it until the first miss, cap the restorable prefix at `prompt.len() - 1` (context 25: the last prompt token is always recomputed so the logits come from this prompt). Also cap at the operator context (`AIEN_KV_CONTEXT_TOKENS`). A restorable prefix that ends inside a chunk uses only whole stored chunks; a partial-tail chunk is used only if its exact token count is the cap. 2. `pin` the keys; S2 allocates one holder per chunk; submit loads (high priority) for all chunks under one `RestoreTxn`; the request's residency becomes `Restoring`. The request stays in the scheduler's waiting queue with a new `SequencePhase::AwaitingRestore` that `build_scheduled_batch` skips: ready resident sequences keep decoding (the #485 slow-I/O proof). 3. When every job of the txn is `Completed` (and none failed): S3 runs `assemble_table(seq, holders)` and the scheduler's new `admit_restored_prefix(seq_id, restored)` (review finding 4). The existing admission cannot be reused as it was designed: for a waiting sequence whose table is ready it sets `prompt_tokens_prefilled = prompt_len` and enters decode (aien-scheduler/src/lib.rs:779-784, VERIFIED), skipping the unprocessed suffix; for a table that is not ready it frees the table and prefills from zero (lib.rs:802-806, VERIFIED). So `admit_restored_prefix` bypasses the waiting queue: it leaves the table `PrefillPending` (never `complete_prefill` at restore), sets `prompt_tokens_prefilled = restored`, `is_prefilled = false`, `phase = Prefill`, and pushes the sequence into `running_sequences`, where the existing \"continuing chunked prefill\" branch schedules `prompt[restored..]` (lib.rs:572-606, VERIFIED) and the existing completion fence marks the table ready only after the last chunk (lib.rs:1023-1033, VERIFIED). Because `restored <= prompt.len() - 1`, at least one token is always left, so the fence always runs and decode can never start on a restored-only table. The backend hook `restore_sequence(seq_id, tokens)` sets `SequenceState.tokens = prompt[..restored]` so the next chunk's positions line up (checks as `fork_sequence`). 4. Any failure or stale completion: txn `Draining` (section 5.5), then `Failed`, holders freed, phase `Waiting` with `prompt_tokens_prefilled = 0`: a plain prefill. No request is ever refused because of the cache; refusal exists only when history itself is unavailable, which is the generation record's job, not this design's. ### 6.4 Non-tensor state Positions: reconstructed from chunk order. Pending prefill token: not needed, the restore ends inside the prompt and the suffix prefill produces a fresh pending token. Sampling state: `SamplingParams` come with every request (abi-core lib.rs:455-460); the sampling seed is `decode_sampling_seed(request_id, position)` with a fresh `request_id` after a restart, so **stochastic continuation is not reproducible across restart and is not claimed**; greedy continuation is. A test for stochastic continuation, if ever wanted, must pin the seed explicitly; that is outside this milestone. ### 6.5 Guarantee: greedy continuation equals the uninterrupted baseline Holds when the restored bf16 block bytes are identical, the remaining prefill runs on the same backend with the same weights and the same `compute_config_digest` (identity guarantees the last two, section 1.2.1). The test runs a prompt cold, records the greedy tokens, parks, restarts the process, restores the prefix and compares tokens. The backend must prefill the remainder starting at the restored position with the same chunking as the cold run would have used from that position (chunked prefill is position-based, lib.rs:572-606). ## 7. Queues, bounds, fairness, drain ### 7.1 Bounds and per-class reservation (review finding 9) Two bounded intake classes (restore, park) and one completion queue, all behind the store's index mutex. Limits are **per class**, not shared: `max_inflight_ops` (default 64) is split 48 restore and 64 park (`max_restore_ops`, `max_park_ops`; park raised from 16 after the C9 bench, section 18.4), and `max_inflight_bytes` (default 256 MiB) is split the same 3:1. A class can never consume the other's reservation, so continuous restores cannot make every park fail before the dispatcher runs. Bytes count the sum of `payload_len + 4096` of every job between Submitted and its terminal completion. `submit_*` refuses with `QueueFull`; the spine treats a refused park as \"not parked this turn\" (the holders are released) and a refused restore as a plain prefill. Restore destination blocks are counted against the pool: S2 refuses when `free_blocks < watermark_blocks + needed` (the scheduler's own watermark, aien-scheduler lib.rs:460-470), so restores can never starve admission. **Completion capacity** is reserved at submit: each accepted job reserves three completion slots (Completed, Published, terminal), so `poll` never overflows and the worker never blocks on a full queue. **Credit release** happens at the job's terminal completion as the store sees it, not when the caller later commits: a slow KV lock cannot hold store credits. **Bounded waiters**: at most `max_waiters_per_job` (default 16) per coalesced load and 1024 in total; the 17th request does a plain prefill instead of attaching. Holder metadata is bounded by the restore-block budget `AIEN_KV_RESTORE_MAX_BLOCKS`. ### 7.2 Fairness Within the reserved shares, the worker dispatches by credits: 3 restores then 1 park when both queues are non-empty (restore latency matters to a waiting user; parks free resident memory and must not starve). Within a queue, FIFO by submission. The reservation of 7.1 guarantees admission fairness; the credits guarantee dispatch fairness. A PLANNED saturation test (C5) offers restores at the maximum rate for 10 000 operations and asserts parks are still admitted and dispatched at no less than their reserved share. ### 7.3 Coalescing (review finding 6) Same-key loads coalesce at the **job and landing-buffer level**, never at the request-table level. One in-flight load per chunk key lands in that chunk's holder; later requests `attach_waiter` to the job and, on `Completed`, each request builds **its own table** with `assemble_table(seq_i, [holder_0 .. holder_k])` from the chunk holders it needs. The shared chunk blocks are immutable once `Completed` and shared by refcount; each request's suffix chunks are its own holders. A request commits (S3) only when all of its chunks are `Completed` and validated. `fork_sequence(first_seq, other_seq)` is never used for coalescing (it would share the first request's whole table and replace the other request's own). Same-key stores: `inflight_stores` set; duplicates are dropped at submit with `Ok(JobId)` of the existing job (the caller only needs \"it will be published\"). ### 7.4 Eviction, reservation and thrash (review finding 7) `submit_store` never evicts and never touches the filesystem; it runs under the spine's lock path and must stay O(1). Under the index mutex it only **reserves**: `reserved_bytes += payload_len + 4096`, admitted when `used + reserved + request <= quota + evictable_bytes` (evictable = unpinned, not in flight, not already evicting). If admitted but `used + reserved` is above quota, the job starts in state `Reclaiming`: the worker selects LRU victims under the index mutex (marking them `Evicting`, so `lookup` already misses them), releases the mutex, `unlink`s them, subtracts their bytes only after each unlink returns, and only when enough space is reclaimed proceeds to P1. If reclamation cannot free enough (everything left is pinned), the job ends `Failed(OutOfMemory)` and its reservation is released. Publication therefore always follows reclamation; no unlink or native slot invalidation ever runs under the spine or KV lock. Keys pinned by an assembling restore chain are never evicted, so a restore cannot be undone by the park it triggered. A sequence whose restore failed twice in a row within `AIEN_KV_RESTORE_RETRY_WINDOW_MS` is prefilled without lookup (counter per namespace+key chain head, bounded map of 1024 entries). ### 7.5 Shutdown drain (review finding 11) Two separate promises. **Intake and drain deadline** (default 2000 ms, `shutdown(intake_deadline_ms)`): stop intake; cancel everything still `Submitted` or `Reclaiming` (temps unlinked); let jobs already past `fsync(file)` finish their rename; cancel all loads. **Eventual I/O termination** is not promised in time, because `fsync`, directory `fsync` and thread join have no bounded completion time on a stalled filesystem. Rules: (a) the worker owns an `Arc` clone of the KV manager and of every source and destination buffer, and keeps them until each job's terminal completion, so memory is never freed under a possibly running I/O (freeing it to force the deadline would violate ownership); (b) `shutdown` returns at the deadline with a `DrainReport` whose `unfinished` list names every job still running (key, bytes, stage) and the counters `kv_shutdown_unfinished_jobs` and `kv_shutdown_unfinished_bytes` are set; (c) the daemon logs the list and may exit; process exit reclaims all memory at once, and any temp left behind is deleted by the next recovery. Guarantee at exit: every job that reported `Published` is on disk or was reported `Indeterminate`; unfinished jobs are reported, never silently dropped; nothing else exists after restart (recovery deletes temps). An embedding that drops the store without exiting leaves the detached worker alive with its `Arc`s until the I/O ends. ## 8. Lock discipline Locks, in the only allowed nesting order: spine `tokio::Mutex` (server.rs:27) -> KV `RwLock` (lib.rs:1685) -> store index `std::Mutex`. Rules: 1. No storage I/O, no `fsync`, no `unlink`, no sleep and no `poll` wait happens while the spine lock or the KV lock is held. The worker thread never takes the spine lock. `submit_store` performs no eviction (section 7.4); eviction, unlink and native slot invalidation run only on the worker. 2. S1, S2 and S3 run on the spine thread (S3 needs `&mut` scheduler access, which only the spine has: spine.rs:24, server.rs:204). The storage worker takes the KV lock only in S4, when a holder guard it owns is released, and never while holding its own state mutex or the index mutex (the worker drops released guards after its state lock, worker.rs `Shared::with`); it releases the index mutex before any I/O. 3. The spine takes the index mutex only through `submit_*`, `poll`, `cancel`, `lookup`, `attach_waiter`, which are O(1)/O(keys) and never block on I/O. 4. The KV lock is held across S1..S4 for O(blocks) bookkeeping; the existing scheduler already holds it for the same order of work (`complete_prefill`, `free_sequence`). S1 runs inside the scheduler's own finish transaction under the guard it already takes for `free_sequence`; it adds only `fork_range` and an outbox push and takes no other lock (the outbox mutex is a leaf lock held for one `Vec::push`). ## 9. Native mapping (aienos #367) 1. **Device contract kept**: every slot write and read is a sequence of `disk_write`/`disk_read` calls of at most `max_blocks_per_io` through the bounce buffer, one command at a time (disk.h:17-24, disk_nvme.h:17-19). The adapter owns no DMA memory: the caller's KV bytes are copied into the bounce buffer by the driver (bounce contract) so DMA visibility is the driver's, not the adapter's; the adapter only guarantees the source slice is unchanged until `disk_write` returns (same rule as `st_transact`, store_engine.h:146-149). Transfer splitting: a 4 MiB chunk is 32 commands of 128 KiB (calc:a81bdf6c; limit from disk_nvme.h:53-56). A faster command path is a profiled-only follow-up (section 15.7), not part of this contract. 2. **Completed vs durable**: `Completed` = payload units written and `disk_flush` returned; `Published` = header unit written; `Durable` = `disk_flush` after the header returned. Interruption between payload and header leaves a zero header (we zeroed and flushed it first) so recovery sees an empty slot: no partial record is ever exposed. A torn header unit is rejected by `unit_sha256`; `nvme_write_is_power_fail_atomic` is consulted at format time and recorded in the slab superblock as a documented limit, not a check. 3. **Bounded progress**: native has no asynchronous completion (context 15, 20). The adapter is therefore a **step-budgeted state machine**: `kv_slab_pump(budget_cmds)` issues at most `budget_cmds` disk commands (default 2, at most 262144 bytes = 256 KiB at the 128 KiB cap, calc:6d37d10d) and returns. Two callers (review finding 14): the between-steps hook, and an **idle pump** loop in the stage that owns the session, because `ck_infer_prompt` leaves its loop on `STEP_LAST` before its callback runs (infer.c:473-474, VERIFIED) and then consumes the request with `aienos_infer_session_cancel()` (infer.c:495-498, VERIFIED), so a park queued after the reply has no between-steps call to ride on. Tokens keep being produced while a slot fills over many steps, which is the bounded progress #367 asks for. **Limitation, reported, not hidden**: with a polled single-command driver on the same core, inference and I/O are interleaved, not overlapped. The evidence that distinguishes real interleaving from mere queueing is the per-step timestamp log: decode steps continue (token timestamps advance) while the slab command counter advances between them. True overlap would need a second core or interrupts and is out of scope. 4. **Separate quota and lifetime**: the slab region is a disjoint LBA range (section 2.5); `kv_disk_bind` refuses overlap; the slab is formatted and erased independently of the Store (`st_format` never touches it; wiping the slab never touches the Store or anchor). Cache eviction is slot overwrite inside the slab only. Existing Store/Cortex tests keep their regions and stay valid, and the explicit regression gates are named in CUTS.md (N2, N5). 5. **Encryption and authorization preserved**: the wire layout and the authenticated mapping from (namespace, chunk key, slot, incarnation, payload hash) into M5 are in section 2.5. `k_domain` exists only after the sealed Store is unlocked (store_boot.h), so a slot is ciphertext to anyone without the volume key: cache reuse cannot bypass session authorization. Decrypt follows the private scratchpad rule (AGENTS.md section 4): the tag is verified before any byte reaches the session's KV (m5_envelope.c:166-171, VERIFIED, uses a private 64 KiB scratch). The native `sharing_namespace` is the sealed Store uuid || identity class || the subject id, so a TEST-class Store never serves a PRODUCTION one. 6. **Native inference path** (review finding 13). `set_pos` alone cannot restore a session: `aienos_infer_session_prompt` resets the cache and sets `fed = 0` (session.rs:213-216, VERIFIED), and `aienos_infer_session_step` feeds `prompt[fed]` regardless of `DecodeState.pos` (session.rs:241-244, VERIFIED), so importing rows and setting only `pos` is either erased by the next prompt or repeats token zero at the restored position. New FFI in `aienos-infer-kernel` (no_std), in two parts so a failed restore can never leave a half-visible prefix: - `aienos_infer_session_kv_export(layer, pos0, n, out_k, out_v)` reads rows `[pos0, pos0+n)` of a layer; `aienos_infer_session_computed()` returns `DecodeState.pos`, the number of positions whose K/V exists (the last sampled token of a finished reply has none: `STEP_LAST` produces a token without running its forward pass, session.rs:253-258). - `aienos_infer_session_kv_import(layer, pos0, n, in_k, in_v)` writes rows only; it never touches `pos` or `fed`, so the rows are invisible until committed. - `aienos_infer_session_restore_commit(n, ids, n_ids)`, called **after** `aienos_infer_session_prompt` has prepared the request: all-or-nothing, it checks `s.fed == 0`, `n < prompt.len()`, `n <= kv_capacity`, `ids[..n] == prompt[..n]`, then sets `st.pos = n` and `fed = n`; the output list and `done` are untouched, logits come from the suffix steps as in a cold run. Any refusal changes nothing. Native **CPU** only; native GPU (#327) is not touched and not claimed. 7. **Park timing and source ownership** (review finding 14). The session's K/V buffers are reused by the next prompt (`reset` only sets `pos = 0`, decode.rs:93-96, VERIFIED), so a park job cannot keep reading them after the reply. At the park point (after `STEP_LAST`, before the consuming `aienos_infer_session_cancel`; `ck_infer_prompt` gains a `park_point` callback there) the stage **exports and seals the chunks synchronously into adapter-owned ciphertext buffers** (bounded: `KV_PARK_STAGE_BYTES`, section 10). From then on the slab job reads only those buffers; the session is free to reset, close or take the next prompt, and none of those events can change what the job writes. Jobs not terminal at a `ck_reset` simply vanish: their slots have a zero or torn header (section 2.5). The pump runs from the idle loop until the queue is empty; the stage's shutdown calls `kv_slab_drain(deadline)`. 8. **Overlap proof or limitation**: reported as limitation (item 3). Multiple outstanding commands are out of scope unless profiling justifies them (section 15.7); the pump budget is the only tuning knob and is not an acceptance claim. ## 10. Memory accounting Reported separately, never conflated (names in METRICS_AND_SETTINGS.md): - `kv_pool_allocated_bytes`: the pool allocation, constant after start (`KvPoolPlan.total_bytes`, shared_kv.rs:144). Freeing blocks never changes it, and the status report says so in its field name. - `kv_pool_free_blocks`, `kv_pool_used_blocks` (existing `free_block_count`/`allocated_block_count`), `kv_pool_holder_blocks` (blocks referenced by storage holders), `kv_restore_inflight_blocks`. - `kv_store_inflight_bytes`, `kv_store_inflight_ops` (queue occupancy), `kv_store_reserved_bytes`, `kv_store_persisted_bytes`, `kv_store_persisted_objects`, `kv_store_unindexed_bytes`, `kv_store_quota_bytes`. - Host staging: `kv_host_tail_scratch_bytes` (the one-block scratch of section 2.2) and, when the `O_DIRECT` path is enabled, nothing else (direct I/O reads into the pool). Buffered mode adds no application buffer but uses the page cache, which is reported as `cache_state`, not as staging. - Native staging, **each reported separately** (review finding 15): `kv_stage_export_bytes` (plaintext snapshot of the chunk being sealed), `kv_stage_cipher_bytes` (queued sealed envelopes, bounded by `KV_PARK_STAGE_BYTES`), `kv_stage_env_bytes` and `kv_stage_plain_bytes` (the contiguous envelope and the decrypt output of one restore chunk), `kv_crypto_scratch_bytes` (the private 64 KiB scratch inside `m5_envelope_open`, `scratch[M5_ENV_MAX_CHUNK]` at m5_envelope.c:170, VERIFIED, on the stack of the call), `kv_slab_bounce_bytes` (the driver's bounce size, a second copy of every transfer), `kv_stage_queued_bytes` (sum owned by queued jobs) and `kv_stage_peak_bytes` (high-water of all of the above together). The earlier text called the bounce buffer the only staging memory; that was wrong. - Native adds `kv_slab_slots_total/used`. ## 11. Guarantee matrix Every cell carries one label: PLANNED, TESTED(receipt), NOT CLAIMED or NOT_RUN. A TESTED receipt is the name of the test that proves the cell (host only, `pkv/integration`); `kv_restart_test.rs::guarantee_matrix_rows_are_labelled` checks the labels and that every named test exists. A cell stays PLANNED until its cut merges with a green run. | scenario | host adapter | native adapter | claim | |---|---|---|---| | adapter recreation (same process, new `KvStore` over the same dir/slab) | TESTED(store_then_recreate_adapter_serves_same_bytes) (C4: recover, lookup, load, bytes equal) | PLANNED, host emulation over `disk_file` (N3) | objects published before `close` are served | | process restart (real child process, `current_exe` pattern of `approved_crash_test.rs:80-89`) | TESTED(process_restart_rediscovers_and_restores_identical_bytes, greedy_continuation_after_restart_matches_uninterrupted_baseline) (C7: real child processes on a temp-dir host store; greedy on the CPU reference backend only) | PLANNED as emulator reboot on one image (N5) | greedy continuation equals baseline | | host fault at each publication boundary (P1 to P5, section 2.4) | TESTED(fault_at_each_publication_boundary_leaves_consistent_outcome) (C4, `FsOps` fault seam) | NOT CLAIMED (no host publication boundaries natively; the slab write order belongs to cut N2) | consistent outcome at every boundary; `Indeterminate` reported, never silent | | clean reboot | NOT CLAIMED on the host (no reboot test; fsync + rename + dir fsync is the standard recipe, INFERRED sufficient) | PLANNED in QEMU only (N5 is a reboot); physical Spark NOT_RUN (aienos#336) | emulator only | | abrupt power loss | NOT CLAIMED on the host | PLANNED in emulation with the `disk_file` power-cut injector at every unit boundary (N2, same method as the store crash tests); physical NOT_RUN | no partial record is ever exposed; durability of `Published`-but-not-`Durable` slots is not claimed | | real cold boot on hardware | NOT CLAIMED | PLANNED on a Raspberry Pi 5, labelled \"native physical (Pi 5)\" (cut P3, section 16); Spark-native stays NOT_RUN (aienos#336) | reboot through tryboot is a firmware restart, not a power cut | ## Consequences - New crate `aien-kv-store` (identity, header codec, validation, trait, fake adapter, host adapter). `aien-kv-cache` gains `fork_range`, `assemble_table` and the reserved holder slot rule. `aien-scheduler` gains `SequencePhase::AwaitingRestore`, `admit_restored_prefix` and the `FinishHook`. `aien-runtime` gains the residency map, the park outbox drained after `step`, restore at submit, status fields. `aien-abi-core` gains `computed_prefix` and `restore_sequence` on the backend trait with defaults (`None` and `Err`). - Objects are never shared across `block_size`, `chunk_tokens`, dtype, layout, backend, compute configuration or model; a model upgrade orphans the old objects, which still count toward quota until evicted (section 4.1, by design). - The design does not add resident retention of parked chunks (an L1 of holders kept alive under low pressure). The ownership model allows it later with no format change. - Native hosted and emulator results do not qualify physical hardware; every physical row stays NOT_RUN until an authorized run, and a Pi 5 result never stands in for a Spark result. ## Known limits - Segment SHA-256 on load costs roughly 1 ms per MiB on one core (INFERRED from typical sha2 throughput, not measured); it runs on the worker and, with per-segment digests, on several cores in parallel (section 15.4), so it adds restore latency, not step latency. BLAKE3 is not adopted for format version 1 (section 15.4 gives the reason and the condition for revisiting it). - The restorable prefix is capped at `prompt.len() - 1`; one token of prefill is always paid. - Quota accounting counts foreign-namespace objects but does not read their payloads; an object with a valid header and a corrupt payload occupies quota until its first load deletes it or LRU evicts it. - `max_objects` default 65536 and the index are per store directory; two daemons sharing one directory are not supported (STORE_ID is advisory, there is no lock file in this milestone). - `arith_id` is a coarse label and `KV_ARITH_EPOCH` is a human-bumped counter backed by a pinned-bytes test; a numeric change the pinned test does not exercise could slip through (UNKNOWN residual risk; the test m\n\nIn one sentence, what is the text above about?", "source_sha256": "2bcc84b25c418cba83df9546344fd4ae28962c314e03defe2aab62a8e6c8abb9"} +{"id": "t32k", "text": " frees the sequence after publication (section 6), so there is no resident-but-parked state to track. `Failed` is sticky per request until the request's recompute path has started, then it is cleared; it exists so a stale completion cannot flip a request back. `Draining` is new (review finding 5): a restore that has a failed chunk still owns its destinations until every sibling job has produced its terminal completion. ### 5.2 Storage references reuse the fork refcount The storage worker never holds a raw block id. A **holder** is a real block table in `AienKvManager` whose id lives in the reserved slot `u32::MAX` (`SequenceId { slot: u32::MAX, generation: job_id as u32 }`, generation nonzero). Arena slot indices start at 0 and grow by one per new slot (`allocate_slot` pushes when `free_slots` is empty, sequence.rs:382-399, VERIFIED), so slot `u32::MAX` is unreachable in practice but not refused today; C3 adds the refusal in `allocate_slot` (slot index must stay below `u32::MAX`) so the reservation is a rule, not an assumption. **One holder per chunk**, both directions: - Park: a new primitive `fork_range(seq, holder, block_range)` takes one reference on exactly the blocks of that chunk (C3). `fork_sequence(seq, holder)` is not used: it copies the parent's whole table (lib.rs:1165-1210, VERIFIED), so a per-chunk holder built with it would pin every block of the sequence. - Restore: `allocate_sequence(holder, tokens)` allocates zeroed blocks owned by that chunk's holder. - Assembly: `assemble_table(seq, holders)` (C3) builds the request's own table from the holders' block lists, adding one reference per block and marking the table `PrefillPending`. It refuses a `seq` that already has a table (unlike `fork_sequence`, which frees a live child id's blocks, lib.rs:1181-1184, VERIFIED) and refuses any holder that is not complete. - Release: `free_sequence(holder)`. Consequences, all from existing code paths: - A block reaches `free_blocks` only when its refcount hits zero (lib.rs:1419-1425), so a slot is reused only after the sequence tables and the storage holders are all done. No new free-list logic. - Shared-prefix owners stay valid when another owner parks or cancels: the holder is one more sharer; the existing COW tests already cover the invariants (`crates/aien-kv-cache/tests/cow_branching_tests.rs`). - A parked sequence that resumes while its park is in flight copies on write only on a partial last block (lib.rs:1234-1255): the worker keeps reading the frozen original. - `fork_range` leaves the parent's state alone; `fork_sequence` sets the parent to `SharedFrozen` (lib.rs:1192-1197), which is the intended meaning for a fully ready parent. ### 5.3 Incarnation checks Every job carries `Incarnation = (seq_id u64 as issued by the arena, residency_epoch u32)`; the spine bumps `residency_epoch` on every state transition of that sequence. A completion is committed only if the sequence still exists with the same `seq_id` (its generation makes a reused slot a different id, sequence.rs:7-50) **and** the same epoch. Anything else is counted `kv_store_stale_completions` and its holder is freed after the terminal completion. A reused sequence id can therefore never be mutated by an old job. ### 5.4 Short critical sections (the only places the KV lock is taken for storage) | name | lock | work | bound | |---|---|---|---| | S1 finish-fork | KV write, **inside the scheduler's finish transaction, before `free_sequence`** (section 6.1) | `fork_range(seq, holder_i, range_i)` per chunk; push a `ParkIntent` to a lock-free outbox | O(blocks) | | S2 restore-alloc | KV write | `allocate_sequence(holder_i, tokens_i)` per chunk; refuse if `free < watermark + needed` | O(blocks) | | S3 restore-commit | KV write, **on the spine thread** while it handles polled completions, never on the storage worker (review 2, new finding 2) | verify incarnation and that **every** job of the txn is `Completed`; `assemble_table(seq, holders)`; scheduler `admit_restored_prefix` (section 6.3) | O(blocks) | | S4 holder-release | KV write | `free_sequence(holder_i)`, only when the txn has no non-terminal job | O(blocks) | | S5 queue | store index mutex | push/pop/complete | O(1) | The segment hashes on load are verified over the destination blocks *before* S3 (they are holder-owned and invisible to the scheduler until assembled), so no copy to a staging buffer is needed on the host. ### 5.5 Cancellation and restore transactions - A **restore transaction** (`RestoreTxn`) owns all of one request's chunk holders and the list of its submitted job ids. It is the unit of ownership: no holder of a txn is freed, reused or handed to prefill while any job of the txn is non-terminal (review finding 5). When chunk A fails while chunk B is mid-transfer: the txn moves to `Draining`, `cancel(job)` is issued for every non-terminal sibling, and the txn waits for each sibling's terminal completion (`Done`, `Failed` or `Cancelled`); only then S4 frees the holders and the request goes to plain prefill. `TooLate` siblings simply finish, their bytes are discarded. - Cancel own waiter only: a request that is cancelled (`CancelSwarm`, `Aborted`, client gone) cancels its own txn the same way. Shared work (a same-key load another request is waiting on) is never cancelled: the coalescing table keeps the job alive while any waiter remains; cancelling removes the waiter only. - Mid-transfer cancel of a store: the worker checks the cancel flag between segment writes (bounded granularity = one block); the temp is unlinked; nothing was published. - The worker never writes into a freed holder: the free happens in S4 only after the terminal completion of every job that targets it, so there is no use-after-free of pool blocks, including on the multi-chunk failure path. ## 6. Park and restore in the runtime ### 6.1 Boundary (review finding 2) The earlier text parked in `AienRuntimeSpine::step` when it processed `DecodeOutput::Finished` (spine.rs:198-230). That is too late (VERIFIED by the review and by reading the scheduler): `AienScheduler::step` frees the sequence's block table inside its own finish handling, `free_sequence(request_id)` at aien-scheduler/src/lib.rs:1106 for a normal finish and at 1152 for a backend-originated `Finished`, before it returns the `Finished` output (lib.rs:1111, 1172). By the time the spine sees `Finished`, the blocks are gone; what remains there is `backend.release_sequence` (spine.rs:225), which only drops backend state. Design: ownership transfer happens **inside the scheduler's finish transaction**. The scheduler gets an optional `FinishHook` (a trait object set by the spine; absent means today's behaviour exactly). At each of the two finish sites, for any finish reason except `Preempted`, in this order and inside one KV write guard: 1. `prefix = backend.computed_prefix(request_id)` (section 6.2), read while the backend still holds the sequence (the backend call happens before the guard is taken, the backend is not touched under the guard). 2. `hook.on_finish(&mut kv, request_id, prefix)`: `fork_range` into per-chunk holders (S1), a `ParkIntent { holders, keys, headers, incarnation }` pushed to an outbox (a `Mutex<Vec>` with O(1) push; no I/O, no store call). 3. The existing `free_sequence(request_id)`. The spine drains the outbox right after `step` returns and calls `submit_store` for each intent; a refused submit frees that holder (S4) and counts `kv_park_failed_total`. Because the fork happens before the free, the blocks have refcount at least 1 at every instant; the window the review found does not exist. Active decode KV stays resident: nothing parks a running sequence (milestone rule). A `Preempted` finish is not parked (its K/V is incomplete by definition). ### 6.2 Park 1. **Computed prefix, not the token list** (review finding 3). The backend exposes `computed_prefix(seq_id) -> Option<Vec<u32>>`, the tokens whose K/V is actually in the pool. VERIFIED facts it rests on: decode reads `pos = tokens.len() - 1` and computes K/V for the last token (transformer_backend.rs:1776-1782), then appends the newly sampled token (2158), so after any decode step the last token in `tokens` has no K/V; after prefill, `tokens.len()` equals the cached positions and the sample is held apart in `pending_prefill_token` (transformer_backend.rs:136-143), also with no K/V. So `computed = tokens.len()` when a pending prefill token exists and no decode has run, otherwise `tokens.len() - 1`. The earlier rule \"tokens plus the pending token\" would have labelled an unwritten position as valid and let a longer later prompt restore it. Nothing beyond `computed` is ever hashed, keyed or written. The mapping is asserted by a red test that reads the pool and shows position `computed` is unwritten. 2. Compute the key chain for full chunks of `computed` and the partial tail (`token_count = computed mod chunk_tokens`). Skip chunks whose keys `lookup` already finds or that are in flight (same-key publication dedup). 3. S1 inside the finish transaction (section 6.1), one holder per chunk. The writer applies the tail-row zeroing of section 2.2 to the last partial block. The stores are low priority (section 7.2). 4. The sequence's own references are dropped as today; the holders keep the blocks until each job is terminal, then S4. ### 6.3 Restore 1. On `submit_request` in the spine, compute the key chain of the prompt, walk it until the first miss, cap the restorable prefix at `prompt.len() - 1` (context 25: the last prompt token is always recomputed so the logits come from this prompt). Also cap at the operator context (`AIEN_KV_CONTEXT_TOKENS`). A restorable prefix that ends inside a chunk uses only whole stored chunks; a partial-tail chunk is used only if its exact token count is the cap. 2. `pin` the keys; S2 allocates one holder per chunk; submit loads (high priority) for all chunks under one `RestoreTxn`; the request's residency becomes `Restoring`. The request stays in the scheduler's waiting queue with a new `SequencePhase::AwaitingRestore` that `build_scheduled_batch` skips: ready resident sequences keep decoding (the #485 slow-I/O proof). 3. When every job of the txn is `Completed` (and none failed): S3 runs `assemble_table(seq, holders)` and the scheduler's new `admit_restored_prefix(seq_id, restored)` (review finding 4). The existing admission cannot be reused as it was designed: for a waiting sequence whose table is ready it sets `prompt_tokens_prefilled = prompt_len` and enters decode (aien-scheduler/src/lib.rs:779-784, VERIFIED), skipping the unprocessed suffix; for a table that is not ready it frees the table and prefills from zero (lib.rs:802-806, VERIFIED). So `admit_restored_prefix` bypasses the waiting queue: it leaves the table `PrefillPending` (never `complete_prefill` at restore), sets `prompt_tokens_prefilled = restored`, `is_prefilled = false`, `phase = Prefill`, and pushes the sequence into `running_sequences`, where the existing \"continuing chunked prefill\" branch schedules `prompt[restored..]` (lib.rs:572-606, VERIFIED) and the existing completion fence marks the table ready only after the last chunk (lib.rs:1023-1033, VERIFIED). Because `restored <= prompt.len() - 1`, at least one token is always left, so the fence always runs and decode can never start on a restored-only table. The backend hook `restore_sequence(seq_id, tokens)` sets `SequenceState.tokens = prompt[..restored]` so the next chunk's positions line up (checks as `fork_sequence`). 4. Any failure or stale completion: txn `Draining` (section 5.5), then `Failed`, holders freed, phase `Waiting` with `prompt_tokens_prefilled = 0`: a plain prefill. No request is ever refused because of the cache; refusal exists only when history itself is unavailable, which is the generation record's job, not this design's. ### 6.4 Non-tensor state Positions: reconstructed from chunk order. Pending prefill token: not needed, the restore ends inside the prompt and the suffix prefill produces a fresh pending token. Sampling state: `SamplingParams` come with every request (abi-core lib.rs:455-460); the sampling seed is `decode_sampling_seed(request_id, position)` with a fresh `request_id` after a restart, so **stochastic continuation is not reproducible across restart and is not claimed**; greedy continuation is. A test for stochastic continuation, if ever wanted, must pin the seed explicitly; that is outside this milestone. ### 6.5 Guarantee: greedy continuation equals the uninterrupted baseline Holds when the restored bf16 block bytes are identical, the remaining prefill runs on the same backend with the same weights and the same `compute_config_digest` (identity guarantees the last two, section 1.2.1). The test runs a prompt cold, records the greedy tokens, parks, restarts the process, restores the prefix and compares tokens. The backend must prefill the remainder starting at the restored position with the same chunking as the cold run would have used from that position (chunked prefill is position-based, lib.rs:572-606). ## 7. Queues, bounds, fairness, drain ### 7.1 Bounds and per-class reservation (review finding 9) Two bounded intake classes (restore, park) and one completion queue, all behind the store's index mutex. Limits are **per class**, not shared: `max_inflight_ops` (default 64) is split 48 restore and 64 park (`max_restore_ops`, `max_park_ops`; park raised from 16 after the C9 bench, section 18.4), and `max_inflight_bytes` (default 256 MiB) is split the same 3:1. A class can never consume the other's reservation, so continuous restores cannot make every park fail before the dispatcher runs. Bytes count the sum of `payload_len + 4096` of every job between Submitted and its terminal completion. `submit_*` refuses with `QueueFull`; the spine treats a refused park as \"not parked this turn\" (the holders are released) and a refused restore as a plain prefill. Restore destination blocks are counted against the pool: S2 refuses when `free_blocks < watermark_blocks + needed` (the scheduler's own watermark, aien-scheduler lib.rs:460-470), so restores can never starve admission. **Completion capacity** is reserved at submit: each accepted job reserves three completion slots (Completed, Published, terminal), so `poll` never overflows and the worker never blocks on a full queue. **Credit release** happens at the job's terminal completion as the store sees it, not when the caller later commits: a slow KV lock cannot hold store credits. **Bounded waiters**: at most `max_waiters_per_job` (default 16) per coalesced load and 1024 in total; the 17th request does a plain prefill instead of attaching. Holder metadata is bounded by the restore-block budget `AIEN_KV_RESTORE_MAX_BLOCKS`. ### 7.2 Fairness Within the reserved shares, the worker dispatches by credits: 3 restores then 1 park when both queues are non-empty (restore latency matters to a waiting user; parks free resident memory and must not starve). Within a queue, FIFO by submission. The reservation of 7.1 guarantees admission fairness; the credits guarantee dispatch fairness. A PLANNED saturation test (C5) offers restores at the maximum rate for 10 000 operations and asserts parks are still admitted and dispatched at no less than their reserved share. ### 7.3 Coalescing (review finding 6) Same-key loads coalesce at the **job and landing-buffer level**, never at the request-table level. One in-flight load per chunk key lands in that chunk's holder; later requests `attach_waiter` to the job and, on `Completed`, each request builds **its own table** with `assemble_table(seq_i, [holder_0 .. holder_k])` from the chunk holders it needs. The shared chunk blocks are immutable once `Completed` and shared by refcount; each request's suffix chunks are its own holders. A request commits (S3) only when all of its chunks are `Completed` and validated. `fork_sequence(first_seq, other_seq)` is never used for coalescing (it would share the first request's whole table and replace the other request's own). Same-key stores: `inflight_stores` set; duplicates are dropped at submit with `Ok(JobId)` of the existing job (the caller only needs \"it will be published\"). ### 7.4 Eviction, reservation and thrash (review finding 7) `submit_store` never evicts and never touches the filesystem; it runs under the spine's lock path and must stay O(1). Under the index mutex it only **reserves**: `reserved_bytes += payload_len + 4096`, admitted when `used + reserved + request <= quota + evictable_bytes` (evictable = unpinned, not in flight, not already evicting). If admitted but `used + reserved` is above quota, the job starts in state `Reclaiming`: the worker selects LRU victims under the index mutex (marking them `Evicting`, so `lookup` already misses them), releases the mutex, `unlink`s them, subtracts their bytes only after each unlink returns, and only when enough space is reclaimed proceeds to P1. If reclamation cannot free enough (everything left is pinned), the job ends `Failed(OutOfMemory)` and its reservation is released. Publication therefore always follows reclamation; no unlink or native slot invalidation ever runs under the spine or KV lock. Keys pinned by an assembling restore chain are never evicted, so a restore cannot be undone by the park it triggered. A sequence whose restore failed twice in a row within `AIEN_KV_RESTORE_RETRY_WINDOW_MS` is prefilled without lookup (counter per namespace+key chain head, bounded map of 1024 entries). ### 7.5 Shutdown drain (review finding 11) Two separate promises. **Intake and drain deadline** (default 2000 ms, `shutdown(intake_deadline_ms)`): stop intake; cancel everything still `Submitted` or `Reclaiming` (temps unlinked); let jobs already past `fsync(file)` finish their rename; cancel all loads. **Eventual I/O termination** is not promised in time, because `fsync`, directory `fsync` and thread join have no bounded completion time on a stalled filesystem. Rules: (a) the worker owns an `Arc` clone of the KV manager and of every source and destination buffer, and keeps them until each job's terminal completion, so memory is never freed under a possibly running I/O (freeing it to force the deadline would violate ownership); (b) `shutdown` returns at the deadline with a `DrainReport` whose `unfinished` list names every job still running (key, bytes, stage) and the counters `kv_shutdown_unfinished_jobs` and `kv_shutdown_unfinished_bytes` are set; (c) the daemon logs the list and may exit; process exit reclaims all memory at once, and any temp left behind is deleted by the next recovery. Guarantee at exit: every job that reported `Published` is on disk or was reported `Indeterminate`; unfinished jobs are reported, never silently dropped; nothing else exists after restart (recovery deletes temps). An embedding that drops the store without exiting leaves the detached worker alive with its `Arc`s until the I/O ends. ## 8. Lock discipline Locks, in the only allowed nesting order: spine `tokio::Mutex` (server.rs:27) -> KV `RwLock` (lib.rs:1685) -> store index `std::Mutex`. Rules: 1. No storage I/O, no `fsync`, no `unlink`, no sleep and no `poll` wait happens while the spine lock or the KV lock is held. The worker thread never takes the spine lock. `submit_store` performs no eviction (section 7.4); eviction, unlink and native slot invalidation run only on the worker. 2. S1, S2 and S3 run on the spine thread (S3 needs `&mut` scheduler access, which only the spine has: spine.rs:24, server.rs:204). The storage worker takes the KV lock only in S4, when a holder guard it owns is released, and never while holding its own state mutex or the index mutex (the worker drops released guards after its state lock, worker.rs `Shared::with`); it releases the index mutex before any I/O. 3. The spine takes the index mutex only through `submit_*`, `poll`, `cancel`, `lookup`, `attach_waiter`, which are O(1)/O(keys) and never block on I/O. 4. The KV lock is held across S1..S4 for O(blocks) bookkeeping; the existing scheduler already holds it for the same order of work (`complete_prefill`, `free_sequence`). S1 runs inside the scheduler's own finish transaction under the guard it already takes for `free_sequence`; it adds only `fork_range` and an outbox push and takes no other lock (the outbox mutex is a leaf lock held for one `Vec::push`). ## 9. Native mapping (aienos #367) 1. **Device contract kept**: every slot write and read is a sequence of `disk_write`/`disk_read` calls of at most `max_blocks_per_io` through the bounce buffer, one command at a time (disk.h:17-24, disk_nvme.h:17-19). The adapter owns no DMA memory: the caller's KV bytes are copied into the bounce buffer by the driver (bounce contract) so DMA visibility is the driver's, not the adapter's; the adapter only guarantees the source slice is unchanged until `disk_write` returns (same rule as `st_transact`, store_engine.h:146-149). Transfer splitting: a 4 MiB chunk is 32 commands of 128 KiB (calc:a81bdf6c; limit from disk_nvme.h:53-56). A faster command path is a profiled-only follow-up (section 15.7), not part of this contract. 2. **Completed vs durable**: `Completed` = payload units written and `disk_flush` returned; `Published` = header unit written; `Durable` = `disk_flush` after the header returned. Interruption between payload and header leaves a zero header (we zeroed and flushed it first) so recovery sees an empty slot: no partial record is ever exposed. A torn header unit is rejected by `unit_sha256`; `nvme_write_is_power_fail_atomic` is consulted at format time and recorded in the slab superblock as a documented limit, not a check. 3. **Bounded progress**: native has no asynchronous completion (context 15, 20). The adapter is therefore a **step-budgeted state machine**: `kv_slab_pump(budget_cmds)` issues at most `budget_cmds` disk commands (default 2, at most 262144 bytes = 256 KiB at the 128 KiB cap, calc:6d37d10d) and returns. Two callers (review finding 14): the between-steps hook, and an **idle pump** loop in the stage that owns the session, because `ck_infer_prompt` leaves its loop on `STEP_LAST` before its callback runs (infer.c:473-474, VERIFIED) and then consumes the request with `aienos_infer_session_cancel()` (infer.c:495-498, VERIFIED), so a park queued after the reply has no between-steps call to ride on. Tokens keep being produced while a slot fills over many steps, which is the bounded progress #367 asks for. **Limitation, reported, not hidden**: with a polled single-command driver on the same core, inference and I/O are interleaved, not overlapped. The evidence that distinguishes real interleaving from mere queueing is the per-step timestamp log: decode steps continue (token timestamps advance) while the slab command counter advances between them. True overlap would need a second core or interrupts and is out of scope. 4. **Separate quota and lifetime**: the slab region is a disjoint LBA range (section 2.5); `kv_disk_bind` refuses overlap; the slab is formatted and erased independently of the Store (`st_format` never touches it; wiping the slab never touches the Store or anchor). Cache eviction is slot overwrite inside the slab only. Existing Store/Cortex tests keep their regions and stay valid, and the explicit regression gates are named in CUTS.md (N2, N5). 5. **Encryption and authorization preserved**: the wire layout and the authenticated mapping from (namespace, chunk key, slot, incarnation, payload hash) into M5 are in section 2.5. `k_domain` exists only after the sealed Store is unlocked (store_boot.h), so a slot is ciphertext to anyone without the volume key: cache reuse cannot bypass session authorization. Decrypt follows the private scratchpad rule (AGENTS.md section 4): the tag is verified before any byte reaches the session's KV (m5_envelope.c:166-171, VERIFIED, uses a private 64 KiB scratch). The native `sharing_namespace` is the sealed Store uuid || identity class || the subject id, so a TEST-class Store never serves a PRODUCTION one. 6. **Native inference path** (review finding 13). `set_pos` alone cannot restore a session: `aienos_infer_session_prompt` resets the cache and sets `fed = 0` (session.rs:213-216, VERIFIED), and `aienos_infer_session_step` feeds `prompt[fed]` regardless of `DecodeState.pos` (session.rs:241-244, VERIFIED), so importing rows and setting only `pos` is either erased by the next prompt or repeats token zero at the restored position. New FFI in `aienos-infer-kernel` (no_std), in two parts so a failed restore can never leave a half-visible prefix: - `aienos_infer_session_kv_export(layer, pos0, n, out_k, out_v)` reads rows `[pos0, pos0+n)` of a layer; `aienos_infer_session_computed()` returns `DecodeState.pos`, the number of positions whose K/V exists (the last sampled token of a finished reply has none: `STEP_LAST` produces a token without running its forward pass, session.rs:253-258). - `aienos_infer_session_kv_import(layer, pos0, n, in_k, in_v)` writes rows only; it never touches `pos` or `fed`, so the rows are invisible until committed. - `aienos_infer_session_restore_commit(n, ids, n_ids)`, called **after** `aienos_infer_session_prompt` has prepared the request: all-or-nothing, it checks `s.fed == 0`, `n < prompt.len()`, `n <= kv_capacity`, `ids[..n] == prompt[..n]`, then sets `st.pos = n` and `fed = n`; the output list and `done` are untouched, logits come from the suffix steps as in a cold run. Any refusal changes nothing. Native **CPU** only; native GPU (#327) is not touched and not claimed. 7. **Park timing and source ownership** (review finding 14). The session's K/V buffers are reused by the next prompt (`reset` only sets `pos = 0`, decode.rs:93-96, VERIFIED), so a park job cannot keep reading them after the reply. At the park point (after `STEP_LAST`, before the consuming `aienos_infer_session_cancel`; `ck_infer_prompt` gains a `park_point` callback there) the stage **exports and seals the chunks synchronously into adapter-owned ciphertext buffers** (bounded: `KV_PARK_STAGE_BYTES`, section 10). From then on the slab job reads only those buffers; the session is free to reset, close or take the next prompt, and none of those events can change what the job writes. Jobs not terminal at a `ck_reset` simply vanish: their slots have a zero or torn header (section 2.5). The pump runs from the idle loop until the queue is empty; the stage's shutdown calls `kv_slab_drain(deadline)`. 8. **Overlap proof or limitation**: reported as limitation (item 3). Multiple outstanding commands are out of scope unless profiling justifies them (section 15.7); the pump budget is the only tuning knob and is not an acceptance claim. ## 10. Memory accounting Reported separately, never conflated (names in METRICS_AND_SETTINGS.md): - `kv_pool_allocated_bytes`: the pool allocation, constant after start (`KvPoolPlan.total_bytes`, shared_kv.rs:144). Freeing blocks never changes it, and the status report says so in its field name. - `kv_pool_free_blocks`, `kv_pool_used_blocks` (existing `free_block_count`/`allocated_block_count`), `kv_pool_holder_blocks` (blocks referenced by storage holders), `kv_restore_inflight_blocks`. - `kv_store_inflight_bytes`, `kv_store_inflight_ops` (queue occupancy), `kv_store_reserved_bytes`, `kv_store_persisted_bytes`, `kv_store_persisted_objects`, `kv_store_unindexed_bytes`, `kv_store_quota_bytes`. - Host staging: `kv_host_tail_scratch_bytes` (the one-block scratch of section 2.2) and, when the `O_DIRECT` path is enabled, nothing else (direct I/O reads into the pool). Buffered mode adds no application buffer but uses the page cache, which is reported as `cache_state`, not as staging. - Native staging, **each reported separately** (review finding 15): `kv_stage_export_bytes` (plaintext snapshot of the chunk being sealed), `kv_stage_cipher_bytes` (queued sealed envelopes, bounded by `KV_PARK_STAGE_BYTES`), `kv_stage_env_bytes` and `kv_stage_plain_bytes` (the contiguous envelope and the decrypt output of one restore chunk), `kv_crypto_scratch_bytes` (the private 64 KiB scratch inside `m5_envelope_open`, `scratch[M5_ENV_MAX_CHUNK]` at m5_envelope.c:170, VERIFIED, on the stack of the call), `kv_slab_bounce_bytes` (the driver's bounce size, a second copy of every transfer), `kv_stage_queued_bytes` (sum owned by queued jobs) and `kv_stage_peak_bytes` (high-water of all of the above together). The earlier text called the bounce buffer the only staging memory; that was wrong. - Native adds `kv_slab_slots_total/used`. ## 11. Guarantee matrix Every cell carries one label: PLANNED, TESTED(receipt), NOT CLAIMED or NOT_RUN. A TESTED receipt is the name of the test that proves the cell (host only, `pkv/integration`); `kv_restart_test.rs::guarantee_matrix_rows_are_labelled` checks the labels and that every named test exists. A cell stays PLANNED until its cut merges with a green run. | scenario | host adapter | native adapter | claim | |---|---|---|---| | adapter recreation (same process, new `KvStore` over the same dir/slab) | TESTED(store_then_recreate_adapter_serves_same_bytes) (C4: recover, lookup, load, bytes equal) | PLANNED, host emulation over `disk_file` (N3) | objects published before `close` are served | | process restart (real child process, `current_exe` pattern of `approved_crash_test.rs:80-89`) | TESTED(process_restart_rediscovers_and_restores_identical_bytes, greedy_continuation_after_restart_matches_uninterrupted_baseline) (C7: real child processes on a temp-dir host store; greedy on the CPU reference backend only) | PLANNED as emulator reboot on one image (N5) | greedy continuation equals baseline | | host fault at each publication boundary (P1 to P5, section 2.4) | TESTED(fault_at_each_publication_boundary_leaves_consistent_outcome) (C4, `FsOps` fault seam) | NOT CLAIMED (no host publication boundaries natively; the slab write order belongs to cut N2) | consistent outcome at every boundary; `Indeterminate` reported, never silent | | clean reboot | NOT CLAIMED on the host (no reboot test; fsync + rename + dir fsync is the standard recipe, INFERRED sufficient) | PLANNED in QEMU only (N5 is a reboot); physical Spark NOT_RUN (aienos#336) | emulator only | | abrupt power loss | NOT CLAIMED on the host | PLANNED in emulation with the `disk_file` power-cut injector at every unit boundary (N2, same method as the store crash tests); physical NOT_RUN | no partial record is ever exposed; durability of `Published`-but-not-`Durable` slots is not claimed | | real cold boot on hardware | NOT CLAIMED | PLANNED on a Raspberry Pi 5, labelled \"native physical (Pi 5)\" (cut P3, section 16); Spark-native stays NOT_RUN (aienos#336) | reboot through tryboot is a firmware restart, not a power cut | ## Consequences - New crate `aien-kv-store` (identity, header codec, validation, trait, fake adapter, host adapter). `aien-kv-cache` gains `fork_range`, `assemble_table` and the reserved holder slot rule. `aien-scheduler` gains `SequencePhase::AwaitingRestore`, `admit_restored_prefix` and the `FinishHook`. `aien-runtime` gains the residency map, the park outbox drained after `step`, restore at submit, status fields. `aien-abi-core` gains `computed_prefix` and `restore_sequence` on the backend trait with defaults (`None` and `Err`). - Objects are never shared across `block_size`, `chunk_tokens`, dtype, layout, backend, compute configuration or model; a model upgrade orphans the old objects, which still count toward quota until evicted (section 4.1, by design). - The design does not add resident retention of parked chunks (an L1 of holders kept alive under low pressure). The ownership model allows it later with no format change. - Native hosted and emulator results do not qualify physical hardware; every physical row stays NOT_RUN until an authorized run, and a Pi 5 result never stands in for a Spark result. ## Known limits - Segment SHA-256 on load costs roughly 1 ms per MiB on one core (INFERRED from typical sha2 throughput, not measured); it runs on the worker and, with per-segment digests, on several cores in parallel (section 15.4), so it adds restore latency, not step latency. BLAKE3 is not adopted for format version 1 (section 15.4 gives the reason and the condition for revisiting it). - The restorable prefix is capped at `prompt.len() - 1`; one token of prefill is always paid. - Quota accounting counts foreign-namespace objects but does not read their payloads; an object with a valid header and a corrupt payload occupies quota until its first load deletes it or LRU evicts it. - `max_objects` default 65536 and the index are per store directory; two daemons sharing one directory are not supported (STORE_ID is advisory, there is no lock file in this milestone). - `arith_id` is a coarse label and `KV_ARITH_EPOCH` is a human-bumped counter backed by a pinned-bytes test; a numeric change the pinned test does not exercise could slip through (UNKNOWN residual risk; the test m\n\nIn one sentence, what is the text above about? frees the sequence after publication (section 6), so there is no resident-but-parked state to track. `Failed` is sticky per request until the request's recompute path has started, then it is cleared; it exists so a stale completion cannot flip a request back. `Draining` is new (review finding 5): a restore that has a failed chunk still owns its destinations until every sibling job has produced its terminal completion. ### 5.2 Storage references reuse the fork refcount The storage worker never holds a raw block id. A **holder** is a real block table in `AienKvManager` whose id lives in the reserved slot `u32::MAX` (`SequenceId { slot: u32::MAX, generation: job_id as u32 }`, generation nonzero). Arena slot indices start at 0 and grow by one per new slot (`allocate_slot` pushes when `free_slots` is empty, sequence.rs:382-399, VERIFIED), so slot `u32::MAX` is unreachable in practice but not refused today; C3 adds the refusal in `allocate_slot` (slot index must stay below `u32::MAX`) so the reservation is a rule, not an assumption. **One holder per chunk**, both directions: - Park: a new primitive `fork_range(seq, holder, block_range)` takes one reference on exactly the blocks of that chunk (C3). `fork_sequence(seq, holder)` is not used: it copies the parent's whole table (lib.rs:1165-1210, VERIFIED), so a per-chunk holder built with it would pin every block of the sequence. - Restore: `allocate_sequence(holder, tokens)` allocates zeroed blocks owned by that chunk's holder. - Assembly: `assemble_table(seq, holders)` (C3) builds the request's own table from the holders' block lists, adding one reference per block and marking the table `PrefillPending`. It refuses a `seq` that already has a table (unlike `fork_sequence`, which frees a live child id's blocks, lib.rs:1181-1184, VERIFIED) and refuses any holder that is not complete. - Release: `free_sequence(holder)`. Consequences, all from existing code paths: - A block reaches `free_blocks` only when its refcount hits zero (lib.rs:1419-1425), so a slot is reused only after the sequence tables and the storage holders are all done. No new free-list logic. - Shared-prefix owners stay valid when another owner parks or cancels: the holder is one more sharer; the existing COW tests already cover the invariants (`crates/aien-kv-cache/tests/cow_branching_tests.rs`). - A parked sequence that resumes while its park is in flight copies on write only on a partial last block (lib.rs:1234-1255): the worker keeps reading the frozen original. - `fork_range` leaves the parent's state alone; `fork_sequence` sets the parent to `SharedFrozen` (lib.rs:1192-1197), which is the intended meaning for a fully ready parent. ### 5.3 Incarnation checks Every job carries `Incarnation = (seq_id u64 as issued by the arena, residency_epoch u32)`; the spine bumps `residency_epoch` on every state transition of that sequence. A completion is committed only if the sequence still exists with the same `seq_id` (its generation makes a reused slot a different id, sequence.rs:7-50) **and** the same epoch. Anything else is counted `kv_store_stale_completions` and its holder is freed after the terminal completion. A reused sequence id can therefore never be mutated by an old job. ### 5.4 Short critical sections (the only places the KV lock is taken for storage) | name | lock | work | bound | |---|---|---|---| | S1 finish-fork | KV write, **inside the scheduler's finish transaction, before `free_sequence`** (section 6.1) | `fork_range(seq, holder_i, range_i)` per chunk; push a `ParkIntent` to a lock-free outbox | O(blocks) | | S2 restore-alloc | KV write | `allocate_sequence(holder_i, tokens_i)` per chunk; refuse if `free < watermark + needed` | O(blocks) | | S3 restore-commit | KV write, **on the spine thread** while it handles polled completions, never on the storage worker (review 2, new finding 2) | verify incarnation and that **every** job of the txn is `Completed`; `assemble_table(seq, holders)`; scheduler `admit_restored_prefix` (section 6.3) | O(blocks) | | S4 holder-release | KV write | `free_sequence(holder_i)`, only when the txn has no non-terminal job | O(blocks) | | S5 queue | store index mutex | push/pop/complete | O(1) | The segment hashes on load are verified over the destination blocks *before* S3 (they are holder-owned and invisible to the scheduler until assembled), so no copy to a staging buffer is needed on the host. ### 5.5 Cancellation and restore transactions - A **restore transaction** (`RestoreTxn`) owns all of one request's chunk holders and the list of its submitted job ids. It is the unit of ownership: no holder of a txn is freed, reused or handed to prefill while any job of the txn is non-terminal (review finding 5). When chunk A fails while chunk B is mid-transfer: the txn moves to `Draining`, `cancel(job)` is issued for every non-terminal sibling, and the txn waits for each sibling's terminal completion (`Done`, `Failed` or `Cancelled`); only then S4 frees the holders and the request goes to plain prefill. `TooLate` siblings simply finish, their bytes are discarded. - Cancel own waiter only: a request that is cancelled (`CancelSwarm`, `Aborted`, client gone) cancels its own txn the same way. Shared work (a same-key load another request is waiting on) is never cancelled: the coalescing table keeps the job alive while any waiter remains; cancelling removes the waiter only. - Mid-transfer cancel of a store: the worker checks the cancel flag between segment writes (bounded granularity = one block); the temp is unlinked; nothing was published. - The worker never writes into a freed holder: the free happens in S4 only after the terminal completion of every job that targets it, so there is no use-after-free of pool blocks, including on the multi-chunk failure path. ## 6. Park and restore in the runtime ### 6.1 Boundary (review finding 2) The earlier text parked in `AienRuntimeSpine::step` when it processed `DecodeOutput::Finished` (spine.rs:198-230). That is too late (VERIFIED by the review and by reading the scheduler): `AienScheduler::step` frees the sequence's block table inside its own finish handling, `free_sequence(request_id)` at aien-scheduler/src/lib.rs:1106 for a normal finish and at 1152 for a backend-originated `Finished`, before it returns the `Finished` output (lib.rs:1111, 1172). By the time the spine sees `Finished`, the blocks are gone; what remains there is `backend.release_sequence` (spine.rs:225), which only drops backend state. Design: ownership transfer happens **inside the scheduler's finish transaction**. The scheduler gets an optional `FinishHook` (a trait object set by the spine; absent means today's behaviour exactly). At each of the two finish sites, for any finish reason except `Preempted`, in this order and inside one KV write guard: 1. `prefix = backend.computed_prefix(request_id)` (section 6.2), read while the backend still holds the sequence (the backend call happens before the guard is taken, the backend is not touched under the guard). 2. `hook.on_finish(&mut kv, request_id, prefix)`: `fork_range` into per-chunk holders (S1), a `ParkIntent { holders, keys, headers, incarnation }` pushed to an outbox (a `Mutex<Vec>` with O(1) push; no I/O, no store call). 3. The existing `free_sequence(request_id)`. The spine drains the outbox right after `step` returns and calls `submit_store` for each intent; a refused submit frees that holder (S4) and counts `kv_park_failed_total`. Because the fork happens before the free, the blocks have refcount at least 1 at every instant; the window the review found does not exist. Active decode KV stays resident: nothing parks a running sequence (milestone rule). A `Preempted` finish is not parked (its K/V is incomplete by definition). ### 6.2 Park 1. **Computed prefix, not the token list** (review finding 3). The backend exposes `computed_prefix(seq_id) -> Option<Vec<u32>>`, the tokens whose K/V is actually in the pool. VERIFIED facts it rests on: decode reads `pos = tokens.len() - 1` and computes K/V for the last token (transformer_backend.rs:1776-1782), then appends the newly sampled token (2158), so after any decode step the last token in `tokens` has no K/V; after prefill, `tokens.len()` equals the cached positions and the sample is held apart in `pending_prefill_token` (transformer_backend.rs:136-143), also with no K/V. So `computed = tokens.len()` when a pending prefill token exists and no decode has run, otherwise `tokens.len() - 1`. The earlier rule \"tokens plus the pending token\" would have labelled an unwritten position as valid and let a longer later prompt restore it. Nothing beyond `computed` is ever hashed, keyed or written. The mapping is asserted by a red test that reads the pool and shows position `computed` is unwritten. 2. Compute the key chain for full chunks of `computed` and the partial tail (`token_count = computed mod chunk_tokens`). Skip chunks whose keys `lookup` already finds or that are in flight (same-key publication dedup). 3. S1 inside the finish transaction (section 6.1), one holder per chunk. The writer applies the tail-row zeroing of section 2.2 to the last partial block. The stores are low priority (section 7.2). 4. The sequence's own references are dropped as today; the holders keep the blocks until each job is terminal, then S4. ### 6.3 Restore 1. On `submit_request` in the spine, compute the key chain of the prompt, walk it until the first miss, cap the restorable prefix at `prompt.len() - 1` (context 25: the last prompt token is always recomputed so the logits come from this prompt). Also cap at the operator context (`AIEN_KV_CONTEXT_TOKENS`). A restorable prefix that ends inside a chunk uses only whole stored chunks; a partial-tail chunk is used only if its exact token count is the cap. 2. `pin` the keys; S2 allocates one holder per chunk; submit loads (high priority) for all chunks under one `RestoreTxn`; the request's residency becomes `Restoring`. The request stays in the scheduler's waiting queue with a new `SequencePhase::AwaitingRestore` that `build_scheduled_batch` skips: ready resident sequences keep decoding (the #485 slow-I/O proof). 3. When every job of the txn is `Completed` (and none failed): S3 runs `assemble_table(seq, holders)` and the scheduler's new `admit_restored_prefix(seq_id, restored)` (review finding 4). The existing admission cannot be reused as it was designed: for a waiting sequence whose table is ready it sets `prompt_tokens_prefilled = prompt_len` and enters decode (aien-scheduler/src/lib.rs:779-784, VERIFIED), skipping the unprocessed suffix; for a table that is not ready it frees the table and prefills from zero (lib.rs:802-806, VERIFIED). So `admit_restored_prefix` bypasses the waiting queue: it leaves the table `PrefillPending` (never `complete_prefill` at restore), sets `prompt_tokens_prefilled = restored`, `is_prefilled = false`, `phase = Prefill`, and pushes the sequence into `running_sequences`, where the existing \"continuing chunked prefill\" branch schedules `prompt[restored..]` (lib.rs:572-606, VERIFIED) and the existing completion fence marks the table ready only after the last chunk (lib.rs:1023-1033, VERIFIED). Because `restored <= prompt.len() - 1`, at least one token is always left, so the fence always runs and decode can never start on a restored-only table. The backend hook `restore_sequence(seq_id, tokens)` sets `SequenceState.tokens = prompt[..restored]` so the next chunk's positions line up (checks as `fork_sequence`). 4. Any failure or stale completion: txn `Draining` (section 5.5), then `Failed`, holders freed, phase `Waiting` with `prompt_tokens_prefilled = 0`: a plain prefill. No request is ever refused because of the cache; refusal exists only when history itself is unavailable, which is the generation record's job, not this design's. ### 6.4 Non-tensor state Positions: reconstructed from chunk order. Pending prefill token: not needed, the restore ends inside the prompt and the suffix prefill produces a fresh pending token. Sampling state: `SamplingParams` come with every request (abi-core lib.rs:455-460); the sampling seed is `decode_sampling_seed(request_id, position)` with a fresh `request_id` after a restart, so **stochastic continuation is not reproducible across restart and is not claimed**; greedy continuation is. A test for stochastic continuation, if ever wanted, must pin the seed explicitly; that is outside this milestone. ### 6.5 Guarantee: greedy continuation equals the uninterrupted baseline Holds when the restored bf16 block bytes are identical, the remaining prefill runs on the same backend with the same weights and the same `compute_config_digest` (identity guarantees the last two, section 1.2.1). The test runs a prompt cold, records the greedy tokens, parks, restarts the process, restores the prefix and compares tokens. The backend must prefill the remainder starting at the restored position with the same chunking as the cold run would have used from that position (chunked prefill is position-based, lib.rs:572-606). ## 7. Queues, bounds, fairness, drain ### 7.1 Bounds and per-class reservation (review finding 9) Two bounded intake classes (restore, park) and one completion queue, all behind the store's index mutex. Limits are **per class**, not shared: `max_inflight_ops` (default 64) is split 48 restore and 64 park (`max_restore_ops`, `max_park_ops`; park raised from 16 after the C9 bench, section 18.4), and `max_inflight_bytes` (default 256 MiB) is split the same 3:1. A class can never consume the other's reservation, so continuous restores cannot make every park fail before the dispatcher runs. Bytes count the sum of `payload_len + 4096` of every job between Submitted and its terminal completion. `submit_*` refuses with `QueueFull`; the spine treats a refused park as \"not parked this turn\" (the holders are released) and a refused restore as a plain prefill. Restore destination blocks are counted against the pool: S2 refuses when `free_blocks < watermark_blocks + needed` (the scheduler's own watermark, aien-scheduler lib.rs:460-470), so restores can never starve admission. **Completion capacity** is reserved at submit: each accepted job reserves three completion slots (Completed, Published, terminal), so `poll` never overflows and the worker never blocks on a full queue. **Credit release** happens at the job's terminal completion as the store sees it, not when the caller later commits: a slow KV lock cannot hold store credits. **Bounded waiters**: at most `max_waiters_per_job` (default 16) per coalesced load and 1024 in total; the 17th request does a plain prefill instead of attaching. Holder metadata is bounded by the restore-block budget `AIEN_KV_RESTORE_MAX_BLOCKS`. ### 7.2 Fairness Within the reserved shares, the worker dispatches by credits: 3 restores then 1 park when both queues are non-empty (restore latency matters to a waiting user; parks free resident memory and must not starve). Within a queue, FIFO by submission. The reservation of 7.1 guarantees admission fairness; the credits guarantee dispatch fairness. A PLANNED saturation test (C5) offers restores at the maximum rate for 10 000 operations and asserts parks are still admitted and dispatched at no less than their reserved share. ### 7.3 Coalescing (review finding 6) Same-key loads coalesce at the **job and landing-buffer level**, never at the request-table level. One in-flight load per chunk key lands in that chunk's holder; later requests `attach_waiter` to the job and, on `Completed`, each request builds **its own table** with `assemble_table(seq_i, [holder_0 .. holder_k])` from the chunk holders it needs. The shared chunk blocks are immutable once `Completed` and shared by refcount; each request's suffix chunks are its own holders. A request commits (S3) only when all of its chunks are `Completed` and validated. `fork_sequence(first_seq, other_seq)` is never used for coalescing (it would share the first request's whole table and replace the other request's own). Same-key stores: `inflight_stores` set; duplicates are dropped at submit with `Ok(JobId)` of the existing job (the caller only needs \"it will be published\"). ### 7.4 Eviction, reservation and thrash (review finding 7) `submit_store` never evicts and never touches the filesystem; it runs under the spine's lock path and must stay O(1). Under the index mutex it only **reserves**: `reserved_bytes += payload_len + 4096`, admitted when `used + reserved + request <= quota + evictable_bytes` (evictable = unpinned, not in flight, not already evicting). If admitted but `used + reserved` is above quota, the job starts in state `Reclaiming`: the worker selects LRU victims under the index mutex (marking them `Evicting`, so `lookup` already misses them), releases the mutex, `unlink`s them, subtracts their bytes only after each unlink returns, and only when enough space is reclaimed proceeds to P1. If reclamation cannot free enough (everything left is pinned), the job ends `Failed(OutOfMemory)` and its reservation is released. Publication therefore always follows reclamation; no unlink or native slot invalidation ever runs under the spine or KV lock. Keys pinned by an assembling restore chain are never evicted, so a restore cannot be undone by the park it triggered. A sequence whose restore failed twice in a row within `AIEN_KV_RESTORE_RETRY_WINDOW_MS` is prefilled without lookup (counter per namespace+key chain head, bounded map of 1024 entries). ### 7.5 Shutdown drain (review finding 11) Two separate promises. **Intake and drain deadline** (default 2000 ms, `shutdown(intake_deadline_ms)`): stop intake; cancel everything still `Submitted` or `Reclaiming` (temps unlinked); let jobs already past `fsync(file)` finish their rename; cancel all loads. **Eventual I/O termination** is not promised in time, because `fsync`, directory `fsync` and thread join have no bounded completion time on a stalled filesystem. Rules: (a) the worker owns an `Arc` clone of the KV manager and of every source and destination buffer, and keeps them until each job's terminal completion, so memory is never freed under a possibly running I/O (freeing it to force the deadline would violate ownership); (b) `shutdown` returns at the deadline with a `DrainReport` whose `unfinished` list names every job still running (key, bytes, stage) and the counters `kv_shutdown_unfinished_jobs` and `kv_shutdown_unfinished_bytes` are set; (c) the daemon logs the list and may exit; process exit reclaims all memory at once, and any temp left behind is deleted by the next recovery. Guarantee at exit: every job that reported `Published` is on disk or was reported `Indeterminate`; unfinished jobs are reported, never silently dropped; nothing else exists after restart (recovery deletes temps). An embedding that drops the store without exiting leaves the detached worker alive with its `Arc`s until the I/O ends. ## 8. Lock discipline Locks, in the only allowed nesting order: spine `tokio::Mutex` (server.rs:27) -> KV `RwLock` (lib.rs:1685) -> store index `std::Mutex`. Rules: 1. No storage I/O, no `fsync`, no `unlink`, no sleep and no `poll` wait happens while the spine lock or the KV lock is held. The worker thread never takes the spine lock. `submit_store` performs no eviction (section 7.4); eviction, unlink and native slot invalidation run only on the worker. 2. S1, S2 and S3 run on the spine thread (S3 needs `&mut` scheduler access, which only the spine has: spine.rs:24, server.rs:204). The storage worker takes the KV lock only in S4, when a holder guard it owns is released, and never while holding its own state mutex or the index mutex (the worker drops released guards after its state lock, worker.rs `Shared::with`); it releases the index mutex before any I/O. 3. The spine takes the index mutex only through `submit_*`, `poll`, `cancel`, `lookup`, `attach_waiter`, which are O(1)/O(keys) and never block on I/O. 4. The KV lock is held across S1..S4 for O(blocks) bookkeeping; the existing scheduler already holds it for the same order of work (`complete_prefill`, `free_sequence`). S1 runs inside the scheduler's own finish transaction under the guard it already takes for `free_sequence`; it adds only `fork_range` and an outbox push and takes no other lock (the outbox mutex is a leaf lock held for one `Vec::push`). ## 9. Native mapping (aienos #367) 1. **Device contract kept**: every slot write and read is a sequence of `disk_write`/`disk_read` calls of at most `max_blocks_per_io` through the bounce buffer, one command at a time (disk.h:17-24, disk_nvme.h:17-19). The adapter owns no DMA memory: the caller's KV bytes are copied into the bounce buffer by the driver (bounce contract) so DMA visibility is the driver's, not the adapter's; the adapter only guarantees the source slice is unchanged until `disk_write` returns (same rule as `st_transact`, store_engine.h:146-149). Transfer splitting: a 4 MiB chunk is 32 commands of 128 KiB (calc:a81bdf6c; limit from disk_nvme.h:53-56). A faster command path is a profiled-only follow-up (section 15.7), not part of this contract. 2. **Completed vs durable**: `Completed` = payload units written and `disk_flush` returned; `Published` = header unit written; `Durable` = `disk_flush` after the header returned. Interruption between payload and header leaves a zero header (we zeroed and flushed it first) so recovery sees an empty slot: no partial record is ever exposed. A torn header unit is rejected by `unit_sha256`; `nvme_write_is_power_fail_atomic` is consulted at format time and recorded in the slab superblock as a documented limit, not a check. 3. **Bounded progress**: native has no asynchronous completion (context 15, 20). The adapter is therefore a **step-budgeted state machine**: `kv_slab_pump(budget_cmds)` issues at most `budget_cmds` disk commands (default 2, at most 262144 bytes = 256 KiB at the 128 KiB cap, calc:6d37d10d) and returns. Two callers (review finding 14): the between-steps hook, and an **idle pump** loop in the stage that owns the session, because `ck_infer_prompt` leaves its loop on `STEP_LAST` before its callback runs (infer.c:473-474, VERIFIED) and then consumes the request with `aienos_infer_session_cancel()` (infer.c:495-498, VERIFIED), so a park queued after the reply has no between-steps call to ride on. Tokens keep being produced while a slot fills over many steps, which is the bounded progress #367 asks for. **Limitation, reported, not hidden**: with a polled single-command driver on the same core, inference and I/O are interleaved, not overlapped. The evidence that distinguishes real interleaving from mere queueing is the per-step timestamp log: decode steps continue (token timestamps advance) while the slab command counter advances between them. True overlap would need a second core or interrupts and is out of scope. 4. **Separate quota and lifetime**: the slab region is a disjoint LBA range (section 2.5); `kv_disk_bind` refuses overlap; the slab is formatted and erased independently of the Store (`st_format` never touches it; wiping the slab never touches the Store or anchor). Cache eviction is slot overwrite inside the slab only. Existing Store/Cortex tests keep their regions and stay valid, and the explicit regression gates are named in CUTS.md (N2, N5). 5. **Encryption and authorization preserved**: the wire layout and the authenticated mapping from (namespace, chunk key, slot, incarnation, payload hash) into M5 are in section 2.5. `k_domain` exists only after the sealed Store is unlocked (store_boot.h), so a slot is ciphertext to anyone without the volume key: cache reuse cannot bypass session authorization. Decrypt follows the private scratchpad rule (AGENTS.md section 4): the tag is verified before any byte reaches the session's KV (m5_envelope.c:166-171, VERIFIED, uses a private 64 KiB scratch). The native `sharing_namespace` is the sealed Store uuid || identity class || the subject id, so a TEST-class Store never serves a PRODUCTION one. 6. **Native inference path** (review finding 13). `set_pos` alone cannot restore a session: `aienos_infer_session_prompt` resets the cache and sets `fed = 0` (session.rs:213-216, VERIFIED), and `aienos_infer_session_step` feeds `prompt[fed]` regardless of `DecodeState.pos` (session.rs:241-244, VERIFIED), so importing rows and setting only `pos` is either erased by the next prompt or repeats token zero at the restored position. New FFI in `aienos-infer-kernel` (no_std), in two parts so a failed restore can never leave a half-visible prefix: - `aienos_infer_session_kv_export(layer, pos0, n, out_k, out_v)` reads rows `[pos0, pos0+n)` of a layer; `aienos_infer_session_computed()` returns `DecodeState.pos`, the number of positions whose K/V exists (the last sampled token of a finished reply has none: `STEP_LAST` produces a token without running its forward pass, session.rs:253-258). - `aienos_infer_session_kv_import(layer, pos0, n, in_k, in_v)` writes rows only; it never touches `pos` or `fed`, so the rows are invisible until committed. - `aienos_infer_session_restore_commit(n, ids, n_ids)`, called **after** `aienos_infer_session_prompt` has prepared the request: all-or-nothing, it checks `s.fed == 0`, `n < prompt.len()`, `n <= kv_capacity`, `ids[..n] == prompt[..n]`, then sets `st.pos = n` and `fed = n`; the output list and `done` are untouched, logits come from the suffix steps as in a cold run. Any refusal changes nothing. Native **CPU** only; native GPU (#327) is not touched and not claimed. 7. **Park timing and source ownership** (review finding 14). The session's K/V buffers are reused by the next prompt (`reset` only sets `pos = 0`, decode.rs:93-96, VERIFIED), so a park job cannot keep reading them after the reply. At the park point (after `STEP_LAST`, before the consuming `aienos_infer_session_cancel`; `ck_infer_prompt` gains a `park_point` callback there) the stage **exports and seals the chunks synchronously into adapter-owned ciphertext buffers** (bounded: `KV_PARK_STAGE_BYTES`, section 10). From then on the slab job reads only those buffers; the session is free to reset, close or take the next prompt, and none of those events can change what the job writes. Jobs not terminal at a `ck_reset` simply vanish: their slots have a zero or torn header (section 2.5). The pump runs from the idle loop until the queue is empty; the stage's shutdown calls `kv_slab_drain(deadline)`. 8. **Overlap proof or limitation**: reported as limitation (item 3). Multiple outstanding commands are out of scope unless profiling justifies them (section 15.7); the pump budget is the only tuning knob and is not an acceptance claim. ## 10. Memory accounting Reported separately, never conflated (names in METRICS_AND_SETTINGS.md): - `kv_pool_allocated_bytes`: the pool allocation, constant after start (`KvPoolPlan.total_bytes`, shared_kv.rs:144). Freeing blocks never changes it, and the status report says so in its field name. - `kv_pool_free_blocks`, `kv_pool_used_blocks` (existing `free_block_count`/`allocated_block_count`), `kv_pool_holder_blocks` (blocks referenced by storage holders), `kv_restore_inflight_blocks`. - `kv_store_inflight_bytes`, `kv_store_inflight_ops` (queue occupancy), `kv_store_reserved_bytes`, `kv_store_persisted_bytes`, `kv_store_persisted_objects`, `kv_store_unindexed_bytes`, `kv_store_quota_bytes`. - Host staging: `kv_host_tail_scratch_bytes` (the one-block scratch of section 2.2) and, when the `O_DIRECT` path is enabled, nothing else (direct I/O reads into the pool). Buffered mode adds no application buffer but uses the page cache, which is reported as `cache_state`, not as staging. - Native staging, **each reported separately** (review finding 15): `kv_stage_export_bytes` (plaintext snapshot of the chunk being sealed), `kv_stage_cipher_bytes` (queued sealed envelopes, bounded by `KV_PARK_STAGE_BYTES`), `kv_stage_env_bytes` and `kv_stage_plain_bytes` (the contiguous envelope and the decrypt output of one restore chunk), `kv_crypto_scratch_bytes` (the private 64 KiB scratch inside `m5_envelope_open`, `scratch[M5_ENV_MAX_CHUNK]` at m5_envelope.c:170, VERIFIED, on the stack of the call), `kv_slab_bounce_bytes` (the driver's bounce size, a second copy of every transfer), `kv_stage_queued_bytes` (sum owned by queued jobs) and `kv_stage_peak_bytes` (high-water of all of the above together). The earlier text called the bounce buffer the only staging memory; that was wrong. - Native adds `kv_slab_slots_total/used`. ## 11. Guarantee matrix Every cell carries one label: PLANNED, TESTED(receipt), NOT CLAIMED or NOT_RUN. A TESTED receipt is the name of the test that proves the cell (host only, `pkv/integration`); `kv_restart_test.rs::guarantee_matrix_rows_are_labelled` checks the labels and that every named test exists. A cell stays PLANNED until its cut merges with a green run. | scenario | host adapter | native adapter | claim | |---|---|---|---| | adapter recreation (same process, new `KvStore` over the same dir/slab) | TESTED(store_then_recreate_adapter_serves_same_bytes) (C4: recover, lookup, load, bytes equal) | PLANNED, host emulation over `disk_file` (N3) | objects published before `close` are served | | process restart (real child process, `current_exe` pattern of `approved_crash_test.rs:80-89`) | TESTED(process_restart_rediscovers_and_restores_identical_bytes, greedy_continuation_after_restart_matches_uninterrupted_baseline) (C7: real child processes on a temp-dir host store; greedy on the CPU reference backend only) | PLANNED as emulator reboot on one image (N5) | greedy continuation equals baseline | | host fault at each publication boundary (P1 to P5, section 2.4) | TESTED(fault_at_each_publication_boundary_leaves_consistent_outcome) (C4, `FsOps` fault seam) | NOT CLAIMED (no host publication boundaries natively; the slab write order belongs to cut N2) | consistent outcome at every boundary; `Indeterminate` reported, never silent | | clean reboot | NOT CLAIMED on the host (no reboot test; fsync + rename + dir fsync is the standard recipe, INFERRED sufficient) | PLANNED in QEMU only (N5 is a reboot); physical Spark NOT_RUN (aienos#336) | emulator only | | abrupt power loss | NOT CLAIMED on the host | PLANNED in emulation with the `disk_file` power-cut injector at every unit boundary (N2, same method as the store crash tests); physical NOT_RUN | no partial record is ever exposed; durability of `Published`-but-not-`Durable` slots is not claimed | | real cold boot on hardware | NOT CLAIMED | PLANNED on a Raspberry Pi 5, labelled \"native physical (Pi 5)\" (cut P3, section 16); Spark-native stays NOT_RUN (aienos#336) | reboot through tryboot is a firmware restart, not a power cut | ## Consequences - New crate `aien-kv-store` (identity, header codec, validation, trait, fake adapter, host adapter). `aien-kv-cache` gains `fork_range`, `assemble_table` and the reserved holder slot rule. `aien-scheduler` gains `SequencePhase::AwaitingRestore`, `admit_restored_prefix` and the `FinishHook`. `aien-runtime` gains the residency map, the park outbox drained after `step`, restore at submit, status fields. `aien-abi-core` gains `computed_prefix` and `restore_sequence` on the backend trait with defaults (`None` and `Err`). - Objects are never shared across `block_size`, `chunk_tokens`, dtype, layout, backend, compute configuration or model; a model upgrade orphans the old objects, which still count toward quota until evicted (section 4.1, by design). - The design does not add resident retention of parked chunks (an L1 of holders kept alive under low pressure). The ownership model allows it later with no format change. - Native hosted and emulator results do not qualify physical hardware; every physical row stays NOT_RUN until an authorized run, and a Pi 5 result never stands in for a Spark result. ## Known limits - Segment SHA-256 on load costs roughly 1 ms per MiB on one core (INFERRED from typical sha2 throughput, not measured); it runs on the worker and, with per-segment digests, on several cores in parallel (section 15.4), so it adds restore latency, not step latency. BLAKE3 is not adopted for format version 1 (section 15.4 gives the reason and the condition for revisiting it). - The restorable prefix is capped at `prompt.len() - 1`; one token of prefill is always paid. - Quota accounting counts foreign-namespace objects but does not read their payloads; an object with a valid header and a corrupt payload occupies quota until its first load deletes it or LRU evicts it. - `max_objects` default 65536 and the index are per store directory; two daemons sharing one directory are not supported (STORE_ID is advisory, there is no lock file in this milestone). - `arith_id` is a coarse label and `KV_ARITH_EPOCH` is a human-bumped counter backed by a pinned-bytes test; a numeric change the pinned test does not exercise could slip through (UNKNOWN residual risk; the test m\n\nIn one sentence, what is the text above about? frees the sequence after publication (section 6), so there is no resident-but-parked state to track. `Failed` is sticky per request until the request's recompute path has started, then it is cleared; it exists so a stale completion cannot flip a request back. `Draining` is new (review finding 5): a restore that has a failed chunk still owns its destinations until every sibling job has produced its terminal completion. ### 5.2 Storage references reuse the fork refcount The storage worker never holds a raw block id. A **holder** is a real block table in `AienKvManager` whose id lives in the reserved slot `u32::MAX` (`SequenceId { slot: u32::MAX, generation: job_id as u32 }`, generation nonzero). Arena slot indices start at 0 and grow by one per new slot (`allocate_slot` pushes when `free_slots` is empty, sequence.rs:382-399, VERIFIED), so slot `u32::MAX` is unreachable in practice but not refused today; C3 adds the refusal in `allocate_slot` (slot index must stay below `u32::MAX`) so the reservation is a rule, not an assumption. **One holder per chunk**, both directions: - Park: a new primitive `fork_range(seq, holder, block_range)` takes one reference on exactly the blocks of that chunk (C3). `fork_sequence(seq, holder)` is not used: it copies the parent's whole table (lib.rs:1165-1210, VERIFIED), so a per-chunk holder built with it would pin every block of the sequence. - Restore: `allocate_sequence(holder, tokens)` allocates zeroed blocks owned by that chunk's holder. - Assembly: `assemble_table(seq, holders)` (C3) builds the request's own table from the holders' block lists, adding one reference per block and marking the table `PrefillPending`. It refuses a `seq` that already has a table (unlike `fork_sequence`, which frees a live child id's blocks, lib.rs:1181-1184, VERIFIED) and refuses any holder that is not complete. - Release: `free_sequence(holder)`. Consequences, all from existing code paths: - A block reaches `free_blocks` only when its refcount hits zero (lib.rs:1419-1425), so a slot is reused only after the sequence tables and the storage holders are all done. No new free-list logic. - Shared-prefix owners stay valid when another owner parks or cancels: the holder is one more sharer; the existing COW tests already cover the invariants (`crates/aien-kv-cache/tests/cow_branching_tests.rs`). - A parked sequence that resumes while its park is in flight copies on write only on a partial last block (lib.rs:1234-1255): the worker keeps reading the frozen original. - `fork_range` leaves the parent's state alone; `fork_sequence` sets the parent to `SharedFrozen` (lib.rs:1192-1197), which is the intended meaning for a fully ready parent. ### 5.3 Incarnation checks Every job carries `Incarnation = (seq_id u64 as issued by the arena, residency_epoch u32)`; the spine bumps `residency_epoch` on every state transition of that sequence. A completion is committed only if the sequence still exists with the same `seq_id` (its generation makes a reused slot a different id, sequence.rs:7-50) **and** the same epoch. Anything else is counted `kv_store_stale_completions` and its holder is freed after the terminal completion. A reused sequence id can therefore never be mutated by an old job. ### 5.4 Short critical sections (the only places the KV lock is taken for storage) | name | lock | work | bound | |---|---|---|---| | S1 finish-fork | KV write, **inside the scheduler's finish transaction, before `free_sequence`** (section 6.1) | `fork_range(seq, holder_i, range_i)` per chunk; push a `ParkIntent` to a lock-free outbox | O(blocks) | | S2 restore-alloc | KV write | `allocate_sequence(holder_i, tokens_i)` per chunk; refuse if `free < watermark + needed` | O(blocks) | | S3 restore-commit | KV write, **on the spine thread** while it handles polled completions, never on the storage worker (review 2, new finding 2) | verify incarnation and that **every** job of the txn is `Completed`; `assemble_table(seq, holders)`; scheduler `admit_restored_prefix` (section 6.3) | O(blocks) | | S4 holder-release | KV write | `free_sequence(holder_i)`, only when the txn has no non-terminal job | O(blocks) | | S5 queue | store index mutex | push/pop/complete | O(1) | The segment hashes on load are verified over the destination blocks *before* S3 (they are holder-owned and invisible to the scheduler until assembled), so no copy to a staging buffer is needed on the host. ### 5.5 Cancellation and restore transactions - A **restore transaction** (`RestoreTxn`) owns all of one request's chunk holders and the list of its submitted job ids. It is the unit of ownership: no holder of a txn is freed, reused or handed to prefill while any job of the txn is non-terminal (review finding 5). When chunk A fails while chunk B is mid-transfer: the txn moves to `Draining`, `cancel(job)` is issued for every non-terminal sibling, and the txn waits for each sibling's terminal completion (`Done`, `Failed` or `Cancelled`); only then S4 frees the holders and the request goes to plain prefill. `TooLate` siblings simply finish, their bytes are discarded. - Cancel own waiter only: a request that is cancelled (`CancelSwarm`, `Aborted`, client gone) cancels its own txn the same way. Shared work (a same-key load another request is waiting on) is never cancelled: the coalescing table keeps the job alive while any waiter remains; cancelling removes the waiter only. - Mid-transfer cancel of a store: the worker checks the cancel flag between segment writes (bounded granularity = one block); the temp is unlinked; nothing was published. - The worker never writes into a freed holder: the free happens in S4 only after the terminal completion of every job that targets it, so there is no use-after-free of pool blocks, including on the multi-chunk failure path. ## 6. Park and restore in the runtime ### 6.1 Boundary (review finding 2) The earlier text parked in `AienRuntimeSpine::step` when it processed `DecodeOutput::Finished` (spine.rs:198-230). That is too late (VERIFIED by the review and by reading the scheduler): `AienScheduler::step` frees the sequence's block table inside its own finish handling, `free_sequence(request_id)` at aien-scheduler/src/lib.rs:1106 for a normal finish and at 1152 for a backend-originated `Finished`, before it returns the `Finished` output (lib.rs:1111, 1172). By the time the spine sees `Finished`, the blocks are gone; what remains there is `backend.release_sequence` (spine.rs:225), which only drops backend state. Design: ownership transfer happens **inside the scheduler's finish transaction**. The scheduler gets an optional `FinishHook` (a trait object set by the spine; absent means today's behaviour exactly). At each of the two finish sites, for any finish reason except `Preempted`, in this order and inside one KV write guard: 1. `prefix = backend.computed_prefix(request_id)` (section 6.2), read while the backend still holds the sequence (the backend call happens before the guard is taken, the backend is not touched under the guard). 2. `hook.on_finish(&mut kv, request_id, prefix)`: `fork_range` into per-chunk holders (S1), a `ParkIntent { holders, keys, headers, incarnation }` pushed to an outbox (a `Mutex<Vec>` with O(1) push; no I/O, no store call). 3. The existing `free_sequence(request_id)`. The spine drains the outbox right after `step` returns and calls `submit_store` for each intent; a refused submit frees that holder (S4) and counts `kv_park_failed_total`. Because the fork happens before the free, the blocks have refcount at least 1 at every instant; the window the review found does not exist. Active decode KV stays resident: nothing parks a running sequence (milestone rule). A `Preempted` finish is not parked (its K/V is incomplete by definition). ### 6.2 Park 1. **Computed prefix, not the token list** (review finding 3). The backend exposes `computed_prefix(seq_id) -> Option<Vec<u32>>`, the tokens whose K/V is actually in the pool. VERIFIED facts it rests on: decode reads `pos = tokens.len() - 1` and computes K/V for the last token (transformer_backend.rs:1776-1782), then appends the newly sampled token (2158), so after any decode step the last token in `tokens` has no K/V; after prefill, `tokens.len()` equals the cached positions and the sample is held apart in `pending_prefill_token` (transformer_backend.rs:136-143), also with no K/V. So `computed = tokens.len()` when a pending prefill token exists and no decode has run, otherwise `tokens.len() - 1`. The earlier rule \"tokens plus the pending token\" would have labelled an unwritten position as valid and let a longer later prompt restore it. Nothing beyond `computed` is ever hashed, keyed or written. The mapping is asserted by a red test that reads the pool and shows position `computed` is unwritten. 2. Compute the key chain for full chunks of `computed` and the partial tail (`token_count = computed mod chunk_tokens`). Skip chunks whose keys `lookup` already finds or that are in flight (same-key publication dedup). 3. S1 inside the finish transaction (section 6.1), one holder per chunk. The writer applies the tail-row zeroing of section 2.2 to the last partial block. The stores are low priority (section 7.2). 4. The sequence's own references are dropped as today; the holders keep the blocks until each job is terminal, then S4. ### 6.3 Restore 1. On `submit_request` in the spine, compute the key chain of the prompt, walk it until the first miss, cap the restorable prefix at `prompt.len() - 1` (context 25: the last prompt token is always recomputed so the logits come from this prompt). Also cap at the operator context (`AIEN_KV_CONTEXT_TOKENS`). A restorable prefix that ends inside a chunk uses only whole stored chunks; a partial-tail chunk is used only if its exact token count is the cap. 2. `pin` the keys; S2 allocates one holder per chunk; submit loads (high priority) for all chunks under one `RestoreTxn`; the request's residency becomes `Restoring`. The request stays in the scheduler's waiting queue with a new `SequencePhase::AwaitingRestore` that `build_scheduled_batch` skips: ready resident sequences keep decoding (the #485 slow-I/O proof). 3. When every job of the txn is `Completed` (and none failed): S3 runs `assemble_table(seq, holders)` and the scheduler's new `admit_restored_prefix(seq_id, restored)` (review finding 4). The existing admission cannot be reused as it was designed: for a waiting sequence whose table is ready it sets `prompt_tokens_prefilled = prompt_len` and enters decode (aien-scheduler/src/lib.rs:779-784, VERIFIED), skipping the unprocessed suffix; for a table that is not ready it frees the table and prefills from zero (lib.rs:802-806, VERIFIED). So `admit_restored_prefix` bypasses the waiting queue: it leaves the table `PrefillPending` (never `complete_prefill` at restore), sets `prompt_tokens_prefilled = restored`, `is_prefilled = false`, `phase = Prefill`, and pushes the sequence into `running_sequences`, where the existing \"continuing chunked prefill\" branch schedules `prompt[restored..]` (lib.rs:572-606, VERIFIED) and the existing completion fence marks the table ready only after the last chunk (lib.rs:1023-1033, VERIFIED). Because `restored <= prompt.len() - 1`, at least one token is always left, so the fence always runs and decode can never start on a restored-only table. The backend hook `restore_sequence(seq_id, tokens)` sets `SequenceState.tokens = prompt[..restored]` so the next chunk's positions line up (checks as `fork_sequence`). 4. Any failure or stale completion: txn `Draining` (section 5.5), then `Failed`, holders freed, phase `Waiting` with `prompt_tokens_prefilled = 0`: a plain prefill. No request is ever refused because of the cache; refusal exists only when history itself is unavailable, which is the generation record's job, not this design's. ### 6.4 Non-tensor state Positions: reconstructed from chunk order. Pending prefill token: not needed, the restore ends inside the prompt and the suffix prefill produces a fresh pending token. Sampling state: `SamplingParams` come with every request (abi-core lib.rs:455-460); the sampling seed is `decode_sampling_seed(request_id, position)` with a fresh `request_id` after a restart, so **stochastic continuation is not reproducible across restart and is not claimed**; greedy continuation is. A test for stochastic continuation, if ever wanted, must pin the seed explicitly; that is outside this milestone. ### 6.5 Guarantee: greedy continuation equals the uninterrupted baseline Holds when the restored bf16 block bytes are identical, the remaining prefill runs on the same backend with the same weights and the same `compute_config_digest` (identity guarantees the last two, section 1.2.1). The test runs a prompt cold, records the greedy tokens, parks, restarts the process, restores the prefix and compares tokens. The backend must prefill the remainder starting at the restored position with the same chunking as the cold run would have used from that position (chunked prefill is position-based, lib.rs:572-606). ## 7. Queues, bounds, fairness, drain ### 7.1 Bounds and per-class reservation (review finding 9) Two bounded intake classes (restore, park) and one completion queue, all behind the store's index mutex. Limits are **per class**, not shared: `max_inflight_ops` (default 64) is split 48 restore and 64 park (`max_restore_ops`, `max_park_ops`; park raised from 16 after the C9 bench, section 18.4), and `max_inflight_bytes` (default 256 MiB) is split the same 3:1. A class can never consume the other's reservation, so continuous restores cannot make every park fail before the dispatcher runs. Bytes count the sum of `payload_len + 4096` of every job between Submitted and its terminal completion. `submit_*` refuses with `QueueFull`; the spine treats a refused park as \"not parked this turn\" (the holders are released) and a refused restore as a plain prefill. Restore destination blocks are counted against the pool: S2 refuses when `free_blocks < watermark_blocks + needed` (the scheduler's own watermark, aien-scheduler lib.rs:460-470), so restores can never starve admission. **Completion capacity** is reserved at submit: each accepted job reserves three completion slots (Completed, Published, terminal), so `poll` never overflows and the worker never blocks on a full queue. **Credit release** happens at the job's terminal completion as the store sees it, not when the caller later commits: a slow KV lock cannot hold store credits. **Bounded waiters**: at most `max_waiters_per_job` (default 16) per coalesced load and 1024 in total; the 17th request does a plain prefill instead of attaching. Holder metadata is bounded by the restore-block budget `AIEN_KV_RESTORE_MAX_BLOCKS`. ### 7.2 Fairness Within the reserved shares, the worker dispatches by credits: 3 restores then 1 park when both queues are non-empty (restore latency matters to a waiting user; parks free resident memory and must not starve). Within a queue, FIFO by submission. The reservation of 7.1 guarantees admission fairness; the credits guarantee dispatch fairness. A PLANNED saturation test (C5) offers restores at the maximum rate for 10 000 operations and asserts parks are still admitted and dispatched at no less than their reserved share. ### 7.3 Coalescing (review finding 6) Same-key loads coalesce at the **job and landing-buffer level**, never at the request-table level. One in-flight load per chunk key lands in that chunk's holder; later requests `attach_waiter` to the job and, on `Completed`, each request builds **its own table** with `assemble_table(seq_i, [holder_0 .. holder_k])` from the chunk holders it needs. The shared chunk blocks are immutable once `Completed` and shared by refcount; each request's suffix chunks are its own holders. A request commits (S3) only when all of its chunks are `Completed` and validated. `fork_sequence(first_seq, other_seq)` is never used for coalescing (it would share the first request's whole table and replace the other request's own). Same-key stores: `inflight_stores` set; duplicates are dropped at submit with `Ok(JobId)` of the existing job (the caller only needs \"it will be published\"). ### 7.4 Eviction, reservation and thrash (review finding 7) `submit_store` never evicts and never touches the filesystem; it runs under the spine's lock path and must stay O(1). Under the index mutex it only **reserves**: `reserved_bytes += payload_len + 4096`, admitted when `used + reserved + request <= quota + evictable_bytes` (evictable = unpinned, not in flight, not already evicting). If admitted but `used + reserved` is above quota, the job starts in state `Reclaiming`: the worker selects LRU victims under the index mutex (marking them `Evicting`, so `lookup` already misses them), releases the mutex, `unlink`s them, subtracts their bytes only after each unlink returns, and only when enough space is reclaimed proceeds to P1. If reclamation cannot free enough (everything left is pinned), the job ends `Failed(OutOfMemory)` and its reservation is released. Publication therefore always follows reclamation; no unlink or native slot invalidation ever runs under the spine or KV lock. Keys pinned by an assembling restore chain are never evicted, so a restore cannot be undone by the park it triggered. A sequence whose restore failed twice in a row within `AIEN_KV_RESTORE_RETRY_WINDOW_MS` is prefilled without lookup (counter per namespace+key chain head, bounded map of 1024 entries). ### 7.5 Shutdown drain (review finding 11) Two separate promises. **Intake and drain deadline** (default 2000 ms, `shutdown(intake_deadline_ms)`): stop intake; cancel everything still `Submitted` or `Reclaiming` (temps unlinked); let jobs already past `fsync(file)` finish their rename; cancel all loads. **Eventual I/O termination** is not promised in time, because `fsync`, directory `fsync` and thread join have no bounded completion time on a stalled filesystem. Rules: (a) the worker owns an `Arc` clone of the KV manager and of every source and destination buffer, and keeps them until each job's terminal completion, so memory is never freed under a possibly running I/O (freeing it to force the deadline would violate ownership); (b) `shutdown` returns at the deadline with a `DrainReport` whose `unfinished` list names every job still running (key, bytes, stage) and the counters `kv_shutdown_unfinished_jobs` and `kv_shutdown_unfinished_bytes` are set; (c) the daemon logs the list and may exit; process exit reclaims all memory at once, and any temp left behind is deleted by the next recovery. Guarantee at exit: every job that reported `Published` is on disk or was reported `Indeterminate`; unfinished jobs are reported, never silently dropped; nothing else exists after restart (recovery deletes temps). An embedding that drops the store without exiting leaves the detached worker alive with its `Arc`s until the I/O ends. ## 8. Lock discipline Locks, in the only allowed nesting order: spine `tokio::Mutex` (server.rs:27) -> KV `RwLock` (lib.rs:1685) -> store index `std::Mutex`. Rules: 1. No storage I/O, no `fsync`, no `unlink`, no sleep and no `poll` wait happens while the spine lock or the KV lock is held. The worker thread never takes the spine lock. `submit_store` performs no eviction (section 7.4); eviction, unlink and native slot invalidation run only on the worker. 2. S1, S2 and S3 run on the spine thread (S3 needs `&mut` scheduler access, which only the spine has: spine.rs:24, server.rs:204). The storage worker takes the KV lock only in S4, when a holder guard it owns is released, and never while holding its own state mutex or the index mutex (the worker drops released guards after its state lock, worker.rs `Shared::with`); it releases the index mutex before any I/O. 3. The spine takes the index mutex only through `submit_*`, `poll`, `cancel`, `lookup`, `attach_waiter`, which are O(1)/O(keys) and never block on I/O. 4. The KV lock is held across S1..S4 for O(blocks) bookkeeping; the existing scheduler already holds it for the same order of work (`complete_prefill`, `free_sequence`). S1 runs inside the scheduler's own finish transaction under the guard it already takes for `free_sequence`; it adds only `fork_range` and an outbox push and takes no other lock (the outbox mutex is a leaf lock held for one `Vec::push`). ## 9. Native mapping (aienos #367) 1. **Device contract kept**: every slot write and read is a sequence of `disk_write`/`disk_read` calls of at most `max_blocks_per_io` through the bounce buffer, one command at a time (disk.h:17-24, disk_nvme.h:17-19). The adapter owns no DMA memory: the caller's KV bytes are copied into the bounce buffer by the driver (bounce contract) so DMA visibility is the driver's, not the adapter's; the adapter only guarantees the source slice is unchanged until `disk_write` returns (same rule as `st_transact`, store_engine.h:146-149). Transfer splitting: a 4 MiB chunk is 32 commands of 128 KiB (calc:a81bdf6c; limit from disk_nvme.h:53-56). A faster command path is a profiled-only follow-up (section 15.7), not part of this contract. 2. **Completed vs durable**: `Completed` = payload units written and `disk_flush` returned; `Published` = header unit written; `Durable` = `disk_flush` after the header returned. Interruption between payload and header leaves a zero header (we zeroed and flushed it first) so recovery sees an empty slot: no partial record is ever exposed. A torn header unit is rejected by `unit_sha256`; `nvme_write_is_power_fail_atomic` is consulted at format time and recorded in the slab superblock as a documented limit, not a check. 3. **Bounded progress**: native has no asynchronous completion (context 15, 20). The adapter is therefore a **step-budgeted state machine**: `kv_slab_pump(budget_cmds)` issues at most `budget_cmds` disk commands (default 2, at most 262144 bytes = 256 KiB at the 128 KiB cap, calc:6d37d10d) and returns. Two callers (review finding 14): the between-steps hook, and an **idle pump** loop in the stage that owns the session, because `ck_infer_prompt` leaves its loop on `STEP_LAST` before its callback runs (infer.c:473-474, VERIFIED) and then consumes the request with `aienos_infer_session_cancel()` (infer.c:495-498, VERIFIED), so a park queued after the reply has no between-steps call to ride on. Tokens keep being produced while a slot fills over many steps, which is the bounded progress #367 asks for. **Limitation, reported, not hidden**: with a polled single-command driver on the same core, inference and I/O are interleaved, not overlapped. The evidence that distinguishes real interleaving from mere queueing is the per-step timestamp log: decode steps continue (token timestamps advance) while the slab command counter advances between them. True overlap would need a second core or interrupts and is out of scope. 4. **Separate quota and lifetime**: the slab region is a disjoint LBA range (section 2.5); `kv_disk_bind` refuses overlap; the slab is formatted and erased independently of the Store (`st_format` never touches it; wiping the slab never touches the Store or anchor). Cache eviction is slot overwrite inside the slab only. Existing Store/Cortex tests keep their regions and stay valid, and the explicit regression gates are named in CUTS.md (N2, N5). 5. **Encryption and authorization preserved**: the wire layout and the authenticated mapping from (namespace, chunk key, slot, incarnation, payload hash) into M5 are in section 2.5. `k_domain` exists only after the sealed Store is unlocked (store_boot.h), so a slot is ciphertext to anyone without the volume key: cache reuse cannot bypass session authorization. Decrypt follows the private scratchpad rule (AGENTS.md section 4): the tag is verified before any byte reaches the session's KV (m5_envelope.c:166-171, VERIFIED, uses a private 64 KiB scratch). The native `sharing_namespace` is the sealed Store uuid || identity class || the subject id, so a TEST-class Store never serves a PRODUCTION one. 6. **Native inference path** (review finding 13). `set_pos` alone cannot restore a session: `aienos_infer_session_prompt` resets the cache and sets `fed = 0` (session.rs:213-216, VERIFIED), and `aienos_infer_session_step` feeds `prompt[fed]` regardless of `DecodeState.pos` (session.rs:241-244, VERIFIED), so importing rows and setting only `pos` is either erased by the next prompt or repeats token zero at the restored position. New FFI in `aienos-infer-kernel` (no_std), in two parts so a failed restore can never leave a half-visible prefix: - `aienos_infer_session_kv_export(layer, pos0, n, out_k, out_v)` reads rows `[pos0, pos0+n)` of a layer; `aienos_infer_session_computed()` returns `DecodeState.pos`, the number of positions whose K/V exists (the last sampled token of a finished reply has none: `STEP_LAST` produces a token without running its forward pass, session.rs:253-258). - `aienos_infer_session_kv_import(layer, pos0, n, in_k, in_v)` writes rows only; it never touches `pos` or `fed`, so the rows are invisible until committed. - `aienos_infer_session_restore_commit(n, ids, n_ids)`, called **after** `aienos_infer_session_prompt` has prepared the request: all-or-nothing, it checks `s.fed == 0`, `n < prompt.len()`, `n <= kv_capacity`, `ids[..n] == prompt[..n]`, then sets `st.pos = n` and `fed = n`; the output list and `done` are untouched, logits come from the suffix steps as in a cold run. Any refusal changes nothing. Native **CPU** only; native GPU (#327) is not touched and not claimed. 7. **Park timing and source ownership** (review finding 14). The session's K/V buffers are reused by the next prompt (`reset` only sets `pos = 0`, decode.rs:93-96, VERIFIED), so a park job cannot keep reading them after the reply. At the park point (after `STEP_LAST`, before the consuming `aienos_infer_session_cancel`; `ck_infer_prompt` gains a `park_point` callback there) the stage **exports and seals the chunks synchronously into adapter-owned ciphertext buffers** (bounded: `KV_PARK_STAGE_BYTES`, section 10). From then on the slab job reads only those buffers; the session is free to reset, close or take the next prompt, and none of those events can change what the job writes. Jobs not terminal at a `ck_reset` simply vanish: their slots have a zero or torn header (section 2.5). The pump runs from the idle loop until the queue is empty; the stage's shutdown calls `kv_slab_drain(deadline)`. 8. **Overlap proof or limitation**: reported as limitation (item 3). Multiple outstanding commands are out of scope unless profiling justifies them (section 15.7); the pump budget is the only tuning knob and is not an acceptance claim. ## 10. Memory accounting Reported separately, never conflated (names in METRICS_AND_SETTINGS.md): - `kv_pool_allocated_bytes`: the pool allocation, constant after start (`KvPoolPlan.total_bytes`, shared_kv.rs:144). Freeing blocks never changes it, and the status report says so in its field name. - `kv_pool_free_blocks`, `kv_pool_used_blocks` (existing `free_block_count`/`allocated_block_count`), `kv_pool_holder_blocks` (blocks referenced by storage holders), `kv_restore_inflight_blocks`. - `kv_store_inflight_bytes`, `kv_store_inflight_ops` (queue occupancy), `kv_store_reserved_bytes`, `kv_store_persisted_bytes`, `kv_store_persisted_objects`, `kv_store_unindexed_bytes`, `kv_store_quota_bytes`. - Host staging: `kv_host_tail_scratch_bytes` (the one-block scratch of section 2.2) and, when the `O_DIRECT` path is enabled, nothing else (direct I/O reads into the pool). Buffered mode adds no application buffer but uses the page cache, which is reported as `cache_state`, not as staging. - Native staging, **each reported separately** (review finding 15): `kv_stage_export_bytes` (plaintext snapshot of the chunk being sealed), `kv_stage_cipher_bytes` (queued sealed envelopes, bounded by `KV_PARK_STAGE_BYTES`), `kv_stage_env_bytes` and `kv_stage_plain_bytes` (the contiguous envelope and the decrypt output of one restore chunk), `kv_crypto_scratch_bytes` (the private 64 KiB scratch inside `m5_envelope_open`, `scratch[M5_ENV_MAX_CHUNK]` at m5_envelope.c:170, VERIFIED, on the stack of the call), `kv_slab_bounce_bytes` (the driver's bounce size, a second copy of every transfer), `kv_stage_queued_bytes` (sum owned by queued jobs) and `kv_stage_peak_bytes` (high-water of all of the above together). The earlier text called the bounce buffer the only staging memory; that was wrong. - Native adds `kv_slab_slots_total/used`. ## 11. Guarantee matrix Every cell carries one label: PLANNED, TESTED(receipt), NOT CLAIMED or NOT_RUN. A TESTED receipt is the name of the test that proves the cell (host only, `pkv/integration`); `kv_restart_test.rs::guarantee_matrix_rows_are_labelled` checks the labels and that every named test exists. A cell stays PLANNED until its cut merges with a green run. | scenario | host adapter | native adapter | claim | |---|---|---|---| | adapter recreation (same process, new `KvStore` over the same dir/slab) | TESTED(store_then_recreate_adapter_serves_same_bytes) (C4: recover, lookup, load, bytes equal) | PLANNED, host emulation over `disk_file` (N3) | objects published before `close` are served | | process restart (real child process, `current_exe` pattern of `approved_crash_test.rs:80-89`) | TESTED(process_restart_rediscovers_and_restores_identical_bytes, greedy_continuation_after_restart_matches_uninterrupted_baseline) (C7: real child processes on a temp-dir host store; greedy on the CPU reference backend only) | PLANNED as emulator reboot on one image (N5) | greedy continuation equals baseline | | host fault at each publication boundary (P1 to P5, section 2.4) | TESTED(fault_at_each_publication_boundary_leaves_consistent_outcome) (C4, `FsOps` fault seam) | NOT CLAIMED (no host publication boundaries natively; the slab write order belongs to cut N2) | consistent outcome at every boundary; `Indeterminate` reported, never silent | | clean reboot | NOT CLAIMED on the host (no reboot test; fsync + rename + dir fsync is the standard recipe, INFERRED sufficient) | PLANNED in QEMU only (N5 is a reboot); physical Spark NOT_RUN (aienos#336) | emulator only | | abrupt power loss | NOT CLAIMED on the host | PLANNED in emulation with the `disk_file` power-cut injector at every unit boundary (N2, same method as the store crash tests); physical NOT_RUN | no partial record is ever exposed; durability of `Published`-but-not-`Durable` slots is not claimed | | real cold boot on hardware | NOT CLAIMED | PLANNED on a Raspberry Pi 5, labelled \"native physical (Pi 5)\" (cut P3, section 16); Spark-native stays NOT_RUN (aienos#336) | reboot through tryboot is a firmware restart, not a power cut | ## Consequences - New crate `aien-kv-store` (identity, header codec, validation, trait, fake adapter, host adapter). `aien-kv-cache` gains `fork_range`, `assemble_table` and the reserved holder slot rule. `aien-scheduler` gains `SequencePhase::AwaitingRestore`, `admit_restored_prefix` and the `FinishHook`. `aien-runtime` gains the residency map, the park outbox drained after `step`, restore at submit, status fields. `aien-abi-core` gains `computed_prefix` and `restore_sequence` on the backend trait with defaults (`None` and `Err`). - Objects are never shared across `block_size`, `chunk_tokens`, dtype, layout, backend, compute configuration or model; a model upgrade orphans the old objects, which still count toward quota until evicted (section 4.1, by design). - The design does not add resident retention of parked chunks (an L1 of holders kept alive under low pressure). The ownership model allows it later with no format change. - Native hosted and emulator results do not qualify physical hardware; every physical row stays NOT_RUN until an authorized run, and a Pi 5 result never stands in for a Spark result. ## Known limits - Segment SHA-256 on load costs roughly 1 ms per MiB on one core (INFERRED from typical sha2 throughput, not measured); it runs on the worker and, with per-segment digests, on several cores in parallel (section 15.4), so it adds restore latency, not step latency. BLAKE3 is not adopted for format version 1 (section 15.4 gives the reason and the condition for revisiting it). - The restorable prefix is capped at `prompt.len() - 1`; one token of prefill is always paid. - Quota accounting counts foreign-namespace objects but does not read their payloads; an object with a valid header and a corrupt payload occupies quota until its first load deletes it or LRU evicts it. - `max_objects` default 65536 and the index are per store directory; two daemons sharing one directory are not supported (STORE_ID is advisory, there is no lock file in this milestone). - `arith_id` is a coarse label and `KV_ARITH_EPOCH` is a human-bumped counter backed by a pinned-bytes test; a numeric change the pinned test does not exercise could slip through (UNKNOWN residual risk; the test m\n\nIn one sentence, what is the text above about?ne 503-511, VERIFIED), so an unseen file is free until found. 23. FS adapter: reversible filename from the key, `.tmp` suffix + `os.replace`, unlink of the temp on failure; no `fsync` anywhere in the file (fs_l2_adapter.py:99-135, 518-532, 640-662, VERIFIED; absence of `fsync` VERIFIED by grep). 24. Tests adapted (test_nixl_store_dynamic_l2_adapter.py): `test_salted_objects_recover_independently_after_restart` (745), `test_store_rejected_when_capacity_exceeded` (985), `test_batched_store_reports_failure_when_capacity_exceeded` (1034), `test_secondary_lookup_finds_key` (1113), `test_secondary_lookup_and_load_data` (1138), `test_load_partial_failure_marks_only_successful` (561), `test_delete_skips_pinned_key` (887). Each is re-expressed as a Rust test; none is copied. Attribution: an Apache-2.0 header on `crates/aien-kv-store/src/identity.rs` (the prefix-chain idea) and the test file that adapts the cases, plus a THIRD_PARTY.md row (\"LMCache, Apache-2.0, ideas adapted: deterministic rolling prefix keys, completed-object publication by temp+rename, lazy disk recovery; no code copied\"). The LMCache clone has a LICENSE and no NOTICE file (VERIFIED by `ls`). ### Prior art in this repository (not depended on) 25. OWN-30B serve branch `own30b/serve` (sc-own30b, unmerged, pinned at commit 69459db): in-memory prefix reuse for one conversation, `reused = common.min(prompt.len() - 1)` so at least the last prompt token is always recomputed to produce logits (crates/aien-inference-abi/src/qwen3_moe_omega.rs:2163 at 69459db, VERIFIED), test `prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run` (fn at 2421 at 69459db, VERIFIED). Line numbers move on that branch; the pin is the commit. This ADR adopts the same \"never restore the last prompt token\" rule (section 6.5) and the same warm-equals-cold test shape. Nothing else overlaps: that branch has no disk, no identity, no sharing across requests. ## Decision drivers 1. Correctness before speed: no byte is reused unless its identity proves compatibility, and validation happens before any allocation or copy. 2. The runtime mutex and the KV lock are never held across storage I/O. 3. Everything is bounded: queue depth, bytes in flight, recovery memory, disk quota including objects never looked up. 4. One record header for host and native, so tooling and tests read both; payloads differ by backend format and are never cross-loaded. 5. The native side keeps the single-command, bounce-buffered NVMe contract and the freestanding no_std rule. 6. Conversation history stays authoritative; the KV store is a cache that may be dropped at any time. ## 1. Versioned chunk identity ### 1.1 Units - A **chunk** is `chunk_tokens = chunk_blocks * block_size` consecutive positions of one sequence, aligned to a multiple of `chunk_tokens`. `chunk_blocks` is a setting fixed into the namespace (default 16 blocks; with the 16-token blocks of `model_dir.rs` that is 256 tokens (calc:ceaa1589), LMCache's default). A chunk is **full** when it holds `chunk_tokens` positions. The last chunk of a parked sequence may be **partial** (`token_count < chunk_tokens`); partial chunks are keyed with their exact token count and therefore only ever match an identical prefix of identical length. Only full chunks are prefix-share candidates. - Hash everywhere is SHA-256 (host: `sha2`, already in the lockfile; native: argus `sha256.h`, used by `store_v1.h`). blake3 is not used because native has no blake3. ### 1.2 Namespace id (binds everything that must be equal for bytes to be reusable) `namespace_id = SHA-256( \"AIEN-PKV-NS-V2\\0\" || fields )` (V1 until sc#504; the domain moved when field 14 started to bind the engine, section 1.2.2, so no V1 namespace can match) where `fields`, in this order, little-endian: | # | field | type | source | |---|---|---|---| | 1 | format_version | u16 = 1 | this ADR | | 2 | model_sha256 | [u8;32] | `ModelIdentity.model_sha256` decoded from hex (generation.rs:25) | | 3 | model_digest_kind | u8 len + bytes | `ModelIdentity.model_digest_kind` (generation.rs:26) | | 4 | model_id | u16 len + bytes | `ModelConfig.model_id` | | 5 | num_layers, num_kv_heads, head_dim, block_size | 4 x u32 | `ModelConfig` | | 6 | rope_theta | u32 (f32 bits) | `ModelConfig.rope_theta` | | 7 | rope_scaling | u8 tag (0 none, 1 llama3) then, if 1: factor f64 bits, low_freq_factor f64 bits, high_freq_factor f64 bits, original_max_position_embeddings u64 | `Llama3RopeScaling` (abi-core lib.rs:45-50) | | 8 | qk_norm | u8 | `ModelConfig.qk_norm` | | 9 | dtype | u8 (1 Fp4, 2 Fp8, 3 Bf16, 4 Fp16, 5 Fp32) | `KvDType` | | 10 | layout | 5 x u64 strides (head, token, kv_plane, layer, block) + u64 element_bytes | `KvLayout` (lib.rs:143-156) | | 11 | backend_format | u8 (1 = host paged pool v1; 2 = native f32 decode state v1) | section 2.3 | | 12 | chunk_tokens | u32 | setting | | 13 | sharing_namespace | u16 len + bytes | setting `AIEN_KV_STORE_NAMESPACE` (host); sealed Store uuid + identity class + subject id (native, section 9) | | 14 | compute_config_digest | [u8;32] | `ComputeConfig::digest_with_engine(engine)`, sections 1.2.1 and 1.2.2 (added by the review, C1 delta in section 12; binds the engine since sc#504) | Rationale: fields 2-8 cover \"which weights, which geometry, which RoPE\"; 9-11 cover \"which bytes\"; 13 is the authorization scope; 14 covers every other number that changes what the forward pass computes. Two runtimes with different `block_size` or `chunk_tokens` cannot share objects, by design: positions and chunk boundaries are part of identity. #### 1.2.1 Compute configuration digest (review finding 1) The review showed (VERIFIED by the orchestrator) that two model directories with the same weights digest and the same fields 1-13 but a different `rms_norm_eps` in `config.json` produce different K/V: the backend reads `weights.config.rms_norm_eps` for every RMSNorm (transformer_backend.rs:738, 1111, 1391, 1760) and the value comes from `config.json` (model_dir.rs:112, 239). The weights digest covers the safetensors bytes only, not `config.json`. `ComputeConfig::digest() = SHA-256(\"AIEN-PKV-CFG-V1\\0\" || ComputeConfig)` (namespace field 14 until sc#504; field 14 is now the V2 digest of section 1.2.2, which hashes the same nine fields first) where `ComputeConfig` is, little-endian and in this order: | # | field | type | source | |---|---|---|---| | 1 | num_heads | u32 | `ModelConfig.num_heads` | | 2 | hidden_dim | u64 | `ModelConfig.hidden_dim` | | 3 | intermediate_dim | u64 | `ModelConfig.intermediate_dim` | | 4 | vocab_size | u64 | `ModelConfig.vocab_size` | | 5 | rms_norm_eps | u32 (f32 bits) | `ModelConfig.rms_norm_eps` | | 6 | tie_word_embeddings | u8 | `ModelConfig.tie_word_embeddings` | | 7 | hidden_act | u8 (1 = silu) | `config.json` `hidden_act`; the loader refuses everything but silu (model_dir.rs:198-199, VERIFIED), so the byte is a constant today and exists so a future activation cannot alias | | 8 | arith_id | u8 len + bytes | `TensorBackend::name()` (backend.rs:131, VERIFIED trait method; implementations return `\"ReferenceCpuBackend\"` at backend.rs:509-511, `\"NativeCpuBackend (Rayon Multi-Core)\"` at mojo_backend.rs:242-244, and an availability-dependent string at omega_backend.rs:815-820, all VERIFIED) | | 9 | arith_epoch | u32 | a constant `KV_ARITH_EPOCH` in `aien-inference-abi`, bumped by any change that alters numeric results of the forward pass | Fields not listed and why (each is a decision, not an omission): `model_id` (field 4 of the namespace), `num_layers`, `num_kv_heads`, `head_dim`, `block_size`, `rope_theta`, `rope_scaling`, `qk_norm` (namespace fields 5-8), `max_sequence_length` (caps context, does not change a K/V value; the cap is applied to the restorable prefix, section 6.3), `eos_token_ids` (decides when to stop, not what is computed), `attention_bias` and `mlp_bias` (the loader refuses true, model_dir.rs:201-203, so they cannot vary). **Why the resolved `ModelConfig` and not a digest of the raw `config.json`** (INFERRED, decision): (a) the raw file carries fields that cannot change a K/V value (`torch_dtype`, `transformers_version`, `use_cache`, `initializer_range`; model_dir.rs:22-52 lists the\n\nIn one sentence, what is the text above about?ne 503-511, VERIFIED), so an unseen file is free until found. 23. FS adapter: reversible filename from the key, `.tmp` suffix + `os.replace`, unlink of the temp on failure; no `fsync` anywhere in the file (fs_l2_adapter.py:99-135, 518-532, 640-662, VERIFIED; absence of `fsync` VERIFIED by grep). 24. Tests adapted (test_nixl_store_dynamic_l2_adapter.py): `test_salted_objects_recover_independently_after_restart` (745), `test_store_rejected_when_capacity_exceeded` (985), `test_batched_store_reports_failure_when_capacity_exceeded` (1034), `test_secondary_lookup_finds_key` (1113), `test_secondary_lookup_and_load_data` (1138), `test_load_partial_failure_marks_only_successful` (561), `test_delete_skips_pinned_key` (887). Each is re-expressed as a Rust test; none is copied. Attribution: an Apache-2.0 header on `crates/aien-kv-store/src/identity.rs` (the prefix-chain idea) and the test file that adapts the cases, plus a THIRD_PARTY.md row (\"LMCache, Apache-2.0, ideas adapted: deterministic rolling prefix keys, completed-object publication by temp+rename, lazy disk recovery; no code copied\"). The LMCache clone has a LICENSE and no NOTICE file (VERIFIED by `ls`). ### Prior art in this repository (not depended on) 25. OWN-30B serve branch `own30b/serve` (sc-own30b, unmerged, pinned at commit 69459db): in-memory prefix reuse for one conversation, `reused = common.min(prompt.len() - 1)` so at least the last prompt token is always recomputed to produce logits (crates/aien-inference-abi/src/qwen3_moe_omega.rs:2163 at 69459db, VERIFIED), test `prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run` (fn at 2421 at 69459db, VERIFIED). Line numbers move on that branch; the pin is the commit. This ADR adopts the same \"never restore the last prompt token\" rule (section 6.5) and the same warm-equals-cold test shape. Nothing else overlaps: that branch has no disk, no identity, no sharing across requests. ## Decision drivers 1. Correctness before speed: no byte is reused unless its identity proves compatibility, and validation happens before any allocation or copy. 2. The runtime mutex and the KV lock are never held across storage I/O. 3. Everything is bounded: queue depth, bytes in flight, recovery memory, disk quota including objects never looked up. 4. One record header for host and native, so tooling and tests read both; payloads differ by backend format and are never cross-loaded. 5. The native side keeps the single-command, bounce-buffered NVMe contract and the freestanding no_std rule. 6. Conversation history stays authoritative; the KV store is a cache that may be dropped at any time. ## 1. Versioned chunk identity ### 1.1 Units - A **chunk** is `chunk_tokens = chunk_blocks * block_size` consecutive positions of one sequence, aligned to a multiple of `chunk_tokens`. `chunk_blocks` is a setting fixed into the namespace (default 16 blocks; with the 16-token blocks of `model_dir.rs` that is 256 tokens (calc:ceaa1589), LMCache's default). A chunk is **full** when it holds `chunk_tokens` positions. The last chunk of a parked sequence may be **partial** (`token_count < chunk_tokens`); partial chunks are keyed with their exact token count and therefore only ever match an identical prefix of identical length. Only full chunks are prefix-share candidates. - Hash everywhere is SHA-256 (host: `sha2`, already in the lockfile; native: argus `sha256.h`, used by `store_v1.h`). blake3 is not used because native has no blake3. ### 1.2 Namespace id (binds everything that must be equal for bytes to be reusable) `namespace_id = SHA-256( \"AIEN-PKV-NS-V2\\0\" || fields )` (V1 until sc#504; the domain moved when field 14 started to bind the engine, section 1.2.2, so no V1 namespace can match) where `fields`, in this order, little-endian: | # | field | type | source | |---|---|---|---| | 1 | format_version | u16 = 1 | this ADR | | 2 | model_sha256 | [u8;32] | `ModelIdentity.model_sha256` decoded from hex (generation.rs:25) | | 3 | model_digest_kind | u8 len + bytes | `ModelIdentity.model_digest_kind` (generation.rs:26) | | 4 | model_id | u16 len + bytes | `ModelConfig.model_id` | | 5 | num_layers, num_kv_heads, head_dim, block_size | 4 x u32 | `ModelConfig` | | 6 | rope_theta | u32 (f32 bits) | `ModelConfig.rope_theta` | | 7 | rope_scaling | u8 tag (0 none, 1 llama3) then, if 1: factor f64 bits, low_freq_factor f64 bits, high_freq_factor f64 bits, original_max_position_embeddings u64 | `Llama3RopeScaling` (abi-core lib.rs:45-50) | | 8 | qk_norm | u8 | `ModelConfig.qk_norm` | | 9 | dtype | u8 (1 Fp4, 2 Fp8, 3 Bf16, 4 Fp16, 5 Fp32) | `KvDType` | | 10 | layout | 5 x u64 strides (head, token, kv_plane, layer, block) + u64 element_bytes | `KvLayout` (lib.rs:143-156) | | 11 | backend_format | u8 (1 = host paged pool v1; 2 = native f32 decode state v1) | section 2.3 | | 12 | chunk_tokens | u32 | setting | | 13 | sharing_namespace | u16 len + bytes | setting `AIEN_KV_STORE_NAMESPACE` (host); sealed Store uuid + identity class + subject id (native, section 9) | | 14 | compute_config_digest | [u8;32] | `ComputeConfig::digest_with_engine(engine)`, sections 1.2.1 and 1.2.2 (added by the review, C1 delta in section 12; binds the engine since sc#504) | Rationale: fields 2-8 cover \"which weights, which geometry, which RoPE\"; 9-11 cover \"which bytes\"; 13 is the authorization scope; 14 covers every other number that changes what the forward pass computes. Two runtimes with different `block_size` or `chunk_tokens` cannot share objects, by design: positions and chunk boundaries are part of identity. #### 1.2.1 Compute configuration digest (review finding 1) The review showed (VERIFIED by the orchestrator) that two model directories with the same weights digest and the same fields 1-13 but a different `rms_norm_eps` in `config.json` produce different K/V: the backend reads `weights.config.rms_norm_eps` for every RMSNorm (transformer_backend.rs:738, 1111, 1391, 1760) and the value comes from `config.json` (model_dir.rs:112, 239). The weights digest covers the safetensors bytes only, not `config.json`. `ComputeConfig::digest() = SHA-256(\"AIEN-PKV-CFG-V1\\0\" || ComputeConfig)` (namespace field 14 until sc#504; field 14 is now the V2 digest of section 1.2.2, which hashes the same nine fields first) where `ComputeConfig` is, little-endian and in this order: | # | field | type | source | |---|---|---|---| | 1 | num_heads | u32 | `ModelConfig.num_heads` | | 2 | hidden_dim | u64 | `ModelConfig.hidden_dim` | | 3 | intermediate_dim | u64 | `ModelConfig.intermediate_dim` | | 4 | vocab_size | u64 | `ModelConfig.vocab_size` | | 5 | rms_norm_eps | u32 (f32 bits) | `ModelConfig.rms_norm_eps` | | 6 | tie_word_embeddings | u8 | `ModelConfig.tie_word_embeddings` | | 7 | hidden_act | u8 (1 = silu) | `config.json` `hidden_act`; the loader refuses everything but silu (model_dir.rs:198-199, VERIFIED), so the byte is a constant today and exists so a future activation cannot alias | | 8 | arith_id | u8 len + bytes | `TensorBackend::name()` (backend.rs:131, VERIFIED trait method; implementations return `\"ReferenceCpuBackend\"` at backend.rs:509-511, `\"NativeCpuBackend (Rayon Multi-Core)\"` at mojo_backend.rs:242-244, and an availability-dependent string at omega_backend.rs:815-820, all VERIFIED) | | 9 | arith_epoch | u32 | a constant `KV_ARITH_EPOCH` in `aien-inference-abi`, bumped by any change that alters numeric results of the forward pass | Fields not listed and why (each is a decision, not an omission): `model_id` (field 4 of the namespace), `num_layers`, `num_kv_heads`, `head_dim`, `block_size`, `rope_theta`, `rope_scaling`, `qk_norm` (namespace fields 5-8), `max_sequence_length` (caps context, does not change a K/V value; the cap is applied to the restorable prefix, section 6.3), `eos_token_ids` (decides when to stop, not what is computed), `attention_bias` and `mlp_bias` (the loader refuses true, model_dir.rs:201-203, so they cannot vary). **Why the resolved `ModelConfig` and not a digest of the raw `config.json`** (INFERRED, decision): (a) the raw file carries fields that cannot change a K/V value (`torch_dtype`, `transformers_version`, `use_cache`, `initializer_range`; model_dir.rs:22-52 lists the\n\nIn one sentence, what is the text above about?ne 503-511, VERIFIED), so an unseen file is free until found. 23. FS adapter: reversible filename from the key, `.tmp` suffix + `os.replace`, unlink of the temp on failure; no `fsync` anywhere in the file (fs_l2_adapter.py:99-135, 518-532, 640-662, VERIFIED; absence of `fsync` VERIFIED by grep). 24. Tests adapted (test_nixl_store_dynamic_l2_adapter.py): `test_salted_objects_recover_independently_after_restart` (745), `test_store_rejected_when_capacity_exceeded` (985), `test_batched_store_reports_failure_when_capacity_exceeded` (1034), `test_secondary_lookup_finds_key` (1113), `test_secondary_lookup_and_load_data` (1138), `test_load_partial_failure_marks_only_successful` (561), `test_delete_skips_pinned_key` (887). Each is re-expressed as a Rust test; none is copied. Attribution: an Apache-2.0 header on `crates/aien-kv-store/src/identity.rs` (the prefix-chain idea) and the test file that adapts the cases, plus a THIRD_PARTY.md row (\"LMCache, Apache-2.0, ideas adapted: deterministic rolling prefix keys, completed-object publication by temp+rename, lazy disk recovery; no code copied\"). The LMCache clone has a LICENSE and no NOTICE file (VERIFIED by `ls`). ### Prior art in this repository (not depended on) 25. OWN-30B serve branch `own30b/serve` (sc-own30b, unmerged, pinned at commit 69459db): in-memory prefix reuse for one conversation, `reused = common.min(prompt.len() - 1)` so at least the last prompt token is always recomputed to produce logits (crates/aien-inference-abi/src/qwen3_moe_omega.rs:2163 at 69459db, VERIFIED), test `prefix_reuse_prefills_only_the_new_tokens_and_matches_a_cold_run` (fn at 2421 at 69459db, VERIFIED). Line numbers move on that branch; the pin is the commit. This ADR adopts the same \"never restore the last prompt token\" rule (section 6.5) and the same warm-equals-cold test shape. Nothing else overlaps: that branch has no disk, no identity, no sharing across requests. ## Decision drivers 1. Correctness before speed: no byte is reused unless its identity proves compatibility, and validation happens before any allocation or copy. 2. The runtime mutex and the KV lock are never held across storage I/O. 3. Everything is bounded: queue depth, bytes in flight, recovery memory, disk quota including objects never looked up. 4. One record header for host and native, so tooling and tests read both; payloads differ by backend format and are never cross-loaded. 5. The native side keeps the single-command, bounce-buffered NVMe contract and the freestanding no_std rule. 6. Conversation history stays authoritative; the KV store is a cache that may be dropped at any time. ## 1. Versioned chunk identity ### 1.1 Units - A **chunk** is `chunk_tokens = chunk_blocks * block_size` consecutive positions of one sequence, aligned to a multiple of `chunk_tokens`. `chunk_blocks` is a setting fixed into the namespace (default 16 blocks; with the 16-token blocks of `model_dir.rs` that is 256 tokens (calc:ceaa1589), LMCache's default). A chunk is **full** when it holds `chunk_tokens` positions. The last chunk of a parked sequence may be **partial** (`token_count < chunk_tokens`); partial chunks are keyed with their exact token count and therefore only ever match an identical prefix of identical length. Only full chunks are prefix-share candidates. - Hash everywhere is SHA-256 (host: `sha2`, already in the lockfile; native: argus `sha256.h`, used by `store_v1.h`). blake3 is not used because native has no blake3. ### 1.2 Namespace id (binds everything that must be equal for bytes to be reusable) `namespace_id = SHA-256( \"AIEN-PKV-NS-V2\\0\" || fields )` (V1 until sc#504; the domain moved when field 14 started to bind the engine, section 1.2.2, so no V1 namespace can match) where `fields`, in this order, little-endian: | # | field | type | source | |---|---|---|---| | 1 | format_version | u16 = 1 | this ADR | | 2 | model_sha256 | [u8;32] | `ModelIdentity.model_sha256` decoded from hex (generation.rs:25) | | 3 | model_digest_kind | u8 len + bytes | `ModelIdentity.model_digest_kind` (generation.rs:26) | | 4 | model_id | u16 len + bytes | `ModelConfig.model_id` | | 5 | num_layers, num_kv_heads, head_dim, block_size | 4 x u32 | `ModelConfig` | | 6 | rope_theta | u32 (f32 bits) | `ModelConfig.rope_theta` | | 7 | rope_scaling | u8 tag (0 none, 1 llama3) then, if 1: factor f64 bits, low_freq_factor f64 bits, high_freq_factor f64 bits, original_max_position_embeddings u64 | `Llama3RopeScaling` (abi-core lib.rs:45-50) | | 8 | qk_norm | u8 | `ModelConfig.qk_norm` | | 9 | dtype | u8 (1 Fp4, 2 Fp8, 3 Bf16, 4 Fp16, 5 Fp32) | `KvDType` | | 10 | layout | 5 x u64 strides (head, token, kv_plane, layer, block) + u64 element_bytes | `KvLayout` (lib.rs:143-156) | | 11 | backend_format | u8 (1 = host paged pool v1; 2 = native f32 decode state v1) | section 2.3 | | 12 | chunk_tokens | u32 | setting | | 13 | sharing_namespace | u16 len + bytes | setting `AIEN_KV_STORE_NAMESPACE` (host); sealed Store uuid + identity class + subject id (native, section 9) | | 14 | compute_config_digest | [u8;32] | `ComputeConfig::digest_with_engine(engine)`, sections 1.2.1 and 1.2.2 (added by the review, C1 delta in section 12; binds the engine since sc#504) | Rationale: fields 2-8 cover \"which weights, which geometry, which RoPE\"; 9-11 cover \"which bytes\"; 13 is the authorization scope; 14 covers every other number that changes what the forward pass computes. Two runtimes with different `block_size` or `chunk_tokens` cannot share objects, by design: positions and chunk boundaries are part of identity. #### 1.2.1 Compute configuration digest (review finding 1) The review showed (VERIFIED by the orchestrator) that two model directories with the same weights digest and the same fields 1-13 but a different `rms_norm_eps` in `config.json` produce different K/V: the backend reads `weights.config.rms_norm_eps` for every RMSNorm (transformer_backend.rs:738, 1111, 1391, 1760) and the value comes from `config.json` (model_dir.rs:112, 239). The weights digest covers the safetensors bytes only, not `config.json`. `ComputeConfig::digest() = SHA-256(\"AIEN-PKV-CFG-V1\\0\" || ComputeConfig)` (namespace field 14 until sc#504; field 14 is now the V2 digest of section 1.2.2, which hashes the same nine fields first) where `ComputeConfig` is, little-endian and in this order: | # | field | type | source | |---|---|---|---| | 1 | num_heads | u32 | `ModelConfig.num_heads` | | 2 | hidden_dim | u64 | `ModelConfig.hidden_dim` | | 3 | intermediate_dim | u64 | `ModelConfig.intermediate_dim` | | 4 | vocab_size | u64 | `ModelConfig.vocab_size` | | 5 | rms_norm_eps | u32 (f32 bits) | `ModelConfig.rms_norm_eps` | | 6 | tie_word_embeddings | u8 | `ModelConfig.tie_word_embeddings` | | 7 | hidden_act | u8 (1 = silu) | `config.json` `hidden_act`; the loader refuses everything but silu (model_dir.rs:198-199, VERIFIED), so the byte is a constant today and exists so a future activation cannot alias | | 8 | arith_id | u8 len + bytes | `TensorBackend::name()` (backend.rs:131, VERIFIED trait method; implementations return `\"ReferenceCpuBackend\"` at backend.rs:509-511, `\"NativeCpuBackend (Rayon Multi-Core)\"` at mojo_backend.rs:242-244, and an availability-dependent string at omega_backend.rs:815-820, all VERIFIED) | | 9 | arith_epoch | u32 | a constant `KV_ARITH_EPOCH` in `aien-inference-abi`, bumped by any change that alters numeric results of the forward pass | Fields not listed and why (each is a decision, not an omission): `model_id` (field 4 of the namespace), `num_layers`, `num_kv_heads`, `head_dim`, `block_size`, `rope_theta`, `rope_scaling`, `qk_norm` (namespace fields 5-8), `max_sequence_length` (caps context, does not change a K/V value; the cap is applied to the restorable prefix, section 6.3), `eos_token_ids` (decides when to stop, not what is computed), `attention_bias` and `mlp_bias` (the loader refuses true, model_dir.rs:201-203, so they cannot vary). **Why the resolved `ModelConfig` and not a digest of the raw `config.json`** (INFERRED, decision): (a) the raw file carries fields that cannot change a K/V value (`torch_dtype`, `transformers_version`, `use_cache`, `initializer_range`; model_dir.rs:22-52 lists the\n\nIn one sentence, what is the text above about?# Omega and AIEN ABI qualification: inventory (2026-10-11) Scope: mission sections 4 to 10 (`~/handoffs/2026-10-11-abi-qualification-mission.md`). Sources read at: omega `6c6180cf` (omega.lock; ABI headers identical to omega main `82f31173`), physics `6d7cf0d4`, aienos `b84c0a67` (omega aienos.lock) and aienos main `3b2004b6`, sovereign-core main `bd438bcc`. Tags: **implemented** (true before this work), **fixed here** (defect or gap closed by the abi-qual PRs), **partial**, **missing**, **unnecessary**. `sc` = this repository, `om` = omega, `ao` = aienos. ## Boundaries | Boundary | Producer | Consumer | Linked into production | |---|---|---|---| | rxc_host v2 (composition facade) | om `src/runtime/rxc_host_abi.h`, `.c`; archive `librx_compose.a` (`mk/rx_compose_lib.mk`) | sc `crates/aien-omega-compose` | yes (aien-runtime, aien-cli) | | omega GPU engine | om `src/omega_gpu_{matmul_api,session,serving,elementwise_api,attention_api}.h`; `libomega_gpu.a` | sc `crates/aien-omega-gpu`, \n\nIn one sentence, what is the text above about?# Omega and AIEN ABI qualification: inventory (2026-10-11) Scope: mission sections 4 to 10 (`~/handoffs/2026-10-11-abi-qualification-mission.md`). Sources read at: omega `6c6180cf` (omega.lock; ABI headers identical to omega main `82f31173`), physics `6d7cf0d4`, aienos `b84c0a67` (omega aienos.lock) and aienos main `3b2004b6`, sovereign-core main `bd438bcc`. Tags: **implemented** (true before this work), **fixed here** (defect or gap closed by the abi-qual PRs), **partial**, **missing**, **unnecessary**. `sc` = this repository, `om` = omega, `ao` = aienos. ## Boundaries | Boundary | Producer | Consumer | Linked into production | |---|---|---|---| | rxc_host v2 (composition facade) | om `src/runtime/rxc_host_abi.h`, `.c`; archive `librx_compose.a` (`mk/rx_compose_lib.mk`) | sc `crates/aien-omega-compose` | yes (aien-runtime, aien-cli) | | omega GPU engine | om `src/omega_gpu_{matmul_api,session,serving,elementwise_api,attention_api}.h`; `libomega_gpu.a` | sc `crates/aien-omega-gpu`, \n\nIn one sentence, what is the text above about?", "source_sha256": "791ef12bc33c74cb23f3318e1543def0a07e6008aa38e8d815381687dd5098b2"} +{"id": "turn2-new", "text": "# Omega and AIEN ABI qualification: inventory (2026-10-11) Scope: mission sections 4 to 10 (`~/handoffs/2026-10-11-abi-qualification-mission.md`). Sources read at: omega `6c6180cf` (omega.lock; ABI headers identical to omega main `82f31173`), physics `6d7cf0d4`, aienos `b84c0a67` (omega aienos.lock) and aienos main `3b2004b6`, sovereign-core main `bd438bcc`. Tags: **implemented** (true before this work), **fixed here** (defect or gap closed by the abi-qual PRs), **partial**, **missing**, **unnecessary**. `sc` = this repository, `om` = omega, `ao` = aienos. ## Boundaries | Boundary | Producer | Consumer | Linked into production | |---|---|---|---| | rxc_host v2 (composition facade) | om `src/runtime/rxc_host_abi.h`, `.c`; archive `librx_compose.a` (`mk/rx_compose_lib.mk`) | sc `crates/aien-omega-compose` | yes (aien-runtime, aien-cli) | | omega GPU engine | om `src/omega_gpu_{matmul_api,session,serving,elementwise_api,attention_api}.h`; `libomega_gpu.a` | sc `crates/aien-omega-gpu`, \n\nIn one sentence, what is the text above about?\n# Omega and AIEN ABI qualification: inventory (2026-10-11) Scope: mission sections 4 to 10 (`~/handoffs/2026-10-11-abi-qualification-mission.md`). Sources read at: omega `6c6180cf` (omega.lock; ABI headers identical to omega main `82f31173`), physics `6d7cf0d4`, aienos `b84c0a67` (omega aienos.lock) and aienos main `3b2004b6`, sovereign-core main `bd438bcc`. Tags: **implemented** (true before this work), **fixed here** (defect or gap closed by the abi-qual PRs), **partial**, **missing**, **unnecessary**. `sc` = this repository, `om` = omega, `ao` = aienos. ## Boundaries | Boundary | Producer | Consumer | Linked into production | |---|---|---|---| | rxc_host v2 (composition facade) | om `src/runtime/rxc_host_abi.h`, `.c`; archive `librx_compose.a` (`mk/rx_compose_lib.mk`) | sc `crates/aien-omega-compose` | yes (aien-runtime, aien-cli) | | omega GPU engine | om `src/omega_gpu_{matmul_api,session,serving,elementwise_api,attention_api}.h`; `libomega_gpu.a` | sc `crates/aien-omega-gpu`, \n\nIn one sentence, what is the text above about?\n# Omega and AIEN ABI qualification: inventory (2026-10-11) Scope: mission sections 4 to 10 (`~/handoffs/2026-10-11-abi-qualification-mission.md`). Sources read at: omega `6c6180cf` (omega.lock; ABI headers identical to omega main `82f31173`), physics `6d7cf0d4`, aienos `b84c0a67` (omega aienos.lock) and aienos main `3b2004b6`, sovereign-core main `bd438bcc`. Tags: **implemented** (true before this work), **fixed here** (defect or gap closed by the abi-qual PRs), **partial**, **missing**, **unnecessary**. `sc` = this repository, `om` = omega, `ao` = aienos. ## Boundaries | Boundary | Producer | Consumer | Linked into production | |---|---|---|---| | rxc_host v2 (composition facade) | om `src/runtime/rxc_host_abi.h`, `.c`; archive `librx_compose.a` (`mk/rx_compose_lib.mk`) | sc `crates/aien-omega-compose` | yes (aien-runtime, aien-cli) | | omega GPU engine | om `src/omega_gpu_{matmul_api,session,serving,elementwise_api,attention_api}.h`; `libomega_gpu.a` | sc `crates/aien-omega-gpu`, \n\nIn one sentence, what is the text above about?\n# Omega and AIEN ABI qualification: inventory (2026-10-11) Scope: mission sections 4 to 10 (`~/handoffs/2026-10-11-abi-qualification-mission.md`). Sources read at: omega `6c6180cf` (omega.lock; ABI headers identical to omega main `82f31173`), physics `6d7cf0d4`, aienos `b84c0a67` (omega aienos.lock) and aienos main `3b2004b6`, sovereign-core main `bd438bcc`. Tags: **implemented** (true before this work), **fixed here** (defect or gap closed by the abi-qual PRs), **partial**, **missing**, **unnecessary**. `sc` = this repository, `om` = omega, `ao` = aienos. ## Boundaries | Boundary | Producer | Consumer | Linked into production | |---|---|---|---| | rxc_host v2 (composition facade) | om `src/runtime/rxc_host_abi.h`, `.c`; archive `librx_compose.a` (`mk/rx_compose_lib.mk`) | sc `crates/aien-omega-compose` | yes (aien-runtime, aien-cli) | | omega GPU engine | om `src/omega_gpu_{matmul_api,session,serving,elementwise_api,attention_api}.h`; `libomega_gpu.a` | sc `crates/aien-omega-gpu`, \n\nIn one sentence, what is the text above about?\n", "source_sha256": "153a5f88932393b2be56fd81f8914d44218169c614ebc5b2753069c9a09bc3a1"} +{"id": "turn2-assistant", "text": "I have read the whole document above and I am ready for your question about it.", "source_sha256": null}