Files
leleka/docs/memory-safety.md
T

19 KiB

Memory safety: inventory, budget governor, shedding, residency

Branch claude/memory-safety (cut from claude/port-gpu-bringup 7330ddb). Code: crates/leleka-memory (new, model-free, no CUDA), crates/leleka-runtime/src/memory_governor.rs (the runtime's glue), the hooks in qwen_forward/original_serve_stack.rs, original_serve_prefix.rs, backend.rs, backend_original_serve.rs, the status plumbing (crates/backend-api, crates/runtime-client, desktop-core/src/runtime_rpc.rs, control-plane/src/memory_view.rs) and the deploy profiles (crates/deploy, deploy/rust-runtime/profiles).

Operator requirement: the port must be memory safe. It must never exhaust the machine, hang it, or silently degrade, under agent-pool workloads (many sessions, contexts up to ~180k tokens, prefix cache, expert tier, CPU pool, the sealed KAR memfd).

1. What went wrong before, and what answers it

History Mechanism Answer in this branch
(1) a second model process beside the 55 GB holder OOM-hung the server nothing compared the fixed footprint of a new process with what was left startup plan (plan::plan): refuses to start, with numbers and the knobs to change, when MemAvailable - fixed footprint < soft floor + reserve
(2) page-cache pressure swapped the sealed memfd out; decode slowed shmem is swappable and is not counted in MemAvailable; a reader of the KAR file next to it competes for the same pages lock (mlock in chunks, within RLIMIT_MEMLOCK/CAP_IPC_LOCK), else detect (smaps Swap: of the mapping, logged with the number) and heal (MADV_POPULATE_READ, rate limited, only at level normal); the shards' page cache is released after the resident bank is loaded
(3) job 916: MemAvailable 19 GB during a 100k prefill; job 927 ended at 6.5 GB caches sized from independent defaults caches are sized from one budget (what is left above the floors); a pressure monitor sheds (evict, then refuse) before the kernel has to
(4) prefix cache auto 7.8 GiB its own formula, floor 4 GiB, 3 GiB insertion guard the governor's rule (auto_prefix_budget), the soft floor as the insertion floor, shed on pressure
(5) K/V in pinned host RAM (12.7 KB/token) fixed at open for the whole serving context (12 x 276,825,088 B at 262,144 cells = 3.094 GiB), not per session part of the fixed footprint in the plan; a request that cannot fit the serving context is a 400 before anything is allocated
(6) bank, rings, MTP staging, complement, pool scratch independent allocations inventory (section 3) and ledger (measured)

2. Design

2.1 Facts (host.rs, procfs.rs)

Pure parsers (/proc/meminfo, /proc/self/status, /proc/self/limits, /proc/self/smaps, /proc/vmstat, /proc/pressure/memory, cgroup v2 and v1 files) behind ProcSource (real /proc, or a fixture in tests). HostFacts::probe gives MemTotal, MemAvailable, swap, Shmem, Mlocked, the tightest memory.max of the cgroup ancestors and its headroom (limit - current + inactive_file), PSI, RLIMIT_MEMLOCK, CapEff, WSL2, and effective_available = min(MemAvailable, cgroup headroom). A malformed or duplicated number is unknown (None), never zero. WSL2: MemTotal is the .wslconfig memory= limit, so the governor budgets against it, and the refusal advice names .wslconfig. A cgroup v1 memory controller (WSL2's hybrid hierarchy, old container hosts) is read too.

2.2 Startup budget (plan.rs)

A  = effective available at start                      (MemAvailable, cgroup headroom)
F  = fixed host items still to be allocated            expert bank (resident copy), pinned K/V image, rings/staging/pool scratch
K  = sealed KAR memfd still to be created              (0 when inherited: it is already out of MemAvailable; 0 for the file profile)
R  = A - F - K
refuse start   when R < soft_floor + reserve
elastic        = R - soft_floor - reserve
  resident complement (--resident-budget-gib)  min(asked, elastic)                       first, it is pinned at open
  prefix cache  auto: cache_share% (75) of what is left, capped (96 GiB; 24 GiB laptop), off under 1 GiB; explicit: clamped to what is left
  conversation checkpoints (when no prefix cache): as many of --prompt-cache as fit, 118 MiB each

Policy::for_host: soft floor 4 GiB (3% of RAM on very large hosts), hard floor 2 GiB, reserve 1 GiB, hysteresis 1 GiB. A refusal prints the numbers and advice, for example (server profile, resident bank, 58 GiB available):

memory budget refused (host_ram): the fixed host footprint (55.39 GiB) leaves 2.61 GiB of 58.00 GiB available, below the 5.00 GiB the runtime needs to
stay out of swap and the OOM killer; available = 58.00 GiB; fixed host footprint = 55.39 GiB; soft floor + reserve = 5.00 GiB; short by = 2.39 GiB;
change: free host memory ...; change: use `--expert-source mapped` ...; change: use `--kar-archive-file` ...; change: lower --context-tokens ...

Missing telemetry (no MemAvailable) does not refuse: the plan is blind, caches are off and the monitor holds shed (fail closed). LELEKA_MEMORY_ENFORCE=0 turns a refusal into a logged note (an emergency override, never a default).

The auto prefix budget is decided twice: in the plan from predicted numbers (to refuse early), and again when the stack opens from the memory that is really available then (resolve_prefix_budget), after the bank is resident. The second one is the one in force.

VRAM: Governor::check_vram (after the context exists) notes a free VRAM below --gpu-budget and refuses only against a measured fixed device footprint (none is set by default: expert slots are not shrunk by this work; the decode-parity branch owns them).

2.3 Runtime monitor (pressure.rs, governor.rs)

One sampler thread reads the host every second and feeds a three-level state machine:

level entered when (any) cache owners requests
normal caches grow under their budgets served
shed available < soft floor; PSI some avg10 >= 20%; cgroup memory.high/memory.max events grew; swap-out >= 25,000 pages/s; telemetry unknown the prefix cache evicts to 3/4 of its size per second (lowest expected-tokens-saved-per-byte first), insertions stop (guard floor = soft floor), conversation checkpoints dropped served
reject available < hard floor; PSI full avg10 >= 5%; cgroup oom/oom_kill events the prefix cache is emptied (budget 0), conversation dropped refused: 503 memory_pressure with Retry-After (5/15 s)

Escalation is immediate; stepping down needs three calm samples and the hysteresis margin, one level at a time. The owner thread applies the directive at the start of every request and between prefill chunks (PrefixServe::apply_shed), so a 60 s prefill follows the pressure; the configured budget is restored when the level returns to normal. If the sampler thread dies, requests re-evaluate a stale level themselves (ensure_fresh), so a reject cannot outlive its sampler; a panic in one sampler round is caught.

Admission (Governor::admit, called by the owner loop before any work): (1) prompt + max_new + 8 > max_context is a 400 context_length_exceeded (the pinned K/V image is the whole serving context, allocated at open, so a request that fits never fails mid-prefill for K/V); (2) level reject is a 503; (3) a request whose own transient (a conversation checkpoint ~118 MB, a prefix node state ~127 MB, import staging: reserve / 4) would take the host below the hard floor is a 503. The control plane gates earlier: it copies the engine's report on its health tick and after every request, and answers reject with 503

  • Retry-After before queueing (streaming requests included, as a real 503 rather than a 200 SSE that fails inside); an engine-side refusal text (memory_pressure: retry_after=N: ...) maps to the same 503; a report older than 30 s never blocks traffic.

Failure behaviour: nothing in the governor blocks (atomics, short mutexes with poison recovery, a bounded thread); a request that is refused, cancelled or fails leaves no buffer in flight (see the unsafe review, section 7); the sampler, the guard thread and the owner loop do not share a lock that a request holds.

2.4 Keeping the memfd resident (lock.rs, Governor::guard_archive)

guard_archive maps a private read-only reopen of the descriptor (/proc/self/fd/N with O_RDONLY): a write-sealed memfd refuses a shared mapping that could become writable (EPERM on kernels up to 5.15, the WSL2 kernel, when the description is read-write); a read-only description can never become writable and works everywhere. The mapping is never dereferenced (only mlock/munlock/mincore/madvise), so no reference into it can dangle, race with the GPU or fault.

  • Lock. plan_lock decides from RLIMIT_MEMLOCK (soft, hard) and CAP_IPC_LOCK before faulting anything in: enough limit -> mlock in 1 GiB chunks, each guarded by the host floors (a swapped-out chunk is read back into RAM); a hard limit that covers it but a soft one that does not -> the soft limit is raised; not enough -> no attempt, and a WARNING with the numbers and the fix (LimitMEMLOCK=infinity in the unit, which leleka up's unit already sets; ulimit -l unlimited; setcap cap_ipc_lock+ep). LELEKA_MEMORY_LOCK=off|try|require (try default; require refuses to start without the lock).
  • Detect. residency_tick (own thread, every 30 s) reads the Swap: of the mapping from /proc/self/smaps and logs WARNING: N MiB of the sealed KAR memfd are swapped out (...) whenever it moves by 64 MiB; the number is in the report (archive.residency).
  • Heal. At level normal and with the memory to spare, MADV_POPULATE_READ over the mapping (256 MiB windows, <= 1 GiB per tick, from a cursor) pulls swapped pages back. LELEKA_MEMORY_HEAL=0 disables it. Healing is deliberately not done under pressure: it would take pages from whoever the kernel just chose.
  • Less cause. After the resident bank is loaded the page cache of the two shards is released (POSIX_FADV_DONTNEED, clean pages only, logged): nothing reads those pages again and they are the cache that competes with the memfd.

Not done (and why): hugetlb for the memfd (needs reserved huge pages, a system setting); lowering vm.swappiness or setting MemoryLow= on the service cgroup (system settings, documented as recommendations, not applied); mlock of the prefix store (its pages are cheaper to evict than to keep; the shed path evicts before swap).

3. Inventory (inventory.rs, ledger.rs)

Two views, never mixed. The inventory is what each owner accounts for its own class (exact formula or its counter); the ledger is what each opening step measured (change of VmRSS, VmPin, Shmem, MemAvailable, the context's accounted bytes and the driver's free VRAM), so it includes allocations nobody registered (cuBLAS workspaces, graphs, the CUDA context). The table is logged once at stack open (leleka-memory: stack open; inventory ..., load ledger ...) and is part of the JSON report: GET /v1/status -> memory, /metrics -> memory, gRPC Snapshot.memory_json.

RESULTS_PLACEHOLDER_INVENTORY

4. Knobs

Knob Default Meaning
--prefix-cache-mib auto|N|0 (profile memory.prefix_cache_mib) off (profiles: auto) prefix cache budget; auto and an explicit value are sized/clamped by the governor
LELEKA_MEMORY_SOFT_FLOOR_MIB / _HARD_FLOOR_MIB 4096 / 2048 (3% / 1.5% of RAM above 128 GiB) shed / refuse thresholds; hard must be below soft
LELEKA_MEMORY_RESERVE_MIB 1024 slack above the soft floor kept after the fixed footprint
LELEKA_MEMORY_HYSTERESIS_MIB 1024 margin to leave a level
LELEKA_MEMORY_CACHE_SHARE_PERCENT 75 share of the elastic memory an auto cache takes
LELEKA_MEMORY_ENFORCE 1 0: log a refusal instead of refusing (emergency)
LELEKA_MEMORY_LOCK try off / try / require for the sealed memfd
LELEKA_MEMORY_HEAL 1 pull swapped memfd pages back when the host has room
LELEKA_MEMORY_SAMPLE_MS, _RESIDENCY_S 1000, 30 sampler and residency-guard cadence
LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB 0 GiB of the mapped expert source page-locked (--resident-budget-gib); now clamped to available - soft floor - reserve

An unparsable override is an error naming the variable (a typo must not silently keep the default of a safety setting). The profiles (deploy/rust-runtime/profiles/*.json) carry a memory section (prefix_cache_mib, floors, reserve, share, lock, heal, resident_budget_gib) that leleka up turns into the engine arguments and environment. The server profile: auto, 4096/2048/1024 MiB, lock try, heal on. The laptop profile (file-backed archive, no memfd): auto, same floors, lock off.

5. Tests

RESULTS_PLACEHOLDER_TESTS

6. How to rerun

Everything is built in WSL (tar/rsync of the tracked files, never on the server); the server runs only through the holder queue.

# model-free, anywhere
cargo test -p leleka-memory                              # parsers, planner, state machine, governor, mapping/mlock, flatness (67 tests)
cargo +nightly miri test -p leleka-memory --lib          # the same pure modules under Miri
cargo test -p strata-control --test memory_gate_http     # gate 503 + Retry-After, engine-side refusal, 600-request soak (threads/fds/RSS flat)
cargo test -p leleka-runtime --lib original_serve_stack::prefix   # shed/restore and the churn test under random shed directives
cargo test -p leleka-deploy                              # profiles carry the memory section

# swap A/B under real pressure, fenced into one cgroup (root; WSL2 or a test box)
cargo build --release -p leleka-memory --example swap_ab
sudo ARMS="A B C" HOG_RELEASE=20 SWAP_AB_BIN=target/release/examples/swap_ab scripts/memory/swap_ab.sh \
     --memfd-mib 6144 --hog-mib 5120 --limit-mib 9216 --secs 60 --reader /path/to/a/12GiB/file

# real model on the 5090, through the serial holder queue (one model process at a time)
cargo test --release -p leleka-runtime --lib --no-run    # the binary; copy it to ~/work/leleka-mem-bin/
cp scripts/memory/jobs/* ~/work/mem-jobs/                 # then: cp ~/work/mem-jobs/91x-*.sh ~/work/gpu-runs/holder2/jobs/
#   910 archive probe (model-free, real 55 GB memfd + competing reader), 911 inventory (idle / 180k / prefix full), 912 soak (220 requests),
#   913 shed path, 917 reader (decode speed and memfd residency next to a page-cache reader)

# real model on the laptop (WSL2, RTX 3080): the same smoke with the laptop profile
cargo test --release -p leleka-runtime --features sm86 --lib --no-run
bash scripts/memory/laptop_run.sh LABEL ~/laptop/BIN LELEKA_MEM_SCENARIO=inventory LELEKA_MEM_TOKENS=24000 LELEKA_MEM_PREFIX_MIB=auto

The job scripts guard the server: a pre-flight needs >= 45 GiB available, experts are file-mapped by default so MemAvailable stays high, the test aborts below 15 GiB (in-process guard and an external watchdog that stops it), the shed scenario moves the floors next to the memory the host has now and uses a 3.5 GiB ballast instead of ever approaching the real limit, and the competing reader is bounded (40 GiB through the page cache, which MemAvailable counts as available).

7. Rust unsafe review

Full review: memory-safety-unsafe.md (method, the table of every unsafe construct reviewed, the lifetime analysis of each asynchronous copy site, Miri and clippy results, residual risks). Summary:

  • leleka-runtime, deploy, desktop-core, serving-policy and the rest contain no unsafe (workspace unsafe_code = "forbid"); the prefix cache itself is safe Rust. The unsafe lives in leleka-cuda-driver (~500 blocks, private FFI modules), leleka-native-cpu-expert (~150), control-plane (36, libc), leleka-model-format (4, the file mapping) and, new in this branch, one module of leleka-memory (lock.rs: mmap/mlock/mincore/madvise over a descriptor, with its invariants stated at the type; and heap.rs: malloc_trim). 306 SAFETY: comment lines were added where the invariant was missing, 35 model-free tests.
  • Asynchronous copies: for every cuMemcpy*Async/memset/cuLaunchHostFunc/mapped-host site the owner of the host buffer was traced through completion, ? returns, request cancellation, Drop and field drop order, context poisoning. A cancelled request cannot free a buffer with a copy in flight: cancellation is polled between chunks and every owner's Drop synchronizes before it releases. The prefix-cache park/import path, PendingOwnedCopy, the expert-cache close and the DeviceBuffer/Context drop order held up.
  • Defects found and fixed (each with a regression test where one is possible): D1 original_expert_stager stop/claim store-buffering race (a worker could still copy from a source the caller then released; the old code failed the new test 9 of 10 runs); D2/D2b mmq_original_host_stage finish/work (a helper could overwrite a ring buffer whose DMA was still reading it; same race pair); D3 HostStage::wait trusted the caller's length against uninitialised pinned memory; D4 mtp_original_full_forward unfenced cuMemsetD8 (needs a GPU to prove). Residual: a cross-stream race candidate in mtp_original_full_round::stage_first_residual_direct, cuMemHostUnregister without a context in HostStage::close/Ring::new, and SIGBUS if a verified mapped file is truncated (the sealed memfd cannot be). All three are written up with what a GPU run would have to show.
  • Miri (nightly in WSL): the unchanged prefix_cache/* and conversation/memory.rs (31 tests) and the pure modules of leleka-memory (procfs, host, plan, pressure, inventory, ledger, census, governor: 61 tests) run clean, no UB, no leaks; tests that call mmap/mlock/malloc_trim or depend on wall-clock threads are skipped under Miri. leleka-runtime itself cannot be built under Miri (it links the CUDA driver). cargo clippy: the new crate and the new code are clean; the existing warnings of cuda-driver (340), leleka-runtime (166) and native-cpu-expert (153) were not cleaned up wholesale.

8. Open

  • The OTHER_FIXED_ESTIMATE (rings, staging, pool scratch, empty checkpoints) in memory_governor.rs is a measured constant, not a formula; re-measure when those owners change.
  • A hard guarantee that the memfd is never swapped needs LimitMEMLOCK=infinity (the deploy unit sets it) or CAP_IPC_LOCK; without it the guard detects and heals but cannot prevent.
  • Rust aborts on a failed allocation: the insertion guards keep the prefix store away from that, but a plain Vec growth under a cgroup limit is the OOM killer's decision, not ours.
  • The control-plane gate reads a report that is at most one health tick old; the engine-side admission is the exact one.