Files
leleka/docs/kar-file-source.md
T
Pavlo RatushnyiandClaude Sonnet 5.5 c864204e45 KAR file source for the 5090: startup read report, per-read identity check, profile rtx5090-32g-file, A/B script
* model-format: VerifiedKarPleArtifact records how the archive was vouched for (full pass / stamp / attested memfd) and what start-up read
  (KarStartupRead); an ordinary archive file keeps the device/inode/size/mtime/ctime it was verified in and every row read compares the open file
  with it (one fstat, the length check already did it); LELEKA_KAR_IDENTITY_RECHECK=off disables. Sealed memfds are unchanged.
* leleka-runtime: one engine log line per load, leleka-kar-startup source=.. verify=.. total_read_bytes=..
* deploy: built-in experimental profile rtx5090-32g-file (kar_source file, resident bank, explicit 6144 MiB prefix cache, never auto-selected);
  the resource planner charges a file archive with a resident bank the engine only.
* scripts: run-e2e.sh accepts E2E_KAR_FILE / E2E_ASSETS; scripts/e2e/decode/kar-file-ab.sh is the paired memfd vs file A/B (not run).
* docs/kar-file-source.md: what the file form reads, guarantees, risks with the measured random-read figures, the A/B command.

Not a performance claim: nothing was run on a GPU.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 15:11:06 +01:00

165 lines
19 KiB
Markdown

