Files
leleka/docs/memory-safety-unsafe.md
T
Pavlo RatushnyiandClaude Sonnet 5.5 904ac58d3a fix(cuda-driver): fence the staged residual rows (cuStreamSynchronize(0)) before the draft graph reads them; budget: reserve 2 GiB, admit floor soft+reserve, resident fixed footprint measured, plan-vs-actual check; leak scenario, slope fit, heap stats
- stage_first_residual_direct: cuMemcpy D2D is ordered on the legacy stream only; the draft graph runs on a non-blocking stream. The copies are now followed by a legacy-stream
  synchronize (not a context synchronize). Model-free ordering tests.
- memory budget from the real Codex CRM session (e2e job 945): plan constant for the resident bank corrected (+1.1 GiB), reserve 2 GiB, prefix insertions stop at soft+reserve,
  note_post_load compares the plan with the host after the stack opened.
- smoke: leak scenario (30 s RSS anon/file/shmem, meminfo, VRAM, prefix store, mallinfo2) with OLS and Theil-Sen slopes; LELEKA_MEMORY_NO_TRIM A/B knob.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 16:17:44 +02:00

289 lines
34 KiB
Markdown

# Rust `unsafe` and host-buffer lifetime review
Scope: everything under `crates/`, `control-plane/` and `desktop-core/` that was added after the Strata import
(`git log 4013e0c..HEAD -- crates`), reviewed at `7330ddb` on branch `claude/memory-safety-unsafe`. `engine/strata/` is
out of scope and untouched. No GPU was used: everything below is source review plus model-free tests, Miri and clippy.
Claims that depend on CUDA driver behaviour are listed separately in section 6.
## 0. Summary
| Result | Count |
| --- | --- |
| Real defects fixed (each with a regression test) | 3 (D1, D2, D3) |
| Missing fence fixed (needs a GPU to prove; no model-free test possible) | 1 (D4) |
| Hardening (bounds / alignment asserts, `checked_add`; no known failing caller) | 8 |
| `// SAFETY:` comments added (lines mentioning SAFETY in the diff) | 306 (cuda-driver 239, native-cpu-expert 67) |
| New model-free tests | 35 (31 inline, 4 in `native-cpu-expert/tests/pool_lifecycle.rs`; all pass) |
| Unsafe constructs in crates without any `unsafe` (`leleka-runtime`, `deploy`, `desktop-core`, `serving-policy`, ...) | 0 (workspace `unsafe_code = "forbid"`) |
Where the unsafe lives: `leleka-cuda-driver` (about 500 `unsafe` blocks, 176 `unsafe extern "C" fn` type aliases, 1 `unsafe fn`),
`leleka-native-cpu-expert` (about 150 blocks, 75 `unsafe fn`, 4 `unsafe impl`), `control-plane` (36), `leleka-model-format` (4).
Every other crate forbids `unsafe_code`. In `leleka-cuda-driver` and `leleka-native-cpu-expert` the crate lint is
`deny` and only named private modules carry `#[allow(unsafe_code)]`; `lib.rs` has no `unsafe` block of its own (its 14
`unsafe_code` mentions are `allow` attributes on modules).
Defects:
- **D1** `original_expert_stager.rs` (`Shared::stop` / `claim`): store-buffering race. `stop` stored `head` then loaded
`active`; a worker did `active += 1` then claimed from `head`. On x86 `stop` could read `active == 0` while a worker still
claimed from the old `head`, so the caller released the mapped file or retained banks while a worker was still copying
from them. Fix: `SeqCst` on all four accesses (new helper `enter_claim`). Test:
`original_expert_stager::tests::stop_leaves_no_worker_claiming_after_it_returns` (statistical: failed 9 of 10 runs with the
old orderings, passes with the fix).
- **D2** `mmq_original_host_stage.rs` (`HostStage::finish` / `work`): `finish` emptied `head`, then raised `released` to
"everything free". A helper that exited its wait loop only because `released` was raised never re-read `head`, and copied into a
ring buffer whose previous DMA could still be reading it (garbled data on an early-return path, no use after free).
Fix: `Shared::finished()` re-check after the wait. Test:
`finish_cancels_a_helper_that_waits_for_a_buffer_still_being_read` (failed before the fix, deterministic).
- **D2b** the same file has the same store-buffering pair as D1 (`finish`: store `head`, load `active`). Fix: `SeqCst` on
`claim`'s CAS, `work`'s `active.fetch_add`, `finish`'s `head.store` and `active.load`. Test
`finish_leaves_no_helper_copying_from_a_released_bank` is a weak statistical guard (it did not fail in 80 x 4000 rounds with the
old orderings); the fix rests on the memory-model argument (x86 allows a store to be buffered behind a later load), not on the test.
- **D3** `HostStage::wait(j, length)` trusted the caller's `length` against page-locked buffers that production allocates
uninitialised: a length beyond what the job's helper copied would expose bytes nobody wrote. It now records the copied bytes per
job (`sizes`) and refuses a longer request. Test `wait_refuses_a_length_beyond_the_bytes_the_job_copied` (failed before).
- **D4** `mtp_original_full_forward.rs` (`FullOwned::new_internal`, around line 729): the scratch was zeroed with `cuMemsetD8_v2`
and no fence followed. A memset on device memory is asynchronous with respect to the host and ordered only on the legacy default
stream, which does not order against non-blocking streams. The `original = false` path (public
`Context::original_mtp_full_forward`) has no later synchronous copy, so the first kernel on a non-blocking stream could race the
zeroing. Fix: `.and_then(|()| c.driver.api.synchronize())` inside the existing context guard (once, at construction; same pattern
as `mtp_original_ring_state.rs::zero_state`). Not testable without a GPU.
Hardening, not defects (the callers already satisfy the contract):
`qsa_resident_index.rs::import` span validation used `first + len` instead of `checked_add` (the later `checked_subspan` already
refused a wrapped offset); `Copy2D` layout compile-time asserts (`CUDA_MEMCPY2D`, 128 bytes); `native-cpu-expert` row-length asserts in
`dot256`/`dot512_n` and the legacy `row256`/`row512`/`row_oracle`, destination length and alignment asserts in `quantize_raw`,
`float_dot` and `convert_bf16`, a const-assert that `Split.hq` is 4-aligned.
## 1. Method
1. Inventory: `grep -rn unsafe crates control-plane desktop-core --include=*.rs` (950 lines at `7330ddb`), grouped by file, then
read every block with the surrounding safe code that establishes its precondition. The areas were done in the priority order of
the task: (a) prefix-cache path, (b) deploy memfd supervisor, (c) pinned and registered host buffers, (d) CPU expert pool,
(e) the rest of `cuda-driver` (FFI wrappers, sampled by pattern).
2. Host-pointer asynchronous calls: every dlsym'd symbol of the async or host-pointer family was found by name
(`cuMemcpyHtoDAsync_v2`, `cuMemcpyDtoHAsync_v2`, `cuMemcpyAsync`, `cuMemcpy2DAsync_v2`, `cuMemcpyBatchAsync_v2`,
`cuMemsetD8Async`, `cuMemHostRegister_v2`/`Unregister`, `cuMemHostAlloc`/`cuMemFreeHost`, `cuMemHostGetDevicePointer_v2`,
`cuLaunchHostFunc`, `cuGraphLaunch`). There are 12 files that bind them (section 3). For each, the owner of the host memory was
traced through normal completion, `?` returns, cancellation, `Drop` and field drop order, and context poisoning.
3. Shared-memory protocols (stager workers, MMQ copy ring helpers, CPU pool) were checked for the memory-model argument, and the
two store-buffering pairs were then written as tests.
4. Every fix has a model-free regression test where one is possible. The driver's C mock (`tests/mock_driver.rs`) mocks only the
synchronous public API, so the host-mapped wrappers were tested by constructing the private owner over a plain 256-aligned heap
block with a counting fake `cuMemFreeHost` (`mapped_audit_*`).
5. Dynamic checks: model-free test suites of the touched crates, Miri on the pure-Rust prefix-cache modules, clippy (sections 4, 5).
Review was split across four reviewers working on disjoint file sets (mtp/sampler/head FFI; stager, file source, GPU schedule,
pinned buffers, `model-format`; CPU pool, `control-plane`, verify/ple/qsa FFI; prefix cache, qsa park/import, deploy, runtime
cancellation). Each file was read by exactly one reviewer.
## 2. Inventory
Verdicts: **sound**, **sound+comment** (sound, SAFETY comment added or repaired), **FIXED**, **RISK** (sound under a stated contract
that the code cannot enforce, documented).
### 2.1 (a) Prefix-cache path
`crates/leleka-runtime/src/prefix_cache/*` and `qwen_forward/original_serve_prefix.rs` contain no `unsafe`
(`unsafe_code = forbid` through the workspace lints). They reach device and pinned memory only through four driver entry points,
which are where the invariants live:
| File | Construct | What is unsafe | Invariant | Verdict |
| --- | --- | --- | --- | --- |
| `cuda-driver/src/qsa_prompt_host_ffi.rs` | `MappedAllocation::new` (dlopen, `cuMemHostAlloc` flags 3, `cuMemHostGetDevicePointer_v2`, `write_bytes`) | driver allocation, zero fill | out pointers valid; alias and host both 256-aligned (checked); allocation zero-filled before first read and never resized | sound+comment |
| same | `write` (`copy_nonoverlapping` into the pinned image) | raw write into GPU-visible memory | `range()` proves `[p, p+len)` inside the live block with checked arithmetic; `&mut self`; the source is a caller slice that cannot overlap driver memory; the GPU must be drained: both callers (`import_pages`, `QsaPromptKv::restore`) call `Context::synchronize` first | sound+comment |
| same | `read` (copy out of the pinned image) | raw read of memory the GPU writes | `range()` bounds; `export_pages` synchronizes the context first | sound+comment |
| same | `close` (`cuMemFreeHost`), `Drop` | free of pinned memory | freed once (`host` cleared only on success); `QsaPromptKv::close_inner` frees only after a successful context synchronize and pop, and `mem::forget`s on any doubt (poisoned context, failed sync, failed enter); `Drop` never frees, it leaks the library handle | sound+comment |
| `cuda-driver/src/qsa_resident_transfer.rs` | `Transfer::new`, `copy`, `copy_fenced` (`cuMemcpyAsync` D2D on mapped aliases and device addresses) | raw addresses | every `(src, dst, n)` is checked non-zero, overflow-free, non-overlapping; addresses come from owners that outlive the call; both entry points always `synchronize` the stream before returning, also on the error path, and poison the context if that fails | sound+comment |
| `cuda-driver/src/qsa_resident_index.rs` | `import` span validation (safe) | wraparound in `first + len` | `copy_from_range` uses `checked_subspan`, so a wrapped offset was already refused | hardening: `checked_add` |
| `cuda-driver/src/qsa_mapped_journal.rs` | `export_pages`, `import_pages` (safe) | none; reach `MappedAllocation` | page counts bounded by `end/4` and the geometry's page limit; `bytes.len()` a multiple of `HOST_PAGE_BYTES`; offsets bounded by `range()` | sound |
| `cuda-driver/src/qsa_prompt_kv.rs` | `Pools`, `close_inner`, `restore` (safe) | none | order in `close_inner`: resolver, then the pinned mapping (after context sync), then device pools; a pinned block is never freed while the context is poisoned | sound |
Cancellation of a prefix-cache or serve request is cooperative (a `cancel()` flag polled between chunks and rounds in
`original_serve_request.rs` and `original_serve_engine.rs`); no driver object is dropped with a copy in flight because every public
driver operation drains its stream before returning. The `Drop` of every owner that can have work in flight synchronizes first (3).
### 2.2 (b) Deploy supervisor and memfd
`crates/deploy`, `desktop-core` and `leleka-runtime` have **no `unsafe`**; descriptors are handled through `rustix` and `std`.
| File | Construct | Invariant | Verdict |
| --- | --- | --- | --- |
| `deploy/src/sealed.rs` `seal_file` | `memfd_create(ALLOW_SEALING|CLOEXEC)`, copy, `fcntl_add_seals(WRITE|GROW|SHRINK|SEAL)`, seal read-back | length pinned, `copied != total` is an error, seals verified after adding | sound |
| same `open_inherited`, `check_inherited_archive` | reopen `/proc/self/fd/N` | N in 3..=1048576; a new open file description (independent offset); result checked: regular file, `nlink == 0`, pinned length, all four seals | sound. Note: opens without `O_NONBLOCK` (the runtime reopen does use it), so a named FIFO passed as `--kar-fd` would block instead of being refused; operator input only |
| same `exec_inherit`, `desktop-core/src/bin/leleka-seal-exec.rs` | `dup`, `dup2_stdin`, `Command::exec` | the dup is inheritable (no `CLOEXEC`), the original source fd is `CLOEXEC`, a descriptor below 3 is refused | sound |
| `deploy/src/supervisor.rs` | engine spawned with `Stdio::from(file.try_clone())` | `try_clone` is `F_DUPFD_CLOEXEC`; the dup2 onto fd 0 in the child clears it; `kill_on_drop` | sound |
| `leleka-runtime/src/model_binding/qwen4exp_kar_ple.rs` `open_sealed_archive_fd` | reopen `/proc/self/fd/N` with `O_NONBLOCK`, require `is_file`, pinned length, `nlink == 0`, all four seals | the sealed inode cannot change or shrink, so a later read-only mapping cannot SIGBUS | sound |
| same `open_read_only_archive` / `check_read_only_archive` (file-backed, low-RAM form) | regular file, pinned length, `nlink == 1`, owned by this user, no write bits, `O_NOFOLLOW` | immutability afterwards rests on the operator (`chmod a-w`) | **RISK**: a truncation of the file after verification gives SIGBUS in every later mapped read. It is the documented trade for a 32 GB machine; the memfd form has no such risk |
### 2.3 (c) Pinned and registered host buffers (`cuda-driver`, `model-format`)
| File | Construct (count) | What is unsafe | Invariant | Verdict |
| --- | --- | --- | --- | --- |
| `api.rs` | `AsyncApi` / `MappedApi` (28) | dlopen/dlsym/transmute; stream, event; `cuMemHostRegister`/`Unregister`; `cuMemcpyHtoDAsync_v2`; `cuMemHostGetDevicePointer_v2`; `cuLaunchKernel` | whole `Vec` registered, never resized; unregistered only after the recorded event completed (`async_owned_copy.rs::cleanup_transport`); parameter values copied at launch; bank aliases 16-aligned and `checked_add`-ed | sound (comments already present) |
| `async_owned_copy.rs` | `PendingOwnedCopy` (safe) | none | owner of `(DeviceBuffer, Vec<u8>)` pairs; `Drop` = `drain_and_close` = blocking event wait, unregister, destroy, release; every uncertain path `retain_uncertain` (forget) | sound |
| `original_expert_cache.rs` | `pending`, `swap_sources`, `close_inner` (safe) | none | `close_inner` runs `sync_queued` (waits for swaps first, then default and fill streams) before dropping the retained sources; poisoned context forgets everything | sound |
| `original_expert_stager_ffi.rs` | 24 blocks | dlopen/dlsym, event, context push/pop, `HtoDAsync`, `cuMemHostAlloc`/`FreeHost` | slot buffer or bank retained until its event or stream is drained; hostfree after every slot event was synchronized; `ExpertFileMap` checks `MAP_FAILED`, bounds each part, unmaps the exact length | sound+comment; `CopyJob::copy_to` and `ExpertFileMap` **RISK** (erased lifetime in a crate-private `fn`; file truncation gives SIGBUS) |
| `original_expert_stager.rs` | workers, `Shared::stop/claim` | shared-memory protocol | see D1 | **FIXED** |
| `original_file_expert_source_ffi.rs` | 26 blocks (module not wired into the runtime at this commit) | malloc, `cuMemHostAlloc`, register, `mlock`, `DtoHAsync`, `from_raw_parts`, `madvise`, `getrlimit` | all bounds checked, return values checked, unregister before free | sound+comment; `Arena`/`Copy` are `usize` records and so auto-`Send` (**RISK**, no thread uses them) |
| `original_gpu_schedule_ffi.rs` | 36 blocks | stream, event, graph, capture, `cuMemcpyBatchAsync_v2` (CUDA 13 8-argument form, `CUmemcpyAttributes` layout verified), `cuLaunchHostFunc` with a leaked `Box<Raise>` reclaimed in the callback | sources retained until the copy stream fence; the callback captures only the word's address and value, the word lives in a `MappedAllocation` closed only after `Context::synchronize` | sound+comment |
| `mmq_original_enqueue_ffi.rs` | 7 blocks | `copy_registered` (HtoDAsync on a non-default stream), `cuLaunchKernel` with parameters in a stable `Box` | source retained to the recorded event | sound+comment |
| `mmq_original_host_stage.rs` | 4 blocks + atomics | page-locked ring buffers, `from_raw_parts[_mut]` inside helper threads | `offset + length <= buffer_bytes`; see D2, D2b, D3 | **FIXED** |
| `mmq_original_ring.rs`, `original_stream_all.rs`, `mmq_original_stream_all.rs`, `mapped_expert_bank.rs` | no `unsafe` | none | `PendingMappedExpertCopy` holds the bank `Rc` until its event is waited; `Ring` closes the host stage after `drain()` | sound |
| `model-format/src/gguf_resident.rs` | 4 blocks (`FileSpan` mmap/munmap/`from_raw_parts`, `madvise`) | file mapping | size checked before and after `mmap`; `start + len <= map_len` by construction; `munmap` of the exact length | sound; **RISK** SIGBUS if the file is truncated after mapping |
| `model-format/src/pinned_arena_plan.rs`, `kar_levels.rs`, `leleka-runtime` `kar_expert_source.rs`, `original_file_cache_source.rs`, `original_cache_startup.rs` | no `unsafe` | none | synchronous `copy_from` or plan arithmetic only | sound |
### 2.4 (c, continued) Mapped-host owners of the MTP / sampler / head family
Files: `mtp_original_{full,scalar,prefill,int8}_ffi.rs`, `*_mapped.rs` (full, scalar, int8 host section), `native_head_ffi.rs`,
`native_head_mapped.rs`, `original_sampler_ffi.rs`, `original_sampler_mapped.rs`, `mtp_original_full_forward.rs`,
`mtp_original_physical_layout.rs`. 127 blocks.
| Construct | What is unsafe | Invariant | Verdict |
| --- | --- | --- | --- |
| `Library::drop`, `sym!` / `sym()` | `dlclose`, `dlsym` + `transmute` | one owned handle; NUL literal; null check; fixed Linux64 signature | sound+comment |
| `Module::load`, `configure_gr`, `cuFuncSetAttribute` | module load | PTX NUL-terminated (checked at entry); runs inside `Context::enter` | sound+comment |
| `launch` | `cuLaunchKernel` | the pointer array is rebuilt per launch into boxed, never-resized storage; the driver copies parameter bytes during the call (also under stream capture) | sound+comment |
| `copy`, `copy2d` | `cuMemcpyAsync`, `cuMemcpy2DAsync_v2` | addresses from `checked_subspan` or `MappedOwner::address`; `Copy2D` is `#[repr(C)]` with compile-time size and offset asserts | sound+comment |
| `copy_host` (`cuMemcpyHtoDAsync_v2` from a pageable `Vec`) | host source | single caller, `mtp_original_scalar_graph.rs`: the `Vec`s are held in `pending_host` until the stream receipt, leaked on drain failure | sound+comment |
| `MappedOwner::new` / `write` / `read` / `close` (x6) | `cuMemHostAlloc`, writes and reads of pinned memory, `cuMemFreeHost` | `range()` uses `checked_add`; the address is kept as `usize`, so no Rust reference aliases GPU-written memory; `Drop` never frees; full owner refuses to close while a scalar view holds the shared `Records` (`Rc::strong_count > 1`) | sound+comment; 11 `mapped_audit_*` tests |
| `zero_state` / `zero` | `cuMemsetD8Async` / `cuMemsetD8_v2` | caller validates the span and fences | sound (`zero`: D4 **FIXED**) |
### 2.5 (d) CPU expert pool (`native-cpu-expert`)
236 constructs. `unsafe impl Send/Sync for Shared` exist in `rust_pool.rs` and `rust_general_pool.rs` (4 impls).
| Construct | Invariant | Verdict |
| --- | --- | --- |
| `Shared` `Send`/`Sync` + `execute`, `phase`, `compute_*`, `prefetch` (`&mut` batch/act/split cells) | claims are epoch-tagged CAS on disjoint row intervals; the host mutates only after `done` and `parked`; a stale-epoch claim fails; `rows == count*per`; output rows are bitmap-checked and pairwise distinct, `checked_mul`, `< out_rows <= 128` | sound+comment |
| `rust_general_pool.rs` n==1 host path, `diagnostic`, `owned_bytes` | modes 1 and 2 only reachable with one thread; single/split indices bounded; `&self` excludes the `&mut self` phases | sound+comment (13) |
| `rust_platform.rs`, `rust_topology.rs` | glibc FFI (`rlimit`, `pthread_attr_t`, `cpu_set_t`, `madvise`); layouts match glibc; `MADV_WILLNEED` neither reads nor writes | sound+comment |
| `rust_simd.rs`, `rust_ggml_native.rs` | cpuid/xgetbv only after the OSXSAVE and max-leaf checks; every `#[target_feature]` call is behind a runtime probe (`avx2_ok()`, plus `dq_ok()` for AVX-512, or `legacy_supported()`) | sound |
| `rust_quant`, `rust_q2`, `rust_legacy`, `rust_iq`, `rust_kq`, `rust_k_blocks`, `rust_ggml_extra` | `loadu`/`storeu` and block dots; the activation is length-asserted or safely indexed | sound; row-length asserts added (hardening) |
| `rust_ggml.rs`, `rust_native_general.rs` `quantize_raw`, `dot_raw` | casts `&mut [u8]` to `Q8K`/`Q8Zero`/`Q8One`/`u16`; bytes sit at offset 0 of a 64-aligned struct; `check(kind, n)`, `NativeFormat::validate` and the 4096/1024-byte caps bound the lengths | sound; extent and alignment asserts added |
| `rust_weight_iq.rs` `qsort` FFI | the comparator never indexes; NaN only mis-orders a 256-byte array | sound (offline tool) |
| `rust_bench_cuda.rs` `env::set_var` | first action of the process-entry leaf, before CUDA and pool threads exist | sound with comment; `pub fn main` must never be called from a multithreaded host |
| `rust_bench_frontend.rs` (22 `printf`) | vararg types checked against formats; the `setenv` branch is dead | sound |
| `rust_bench_model.rs` `mmap`/`munmap` | `MAP_FAILED` checked; `checked_add` on the cursor | sound; **RISK** SIGBUS on external truncation |
### 2.6 (e) Rest of `cuda-driver` and `control-plane`
| File(s) | Construct | Invariant | Verdict |
| --- | --- | --- | --- |
| `ffi.rs` (117 lines with `unsafe`) | loader macros (`symbol!`, `Api::load`); `LaunchArguments`, `MatvecArguments`, `Q8/Q5/Q6/Projection/QsaSelected/HeadGreedy` argument storage (`Box::into_raw` + `NonNull`, self-referential `parameters` array) | allocation raw-owned and never reborrowed; each `Drop` rebuilds the `Box` once; owners are dropped only before the launch or after the synchronize, otherwise `mem::forget`-ed; `cuLaunchKernel` copies parameter values anyway; synchronous `cuMemcpyHtoD/DtoH` (pageable) for `DeviceBuffer` | sound (comments present). The ~70 `launch_*` wrappers were read by pattern, not one by one |
| `lib.rs` `Context`, `DeviceBuffer`, `CurrentGuard` | none (`#![deny(unsafe_code)]`); safe types enforcing the contract | `DeviceBuffer<'ctx>` borrows the `Context`, so a context cannot be closed under a live buffer; every copy synchronizes, and on a failed synchronize the staging `Vec` is `forget`-ed and the context poisoned; `free` is `cuMemFree`, which synchronizes the device | sound |
| `original_verify_mapped.rs` (19) | `cuMemHostAlloc` wrapper | `range()` bounds and alignment; `close()` reached only from `Physical::close` after `context.synchronize()`; `Drop` never frees | sound |
| `original_verify_diag.rs` (2) | watchdog `AtomicU32::from_ptr` on registered addresses | `registration = None` precedes `bank.close()` (`original_verify_schedule.rs:239`) and `Drop` calls `close_inner` | sound, order-dependent |
| `original_verify_ffi`, `ple_batch_ffi`, `qsa_index_ffi`, `qsa_prompt_attention_ffi`, `native_parity_ffi`, `arch_ptx`, `gdn_*_ffi`, `moe_prefill_batch_ffi`, `kar_decode_levels_ffi`, `mmq_ffi`, `gdn_native_batch_abi`, `qwen_ffi` | `dlsym` transmutes; `cuLaunchKernel` with parameters in boxed storage | parameter pointers rebuilt per launch into reserved heap storage; modules unloaded after drain; library forgotten on failure | sound (pattern review; ~190 blocks) |
| `control-plane/src/*` (36 blocks: `key_init`, `embedded_engine`, `ggml_bridge`, `immutable_directory`, `history_store`, `service_install`, `service_switch`, `model`, `preflight`, `build.rs`) | `getrandom`/`openat`/`linkat`/`fchmod`/`renameat2`, memfd, `geteuid`, C ggml decoder | fds adopted once; `CString`s outlive calls; the decoder is guarded by geometry equality, a block-multiple length check and 16-byte alignment; no `set_var` anywhere | sound. SAFETY comments (22) were prepared but **not committed** here, because `control-plane/` is out of this branch's scope |
## 3. Asynchronous host-pointer calls: who owns the buffer, and why it outlives the copy
Twelve files bind a host-pointer or async entry point; they fall into eight classes. In all of them an uncertain completion ends in
`mem::forget` (a leak bounded by the context budget), never in a free.
| # | Class | Sites | Owner of the host memory | Why it outlives the work |
| --- | --- | --- | --- | --- |
| 1 | Registered `Vec` + event | `api.rs::AsyncApi::{register,copy}`, `async_owned_copy.rs` | `PendingOwnedCopy.pairs` | never resized (private field); `Drop` and `close` block on the event before unregister and release; error before any copy is attempted releases the partial registration; after `attempted`, `retain_uncertain` forgets pairs, ABI, stream, event |
| 2 | Retained bank `Rc` / file blob | `original_expert_cache.rs` fills and swaps | `pending`, `swap_sources` | cleared only after `sync_queued`/`wait_swaps`/`poll_swaps` saw the copy complete; `close_inner` drains first; a bank cannot close while an `Rc` is retained |
| 3 | Pinned staging ring + worker threads | `original_expert_stager*.rs`, `mmq_original_host_stage.rs`, `mmq_original_ring.rs`, `original_stream_all.rs` | stager / schedule | `close_inner`: drain (stop, stream sync), join workers, sync every slot event, only then `cuMemFreeHost`, then drop the source; the `stop`/`finish` fences were the D1/D2 races; failure paths leak |
| 4 | Mapped host (device-visible) kernel arguments | `*_mapped.rs`, `original_verify_mapped.rs`, `qsa_prompt_host_ffi.rs`, `api.rs::bank_alias` | `MappedOwner` / `MappedAllocation` / bank | `Drop` never frees; `close()` is called after a context or stream synchronize; graphs hold `Rc` clones and `OriginalGpuGraph::close_inner` syncs the stream before dropping them; CPU writes to the image happen only when the graph is not launched or after a drain |
| 5 | `cuMemcpyBatchAsync_v2` | `original_verify_gpu_plan.rs`, `original_gpu_schedule_ffi.rs` | bank retained in `pcie_sources` | released after the copy-stream sync (`original_verify_schedule.rs`) |
| 6 | `cuLaunchHostFunc` | `original_gpu_schedule_ffi.rs` (`raise_after_copies`) | `Box<Raise{word,value}>`, no owner reference; the word lives in a `MappedAllocation` | allocation closed only after `Context::synchronize` (which retires queued host functions); `Stream::close` synchronizes before destroy |
| 7 | Pageable `cuMemcpyHtoDAsync_v2` | `mtp_original_scalar_ffi.rs::copy_host` | `pending_host: Vec<Vec<u8>>` | cleared after the stream receipt; leaked on drain failure; early `?` leaves `has_pending`, the next record call or `close_inner` drains |
| 8 | Device-to-device `cuMemcpyAsync` | `qsa_resident_transfer.rs`, `mtp_original_*_ffi.rs::copy` | device buffers and mapped aliases held by the caller | `Transfer::copy*` always synchronize the stream before return; the other `copy` sites are followed by a stream receipt or an `Execute`-level synchronize |
Cancellation and `Drop` order:
- Cancellation (`cancel()` closure) is polled between prefill chunks and between rounds; nothing is dropped at that point, and every
public driver call drains. A cancelled request returns to the stack, which resets its owners at the next request.
- `OriginalServeStack` declares its owners "dependents first" and fields drop in declaration order (`history`, `arena`,
`expert_cache`, `executor`, `draft`, `session`, `pool`, `kar`, `moe`, `dense`, ...); `close()` takes them apart in the same order, drops
the residency span cache before the bank it caches, and every owner's `Drop` calls its `close_inner`, which synchronizes first.
- Poisoned context: every owner's `close_inner` checks `Context::is_poisoned()` and forgets the pinned memory, device buffers and
library handle instead of freeing them. The one place that admits a free under uncertainty would be a regression of this rule, and
the `mapped_audit_*` tests pin it (`..._drop_without_close_never_frees`).
- The primary `Api` (used by `DeviceBuffer::copy_from` / `copy_to`) is entirely synchronous (`cuMemcpyHtoD_v2`/`DtoH_v2` plus
`cuCtxSynchronize`), so a host `Vec` is never handed to a copy that outlives the call.
- Device buffers: `DeviceBuffer<'ctx>` borrows the context; checkpoint buffers go to a pool (`OriginalQsaResidentIndex.pool`) by
moving the handle (`handle.take()`, then a new `DeviceBuffer`), so there is no double free; the `Placement` guard in `placed`
swaps buffers back in `Drop`, also on unwinding.
- `unsafe impl Send/Sync`: only the two `Shared` in the CPU pool (2.5). No other type is sendable across threads by an `unsafe impl`;
`Rc`-based driver owners and raw-pointer owners are `!Send`. Two plain `usize` records (`Arena`, `Copy` in
`original_file_expert_source_ffi.rs`) are auto-`Send`; no thread uses them.
## 4. Miri
Miri (`nightly-2026-10-16`, `miri` and `rust-src` components, installed in WSL) cannot build `leleka-runtime`: the crate
links `leleka-cuda-driver`, which `dlopen`s `libcuda`, plus `rustix`, `minijinja`, `sha2` and a native CPU crate with inline asm and
AVX-512, none of which Miri can run. Nothing was extracted into the repository. Instead the pure-Rust modules
`prefix_cache/{budget,hash,store,summary,mod}.rs` and `conversation/memory.rs` (a dependency of `budget.rs`) were copied unchanged into
a scratch cargo package outside the repo (`~/work/miri-prefix` in WSL, deps `serde`, `serde_json`) and run with
`cargo +nightly miri test`:
- 31 tests passed, 1 ignored (`twelve_sessions_growing_to_180k_tokens...`, a scale simulation of seconds in release; not run
under Miri), 1 skipped (`conversation::memory::tests::provider_returns_bytes_or_unknown`, which reads `/proc/meminfo`, and Miri
isolation aborts on files in `/proc`).
- No undefined behaviour reported. The modules contain no `unsafe`, so this is a check for the safe code's behaviour under Miri's
strict checks (integer overflow in `debug` profile, aliasing of the standard collections), not a proof about the driver.
- Not run under Miri, and why: everything under `cuda-driver` (needs libcuda and hardware), `native-cpu-expert` (inline asm, AVX-512 and
AVX2 intrinsics, thread pool with spinning workers), the mapped-host owners (the new `mapped_audit_*` tests build the private owner
over a plain heap block and would be Miri candidates if the crate could be built without the driver; it cannot, since its lib tests
need `--features cuda-driver`).
## 5. Clippy
Commands (WSL, toolchain 1.99.0, `--all-targets`): `cargo clippy` (workspace default members) and
`cargo clippy -p leleka-cuda-driver -p leleka-runtime -p leleka-native-cpu-expert -p leleka-model-format`.
| Crate (lib target) | Baseline `7330ddb` | After this branch |
| --- | --- | --- |
| `leleka-cuda-driver` | 340 | 340 |
| `leleka-runtime` | 166 | 166 |
| `leleka-native-cpu-expert` | 158 | 153 |
| `leleka-model-format` | 4 | 4 |
| `strata-desktop-core` | 2 | 2 |
Diagnostics in test targets introduced by this branch (3: `chunks_exact_mut` in a `host_stage` test, a no-effect mask in a
`physical_layout` test, `chunks_exact` in `pool_lifecycle.rs`) were fixed. The 5 fewer warnings in `native-cpu-expert` are
`this looks like an else {..} but the else is missing` lints, which fire on `}` directly followed by `{` in the dense one-line
code and went away because an inline SAFETY comment now sits between them (no behavioural change). No repo-wide cleanup was
attempted: about 660 pre-existing warnings remain in the library targets (about 800 counting test targets and duplicates). Top
categories: 74 `else if` without `else` (same dense one-line style), 50 collapsible `if`, 26 `map_err` instead of `inspect_err`, 22 `chunks_exact` with a constant
size, 17 complex types, 10 `unnecessary unsafe block` in `rust_simd.rs` and neighbours (safe `#[target_feature]` calls in edition
2024; removing the blocks would be a separate change).
## 6. Residual risks and what a GPU run would confirm
1. **D4 (scratch zero fence)** compiles and is logically right under the documented CUDA semantics (a memset to device memory is
asynchronous with respect to the host and only ordered on the legacy default stream). It needs a GPU run of the
`original = false` full-forward construction to be observed; its cost is one context synchronize at construction.
2. **Cross-stream race, FIXED in claude/memory-safety (needs a GPU run to observe; model-free test of the ordering):** the issue was `mtp_original_full_round.rs::stage_first_residual_direct` fills rows 1..T of the
verifier's R bank with `copy_sync` (`cuMemcpy`, device to device) on the legacy default stream, and the draft graph then runs
on a **non-blocking** stream. A device-to-device `cuMemcpy` does not block the host and the legacy stream does not order against
non-blocking streams, so the graph could read a row before it is copied. The copy is 40 KB per row, issued before graph
capture and launch, so the window is microseconds against milliseconds; it never showed in parity runs. A `cuCtxSynchronize` after
the copies would close it but would also wait for a pending verifier commit, which needs a paired A/B before landing.
Fix: `copy_rows_then_fence` issues the copies and then `cuStreamSynchronize(0)` (`Module::fence_legacy_stream`), which waits for the legacy-stream
copies only and not for work on non-blocking streams, so a pending verifier commit is not waited for; tests `stage_fence_tests` pin copy-then-fence order, no fence after a failed copy,
and that a failed fence is an error.
3. **`HostStage::close` and `Ring::new`'s `old.close()?` call `cuMemHostUnregister` with no context entered**
(`mmq_original_ring.rs`). If the driver answers `CUDA_ERROR_INVALID_CONTEXT`, the pinned ring leaks (deliberately: the allocation
is not returned to the allocator) and `close` returns an error. A fix would wrap those calls in `context.enter()`. Not changed
without a GPU to see whether the driver needs it.
4. **`PhysicalRing::close_inner` (`mtp_original_int8.rs`) frees without its own context synchronize.** Safe under the current `Rc`
discipline (the last holder is a graph whose close synchronizes first); one added `Context::synchronize` would match the siblings.
5. **Kernel arguments versus PTX `.param` sizes** are not checked: a wrong-length `kernelParams` array makes the driver read past it. Only
GPU parity tests cover it.
6. `MappedExpertBank::close_inner` returns on `enter()?` without `retain_uncertain`; if that happens in a bare `Drop`, the registered
range could be freed while still registered (the driver keeps the pages pinned; no host corruption).
7. `HostStage` loads a `MappedApi` module and never calls `MappedApi::close()` (small leak). `rust_topology.rs`
`pin_current_thread` / `restore_thread_affinity` is `pub`, has no callers, and restores only the first 64 CPUs.
8. SIGBUS if a memory-mapped GGUF, expert file or the file-backed KAR archive is truncated after verification (stager `ExpertFileMap`,
`gguf_resident::FileSpan`, `rust_bench_model`). Not fixable in code; the sealed memfd form of the KAR archive has no such risk.
9. **Driver behaviour assumed, not tested:** pageable `cuMemcpyHtoDAsync` is staged before the call returns; `cuMemFree` synchronizes
the device; `cuMemcpyBatchAsync` consumes its descriptor arrays during the call; kernel parameters are copied at launch;
stream and context synchronize retire queued host functions; a UVA alias equals the host pointer.
10. The two store-buffering fixes (D1, D2b) are justified by the x86-TSO argument; the tests are statistical and failed on the old
orderings only for D1. On a weaker memory model they would matter more, so the `SeqCst` accesses should stay.