interplane.Get Omega
Read in your language

gpu-head-to-head

aien-dev/gpu-head-to-head

Brought by drakestapleton

branch main Branches Tags History

gpu-head-to-head / prompts / ttft.jsonl

5 lines · 172211 bytes Raw Blame History
1{"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"}
2{"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"}
3{"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"}
4{"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"}
5{"id": "turn2-assistant", "text": "I have read the whole document above and I am ready for your question about it.", "source_sha256": null}