# The KAR archive as a file on the 5090 (experimental profile `rtx5090-32g-file`)
Date 2026-10-30, branch `claude/kar-file-source`. Owner requirement: at engine start do not load the 55 GB archive, load what is needed when it is needed (like a page cache); a slower cold start is
acceptable (the server has 128 GB, the model is ~50 GB, and models larger than RAM must work too). Today the 5090 profile seals the archive into a memfd (eager copy of 55.3 GB, ~162 s from this disk
(`holder2 ready ... in 162.4s`), 51.5 GiB of shmem for the life of the service, of which about 36.6 GiB is never read: `docs/design/memory-single-copy-and-elastic-state.md` A.4).
Evidence labels: **S** read from source (paths named), **M** measured (log or command named), **E** estimate (derivation given), **U** not verified. Nothing here is a speed or quality result: the A/B in
section 6 has not been run (AGENTS.md).
## 1. What `kar_source: file` does today (S)
| step | what happens | reads of the archive |
| --- | --- | --- |
| supervisor (`crates/deploy/src/supervisor.rs`, `drive`) | `KarSource::File`: no copy, no seal, no descriptor; engine gets `--kar-archive-file PATH --kar-provenance PATH` (`config.rs` `engine_args`). `leleka up` makes the file mode 0400 (`steps.rs`). No holder. | none |
| admission (`qwen4exp_kar_ple.rs` `open_read_only_file`) | opens `O_NOFOLLOW`, requires regular file, exactly the pinned 55,295,529,472 bytes, one link, owned by the service user, **no write bit**; provenance JSON (403 KB) hashed against its pin | 403 KB provenance |
| verify (`load_pinned_inherited_archive`, `kar.rs` `VerifiedKarPleArtifact::verify`) | re-opens the same inode through `/proc/self/fd`; `inspect` reads header (256 B), name table and directory (about 1 MB, checked by the header's directory digest); the two partition books (8 B each). **Then, unless a stamp trusts the file: SHA-256 of all 55.3 GB plus every section CRC-32**, one read-ahead thread feeding two consumers | ~1 MB with a current stamp; **55.3 GB through the page cache without one** |
| governor (`memory_governor.rs` `guard_archive`) | returns at once for a file-backed archive: no `mlock`, no heal, no `MADV_POPULATE`, no mapping. `StartArgs.kar_file_backed` selects `KarForm::File` (plan charges 0 bytes) and the *laptop* policy flag (prefix cache cap 24 GiB instead of 96 GiB; `leleka-memory/src/plan.rs`) | none |
| serve (`kar.rs` `read_rows_chunk`) | **pread, not mmap**: per PLE row three positional reads, 10 B of scales at `scales+10*row`, 20 B at `planes+20*row`, 20 B at `planes+stride+20*row`. No `fadvise`/`madvise`. Decode: `read_rows` (16 rows = 48 preads; a first row timed, <= 20 us means page-cache warm and the other 15 are read on the calling thread, else 8 threads on cloned handles and the next 256 calls skip the probe). Prefill: `read_rows_batch` (32 threads, 512 rows each) and `row_reader` (read-ahead of the next chunk's rows on a thread of its own, `KarPleCache`) | only the 4 KiB pages that hold a requested row |
| anything else | the Original serve path reads no expert from the archive (`kar_expert_source` is `None`; the resident bank comes from GGUF shard 0). The 36.6 GiB the memfd holds beyond the PLE extents is read by nothing | none |
A scattered small `pread` on a file nobody reads sequentially is served by the kernel as a standalone one-page read (`ondemand_readahead`, "small read: read as is"), so a cold row costs three 4 KiB
page reads (scale page, plane-0 page, plane-1 page) and a warm row three page-cache copies (~1 us each, `window.ple` 0.1-0.2 ms per window on the memfd).
### Where the "20 s kar_inspect_verify" and "37 s shard sha256" came from (S, M)
They are the engine's `leleka-load-time` spans in holder jobs. `scripts/e2e/run-e2e.sh` starts the engine with `--kar-archive-fd` and **neither** `--kar-attested-by-stamp` **nor** `--verify-stamps`, so the
engine hashes the memfd (55 GB from RAM, SHA-256 and CRC pipelined, 20 s = 2.7 GB/s) and both shards (83.6 GB in two threads, 37 s) at every start. The production supervisor (`leleka run`) skips both:
`--verify-stamps DIR` always (a stamp = device, inode, size, mtime, ctime of the file plus the pinned digest, recorded only after a full pass whose before/after identity matched; `ctime` cannot be set from
user space), and `--kar-attested-by-stamp` for a memfd copied from a stamped file. **For the file form the stamp is the whole mechanism**: with a current stamp the archive is not read at start beyond
the ~1 MB above; without one (first start, or after the file's ctime moved, for example by `chmod 0400`) that start hashes the 55.3 GB once, which also fills the page cache.
The new log line `leleka-kar-startup source=file|memfd verify=stamp|full-pass|attested-memfd metadata_bytes=.. book_bytes=.. hashed_bytes=.. total_read_bytes=.. identity_recheck=..` is printed once per load
(`model-format` `KarStartupRead`); the A/B and the deploy status read it.
## 2. What the sealed memfd guarantees that a file does not, and what we do about it
| | sealed memfd | read-only file |
| --- | --- | --- |
| immutability | `WRITE|GROW|SHRINK|SEAL` seals: nobody can change a byte, not the owner, not root through the file API | mode 0400, one link, owner = service user; the owner or root can chmod and write; the disk can rot |
| identity | the memfd is the copy that was hashed (or attested); unlinked, so it cannot be swapped | the path can be replaced; the engine holds one open descriptor (reads follow the inode, not the path) |
| verification | full SHA-256 + CRC of the copy at start, or the supervisor's attestation | the same pass, or a stamp of the file's state |
| failure to change | n/a | a write after verification would be served unseen |
What the code now does for the file form (S, tests in `kar.rs` `row_read_tests`):
1. At start the identity (device, inode, size, mtime, ctime) of the opened file is taken before the verification, compared after it (`KAR archive file changed while it was verified`), and kept.
2. **Every row read compares the open file with that state** (`check_archive_state`: the `fstat` that already checked the length; size, mtime or ctime different, so a write, `touch`, `chmod`, rename or
hard link made after verification, refuses the read: `KAR archive file changed since it was verified`). A sealed memfd has no identity and keeps the length check only. The comparison is the lazy,
per-use form of the stamp: a start verifies once (or trusts the stamp), the service re-checks the same fields on each read batch, for one `fstat`.
3. Off switch for a file system whose `ctime` is not stable: `LELEKA_KAR_IDENTITY_RECHECK=off`. Default on. A refusal fails the request (not the process); a restart verifies again.
Not covered (and not covered by the memfd either, where it is RAM instead of disk): bit rot of a page after the verification. The per-section CRC-32 cannot be used per row (a section is gigabytes). If
this must be closed for the file form, the follow-up is a sidecar of per-4-KiB-page digests of the PLE extents (16 GB / 4 KiB x 32 B = 128 MB, built once from a verified archive, checked at the first
read of each page); it is not built.
## 3. The profile
`deploy/rust-runtime/profiles/rtx5090-32g-file.json`, built in (`leleka profiles`), never auto-selected (empty `select` window, so `auto` still picks exactly one profile): identical to `rtx5090-32g`
(budget 32,819,404,800, 262,144 context, chunk and grid 8192, resident expert bank, seed off, `EXPERT_PER_LAYER`, chain `all`) except
* `kar_source: file`; `min_ram_available_bytes` 62 GB and `min_ram_total_bytes` 64 GiB instead of 113 GB / 100 GiB (E: fixed footprint 54 GiB + floors; the archive is page cache, not a charge; preflight and
the resource planner (`resources.rs`) charge a file archive with a resident bank the engine only, and fall back to the mapped form below that);
* `memory.prefix_cache_mib: "6144"` explicit: with `auto` the freed RAM would be handed to the prefix cache (75 % of the elastic memory, capped at 24 GiB for a file archive), which is the hazard the
single-copy design page flags; 6144 MiB is what `auto` resolves to on the memfd profile today and the 245k session needs about 4 GiB;
* `lock: off`, `heal: false` (memfd-only switches).
Where the archive lives is the existing mechanism: `leleka up --profile rtx5090-32g-file --assets ~/work/leleka/models/leleka-gates/assets` (the file is `ASSETS/qwen-iq3-s-l2-v4.kar`, provenance next to it;
`LELEKA_ASSETS` works too). `up` sets mode 0400 and `leleka run` passes `--verify-stamps STATE/stamps/engine`. The page cache keeps what was read across
engine restarts, `leleka reconfigure` and a supervisor restart, for as long as RAM allows; no holder exists in this form.
## 4. Risks, quantified
### 4.1 Cold random PLE reads on this disk (M for the device, E for the workload)
Probe, read-only, 2026-10-30 14:00 UTC, server idle, holder up: 4 KiB `O_DIRECT` (page cache bypassed) random reads in the last 29 % of the archive file, Python threads (a lower bound for the device):
| threads | reads | IOPS | MiB/s | latency p50 / p99 / max |
| ---: | ---: | ---: | ---: | --- |
| 1 | 1,000 | 4,639 | 18 | 0.20 / 0.59 / 0.61 ms |
| 4 | 4,000 | 16,952 | 66 | 0.20 / 0.63 / 2.9 ms |
| 16 | 20,000 | 61,506 | 240 | 0.24 / 0.65 / 1.4 ms |
| 32 | 32,000 | 84,203 | 329 | 0.36 / 0.85 / 1.8 ms |
So the number that matters is not the 300-660 MB/s sequential figure but **0.2 ms per dependent read and ~60-85k reads/s with 16-32 in flight** (330 MB/s of 4 KiB pages). The probe read 0.2 GB in total;
no file was written.
What a session asks of that (E, from the code in section 1 and `docs/experiments/decode-tail-5090.md`, 1M distinct rows after ~250k tokens, ~4 distinct rows per token):
* **First decode tokens, cold:** 16 rows = 48 preads in 8 threads of 2 rows x 3 dependent reads: 2 x 3 x 0.2-0.35 ms = **1.2-2.1 ms added to a ~7.7 ms token (130 tok/s)** while the rows are not in the cache, i.e.
up to -15 to -21 % for such a token; rows repeat quickly (common n-grams), so the average over a reply is far smaller. After the first cold verdict the probe is skipped for 256 calls.
* **Prefill:** 1M distinct rows touch about 2.0M distinct pages (1M rows over 782k scale pages (72 %) and two plane tables of 1.56M pages each (47 %)): **~7.9 GiB read, ~2.0M random reads, 24-33 s of
aggregate device time** at 60-85k reads/s, spread over a 55-60 s prefill (5-turn session, M: TTFT sum 57.3 s) and done by the read-ahead thread one chunk early: a chunk of 8192 tokens is ~33k rows = ~98k preads = 1.2-1.6 s against a
1.68 s chunk (M at 139k). So it is hidden while the disk has nothing else to do; **the first chunk of the first request is not** (+1.2-1.6 s) and anything else that reads this disk (shard reads, a
second job, the hang-prone sequential load) lands on the same queue.
* Net E for turn 1 (45.8k tokens, ~180k rows, ~0.4M pages): **+1 to +5 s TTFT cold, ~0 warm**; later turns less (the rows of the earlier prompt are cached, only the new tokens' rows are cold). The A/B
measures exactly this; do not quote the E as a result.
### 4.2 Memory short (S, U)
The archive pages are clean page cache: under pressure the kernel evicts them (LRU, oldest first) and the next touch of such a row re-reads three pages at ~0.2 ms each. It does **not** OOM and does not swap
anonymous memory because of them. What stays: the 46.84 GiB page-locked expert bank, the 3.09 GiB pinned K/V, the 6 GiB prefix store (anon), the CUDA pins and the engine heap (about 54 GiB fixed in
total) plus the host's own use; the 8-12 GiB the touched part of the archive needs (E) is the only elastic item, and it is the one given back first. Consequences to know:
* `MemAvailable` counts that page cache as available, so the governor's soft/hard floors (4/2 GiB) and the `auto` sizing see it as free memory. It does not shed or refuse because the cache is full; it sheds the
prefix cache and refuses requests only when `MemAvailable` itself falls below the floors (the cache has been given back by then), or when memory PSI is high while `MemAvailable` is below 12 GiB
(`psi_guard_available`, `Policy::for_host`).
* A host with less RAM than the plan needs is refused at start with numbers (`host_ram`), or moved by the resource planner to `expert_source: mapped` (existing ladder), not by this form.
* With RAM exhausted by someone else the cost shows as decode/prefill time (re-reads at 0.2 ms), visible in `window.ple` and `/v1/status`, not as a crash. **U:** this was not exercised; the control is a
run under `systemd-run --scope -p MemoryMax=...` or a second reader that pushes the archive out of the cache, with `window.ple` and TTFT recorded.
* Eviction cannot corrupt: pages are clean and re-read from the same inode, and section 2's identity check applies to every read.
### 4.3 Other
* First start with the file form (stamp absent or voided): one full pass over both shards and the archive (about 138 GB sequential). That is the heaviest I/O this change involves; `kar-file-ab.sh` does it
once, up front, outside any arm. `chmod 0400` on the existing archive (needed for the file form) changes its ctime and voids its stamps, once.
* The identity check refuses reads if anything touches the file (`touch`, `chmod`, rename, hard link, backup tools that reset times): fail closed and loud. Switch: `LELEKA_KAR_IDENTITY_RECHECK=off`.
* There are two copies of the archive on the server (`~/leleka-gates/assets`, root disk, and `~/work/leleka/models/leleka-gates/assets`, `/data`); the holder and the A/B use the `/data` one.
* The 5090 profile keeps the memfd as default. The file form removes 51.5 GiB of shmem and the holder, and takes 8-12 GiB of reclaimable cache instead (E); it is not a RAM win for the page cache of a session that
fits, it is a start-up and elasticity win.
## 5. Tests (CPU only, WSL, `--release --locked --no-fail-fast`)
`leleka-model-format`: 141 passed, 3 failed (the known three /mnt/c retained-fd tests: `qwen_rows_sdet::retained_fd_and_chunked_streams...`, `sec_uc143_both_replaced_paths...`,
`sec_uc143_rank1_float_vectors...`); new: `an_ordinary_archive_file_must_still_be_in_the_state_that_was_verified` (touch, chmod, new identity, owned reader), `the_startup_figures_add_up`.
`leleka-deploy`: 127 + 6 passed; new: the profile variant differs from `rtx5090-32g` only where the archive form matters and is never auto-selected, the resource planner charges a file archive the engine only
and falls back correctly. `leleka-runtime`: 618 passed, 2 failed (the known two `backing::` tests). The release build of the four binaries was made from this branch's code on 2026-10-30 (WSL, 2m22s; `leleka-inference` sha256 `821110de1cc0b5df46656ac4b8458fa18c61efe166acad52f6e3fdd44d24c5a3`, 74,477,312 B, in `target/release/` of the worktree, not copied anywhere).
## 6. The A/B: `scripts/e2e/decode/kar-file-ab.sh` (not run)
Header of the script has the full protocol; summary here. Same binary for all arms (built from this branch; the memfd path is unchanged by it), frozen corpus
`/data/leleka-e2e/decode/corpus/src/crates`, `long_session.py` 5 turns / 245k tokens / 300 output tokens, upstream ranked profile, seed OFF, chunk 8192, `--prefix-cache-mib 6144` in both arms.
Arms alternate: `base-memfd` (this script seals its own memfd with the holder's copy loop; seal time reported separately), `new-file-cold` (archive page cache dropped with `posix_fadvise(DONTNEED)`,
`--kar-archive-file --verify-stamps`), `new-file-warm` (restart without dropping anything). Recorded every 5 s: MemAvailable, Shmem, Cached, AnonPages, SwapFree, PSI io/memory, pswpin, pgmajfault, the engine's
RssAnon/RssFile/RssShmem and `/proc/PID/io`; every 15 s the bytes of the archive and the shards resident in the page cache (`fincore`, a `mincore` walk, no I/O); one UTC timestamp per turn. Output: time to ready,
`leleka-kar-startup` line and load phases, per-turn TTFT, decode tok/s, input/cached tokens, `window.ple` per request, archive cache growth per turn, MemAvailable, swap, paired differences.
Install and run (the holder must be stopped; this is not a holder job):
```sh
# laptop, WSL, in the worktree: the four binaries (about 1-4 min incremental)
wsl -d Ubuntu -- bash -lc ". ~/.cargo/env; cd /mnt/c/Users/pavel/work/leleka/.git/wt/kar-file-source && export CARGO_TARGET_DIR=\$PWD/target && cargo build --release --locked -j 10 -p strata-desktop-core --bin leleka-inference --bin leleka-daemon --bin leleka-cli -p strata-control --bin strata-next"
# server (orchestrator): copy binaries + scripts; ~100 MB total, light I/O
ssh rnr5090 'mkdir -p /data/leleka-e2e/decode/dt/bin-karfile /data/leleka-e2e/decode/dt/jobs-manual'
scp target/release/{leleka-inference,leleka-daemon,leleka-cli,strata-next} rnr5090:/data/leleka-e2e/decode/dt/bin-karfile/
scp scripts/e2e/run-e2e.sh rnr5090:/data/leleka-e2e/decode/dt/scripts/e2e/run-e2e-karfile.sh
scp scripts/e2e/decode/kar-file-ab.sh rnr5090:/data/leleka-e2e/decode/dt/jobs-manual/
# server, once: file mode (voids the old stamps), stop the holder (frees 51.5 GiB and MODEL.lock), then run
chmod 0400 ~/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar
touch ~/work/gpu-runs/holder2/jobs/STOP # wait until `pgrep -f kar_holder2` prints nothing
nohup bash /data/leleka-e2e/decode/dt/jobs-manual/kar-file-ab.sh > /data/leleka-e2e/runs/kar-file-ab.job.log 2>&1 &
# afterwards: restart the holder cd ~/work/gpu-runs/holder2 && rm jobs/STOP && nohup bash run_holder2.sh > holder2.out 2>&1 &
```
Estimate (E, from the 12 min an arm of `speedtrain3-ab.sh` and the 162 s holder copy): `base-memfd` ~15 min (12 + seal 2.7), each new arm ~12 min; default six arms (two blocks of base, cold, warm) ~80 min;
4-arm minimum (`ARMS="base-memfd new-file-cold base-memfd new-file-cold"`) ~55 min; plus the one-time stamp seed (CPU only, up to ~138 GB sequential, 4-8 min at 300-660 MB/s, seconds when the stamps are current).
Heavy I/O per base arm: the 55 GB seal; per arm: the 47 GB shard-0 copy of the expert bank. Needs the GPU lock and MODEL.lock (taken by the script) and at least 100 GiB MemAvailable at start (the script refuses below that).
## 7. Not verified
* Everything on the server with the new binary: the engine with `--kar-archive-file` on the 5090, the `leleka-kar-startup` line, a stamp hit on the real 55 GB archive, the first-chunk and first-token cost of cold reads,
page-cache growth per turn, behaviour under memory pressure, the paired TTFT/decode comparison, greedy identity (the rows are the same bytes by construction; no logprob comparison was made).
* `kar-file-ab.sh`: `bash -n` and the summary on synthetic run directories only; the arm logic, the samplers and the `seal_exec` helper have not run.
* The disk figures are one 25-second probe of an otherwise idle server with Python threads; the workload figures are estimates from the code and earlier logs.
* Windows: the identity check is off there (no `FileIdentity`); `rtx5090-32g-file` is Linux-only in practice (the resident bank).