41 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/engine-qwen35-cuda/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).
With a file-mapped expert bank (--expert-source mapped, the laptop form) the hot part of the bank (half of the host RAM, at most the bank) is a fixed item: its pages are reclaimable,
so MemAvailable counts them as free, but every decode touches them; a cache sized into them made the kernel evict experts and swap anonymous memory instead (WSL2 laptop: VmSwap 0.1 -> 4.4 GiB and repeated swap-out sheds with a 20 GiB auto cache).
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% (PSI counts only while available < 3 x soft floor: it is system wide, and a page-cache reader alone drove full to 5.2% with 68 GiB free in job 910); 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-Afterbefore 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_lockdecides fromRLIMIT_MEMLOCK(soft, hard) andCAP_IPC_LOCKbefore faulting anything in: enough limit ->mlockin 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=infinityin the unit, whichleleka up's unit already sets;ulimit -l unlimited;setcap cap_ipc_lock+ep).LELEKA_MEMORY_LOCK=off|try|require(trydefault;requirerefuses to start without the lock). - Detect.
residency_tick(own thread, every 30 s) reads theSwap:of the mapping from/proc/self/smapsand logsWARNING: 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
normaland with the memory to spare,MADV_POPULATE_READover the mapping (256 MiB windows, <= 1 GiB per tick, from a cursor) pulls swapped pages back.LELEKA_MEMORY_HEAL=0disables 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.
3.1 Measured on the RTX 5090 server (job 911, 2026-10-18; sealed memfd inherited from the holder, file-mapped experts, INT8 K/V --kv-resident 20480, max context 262,144, chunk 8192, VRAM expert tier 2,048 slots, --prefix-cache-mib 4096)
Experts are file-mapped in these jobs on purpose (the operator rule: MemAvailable >= 15 GiB at all times; the resident bank leaves 11-17 GiB at idle, 14.5 GiB in job 927). The resident bank is
therefore taken from the loader's own report and from earlier logs (below), not re-measured here.
Allocation classes (inventory, idle; the planned column is the startup plan's prediction):
| space | when | class | MiB | planned | swappable | size formula |
|---|---|---|---|---|---|---|
| host shmem | startup | kar.memfd |
52,733.9 | yes (unless locked) | the sealed level-2 archive, 55,295,529,472 B, shared with the holder; not in MemAvailable |
|
| host pinned | startup | kv.host_pinned |
3,168.0 | 3,168.0 | no | 12 QSA layers x serving cells (262,144) x 1056 B, pinned and device-mapped, the whole serving context at open (exact: the plan equals the measurement) |
| host pinned | startup | native head / MTP / ring pins | ~322 + ~266 | (in "other") | no | cuMemHostAlloc of the head, the drafter and the verifier (shows as Shmem in the ledger) |
| host file-mapped | startup | expert_bank.file_mapped |
47,962.5 | reclaimable | routed experts of shard 0 mapped from the GGUF (page cache; the working set of every decode) | |
| host pageable | elastic | prefix.store |
0 -> 4,088 (budget 4,096) | yes | blocks 14,208 B/token + node states ~127 MiB | |
| host pageable | elastic | conversation.checkpoints |
n x 118 | yes | only without the prefix cache | |
| host pageable | startup | dense weights host side, MoE arena, CPU pool, checkpoints | ~1,400 + ~75 + ~28 | yes | OTHER_FIXED_ESTIMATE below |
|
| device | startup | expert_cache.slots |
5,200.0 | no | 2,048 slots/layer-mode, --expert-cache-per-layer |
|
| device | startup | kv.prompt_stage |
264.3 | no | one INT8 staging pool of the prompt path | |
| device | startup | kv.vram_window |
251.7 | no | 12 layers x 5,120 resident pages x 4,244 B | |
| device | startup | dense weights / head / embedding / MoE arena / MTP | 3,890 + 497 + 322 + 818 + 882 | no | measured by the ledger (context-accounted) | |
| device | lazy | CUDA context, cuBLAS, graphs | 1,277 at idle, 1,361 after the first 180k request | no | cuMemGetInfo used minus the context's accounted bytes |
Load ledger (what each opening step measured; deltas of MemAvailable, Shmem, the context's accounted bytes and the driver-seen used VRAM):
| stage | ms | RSS MiB | shmem MiB | MemAvailable MiB | device acct MiB | device driver MiB |
|---|---|---|---|---|---|---|
| embedding table | 102 | +16 | 0 | -346 | +322 | +324 |
| native head + embedding | 498 | +345 | +322 | -487 | +497 | +506 |
| KAR PLE cache | 0 | 0 | 0 | 0 | +64 | +64 |
| dense weights | 4,461 | +1,403 | 0 | -946 | +3,890 | +4,578 |
| MoE arena cache | 574 | +74 | 0 | -426 | +818 | +850 |
| prompt executor + MTP drafter (incl. the 3,168 MiB K/V pin) | 1,054 | +3,456 | +3,434 | -3,061 | +882 | +920 |
| CPU expert pool (15 workers) | 13 | +28 | 0 | -38 | 0 | 0 |
| expert tier (VRAM slots + profile fill) | 6,953 | +4,027 | 0 | -56 | +5,200 | +5,200 |
| total, excluding bank and memfd | -5,360 | +11,663 | +12,442 |
So the fixed host footprint of the opening steps other than the bank and the K/V image is 5,360 - 3,168 = 2,192 MiB (the plan's constant is 2.5 GiB). With the bank as a RAM copy
(--expert-source resident, 50.3 GB, page-locked by cuMemHostRegister) the server profile's fixed footprint is 3.09 + 46.85 + 2.5 = 52.4 GiB, which is what the plan subtracts from the ~67 GiB
available while the holder is idle.
Census (process, from /proc/self/status, cuMemGetInfo):
| moment | RSS | VmSwap | threads | fds | MemAvailable | device used (driver) | device accounted |
|---|---|---|---|---|---|---|---|
| idle after open | 9.44 GiB | 0 | 23 | 47 | 61.83 GiB | 12.65 GiB | 11.40 GiB |
| after one 179,997-token request (130 s) | 56.05 GiB | 0 | 55 | 47 | 57.35 GiB | 12.87 GiB | 11.54 GiB |
| prefix cache full (4,088 of 4,096 MiB) | 56.45 GiB | 0 | 55 | 47 | 57.08 GiB | 12.87 GiB | 11.54 GiB |
The RSS growth is file-mapped expert pages touched by the request (reclaimable, counted in MemAvailable); the cost of the request that is not reclaimable is the prefix store (+4.1 GiB at its
budget; MemAvailable fell 4.5 GiB after the request and 4.75 GiB at full) and +230 MiB of VRAM the first long request allocated lazily (graphs, workspaces), flat afterwards. The request itself holds no host memory beyond
the 3,168 MiB image that was allocated at open: the pinned K/V does not grow with the context, so a prompt that fits the serving context never fails mid-prefill for K/V.
4. Knobs
| Knob | Default | Meaning |
|---|---|---|
--prefix-cache-mib auto|N|0 (profile memory.prefix_cache_mib) |
off (profiles: rtx5090-32g 6144, rtx3080-16g auto) |
prefix cache budget; auto is 75 % of what is elastic when the stack opens and grows when RAM is freed elsewhere; an explicit value is clamped to what the host has and never grows (plan::explicit_prefix_budget), which is why the dedicated 5090 profile carries one |
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_MEMORY_SWAPOUT_PAGES_PER_S, _PSI_SOME_SHED, _PSI_FULL_REJECT, _PSI_GUARD_MIB |
25000, 20, 5, 3 x soft floor | the other pressure signals (system-wide swap-out rate, PSI limits, and the available memory above which PSI is ignored) |
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: prefix cache 6144 MiB (an explicit cap, so RAM freed elsewhere cannot grow it), floors 4096/2048 MiB and reserve 2048 MiB, lock try, heal on. The laptop profile (file-backed archive, no memfd): auto, same floors, lock off.
The experimental memfd_extents: ple_only (a sealed memfd that holds only the ~16 GB the serve path reads, locked and healed by extents) is described in docs/kar-sparse-memfd.md; it is off by default.
5. Tests
5.1 Model-free (all pass; run in WSL)
| suite | what it proves |
|---|---|
leleka-memory unit tests (67) |
parsers reject malformed/duplicated numbers; cgroup v2 tightest-ancestor headroom and the v1 controller; planner: the 5090 gets an auto cache from what is left, a host that cannot hold the footprint is refused with numbers and advice (also "a second model process beside the holder"), the memfd still to be created counts, explicit caches are clamped and the clamp reported, the laptop profile fits, WSL advice, missing telemetry is blind not zero; monitor: immediate escalation, hysteresis and three calm samples to step down, unknown holds shed, PSI only below the guard, cgroup oom/high deltas, swap-out storm; governor: admission (400 context, 503 pressure, transient), shed order and recovery, env overrides validated, sampler thread starts/publishes/stops, a dead sampler cannot leave reject stuck; mapping/mlock/mincore/madvise over a real descriptor, bounds refused before any syscall; flatness checker catches 1 thread / 1 fd / 4 KiB-per-10-requests leaks |
Miri (cargo +nightly miri test -p leleka-memory --lib) |
61 tests, no UB, no leaks (syscall and wall-clock tests skipped) |
strata-control --test memory_gate_http (4) |
reject report -> 503 memory_pressure + Retry-After on /v1/responses, /v1/chat/completions (JSON and stream), /v1/messages and streaming, nothing reaches the engine; shed still serves; stale/garbage report never blocks; engine-side refusal text -> same 503; 600-request soak (served, streamed, abandoned mid-stream, engine failures, pressure flips every 12 requests): 289 served, 120 refused, 96 abandoned, 95 failed; threads 4 -> 4, descriptors 14 -> 14, RSS +0.27 MB (tolerance 96 MiB) |
leleka-runtime original_serve_stack::prefix (13) |
shed evicts to the target and restores the configured budget; 300 random requests under random shed directives: every resume is exact (digest equals a full read), the store never exceeds its budget, invariants hold |
leleka-deploy (77) |
profiles carry the memory section into engine arguments and environment; invalid sections refused |
cuda-driver, native-cpu-expert, model-format suites |
from the unsafe review (371 / all / 129 pass) |
5.2 Real model, RTX 5090 (through the holder queue; experts file-mapped; MemAvailable never below 58 GiB, guard 15 GiB)
- Job 910 (archive probe, no model). The holder's real 55 GB memfd: lock decision
insufficient(RLIMIT_MEMLOCKsoft = hard = 8 MiB, noCAP_IPC_LOCK) with the WARNING and the three fixes, no attempt made; the smaps read of the 51.5 GiB mapping costs 0-1 ms; memfd swapped 0 MiB for 75 s next to a competingddof the KAR file (40 GiB, 259 MB/s, page cache only): with 68 GiB available a page-cache reader does not swap the memfd (a negative result worth stating: the incident needs real pressure). Side finding: that reader drove system-wide PSIfullto 5.2%, which made the first monitor reject at 68 GiB available; PSI now counts only below 3 x the soft floor (psi_guard_available). - Job 911 (inventory). Section 3.1.
- Job 912 (soak). 220 requests in 3,322 s: 171 served, 29 cancelled (alternating mid-prefill and after the first decode round), 20 over-long prompts refused before any allocation (400
context_length_exceeded), 3 big prompts (100k, 180k, 100k tokens), 6 sessions growing to 60k tokens with a 2 GiB prefix cache (200 cache requests: 53 hits, 147 misses, 446 checkpoint candidates rejected by the full 2 GiB budget, 10 evictions).MemAvailable62.9 GiB throughout. Flatness after warm-up (39 censuses): RSS +0.25 GB (tolerance 0.5 GB; file-mapped experts still warming), VmSwap 0 -> 0, pinned 0, threads 55 -> 55, fds 47 -> 47, VRAM used (driver) 13,821,542,400 -> 13,821,542,400, VRAM accounted 12,394,862,172 -> 12,394,862,172. No stack health event, no failed request. - Job 913 (shed path). Floors moved next to the memory the host had (soft 1,536 MiB, hard 3,072 MiB below 63,132 MiB), prefix budget 6 GiB, ballast 2 GiB: growing the prefix cache by 20k-token sessions crossed the
soft floor at the second request (
normal -> shed: available 61543 MiB below the soft floor 61596 MiB); the next request found the cache evicted from 702 MiB to 351 MiB,MemAvailable61,471 -> 61,885 MiB and RSS -305 MiB (the freed blocks went back to the OS:malloc_trimafter an eviction); the ballast then crossed the hard floor (shed -> reject),admitanswered503 memory_pressure,retry_after=15s, and the next request found the cache emptied. The recovery phase of that smoke compared against a baseline that had drifted (file-mapped expert pages warmed up during the test) and never reached the 1 GiB hysteresis margin, so the smoke reportedfailedon its own expectation, not on the governor (reject -> shedhappened after the ballast was freed, as designed). The smoke now re-centres the floors before the recovery phase; the re-run is in section 5.5. - Job 917 (reader), first attempt, not a result. The request decoded one token (the filler prompt ends in EOS) and the reader thread only ran for ~4 s (0 GiB through the cache), so decode speed 6.9 / 7.9 / 8.0 tok/s (A/B/C) says nothing;
the memfd stayed at 0 swapped MiB and
pswpin/outat 0 throughout. The scenario now decodes a fixed 64 tokens without stopping at EOS and lasts until the reader has streamed its 40 GiB; the re-run is in section 5.5.
5.5 Job 914 (binary a7): shed with recovery, and decode speed next to a 40 GiB competing reader
- Shed path, complete. Floors 1.5 / 3 GiB below the memory the host had (63,350 MiB), prefix budget 6 GiB, ballast 2.3 GiB:
normal -> shedat the soft floor, the next request found the cache evicted 351 -> 0 MiB withMemAvailable62,089 -> 62,442 MiB and RSS -312 MiB; the ballast crossed the hard floor (shed -> reject),admitanswered 503memory_pressure,retry_after=15s; with the ballast freed and the floors re-centred the level wentreject -> shed -> normalin 4 samples, the request after it was served and the prefix budget was back at 6,144 MiB.MEM-RESULT scenario=shed failed=[].MemAvailablenever below 58 GiB. - Reader, decode speed. 6 requests without the reader (A), 54 requests while a thread streamed 40 GiB of the KAR file through the page cache (B), 6 after (C); 64 decoded tokens each, no EOS stop:
A 18.12 tok/s, B 19.30 tok/s (B/A 1.07: no drop while the reader ran), C 15.95 (the first two requests after the reader ran at 11 tok/s, the following four at 17.1-19.6: the 40 GiB of KAR file evicted part of the file-mapped expert pages
from the page cache and they were read back once; that is the mapped bank, not the memfd).
memfd_swapped_mib= 0 on every request,pswpin/out0 (one page of swap-in in B),MemAvailable62.0-62.3 GiB throughout. Same conclusion as job 910: with the host not short of memory a page-cache reader does not move the memfd; the conditions that do are in 5.3.
5.6 Does the daemon RSS leak? Evidence from the e2e sessions, and the long soak (NOT YET RUN)
What exists: the leak scenario of the memory smoke (time-bounded mixed workload: shared growing sessions, unshared 8k-30k sessions, 100k/180k prompts every 120 requests, 8% cancels, 4% over-long refusals, prefix cache auto under constant churn),
sampled every 30 s: VmRSS split into RssAnon / RssFile / RssShmem, VmSwap, MemAvailable, Cached, Shmem, active/inactive file, VRAM used and accounted, the prefix store, mallinfo2 (arena, in use, free, mmapped), threads, fds; a TSV per run
(~/work/gpu-runs/mem-logs/*.tsv, outside Git); at the end it prints, per series, the slope in MiB per 1000 requests after a 25% warm-up with its 95% interval and the Theil-Sen slope (MEM-LEAK-FIT lines);
scripts/memory/leak_fit.py RUN.tsv re-fits any run offline and --compare lines up arms. Jobs: 919 7-minute check of the scenario, 920 the 3 h 03 min run (default allocator, malloc_trim after every eviction), 921 45 min with MALLOC_ARENA_MAX=2,
922 45 min with LELEKA_MEMORY_NO_TRIM=1 (what the trim buys); compare 921 and 922 with the first 45 min of 920 (leak_fit.py --compare 920.tsv:default 921.tsv:arena2 922.tsv:notrim --tmax 2700). File-mapped experts, so MemAvailable stays ~58 GiB (the 15 GiB rule);
an anonymous or shmem leak shows the same as with the resident bank.
Queue state: 919 was a duplicate of 920 and is skipped; 920, 921 and 922 were moved to holder2/jobs-deferred/ by the coordinator so that they do not block the speed jobs for hours; 920 will run in a quiet window (overnight), 921/922 only if 920 shows a slope. The soak below is therefore not measured. What the evidence says today (fits of the committed e2e data with scripts/memory/fit_e2e_env.py, RSS against request count; docs/e2e-data/945-*, 943b-*):
| session | span | series | slope (MiB / 1000 requests) | note |
|---|---|---|---|---|
| 945 CRM (resident bank, 84 requests, ctx to 123k) | whole run | RssAnon | +70,029 [+66,617, +73,441] | the prefix store filling: +6,647 MiB RssAnon vs +6,748 MiB store |
| 945 | requests >= 70 (store full; 23 samples, 13 requests, 6 min) | RssAnon / VmRSS | 0.0 (56,337 / 60,383 MiB at every sample) | too short to bound a small slope: 13 requests |
| 943b tic-tac-toe (conversation cache, 51 requests, ctx to 82k) | last 40% of requests (37 samples) | RssAnon | +464 [-587, +1,515], Theil-Sen 0.0 | first 50,894 -> last 50,879 MiB |
RssShmem is constant in both (3,836 MiB), RssFile is 0, so there is no anonymous or shmem growth after the cache fills and no file growth at all. That is consistent with no leak; the intervals (hundreds of MiB per 1000 requests) are far too wide to exclude a slow one, which is what the soak is for. The bisect (prefix cache off, CPU pool lookahead off, seed off, K/V imports) is
prepared as environment switches of the smoke (LELEKA_MEM_PREFIX_MIB=0, LELEKA_ORIGINAL_SERVE_SEED=off) and has to wait for a slope to bisect.
5.3 Swap A/B under real pressure (WSL2 laptop, cgroup v1 memory controller, 9 GiB limit; sealed memfd 6 GiB, anonymous hog 5 GiB, a reader streaming a 12 GiB file; kernel 5.15)
| arm | memfd swapped out | notes |
|---|---|---|
| A: no lock, no heal | 2,126 MiB at t=8 s, stays 2,126-2,552 MiB for the whole run (also 50 s after the hog is gone) | the incident in miniature: the kernel chose the memfd |
| B: heal on | 2,106 MiB peak while the hog lives (level reject: healing is deliberately off under pressure); after the hog exits the guard pulls it back: 2,098 -> 1,129 -> 28 -> 15 MiB in 20 s |
MADV_POPULATE_READ, rate limited |
C: mlock (require) |
0 MiB swapped, 6,144 MiB locked | the hog is swapped instead (2.1 GiB, 45k pages/s in and out: the price of pinning when the host is genuinely oversubscribed) |
Finding on the way: on kernel 5.15 mmap(PROT_READ, MAP_SHARED) of a write-sealed memfd opened read-write fails with EPERM; the guard therefore maps a read-only reopen (/proc/self/fd/N), which is how the engine
holds the archive anyway.
5.4 Real model, RTX 3080 laptop (WSL2, 39 GB, laptop profile: read-only KAR file, mapped experts, context 32,768; scripts/memory/laptop_run.sh)
Runs (the laptop was power-capped to 30 W by another agent, so no timing here means anything; memory does):
- Inventory (12,000-token request, 3 GiB prefix cache). Ledger and inventory as on the server except the K/V image and pins land in
Shmem(+3,462 MiB in the executor stage, +324 MiB in the head stage):VmPinstays 0 on this kernel, so pinned memory is read fromShmem. Measured fixed footprint of the opening steps:MemAvailable-5,096 MiB (plan: 5.5 GiB). Device: 13,367 MiB accounted, 15,373 MiB used by the driver at idle (+304 MiB after the first long request, flat afterwards); the VRAM expert tier took 6,294 MiB. Census: idle RSS 12.9 GB / VmSwap 0.1 GB -> after the request RSS 33.2 GB / VmSwap 2.0 GB -> prefix cache full (2,987 of 3,072 MiB) RSS 31.8 GB / VmSwap 4.4 GB. The 8 GB WSL swap fills with anonymous pages while the mapped experts (48 GB of file, 39 GB of RAM) occupy the page cache: this host has no room for a 20 GiBautocache, which is what the old formula granted (prefix cache on: ... budget 19654 MiB) and what the working-set reserve now prevents. The governor noticed: 5normal -> shedepisodes on swap-out rates of 26k-53k pages/s, each recovered within seconds. - Soak (60 requests, 1.5 GiB cache, context 32,768): 39 served, 6 cancelled, 5 refused (context), 2 big (8k and 12k tokens); 9 censuses after warm-up: RSS -230 MB, VmSwap -33 MB, threads 47 -> 47, descriptors 30 -> 30, VRAM used
15,676,735,488 -> 15,676,735,488, accounted 13,514,519,132 -> 13,514,519,132: flat. (The smoke marked the run failed because its sessions grew past the 32k context and the engine refused them with
Refused(Context), which is the correct answer; the smoke now bounds the session length by the context, so a rerun reports a clean pass.)
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-engine-qwen35-cuda --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-engine-qwen35-cuda --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-engine-qwen35-cuda --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-policyand the rest contain nounsafe(workspaceunsafe_code = "forbid"); the prefix cache itself is safe Rust. The unsafe lives inleleka-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 ofleleka-memory(lock.rs:mmap/mlock/mincore/madviseover a descriptor, with its invariants stated at the type; andheap.rs:malloc_trim). 306SAFETY: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,Dropand 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'sDropsynchronizes before it releases. The prefix-cache park/import path,PendingOwnedCopy, the expert-cache close and theDeviceBuffer/Contextdrop order held up. - Defects found and fixed (each with a regression test where one is possible): D1
original_expert_stagerstop/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/D2bmmq_original_host_stagefinish/work (a helper could overwrite a ring buffer whose DMA was still reading it; same race pair); D3HostStage::waittrusted the caller's length against uninitialised pinned memory; D4mtp_original_full_forwardunfencedcuMemsetD8(needs a GPU to prove). Residual: a cross-stream race candidate inmtp_original_full_round::stage_first_residual_direct,cuMemHostUnregisterwithout a context inHostStage::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/*andconversation/memory.rs(31 tests) and the pure modules ofleleka-memory(procfs,host,plan,pressure,inventory,ledger,census,governor: 61 tests) run clean, no UB, no leaks; tests that callmmap/mlock/malloc_trimor depend on wall-clock threads are skipped under Miri.leleka-runtimeitself cannot be built under Miri (it links the CUDA driver).cargo clippy: the new crate and the new code are clean; the existing warnings ofcuda-driver(340),leleka-runtime(166) andnative-cpu-expert(153) were not cleaned up wholesale.
8. The real Codex CRM session (e2e job 945): what the memory did, and what changed in the budget
Session: --prefix-cache-mib auto, resident expert bank, sealed memfd from the holder, 84 requests, context 10k -> 123k tokens, 25 minutes (~/work/leleka-e2e/runs/945-codex-crm/env.tsv, inference.log).
That build (leleka-e2e/bin-sm120) predates this branch: no governor ran. What the numbers say:
| time | VmRSS | RssAnon | RssShmem | RssFile | MemAvailable |
|---|---|---|---|---|---|
| 0 s (after load) | 53,723 MiB | 49,690 | 3,836 | 0 | 13,991 MiB |
| 592 s (ctx 55k) | 58,152 | 54,106 | 3,836 | 0 | 9,710 |
| 1194 s (ctx 95k) | 60,360 | 56,314 | 3,836 | 0 | 7,474 |
| 1395 s (ctx 115k) | 60,383 | 56,337 | 3,836 | 0 | 7,459 |
- Real, not reclaimable. The growth is
RssAnon(+6,647 MiB);RssShmemis constant (the pinned K/V image and head, 3,836 MiB),RssFileis 0 (the resident bank is anonymous), and the 51 GB memfd is outside the process RSS and outsideMemAvailable(shmem is not counted there).MemAvailablefell by 6,532 MiB: one for one with the anonymous growth. There was no reclaimable page cache to give back (the shard cache had been dropped after the load); the dip was the prefix store filling its budget (582 MiB at the first request, 7,330 of 7,476 MiB at the end, 58 admitted, 23 evicted) and it plateaued exactly when the store reached the budget. That also answers "does the RSS leak" for this run: RSS growth (6,647 MiB) = store growth (6,748 MiB) within 1.5%; the soak in section 5.6 tests the plateau itself. - Why nothing shed or refused. (1) No governor in that build. (2) With it, the old rule would not have shed either: the budget was 75% of (14,064 - 4,096) = 7,476 MiB, which leaves 6.9 GiB available with the cache full (observed 7.46 GiB) against floors of 4 GiB (shed) and 2 GiB (reject). The plan designed a minimum of 7 GiB available, and the operator's 15 GiB cannot hold in resident mode at all (idle is already 14 GiB).
- Was the startup plan using the real post-load footprint? Partly. The plan subtracts a predicted footprint from the available memory before the load. Real: 68,762 -> 13,991 MiB = 54,771 MiB; predicted (bank 46.85 GiB + K/V 3.09 GiB + 2.5 GiB other) = 53,700 MiB: 1.1 GiB short, because the "other" constant had been measured
with the file-mapped bank (2.19 GiB); with the resident bank it is 3.55 GiB. The cache budget itself was never taken from the prediction: it is recomputed at open from the real
MemAvailable(so the 1.1 GiB error did not enter it), but the refusal decision and the logged plan used the optimistic number. - Changes.
OTHER_FIXED_ESTIMATE_RESIDENT= 3.6 GiB for the resident bank (2.5 GiB stays for the mapped one);Policy::reserve1 -> 2 GiB (the first long request plus the store's own overhead grew the process ~1 GiB beyond the plan); the caches stop admitting atsoft_floor + reserve(6 GiB) instead of at a 3 GiB insertion floor, i.e. before a shed is needed; and after the stack opensnote_post_loadcompares the plan with the measured availability, logs a WARNING above 512 MiB error and publishes it asplan_checkin the report. For the CRM host state theautobudget becomes 6.0 GiB (was 7.3) and ~8 GiB stay available with the cache full (was 7.4); a 180k session (2.6 GB of blocks + 127 MiB per node) still fits. The file-mapped bank was already accounted since section 2.2 (hot half of RAM kept out of the elastic memory); the resident bank is a fixed item of the plan.
9. Open
- The
OTHER_FIXED_ESTIMATE(rings, staging, pool scratch, empty checkpoints) inmemory_governor.rsis 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) orCAP_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
Vecgrowth 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.