prefix cache: 60-minute session retention (wall-time expiry, oldest-idle displaced first), idle sweep; docs for telemetry and retention

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-24 20:02:09 +02:00
co-authored by Claude Sonnet 5.5
parent 08e2c78761
commit 07a540aa52
6 changed files with 533 additions and 352 deletions
@@ -648,9 +648,24 @@ mod runner {
return Ok(());
}
let mut unload_reply = None;
let mut last_sweep = Instant::now();
while !shared.shutdown.load(Ordering::Acquire) {
match rx.recv_timeout(Duration::from_millis(100)) {
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(mpsc::RecvTimeoutError::Timeout) => {
// sessions idle past the retention time give their host memory back
if last_sweep.elapsed() >= Duration::from_secs(15) {
last_sweep = Instant::now();
if let Some(owner) = stack.as_mut() {
let expired = owner.prefix_expire_idle();
if expired > 0 {
use std::io::Write;
let _ = writeln!(std::io::stderr().lock(), "leleka-serve prefix retention: expired {expired} idle checkpoint(s); {}", owner.prefix_metrics().unwrap_or_default());
publish_prefix_summary(owner, shared);
}
}
}
continue;
}
Err(_) => break,
Ok(Command::Load(_, _, reply)) => {
let _ = reply.send(Err(exhausted("unload the existing model before another load")));
+117 -3
View File
@@ -40,10 +40,25 @@ pub struct PolicyParams {
pub continuation_weight: f64,
/// Requests after which priors and hit mass halve.
pub half_life: f64,
/// Session retention in milliseconds of wall time: a node nobody has used for this long is dropped (`expire`), and
/// until then the older a node's last use, the lower it ranks against newer sessions when the budget runs out
/// (`recency_floor` at the limit). 0 = no time limit. Default 60 minutes.
pub retention_ms: u64,
/// Share of a node's value that survives at the end of the retention window (1.0 = age never matters).
pub recency_floor: f64,
}
impl Default for PolicyParams {
fn default() -> Self {
Self { frontier_prior: 0.5, interior_prior: 0.03, hit_gain: 1.0, shared_weight: 3.0, continuation_weight: 0.0, half_life: 256.0 }
Self {
frontier_prior: 0.5,
interior_prior: 0.03,
hit_gain: 1.0,
shared_weight: 3.0,
continuation_weight: 0.0,
half_life: 256.0,
retention_ms: 60 * 60 * 1000,
recency_floor: 0.1,
}
}
}
@@ -72,6 +87,8 @@ pub struct Stats {
pub already_cached: u64,
pub rejected: u64,
pub evicted: u64,
/// Nodes dropped because no request used them for the retention time (also counted in `evicted`).
pub expired: u64,
/// Admitted on an estimate, then evicted at once because the real payload was bigger and worth less.
pub rejected_after_build: u64,
}
@@ -99,6 +116,8 @@ struct Node<N, B> {
payload: N,
bytes: usize,
touched: u64,
/// Wall time (the store's `now_ms`) of the last request that used this node, or of its creation.
last_used_ms: u64,
hit_mass: f64,
hit_stamp: u64,
hits: u64,
@@ -174,6 +193,8 @@ pub struct PrefixStore<N, B> {
/// Tail nodes by the chain value of the last full block they extend.
tails: HashMap<u64, Vec<u64>>,
clock: u64,
/// Wall time in milliseconds as of the last `tick_at` / `set_now`; supplied by the caller so the policy is deterministic.
now_ms: u64,
node_bytes: usize,
block_bytes: usize,
stats: Stats,
@@ -185,7 +206,7 @@ pub struct PrefixStore<N, B> {
impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
pub fn new(cfg: StoreConfig) -> Self {
assert!(cfg.block_tokens > 0 && cfg.block_tokens % 4 == 0, "block_tokens must be a positive multiple of the 4-cell page");
Self { cfg, blocks: HashMap::new(), nodes: HashMap::new(), tails: HashMap::new(), clock: 0, node_bytes: 0, block_bytes: 0, stats: Stats::default(), orphans: HashSet::new() }
Self { cfg, blocks: HashMap::new(), nodes: HashMap::new(), tails: HashMap::new(), clock: 0, now_ms: 0, node_bytes: 0, block_bytes: 0, stats: Stats::default(), orphans: HashSet::new() }
}
pub fn config(&self) -> &StoreConfig {
&self.cfg
@@ -219,6 +240,42 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
self.stats.prompt_tokens += prompt_tokens as u64;
}
/// `tick` with the wall time of the request, in milliseconds on any monotonic scale.
pub fn tick_at(&mut self, prompt_tokens: usize, now_ms: u64) {
self.now_ms = self.now_ms.max(now_ms);
self.tick(prompt_tokens);
}
/// Advance the wall time without a request (the idle sweep).
pub fn set_now(&mut self, now_ms: u64) {
self.now_ms = self.now_ms.max(now_ms);
}
/// Drop every node unused for longer than the retention time; returns how many went (their blocks with them).
pub fn expire(&mut self) -> usize {
let limit = self.cfg.policy.retention_ms;
if limit == 0 {
return 0;
}
let now = self.now_ms;
let stale: Vec<u64> = self.nodes.iter().filter(|(_, node)| now.saturating_sub(node.last_used_ms) > limit).map(|(key, _)| *key).collect();
for key in &stale {
self.evict(*key);
}
self.stats.expired += stale.len() as u64;
stale.len()
}
/// How much of its value a node keeps at its age: 1 when just used, `recency_floor` at the retention limit.
fn recency(&self, node: &Node<N, B>) -> f64 {
let p = &self.cfg.policy;
if p.retention_ms == 0 {
return 1.0;
}
let age = self.now_ms.saturating_sub(node.last_used_ms) as f64 / p.retention_ms as f64;
1.0 - (1.0 - p.recency_floor) * age.min(1.0)
}
pub fn contains_node(&self, key: u64) -> bool {
self.nodes.contains_key(&key)
}
@@ -338,6 +395,7 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
node.hit_mass = decayed(node.hit_mass, clock - node.hit_stamp, half_life) + weight;
node.hit_stamp = clock;
node.touched = clock;
node.last_used_ms = self.now_ms;
node.hits += 1;
node.shared_hits += u64::from(shared);
self.stats.hits += 1;
@@ -351,7 +409,7 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
let prior = if children == 0 && node.frontier { p.frontier_prior } else { 1.0 - (1.0 - p.interior_prior).powi(1 + children as i32) };
let base = prior * decayed(1.0, self.clock - node.touched, p.half_life);
let mass = decayed(node.hit_mass, self.clock - node.hit_stamp, p.half_life);
1.0 - (1.0 - base) * (-p.hit_gain * mass).exp()
(1.0 - (1.0 - base) * (-p.hit_gain * mass).exp()) * self.recency(node)
}
/// Value of every node not in `removed`: expected tokens saved per byte its eviction frees. A node's saving is
@@ -443,6 +501,7 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
let key = if tail_len == 0 { prev } else { chain_step(prev, &tokens[tokens.len() - tail_len..]) };
if let Some(node) = self.nodes.get_mut(&key) {
node.touched = self.clock;
node.last_used_ms = self.now_ms;
self.stats.already_cached += 1;
return Consider::Exists;
}
@@ -557,6 +616,7 @@ impl<N: ByteSize, B: ByteSize> PrefixStore<N, B> {
payload: state,
bytes,
touched: self.clock,
last_used_ms: self.now_ms,
hit_mass: 0.0,
hit_stamp: self.clock,
hits: 0,
@@ -889,6 +949,60 @@ mod tests {
assert_eq!(s.longest_match(&newest, newest.len()).unwrap().tokens, G + 3);
}
const MINUTE: u64 = 60_000;
#[test]
fn a_session_is_kept_for_the_retention_time_and_dropped_after_it() {
let mut s = store(100_000);
let a = tokens(1, 0, 4);
s.tick_at(a.len(), 0);
put(&mut s, &a, 4, true);
// 59 minutes idle: still there
s.set_now(59 * MINUTE);
assert_eq!(s.expire(), 0);
assert!(s.longest_match(&a, a.len() + 1).is_some());
// a request that uses it renews the clock
s.tick_at(a.len(), 59 * MINUTE);
let m = s.longest_match(&a, a.len()).unwrap();
s.record_hit(&m);
s.set_now(100 * MINUTE);
assert_eq!(s.expire(), 0, "41 minutes since the last use");
// 61 minutes without a request: gone, with its blocks
s.set_now(121 * MINUTE);
assert_eq!(s.expire(), 1);
assert_eq!((s.node_count(), s.block_count(), s.bytes()), (0, 0, 0));
assert_eq!((s.stats().expired, s.stats().evicted), (1, 1));
s.check_invariants();
}
#[test]
fn retention_zero_never_expires() {
let mut s = PrefixStore::<Payload, Payload>::new(StoreConfig { block_tokens: G, budget_bytes: 100_000, max_nodes: 64, policy: PolicyParams { retention_ms: 0, ..PolicyParams::default() } });
let a = tokens(1, 0, 2);
put(&mut s, &a, 2, true);
s.set_now(1_000_000 * MINUTE);
assert_eq!(s.expire(), 0);
assert_eq!(s.node_count(), 1);
}
#[test]
fn when_the_budget_runs_out_the_session_idle_longest_is_displaced_first() {
// room for two 3-block sessions (3 blocks + state = 190 bytes each), not three
let mut s = store(2 * (3 * BLOCK + STATE) + 20);
let (a, b, c) = (tokens(1, 0, 3), tokens(2, 0, 3), tokens(3, 0, 3));
s.tick_at(a.len(), 0);
put(&mut s, &a, 3, true);
s.tick_at(b.len(), 30 * MINUTE);
put(&mut s, &b, 3, true);
// A has been idle for 40 minutes, B for 10: C displaces A, not B
s.tick_at(c.len(), 40 * MINUTE);
assert_eq!(put(&mut s, &c, 3, true), Consider::Exists);
assert!(s.longest_match(&a, a.len() + 1).is_none(), "the oldest session was displaced");
assert!(s.longest_match(&b, b.len() + 1).is_some(), "the newer session stays");
assert!(s.longest_match(&c, c.len() + 1).is_some());
s.check_invariants();
}
#[test]
fn an_existing_node_is_only_touched() {
let mut s = store(10_000);
@@ -183,6 +183,12 @@ pub(super) struct PrefixServe<S: ByteSize, B: ByteSize> {
shed: bool,
}
/// Milliseconds since the first call, on the monotonic clock (the store's wall-time scale for session retention).
fn wall_ms() -> u64 {
static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64
}
fn lcp(a: &[i32], b: &[i32]) -> usize {
a.iter().zip(b).take_while(|(x, y)| x == y).count()
}
@@ -327,7 +333,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
self.req = None;
return Ok(None);
}
self.store.tick(prompt.len());
self.store.tick_at(prompt.len(), wall_ms());
let limit = prompt.len().saturating_sub(1);
self.req = Some(Req { limit, last_grid: limit / g * g });
let lookup = Instant::now();
@@ -526,10 +532,16 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
}
/// The metrics line.
/// Drop the sessions nobody used for the retention time (called from the idle loop); returns how many nodes went.
pub(super) fn expire_idle(&mut self) -> usize {
self.store.set_now(wall_ms());
self.store.expire()
}
pub(super) fn describe(&self) -> String {
let s = self.store.stats();
format!(
"prefix stats: nodes={} blocks={} used_mib={} budget_mib={} requests={} hits={} shared_hits={} misses={} reused_tokens={} prompt_tokens={} admitted={} rejected={} evicted={} already_cached={} live_tokens={}",
"prefix stats: nodes={} blocks={} used_mib={} budget_mib={} requests={} hits={} shared_hits={} misses={} reused_tokens={} prompt_tokens={} admitted={} rejected={} evicted={} expired={} already_cached={} live_tokens={}",
self.store.node_count(),
self.store.block_count(),
self.store.bytes() >> 20,
@@ -543,6 +555,7 @@ impl<S: ByteSize, B: ByteSize> PrefixServe<S, B> {
s.admitted,
s.rejected + s.rejected_after_build,
s.evicted,
s.expired,
s.already_cached,
self.live.len()
)
@@ -723,6 +723,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
}
}
/// Drop the cached sessions nobody used for the retention time (60 minutes by default); the idle loop calls this.
pub(crate) fn prefix_expire_idle(&mut self) -> usize {
self.prefix.as_mut().map_or(0, |prefix| prefix.expire_idle())
}
/// The prefix cache's summary for a front router (`None` when the cache is off).
#[allow(dead_code)]
pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option<PrefixSummary> {
+362 -346
View File
@@ -1,346 +1,362 @@
# One-command deployment: `leleka up`
Status 2026-10-17, branch `claude/deploy` (base `claude/port-gpu-bringup` @ `5e0bd84`). This page describes the deployment
tool `leleka` (crate `crates/deploy`, no Python at run time), what it does, every flag, and what was and was not run to
check it. Results are in [section 10](#10-what-was-run-and-what-was-not); nothing here is a performance or model-quality
claim. Background: [`rust-runtime-run.md`](rust-runtime-run.md) (the processes), [`model-assets.md`](model-assets.md) (the model
commands `leleka` drives), [`laptop-profile.md`](laptop-profile.md), [`sm86-assets.md`](sm86-assets.md),
[`delivery-gap-audit.md`](delivery-gap-audit.md) section 5 (the packaging gaps this closes in part).
## 1. Quickstart
Server (Linux x86_64, NVIDIA driver >= 595, systemd), as root, from the unpacked release:
```sh
tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
sudo ./install.sh --assets /data/leleka # preflight, fetch+verify, KAR archive, install, start, wait for ready
```
WSL2 laptop (RTX 3080 16 GB), as your user, in a terminal (WSL2 usually has no systemd):
```sh
./install.sh --assets ~/leleka --foreground # keep the terminal open; Ctrl-C drains and stops
```
Both do the same thing, idempotently, and print the endpoint, model digest, GPU, the VRAM/RAM budget that was chosen, and the
log directory when the service answers `/ready`. Look first with `--dry-run`: it prints the preflight and the plan and changes nothing.
```sh
./bin/leleka up --dry-run --assets /data/leleka
```
This is charter goal G2 (`PROJECT_CHARTER.md` section 6): one command, GPU and memory plan chosen automatically, external model volume, readiness only after the model is loaded, orderly stop and restart of the worker, no Python at run time.
Its acceptance test (a clean Linux GPU node, driver installed, one command, no re-download after a restart) has **not** been run; section 10 lists what was.
Container: [section 7](#7-container-image). Build your own release: [section 8](#8-build-a-release-tarball).
## 2. What `up` does
| # | step | what happens | idempotency |
| --- | --- | --- | --- |
| 1 | preflight | driver >= 595, GPU architecture, VRAM free vs budget, RAM total/available, disk on each volume, WSL2 mounts, `libcublas.so.12`, `memfd_create`, ports, systemd, the six binaries | read-only; any FAIL stops before anything is changed |
| 2 | layout | state (0700), logs, run, stamps, assets | `mkdir -p` |
| 3 | binaries | copy `bin/*` to `PREFIX/bin`, SHA-256 checked against `MANIFEST.json` | skipped when identical; replaced by rename (safe for a running binary) |
| 4 | cuBLAS 12 | uses what the host has; otherwise downloads the pinned NVIDIA 12.9.1.4 redistributable (SHA-256 pinned, resumable) into `PREFIX/lib/cublas` | skipped when `libcublas.so.12` and `libcublasLt.so.12` are found |
| 5 | secrets | two service tokens into `STATE/runtime.env` (0600), API key through `strata-next api-key init` | never rotated; only missing/invalid ones are created |
| 6 | model | `strata-next model fetch qwen-iq3-s` then `model verify` (resumable `.part` files, SHA-256) | stamped with size+mtime: skipped on re-runs unless `--reverify` |
| 7 | KAR archive | `strata-next model ensure-sharded-streamed qwen-iq3-s --levels 2` (level 2, the pinned 55,295,529,472-byte archive + provenance) | stamped; also checks the length the engine admits |
| 8 | MTP pack | `ASSETS/data/mtp-rt` must exist; `--mtp-pack` imports it from a directory or tarball | skipped when present |
| 9 | tokenizer | `model extract-tokenizer` from shard 1 | skipped when present |
| 10 | config | `leleka.json`, `daemon.json`, `strata.json`, `profile.json`, `runtime.env` | rewritten only when the content changes |
| 11 | service | systemd unit (system or user), `daemon-reload`, `enable`; none in foreground mode | rewritten only when the content changes; a changed unit restarts a running service |
| 12 | start / ready | start the unit (or run the supervisor in this terminal), poll `/ready` with the key, print the summary | an already ready service is left alone |
The archive step runs `ensure-sharded-streamed`, which fetches and verifies the shards itself, so on a first run step 6 is folded into
step 7 (the plan says so). The strict verification of an *existing* archive re-derives the 708 GB virtual F32 stream and is slow; a
machine that already holds the archive can pass `--trust-archive`: the archive is accepted when it has the pinned length and a
provenance file, and the engine checks its SHA-256 and every CRC against the pinned digest at each load anyway.
A failed run is resumable: fix the cause and run the same command; finished steps are skipped (downloads continue from `.part`).
## 3. The processes and files
```text
leleka run (supervisor, the systemd ExecStart or your terminal)
|- seals the KAR archive into a memfd ONCE (memfd profile) -- or hands the engine a read-only file (file profile)
|- leleka-daemon gateway for the typed lifecycle, 127.0.0.1:18080
|- leleka-inference engine, gRPC 127.0.0.1:18766 (started through `leleka exec-inherit`, which passes the sealed fd)
|- leleka-cli load-mtp qwen-iq3 qwen4exp-kar-ple-mtp-v1 -> wait for model_ready (the engine verifies shards + archive here)
`- strata-next serve public API (Responses, Chat, Messages, tools, ...), 127.0.0.1:8081, bearer key
```
```text
PREFIX/bin/{leleka,strata-next,leleka-inference,leleka-daemon,leleka-cli,leleka-seal-exec} PREFIX/lib/cublas/
STATE/{leleka.json,daemon.json,strata.json,profile.json,runtime.env,api-key} STATE/{logs,run/status.json,stamps,mtp-staging}
ASSETS/model/*.gguf ASSETS/qwen-iq3-s-l2-v4.kar(.provenance.json) ASSETS/data/mtp-rt/ ASSETS/tokenizer-assets/
```
Defaults: root gets `/opt/leleka`, `/var/lib/leleka/state`, `/var/lib/leleka/assets`; a user gets `~/.local/share/leleka`,
`~/.local/state/leleka`, `~/.local/share/leleka/assets`. Environment: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`.
**Put `--assets` on the big volume**: about 140 GB (shards 83.6 GB + archive 55.3 GB); the first run needs that plus slack.
### The sealed KAR archive is made by the service
The engine accepts the archive only as a sealed memfd (regular, unlinked, pinned length, `WRITE|GROW|SHRINK|SEAL`). Until now an operator
tool (`kar_holder.py` / `seal_exec.py`, outside the repository) did that. `leleka run` now does it natively: it copies the archive into a
sealed memfd once (about 10 s for 55 GB from a warm cache, minutes cold), keeps the descriptor close-on-exec in the supervisor, and hands a duplicate
to each engine start through `leleka exec-inherit` (standard input in, a descriptor number >= 3 out). An engine restart therefore does
**not** copy 55 GB again, and the API, the gateway and the CLI never see the descriptor. `leleka-seal-exec` still ships for manual runs.
`--kar-fd N` (on `up` and `run`) reuses a descriptor inherited from a parent that already holds one (a holder, a test harness): no second copy, and its RAM is not demanded.
The **file profile** (laptop) cannot afford 55 GB of shmem. `leleka-inference` gained `--kar-archive-file PATH --kar-provenance PATH`
(`InheritedKarArchive::open_read_only_file`, the form `docs/laptop-profile.md` measured in a bench): the archive stays an ordinary file;
it must be regular, single-link, owned by the service user and without write bits (`up` sets mode 0400). It is weaker than the seal (immutability rests on
the file system) and is selected only by that profile. The full SHA-256 and all CRCs are still checked at load.
## 4. Memory profiles
`--profile auto` (default) picks by the GPU `nvidia-smi` reports; `--profile NAME` or `--profile FILE.json` overrides it, and
`--gpu-budget-gib` / `--context-tokens` override single values. `leleka profiles` lists them, `leleka profiles show NAME` prints one to copy and edit.
The files live in [`deploy/rust-runtime/profiles/`](../deploy/rust-runtime/profiles/) and are embedded in the binary.
| profile | selected for | GPU budget | context | KAR archive | routed experts | RAM floor (total / available at start) | other |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `rtx5090-32g` | sm_12x, >= 30 GB VRAM | 24 GiB | 262,144 | sealed memfd (55.3 GB of RAM) | `resident`: page-locked RAM copy (50.3 GB) | 100 GiB / 113 GB (58 GB when `--kar-fd` supplies the archive) | the documented bring-up configuration |
| `rtx3080-16g` | sm_80..119, 14-24 GB VRAM | 15 GiB (needs 14,500 MiB free) | 8,192 | read-only file | `mapped`: read-only mappings of shard 0 | 22 GiB / 10 GiB; advice `.wslconfig memory=32GB` | optional VRAM expert tier when `ASSETS/data/expert-profile.bin` has the pinned SHA-256 `8f59b4aa...388975baf` |
Both profiles also carry a `memory` section (prefix cache `auto`, soft/hard floors 4096/2048 MiB, reserve, lock and heal of the sealed memfd): the engine sizes its caches from the memory left after the fixed footprint, sheds and refuses under pressure, and refuses to start with numbers when the footprint does not fit ([`memory-safety.md`](memory-safety.md)). The unit sets `LimitMEMLOCK=infinity`, which is what lets the lock keep the 55 GB memfd out of swap.
Both profiles run `--backend-mode original` and the level-2 archive; the routed-expert bank must be admitted before the Original stack opens, which `leleka-inference` now does from `--expert-source resident|mapped` (see section 10, finding 1). They select documented switches only (budget, context, archive form, the
`LELEKA_ORIGINAL_SERVE_*` environment); they are **not** tuned, not quality-gated and carry no speed claim. A GPU that fits neither
(a 24 GB 4090, say) gets an error that names the way out: write a profile file. Fields: see `crates/deploy/src/profile.rs`
(`gpu_budget_bytes`, `context_tokens`, `prefill_capacity`, `kv`, `kv_resident`, `prompt_cache`, `kar_source`, `min_*`, `engine_env`
restricted to `LELEKA_ORIGINAL_SERVE_*`); unknown fields are refused.
One binary serves both architectures: the sealed sm_120 PTX is used as is on Blackwell, and the build with `--features sm86`
(every release) swaps in the sm_86 companion PTX on 8.6 <= cc < 12.0 cards ([`sm86-assets.md`](sm86-assets.md)). Preflight reads `MANIFEST.json` and refuses a
binary built without `sm86` on such a card. All PTX is embedded in the binaries (the release also ships the files and a `SHA256SUMS` for audit).
## 4b. Resource presets
`leleka up` computes what the runtime takes of the host (`crates/deploy/src/resources.rs`, a pure function of the probed host facts and the profile), prints it, and bakes it into `leleka.json` (the profile's budget and floors, and `LELEKA_ORIGINAL_SERVE_CPU_WORKERS`). Two presets:
| | `dedicated` (default) | `workstation` |
| --- | --- | --- |
| purpose | the host belongs to the runtime | Docker, agents and the IDE share the machine |
| CPU expert workers | `min(cores - 2, 8)` | `min(cores - leave, 8)`, leave 4 cores (8 above 16 cores) |
| host RAM kept free | the profile's governor floors (server: soft 4 GiB, hard 2 GiB) | soft floor 8 / 12 / 16 GiB (hosts under 32 / under 64 / from 64 GiB RAM), hard floor half of it; the profile's floors are only raised. The governor sheds the prefix cache first, then refuses new requests with 503 `memory_pressure` |
| VRAM | the profile budget | `min(profile, free - 4 GiB)` rounded down to GiB; the expert tier is sized from what remains |
More than 8 CPU workers do not help (decode is bound by host memory bandwidth, `docs/roofline.md`), so on a large host the cores that `dedicated` leaves free are the spare ones, and `workstation` mainly guarantees the RAM and VRAM headroom. If the workstation target cannot be met (less than half of the profile's VRAM budget would remain) the preflight fails with the numbers; a RAM shortfall does not fail: when the pinned form (sealed archive plus engine, about 58 GiB on the server) would leave less than the free target, `up` switches the profile to the mapped form of the laptop profile: the archive stays a read-only file and the experts are memory-mapped from SSD/HDD, with `available - target - 8 GiB` of experts page-locked (`resident_budget_gib`, 0 on a small host). It prints a warning, because decode is slower than with everything in RAM. The same fallback applies to `dedicated` when the host cannot hold the pinned form at all. `--gpu-budget-gib` and explicit profile fields win over the preset.
## 5. Flags
`leleka up [OPTIONS]` (also accepted by `preflight`, `status`, `down`):
| flag | meaning |
| --- | --- |
| `--dry-run` | print preflight and plan (and the exact engine command); change nothing; exit 1 if a check fails or a step is blocked |
| `--json` | machine-readable plan / summary on stdout (logs stay on stderr) |
| `--profile auto\|NAME\|FILE` | memory profile |
| `--gpu N` | CUDA device ordinal (default 0) |
| `--assets DIR` `--state-dir DIR` `--prefix DIR` | the three roots (section 3) |
| `--bin-src DIR` | where the six binaries come from (default: the directory of `leleka`, i.e. the release `bin/`) |
| `--mode auto\|system\|user\|foreground\|none`, `--foreground` | `auto`: root with systemd -> system unit; a user with a systemd user session -> user unit; otherwise foreground. `none` prepares and starts nothing |
| `--service-user NAME` | system unit only: the account the service runs as (default `leleka`, created with `useradd --system`; state and assets are chowned to it) |
| `--api-port` `--engine-port` `--daemon-port` | ports (defaults 8081, 18766, 18080) |
| `--api-bind IP` | API listen address, default `127.0.0.1`; `0.0.0.0` only inside a container whose port is published to the host's loopback or tunnelled (the bearer key is the only protection, no TLS). The engine and gateway are always loopback |
| `--preset dedicated\|workstation` | how much of the host the engine takes (env `LELEKA_PRESET`, section 4b; recorded in `leleka.json`) |
| `--gpu-budget-gib N` `--context-tokens N` | override one profile value |
| `--no-fetch` | never download or build; require verified files to exist |
| `--reverify` | ignore the stamps and hash everything again |
| `--trust-archive` | accept an existing pinned-length archive + provenance without the strict re-derivation (section 2) |
| `--mtp-pack PATH` | import the MTP pack (directory or `.tar/.tar.gz/.tgz/.tar.xz`, sub-directories searched) |
| `--cublas-dir DIR` / `--no-install-cublas` | use this CUDA 12 cuBLAS / fail instead of downloading it |
| `--kar-fd N` | an already sealed archive descriptor inherited from the parent (foreground or `--mode none` only) |
| `--timeout-s N` | wait this long for `/ready` (default 3600) |
Other commands: `leleka verify` (full parallel hash of shards and archive, renews the stamps; section 6b), `leleka preflight` (checks only, exit 1 on FAIL), `leleka status` (cheap: no GPU probe; exit 0 only when ready; this is the container health check),
`leleka down` (stop the systemd unit), `leleka run --config STATE/leleka.json [--kar-fd N]` (the supervisor), `leleka profiles [show NAME]`.
`HF_TOKEN` in the environment is used only by `model fetch`, is sent only to `https://huggingface.co`, is removed from every child the supervisor starts, and is never printed or written.
## 6. Operating it
* systemd: `systemctl status leleka`, `journalctl -u leleka -f` (user unit: add `--user`; run `loginctl enable-linger USER` to start without a login). The unit has
`Restart=on-failure` with `RestartSec=30`, at most 3 starts in 30 minutes, and no restart after exit code 2 (configuration), because every start re-reads 55 GB.
* The supervisor restarts a dead engine up to twice (counter reset after 10 ready minutes) with the same sealed descriptor and loads the model again; the API process stays up and
answers not-ready meanwhile. A dead gateway (3) or API (5) is restarted too. Then it exits 1 and systemd decides.
* `SIGTERM`/`SIGINT` drain: the API first (`shutdown_grace_s` 10), then the gateway and the engine (both handle SIGINT only, so the supervisor sends SIGINT), then SIGKILL after the grace.
* Logs: `STATE/logs/{leleka,engine,gateway,api,install}.log` (rotated once past 64 MiB at start). Status: `STATE/run/status.json` (`phase`: sealing, starting_engine, loading, starting_api, ready, engine_restarting, draining, stopped, failed).
* Use it: `curl -H "Authorization: Bearer $(cat STATE/api-key)" -H 'content-type: application/json' -d '{"model":"qwen-iq3","input":"hello","max_output_tokens":32}' http://127.0.0.1:8081/v1/responses`.
Remote clients: an SSH tunnel. Known limits of this API-over-engine path (4096 output tokens, 256 generations per engine epoch, no image input) are in [`api-over-rust-engine.md`](api-over-rust-engine.md).
## 6b. Fast restarts: where a cold start went and what was changed
A start used to hash 83.6 GB of shards and the 55 GB archive one after the other, each in a single thread that alternated
`read` and `update` (laptop, cold: shard 0 115-134 s, shard 1 64-96 s, archive 95-181 s; 265-400 s in all, 100-215 s of it system time in
`read`). Every engine now prints `leleka-load-time phase=... seconds=... total=...` lines on stderr (`STATE/logs/engine.log`), and
`leleka-inference --verify-only` runs just the source verification (no CUDA) so that phase can be measured anywhere.
| change | where | effect |
| --- | --- | --- |
| shard 0, shard 1 and the archive are verified at the same time | `backend.rs` `verify_sources_parallel`; refusals consumed in the old order (shard 0, shard 1, binding) | wall = the slowest file, not the sum |
| a reader thread keeps 6 x 8 MiB chunks ahead of the hasher (`pread`, `FADV_SEQUENTIAL`, recycled buffers) | `model-format/src/readahead.rs`, used by `VerifiedGgufFile::open` and the archive scan | I/O and hashing overlap |
| archive scan: SHA-256 on one thread, per-section CRC-32 on another | `kar.rs` `verify_integrity_pipelined`; same verdicts and precedence (SHA mismatch before CRC failure), tested against the stream scan | the 55 GB pass costs the slower of the two |
| **verification stamps**: a file that matched its pinned digest and is unchanged (device, inode, size, mtime, **ctime**) is not hashed again | `model-format/src/verify_stamp.rs`, `leleka-inference --verify-stamps DIR` (the supervisor passes `STATE/stamps/engine`) | a restart hashes nothing that did not change |
| the supervisor copies the archive into the memfd with several threads and checks that the source did not change while it was copied | `sealed.rs` `seal_file_with_identity` | the fill runs at memory bandwidth |
| a sealed memfd that this supervisor already had verified (an earlier engine) or that was copied from a file whose `kar-source` stamp matched is not hashed again: `--kar-attested-by-stamp` | `supervisor.rs`, `verify_stamp::set_attested_archive` | engine restarts and service restarts skip the 55 GB hash |
| on the first start, a CPU-only `--verify-only` hashes the shards while the supervisor fills the memfd | `supervisor.rs` `spawn_shard_preverify` | the two big reads overlap |
| `leleka verify` | `app.rs` | hashes shards and archive in full, in parallel, renews every stamp |
Stamp rules (fail closed). A stamp is one line per (kind, pinned digest) in a directory that must be owned by the service account and closed to
group and others; any difference in any field, an unreadable, malformed or extra-long stamp, a symlink, or a stamp directory that is not private means
"hash in full". `ctime` changes on every write, truncate, chmod, chown and rename and cannot be set from user space, so a rewritten file does not match even
when its `mtime` is restored (unit-tested). A stamp is recorded only if the file's identity is the same before and after the full hash, and it is keyed by the pinned
digest, so it never replaces the pin. A changed file is hashed in full and refused if it no longer matches. What a stamp cannot defend against is someone who can write both the stamp
directory and the model file as the service account; that account also owns the archive the engine maps. `--verify-rehash` / `leleka verify` ignore existing stamps; `"verify_stamps": false` in
`STATE/leleka.json` turns the whole mechanism off (every start hashes everything, in parallel).
Measured so far (CPU-only `--verify-only`, laptop i9-11900H, WSL2 ext4, shards and archive evicted from the guest page cache first; the host may still cache the virtual disk):
| run | shard 0 | shard 1 | archive | wall |
| --- | --- | --- | --- | --- |
| before: sequential, `read` + `update` in one thread | 115 s | 64 s | 95 s | 265 s (a first run with a colder host cache: 400 s) |
| after: parallel + read-ahead, no stamps | 74 s | 57 s | 74 s | 72 s |
| after: parallel, second sample (warmer host cache) | 47 s | 28 s | 47 s | 45-51 s |
| after: stamps current | 0.02 s | 0.01 s | 0.00 s | 0.02 s |
The laptop reads at about 1 GB/s at best; the 5090 server numbers are in the holder jobs `9g1`-`9g6` (section 10).
## 7. Container image
[`deploy/Containerfile.rust-runtime`](../deploy/Containerfile.rust-runtime): Ubuntu 24.04 (glibc 2.39, the floor of the binaries) + the six binaries + cuBLAS 12.9.1.4
(downloaded by BuildKit with `ADD --checksum`, only `libcublas.so.12*` and `libcublasLt.so.12*` kept) + the manifest/provenance. The sealed PTX is inside the binaries; `ldd` shows only libc, libm
and libgcc_s, and the engine `dlopen`s `libcuda.so.1` (injected by the NVIDIA Container Toolkit) and `libcublas.so.12`. Not in the image, by design: the model, the driver, any secret. Non-root (uid 10001), volumes `/models` and `/state`,
`HEALTHCHECK` = `leleka status`.
```sh
tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
docker build -f /path/to/repo/deploy/Containerfile.rust-runtime --build-arg VERSION=VERSION -t leleka-runtime:VERSION .
# pin the base for a release: docker buildx imagetools inspect ubuntu:24.04 then --build-arg BASE=ubuntu:24.04@sha256:...
docker run -d --name leleka --gpus all --restart unless-stopped \
-v /data/leleka-models:/models -v leleka-state:/state -p 127.0.0.1:8081:8081 \
leleka-runtime:VERSION # default command: up --foreground --no-install-cublas --api-bind 0.0.0.0
docker logs -f leleka # first start: hours (download, verification, archive build); later starts: minutes
docker exec leleka cat /state/api-key
```
The memfd profile needs the host to give the container ~60 GB of RAM (no `--memory` below that; memfd is shmem charged to the container, not limited by `--shm-size`). Docker's default seccomp
profile allows `memfd_create`. Build is not run in CI; see section 10 for what was checked.
## 8. Build a release tarball
On Linux/WSL, from a tree with the toolchain pinned by `rust-toolchain.toml` (no CUDA toolkit is needed; the PTX is checked in):
```sh
cargo build --release --locked -p strata-desktop-core --features sm86 \
--bin leleka-inference --bin leleka-daemon --bin leleka-cli --bin leleka-seal-exec
cargo build --release --locked -p strata-control --bin strata-next
cargo build --release --locked -p leleka-deploy --bin leleka
# provenance is made where git exists (an exported tree has no .git); the tree must be clean or --allow-dirty marks it
python3 scripts/package-release.py provenance --repo . --out provenance.json
python3 scripts/package-release.py package --repo . --target-dir target --provenance provenance.json --out dist
```
`dist/leleka-VERSION-COMMIT12-linux-x86_64.tar.xz` (+ `.sha256`) contains `bin/` (six binaries), `share/leleka/ptx/{sm_120,sm_86}` (the sealed PTX and `SHA256SUMS`), `share/leleka/{profiles,templates,docs}`,
`MANIFEST.json` (version, commit, `features`, SHA-256 of every binary, rustc/glibc of the builder), `PROVENANCE.json`, `SHA256SUMS` for every file, and `install.sh`. `--no-ptx` omits the PTX files (they are embedded anyway);
`--with-cublas DIR` bundles cuBLAS (NVIDIA's redistribution terms apply).
`PROVENANCE.json` records the git commit, whether the tree was dirty (and a digest of the diff), the `Cargo.lock` digest, and for `engine/strata`: the upstream URL and commit from [`upstream.md`](upstream.md),
the subtree tree id, the import commit, every later commit touching the subtree, and the diff since import (shortstat + digest). The diff against the upstream tree itself is computed only when the upstream commit is present
in the repository (`git fetch strata-upstream`); otherwise the record says so. `engine/strata` is not modified by this work.
## 9. Troubleshooting
| message (preflight / run) | cause and fix |
| --- | --- |
| `NVIDIA GPU: nvidia-smi was not found` | no driver. Linux: install the NVIDIA driver >= 595. WSL2: install the Windows driver (never a Linux driver inside WSL), `wsl --shutdown`, retry |
| `driver version: 580.x is older than 595` | the sealed PTX needs ISA 9.2 (CUDA 13.2): update the driver |
| `GPU memory: N MiB free but the engine needs M MiB` | another process holds VRAM (`nvidia-smi`); stop it or lower `--gpu-budget-gib` |
| `architecture: ... built WITHOUT the sm86 feature` | an RTX 30-series card needs a release made with `--features sm86` |
| `memory: ... available is below ...` | the sealed archive copy needs the whole 55 GB in RAM. Free memory, or use the file profile if the GPU fits it. On WSL2 put `[wsl2] memory=32GB swap=8GB` in `%UserProfile%\.wslconfig` and `wsl --shutdown` |
| `WSL2 file system: ... is on a Windows/network mount` | `/mnt/c` is 9p: far too slow for mapped reads. Use a path on the WSL ext4 disk |
| `cuBLAS 12: libcublas.so.12 ... not found` | let `up` download the pinned 12.9.1.4 (needs curl or wget, tar, xz), or `--cublas-dir DIR`, or `apt install libcublas12` |
| `disk space: assets ...: N GiB free, M needed` | nothing was downloaded yet; point `--assets` at a larger volume |
| `loopback ports: already in use` | another listener; `--api-port` / `--engine-port` / `--daemon-port` |
| `permission denied` on `/dev/nvidia*` in the system unit | the device nodes are not world-accessible: add the service user to the `video` (or `render`) group and restart the unit |
| `systemd: not running` | WSL2 without systemd or a container: `--foreground`, or enable systemd in `/etc/wsl.conf` |
| `step mtp-pack is blocked` | the MTP pack has no automated producer yet; copy `data/mtp-rt` from a machine that has it (`--mtp-pack` takes a directory or tarball) |
| `... has N bytes but the engine only admits the pinned 55295529472-byte level-2 archive` | the archive was built with another level or policy; the engine would refuse it. Rebuild with `--levels 2` |
| `step model failed: ... 401/403` | the repository needs a token: `export HF_TOKEN=...` (sent only to huggingface.co) |
| `load-mtp was refused` | read `STATE/logs/engine.log` (the engine prints a fixed code, never a path or a secret) |
| `the model was not ready within 1800 s` | the engine verifies 84 GB of shards and 55 GB of archive at load; a cold disk can need longer: raise `load_timeout_s` in `STATE/leleka.json` |
| a stale `Another supervisor is running for ...` | `leleka down` (systemd) or stop the other process; `STATE/run/status.json` names its pid |
## 10. What was run and what was not
All of this is bring-up evidence, not a performance or quality result: no paired A/B, one request, no token statistics beyond what is quoted.
### Findings that the real run produced
1. **The production `Load` of the Original path could not succeed.** `leleka-inference ... --backend-mode original` never admitted a routed-expert bank
(the serve smokes call `load_resident_expert_source()` themselves; `backend.rs` did that only for the `--experimental-optimized-*` modes), so the first real `load-mtp`
through the daemon failed in `OriginalServeStack::open` with `MoeWeightCache::new_original_prompt_arena: InputRead` (`leleka-load phase=OriginalStack class=BackendUnavailable` in
`engine.log`) and the engine process stayed up. Fixed here: `OriginalServeOptions.expert_source` and `--expert-source resident|mapped` (default `resident`, the smoke form);
`backend.rs` admits the chosen bank before the driver, as it does for the optimized modes. The profile files select `resident` (server) and `mapped` (laptop).
2. **The supervisor waited out the load timeout for a refused load.** The engine does not exit on a failed load; `leleka` now reads the operation record
(`leleka-cli operation`, state FAILED/INDETERMINATE) and stops with the last lines of `engine.log`.
3. `leleka-inference` had no way to take the archive as a read-only file (only the 55 GB sealed memfd); `--kar-archive-file` is new and was exercised on the laptop.
### Real runs
| where | what | result |
| --- | --- | --- |
| WSL2 laptop, RTX 3080 Laptop 16 GB, driver 617.42, Ubuntu 24.04 with systemd, RAM 40 GB (`.wslconfig`) | `leleka up` from the unpacked release (commit `e03d97d`, 30.7 MB tarball, sm86 build), user unit, real shards and archive (copied to the WSL ext4 disk), profile `rtx3080-16g` chosen by `auto` | preflight 13 ok / 1 warning (cuBLAS missing); cuBLAS 12.9.1.4 unpacked from the pinned archive (SHA-256 checked; **the download itself was not exercised**: the archive was placed in `PREFIX/lib` beforehand); fetch + verify of the real shards about 3 min (hash reuse, no download); tokens, configs, tokenizer, `systemctl --user enable/start`; **model loaded in 198 s, `/ready` 200**; one `POST /v1/responses` (59 input tokens, 16 output tokens, 21.4 s wall, stopped by `max_output_tokens`, text is the model's reasoning preamble) |
| same | peak during that request | VRAM 13,971 MiB; engine RSS 26.4 GB (anon 2.6, file-backed 19.9, shmem 4.0); the engine log shows 3,133 VRAM expert slots (the expert tier was on because `expert-profile.bin` had the pinned digest) |
| same | idempotence | a second `up` against the running service: 0.27 s, same systemd `MainPID`, every step `done`; `leleka down`: 1.9 s, no process left, VRAM back to 0 |
| same | engine killed with `kill -9` | phase `engine_restarting`, `/ready` false, the engine restarted and reloaded: ready again 293 s after the kill (load 286 s), restart counter 1, gateway and API processes unchanged, one request served afterwards |
| RTX 5090 server (Ubuntu 26.04, driver 595.99.02, 121 GB RAM) | `leleka up --dry-run` with the real assets and the real preflight | 12 checks ok; the plan names the exact engine command; nothing created. The real-model jobs `930-deploy-prepare.sh` and `931-deploy-serve.sh` are in the holder queue (they inherit the holder's sealed descriptor with `--kar-fd`); see "Server job" below for their state |
### Tests (no GPU, no model)
* `cargo test -p leleka-deploy --features test-fakes` (71 unit, 11 end-to-end, 4 recipe tests, all passing in WSL): unit tests (profiles, facts parsers, preflight on synthetic hosts - server, laptop under default WSL2 memory, old driver, busy GPU,
no cuBLAS, full disk, `/mnt/c`, no systemd -, plan, units, CLI, sealed memfd, stamps, HTTP), `tests/e2e.rs` against a test double of the five programs
(supervisor lifecycle with an inherited sealed descriptor and with a read-only file: ready, SIGKILL of the engine -> restart with API/gateway unchanged -> SIGTERM drain with every child gone;
an engine that cannot start; a refused load fails fast; weak tokens are exit code 2; `up` is idempotent, resumable after a deleted archive, never rotates secrets, `--trust-archive`, wrong-size archive refused;
`--dry-run` creates nothing; a failing preflight changes nothing), `tests/recipe.rs` (the Containerfile is non-root, has a health check, copies no model or secret; the cuBLAS pin agrees in three places; `install.sh` verifies before it runs).
`cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` are clean.
* `cargo test -p strata-desktop-core --bin leleka-inference` (14 argument-parsing tests, including `--kar-archive-file` and `--expert-source`).
* Linux only for the process tests; the portable parts also run on Windows (`cargo test -p leleka-deploy`), where the POSIX-path tests are not meaningful.
### Not done / open
* **No container image was built.** Docker Desktop on this laptop does not start: its backend aborts on stale `AF_UNIX` socket files (`%LOCALAPPDATA%\Docker
un\dockerInference`,
`userAnalyticsOtlpHttp.sock`, dated 2025-06) that Windows refuses to delete without elevation (`Error 1920`). The recipe is checked statically (`tests/recipe.rs`) and by simulation: the `COPY` layout
rebuilt under `/opt/leleka` in WSL, `env -i`, the container's environment variables: `ldd` resolves every library from the base alone (libc, libm, libgcc_s), `libcublas.so.12` is found in
`PREFIX/lib/cublas`, `leleka status` answers in 2 ms; the content is 167 MB of binaries + 815 MB of cuBLAS = 982 MB before the Ubuntu base layer (no image digest exists).
Build it on a machine with a working engine (section 7) and record the digest and size.
* The **system-scope** unit (`useradd`, chown of state and assets, `/etc/systemd/system`) and the `curl` branch of the cuBLAS download have unit tests / renders but were not run for real.
* No clean Ubuntu 24.04 / 26.04 VM was installed from nothing; the first-ever archive build (`ensure-sharded-streamed` creating 55 GB) was not repeated.
* The MTP pack has no producer in the repository (`mtp_pack`); `up` needs it in `ASSETS/data/mtp-rt` or via `--mtp-pack`.
* Not measured: the load time of the server profile under the supervisor, the RAM peak of 55 GB memfd + 50 GB bank, anything about throughput.
* Native Windows is not a target. TLS and remote access are not part of this: use an SSH tunnel.
### Server job (RTX 5090)
Two holder jobs are queued on `rnr5090` (`~/work/gpu-runs/holder2/jobs/`), written to run after each other and to inherit the holder's sealed descriptor, so nothing is copied or downloaded:
* `930-deploy-prepare.sh`: `up --dry-run`, then `up --mode none --kar-fd $LELEKA_STRA169_KAR_FD --trust-archive` against `~/leleka-gates/assets` (real `model fetch`/`verify` of the existing shards by hash reuse,
tokens, configs, tokenizer extraction into `assets/tokenizer-assets`), then a second dry-run and a second `up` to show that nothing is redone.
* `931-deploy-serve.sh`: `up --foreground --kar-fd ...` with the real model (typed load, `/ready`), one request through the API, an unauthenticated request (must be refused), SIGTERM, the logs and a check that no process is left.
The release is unpacked at `~/work/deploy-run/rel`, state is `~/work/deploy-run/state`. At the time of writing the holder was busy with earlier queue entries (the holder takes a snapshot of the job list per pass, so entries added later run in the next pass), so
**these two jobs had not run**; read `930-deploy-prepare.log` and `931-deploy-serve.log` next to the scripts. The strict re-verification of the existing archive (`ensure-sharded-streamed` without `--trust-archive`) was deliberately not queued:
it re-derives the 708 GB virtual F32 stream (the analysis tool was stopped after 13 minutes at the same step, `build-validation.md`).
### Startup profile jobs (RTX 5090, queued)
`~/work/gpu-runs/holder2/jobs/9g1`-`9g6` (templates in `scripts/startup-profile/`) measure the phases of a
supervised start on the real assets with the holder's sealed descriptor: `9g1` verification only, baseline binaries (warm, cold shards, warm); `9g2`/`9g3` a full start with the baseline binaries
(warm / shards evicted); `9g4` verification only, new binaries (without stamps, with stamps first and second run, `--verify-rehash`); `9g5`/`9g6` two consecutive starts with the new binaries
(the second one is the restart that uses the stamps), warm / cold. Each prints the `leleka-load-time` lines, the governor's load ledger of the stack opening, the supervisor's
`start_to_ready` seconds and two requests (the second shows the warm-up cost of the first). They are FIFO behind the other queue entries; at the time of writing none had run.
The baseline binaries are the commit `cceb4b4` build (phase lines and `--verify-only`, sequential verification); the new ones the final build of this branch.
# One-command deployment: `leleka up`
Status 2026-10-17, branch `claude/deploy` (base `claude/port-gpu-bringup` @ `5e0bd84`). This page describes the deployment
tool `leleka` (crate `crates/deploy`, no Python at run time), what it does, every flag, and what was and was not run to
check it. Results are in [section 10](#10-what-was-run-and-what-was-not); nothing here is a performance or model-quality
claim. Background: [`rust-runtime-run.md`](rust-runtime-run.md) (the processes), [`model-assets.md`](model-assets.md) (the model
commands `leleka` drives), [`laptop-profile.md`](laptop-profile.md), [`sm86-assets.md`](sm86-assets.md),
[`delivery-gap-audit.md`](delivery-gap-audit.md) section 5 (the packaging gaps this closes in part).
## 1. Quickstart
Server (Linux x86_64, NVIDIA driver >= 595, systemd), as root, from the unpacked release:
```sh
tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
sudo ./install.sh --assets /data/leleka # preflight, fetch+verify, KAR archive, install, start, wait for ready
```
WSL2 laptop (RTX 3080 16 GB), as your user, in a terminal (WSL2 usually has no systemd):
```sh
./install.sh --assets ~/leleka --foreground # keep the terminal open; Ctrl-C drains and stops
```
Both do the same thing, idempotently, and print the endpoint, model digest, GPU, the VRAM/RAM budget that was chosen, and the
log directory when the service answers `/ready`. Look first with `--dry-run`: it prints the preflight and the plan and changes nothing.
```sh
./bin/leleka up --dry-run --assets /data/leleka
```
This is charter goal G2 (`PROJECT_CHARTER.md` section 6): one command, GPU and memory plan chosen automatically, external model volume, readiness only after the model is loaded, orderly stop and restart of the worker, no Python at run time.
Its acceptance test (a clean Linux GPU node, driver installed, one command, no re-download after a restart) has **not** been run; section 10 lists what was.
Container: [section 7](#7-container-image). Build your own release: [section 8](#8-build-a-release-tarball).
## 2. What `up` does
| # | step | what happens | idempotency |
| --- | --- | --- | --- |
| 1 | preflight | driver >= 595, GPU architecture, VRAM free vs budget, RAM total/available, disk on each volume, WSL2 mounts, `libcublas.so.12`, `memfd_create`, ports, systemd, the six binaries | read-only; any FAIL stops before anything is changed |
| 2 | layout | state (0700), logs, run, stamps, assets | `mkdir -p` |
| 3 | binaries | copy `bin/*` to `PREFIX/bin`, SHA-256 checked against `MANIFEST.json` | skipped when identical; replaced by rename (safe for a running binary) |
| 4 | cuBLAS 12 | uses what the host has; otherwise downloads the pinned NVIDIA 12.9.1.4 redistributable (SHA-256 pinned, resumable) into `PREFIX/lib/cublas` | skipped when `libcublas.so.12` and `libcublasLt.so.12` are found |
| 5 | secrets | two service tokens into `STATE/runtime.env` (0600), API key through `strata-next api-key init` | never rotated; only missing/invalid ones are created |
| 6 | model | `strata-next model fetch qwen-iq3-s` then `model verify` (resumable `.part` files, SHA-256) | stamped with size+mtime: skipped on re-runs unless `--reverify` |
| 7 | KAR archive | `strata-next model ensure-sharded-streamed qwen-iq3-s --levels 2` (level 2, the pinned 55,295,529,472-byte archive + provenance) | stamped; also checks the length the engine admits |
| 8 | MTP pack | `ASSETS/data/mtp-rt` must exist; `--mtp-pack` imports it from a directory or tarball | skipped when present |
| 9 | tokenizer | `model extract-tokenizer` from shard 1 | skipped when present |
| 10 | config | `leleka.json`, `daemon.json`, `strata.json`, `profile.json`, `runtime.env` | rewritten only when the content changes |
| 11 | service | systemd unit (system or user), `daemon-reload`, `enable`; none in foreground mode | rewritten only when the content changes; a changed unit restarts a running service |
| 12 | start / ready | start the unit (or run the supervisor in this terminal), poll `/ready` with the key, print the summary | an already ready service is left alone |
The archive step runs `ensure-sharded-streamed`, which fetches and verifies the shards itself, so on a first run step 6 is folded into
step 7 (the plan says so). The strict verification of an *existing* archive re-derives the 708 GB virtual F32 stream and is slow; a
machine that already holds the archive can pass `--trust-archive`: the archive is accepted when it has the pinned length and a
provenance file, and the engine checks its SHA-256 and every CRC against the pinned digest at each load anyway.
A failed run is resumable: fix the cause and run the same command; finished steps are skipped (downloads continue from `.part`).
## 3. The processes and files
```text
leleka run (supervisor, the systemd ExecStart or your terminal)
|- seals the KAR archive into a memfd ONCE (memfd profile) -- or hands the engine a read-only file (file profile)
|- leleka-daemon gateway for the typed lifecycle, 127.0.0.1:18080
|- leleka-inference engine, gRPC 127.0.0.1:18766 (started through `leleka exec-inherit`, which passes the sealed fd)
|- leleka-cli load-mtp qwen-iq3 qwen4exp-kar-ple-mtp-v1 -> wait for model_ready (the engine verifies shards + archive here)
`- strata-next serve public API (Responses, Chat, Messages, tools, ...), 127.0.0.1:8081, bearer key
```
```text
PREFIX/bin/{leleka,strata-next,leleka-inference,leleka-daemon,leleka-cli,leleka-seal-exec} PREFIX/lib/cublas/
STATE/{leleka.json,daemon.json,strata.json,profile.json,runtime.env,api-key} STATE/{logs,run/status.json,stamps,mtp-staging}
ASSETS/model/*.gguf ASSETS/qwen-iq3-s-l2-v4.kar(.provenance.json) ASSETS/data/mtp-rt/ ASSETS/tokenizer-assets/
```
Defaults: root gets `/opt/leleka`, `/var/lib/leleka/state`, `/var/lib/leleka/assets`; a user gets `~/.local/share/leleka`,
`~/.local/state/leleka`, `~/.local/share/leleka/assets`. Environment: `LELEKA_PREFIX`, `LELEKA_STATE`, `LELEKA_ASSETS`.
**Put `--assets` on the big volume**: about 140 GB (shards 83.6 GB + archive 55.3 GB); the first run needs that plus slack.
### The sealed KAR archive is made by the service
The engine accepts the archive only as a sealed memfd (regular, unlinked, pinned length, `WRITE|GROW|SHRINK|SEAL`). Until now an operator
tool (`kar_holder.py` / `seal_exec.py`, outside the repository) did that. `leleka run` now does it natively: it copies the archive into a
sealed memfd once (about 10 s for 55 GB from a warm cache, minutes cold), keeps the descriptor close-on-exec in the supervisor, and hands a duplicate
to each engine start through `leleka exec-inherit` (standard input in, a descriptor number >= 3 out). An engine restart therefore does
**not** copy 55 GB again, and the API, the gateway and the CLI never see the descriptor. `leleka-seal-exec` still ships for manual runs.
`--kar-fd N` (on `up` and `run`) reuses a descriptor inherited from a parent that already holds one (a holder, a test harness): no second copy, and its RAM is not demanded.
The **file profile** (laptop) cannot afford 55 GB of shmem. `leleka-inference` gained `--kar-archive-file PATH --kar-provenance PATH`
(`InheritedKarArchive::open_read_only_file`, the form `docs/laptop-profile.md` measured in a bench): the archive stays an ordinary file;
it must be regular, single-link, owned by the service user and without write bits (`up` sets mode 0400). It is weaker than the seal (immutability rests on
the file system) and is selected only by that profile. The full SHA-256 and all CRCs are still checked at load.
## 4. Memory profiles
`--profile auto` (default) picks by the GPU `nvidia-smi` reports; `--profile NAME` or `--profile FILE.json` overrides it, and
`--gpu-budget-gib` / `--context-tokens` override single values. `leleka profiles` lists them, `leleka profiles show NAME` prints one to copy and edit.
The files live in [`deploy/rust-runtime/profiles/`](../deploy/rust-runtime/profiles/) and are embedded in the binary.
| profile | selected for | GPU budget | context | KAR archive | routed experts | RAM floor (total / available at start) | other |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `rtx5090-32g` | sm_12x, >= 30 GB VRAM | 24 GiB | 262,144 | sealed memfd (55.3 GB of RAM) | `resident`: page-locked RAM copy (50.3 GB) | 100 GiB / 113 GB (58 GB when `--kar-fd` supplies the archive) | the documented bring-up configuration |
| `rtx3080-16g` | sm_80..119, 14-24 GB VRAM | 15 GiB (needs 14,500 MiB free) | 8,192 | read-only file | `mapped`: read-only mappings of shard 0 | 22 GiB / 10 GiB; advice `.wslconfig memory=32GB` | optional VRAM expert tier when `ASSETS/data/expert-profile.bin` has the pinned SHA-256 `8f59b4aa...388975baf` |
Both profiles also carry a `memory` section (prefix cache `auto`, soft/hard floors 4096/2048 MiB, reserve, lock and heal of the sealed memfd): the engine sizes its caches from the memory left after the fixed footprint, sheds and refuses under pressure, and refuses to start with numbers when the footprint does not fit ([`memory-safety.md`](memory-safety.md)). The unit sets `LimitMEMLOCK=infinity`, which is what lets the lock keep the 55 GB memfd out of swap.
Both profiles run `--backend-mode original` and the level-2 archive; the routed-expert bank must be admitted before the Original stack opens, which `leleka-inference` now does from `--expert-source resident|mapped` (see section 10, finding 1). They select documented switches only (budget, context, archive form, the
`LELEKA_ORIGINAL_SERVE_*` environment); they are **not** tuned, not quality-gated and carry no speed claim. A GPU that fits neither
(a 24 GB 4090, say) gets an error that names the way out: write a profile file. Fields: see `crates/deploy/src/profile.rs`
(`gpu_budget_bytes`, `context_tokens`, `prefill_capacity`, `kv`, `kv_resident`, `prompt_cache`, `kar_source`, `min_*`, `engine_env`
restricted to `LELEKA_ORIGINAL_SERVE_*`); unknown fields are refused.
One binary serves both architectures: the sealed sm_120 PTX is used as is on Blackwell, and the build with `--features sm86`
(every release) swaps in the sm_86 companion PTX on 8.6 <= cc < 12.0 cards ([`sm86-assets.md`](sm86-assets.md)). Preflight reads `MANIFEST.json` and refuses a
binary built without `sm86` on such a card. All PTX is embedded in the binaries (the release also ships the files and a `SHA256SUMS` for audit).
## 4b. Resource presets
`leleka up` computes what the runtime takes of the host (`crates/deploy/src/resources.rs`, a pure function of the probed host facts and the profile), prints it, and bakes it into `leleka.json` (the profile's budget and floors, and `LELEKA_ORIGINAL_SERVE_CPU_WORKERS`). Two presets:
| | `dedicated` (default) | `workstation` |
| --- | --- | --- |
| purpose | the host belongs to the runtime | Docker, agents and the IDE share the machine |
| CPU expert workers | `min(cores - 2, 8)` | `min(cores - leave, 8)`, leave 4 cores (8 above 16 cores) |
| host RAM kept free | the profile's governor floors (server: soft 4 GiB, hard 2 GiB) | soft floor 8 / 12 / 16 GiB (hosts under 32 / under 64 / from 64 GiB RAM), hard floor half of it; the profile's floors are only raised. The governor sheds the prefix cache first, then refuses new requests with 503 `memory_pressure` |
| VRAM | the profile budget | `min(profile, free - 4 GiB)` rounded down to GiB; the expert tier is sized from what remains |
More than 8 CPU workers do not help (decode is bound by host memory bandwidth, `docs/roofline.md`), so on a large host the cores that `dedicated` leaves free are the spare ones, and `workstation` mainly guarantees the RAM and VRAM headroom. If the workstation target cannot be met (less than half of the profile's VRAM budget would remain) the preflight fails with the numbers; a RAM shortfall does not fail: when the pinned form (sealed archive plus engine, about 58 GiB on the server) would leave less than the free target, `up` switches the profile to the mapped form of the laptop profile: the archive stays a read-only file and the experts are memory-mapped from SSD/HDD, with `available - target - 8 GiB` of experts page-locked (`resident_budget_gib`, 0 on a small host). It prints a warning, because decode is slower than with everything in RAM. The same fallback applies to `dedicated` when the host cannot hold the pinned form at all. `--gpu-budget-gib` and explicit profile fields win over the preset.
## 4c. What the runtime reports (`leleka status`)
The engine samples itself once a second and records every request (`crates/leleka-memory/src/telemetry.rs`). The document travels
gRPC `Snapshot.telemetry_json` -> the gateway -> `GET /v1/status` `machine` -> `leleka status` (also `--json`):
| block | figures |
| --- | --- |
| `gpu` | utilisation %, memory-bus %, VRAM used/total (NVML, loaded with `dlopen`; absent when NVML is not installed), power, SM clock |
| `ram` | host total/available, engine resident and pinned, swap in use |
| `cpu` | engine CPU in busy cores (of the cores this process may use), whole-system busy % |
| `throughput` | prefill tok/s (last request, running average, lifetime) and decode tok/s (same, plus the live rate of the request in flight) |
| `cache` | requests and how many reused a checkpoint, prompt tokens reused of all, the last request's reused/prompt tokens |
| `context` | tokens live in the session, the configured maximum, percent used; `phase` idle/prefill/decode |
Prefill rate counts the tokens actually prefilled (prompt minus reused). Rates are `null` until a request has been measured.
## 5. Flags
`leleka up [OPTIONS]` (also accepted by `preflight`, `status`, `down`):
| flag | meaning |
| --- | --- |
| `--dry-run` | print preflight and plan (and the exact engine command); change nothing; exit 1 if a check fails or a step is blocked |
| `--json` | machine-readable plan / summary on stdout (logs stay on stderr) |
| `--profile auto\|NAME\|FILE` | memory profile |
| `--gpu N` | CUDA device ordinal (default 0) |
| `--assets DIR` `--state-dir DIR` `--prefix DIR` | the three roots (section 3) |
| `--bin-src DIR` | where the six binaries come from (default: the directory of `leleka`, i.e. the release `bin/`) |
| `--mode auto\|system\|user\|foreground\|none`, `--foreground` | `auto`: root with systemd -> system unit; a user with a systemd user session -> user unit; otherwise foreground. `none` prepares and starts nothing |
| `--service-user NAME` | system unit only: the account the service runs as (default `leleka`, created with `useradd --system`; state and assets are chowned to it) |
| `--api-port` `--engine-port` `--daemon-port` | ports (defaults 8081, 18766, 18080) |
| `--api-bind IP` | API listen address, default `127.0.0.1`; `0.0.0.0` only inside a container whose port is published to the host's loopback or tunnelled (the bearer key is the only protection, no TLS). The engine and gateway are always loopback |
| `--preset dedicated\|workstation` | how much of the host the engine takes (env `LELEKA_PRESET`, section 4b; recorded in `leleka.json`) |
| `--gpu-budget-gib N` `--context-tokens N` | override one profile value |
| `--no-fetch` | never download or build; require verified files to exist |
| `--reverify` | ignore the stamps and hash everything again |
| `--trust-archive` | accept an existing pinned-length archive + provenance without the strict re-derivation (section 2) |
| `--mtp-pack PATH` | import the MTP pack (directory or `.tar/.tar.gz/.tgz/.tar.xz`, sub-directories searched) |
| `--cublas-dir DIR` / `--no-install-cublas` | use this CUDA 12 cuBLAS / fail instead of downloading it |
| `--kar-fd N` | an already sealed archive descriptor inherited from the parent (foreground or `--mode none` only) |
| `--timeout-s N` | wait this long for `/ready` (default 3600) |
Other commands: `leleka verify` (full parallel hash of shards and archive, renews the stamps; section 6b), `leleka preflight` (checks only, exit 1 on FAIL), `leleka status` (cheap: no GPU probe; exit 0 only when ready; this is the container health check),
`leleka down` (stop the systemd unit), `leleka run --config STATE/leleka.json [--kar-fd N]` (the supervisor), `leleka profiles [show NAME]`.
`HF_TOKEN` in the environment is used only by `model fetch`, is sent only to `https://huggingface.co`, is removed from every child the supervisor starts, and is never printed or written.
## 6. Operating it
* systemd: `systemctl status leleka`, `journalctl -u leleka -f` (user unit: add `--user`; run `loginctl enable-linger USER` to start without a login). The unit has
`Restart=on-failure` with `RestartSec=30`, at most 3 starts in 30 minutes, and no restart after exit code 2 (configuration), because every start re-reads 55 GB.
* The supervisor restarts a dead engine up to twice (counter reset after 10 ready minutes) with the same sealed descriptor and loads the model again; the API process stays up and
answers not-ready meanwhile. A dead gateway (3) or API (5) is restarted too. Then it exits 1 and systemd decides.
* `SIGTERM`/`SIGINT` drain: the API first (`shutdown_grace_s` 10), then the gateway and the engine (both handle SIGINT only, so the supervisor sends SIGINT), then SIGKILL after the grace.
* Logs: `STATE/logs/{leleka,engine,gateway,api,install}.log` (rotated once past 64 MiB at start). Status: `STATE/run/status.json` (`phase`: sealing, starting_engine, loading, starting_api, ready, engine_restarting, draining, stopped, failed).
* Use it: `curl -H "Authorization: Bearer $(cat STATE/api-key)" -H 'content-type: application/json' -d '{"model":"qwen-iq3","input":"hello","max_output_tokens":32}' http://127.0.0.1:8081/v1/responses`.
Remote clients: an SSH tunnel. Known limits of this API-over-engine path (4096 output tokens, 256 generations per engine epoch, no image input) are in [`api-over-rust-engine.md`](api-over-rust-engine.md).
## 6b. Fast restarts: where a cold start went and what was changed
A start used to hash 83.6 GB of shards and the 55 GB archive one after the other, each in a single thread that alternated
`read` and `update` (laptop, cold: shard 0 115-134 s, shard 1 64-96 s, archive 95-181 s; 265-400 s in all, 100-215 s of it system time in
`read`). Every engine now prints `leleka-load-time phase=... seconds=... total=...` lines on stderr (`STATE/logs/engine.log`), and
`leleka-inference --verify-only` runs just the source verification (no CUDA) so that phase can be measured anywhere.
| change | where | effect |
| --- | --- | --- |
| shard 0, shard 1 and the archive are verified at the same time | `backend.rs` `verify_sources_parallel`; refusals consumed in the old order (shard 0, shard 1, binding) | wall = the slowest file, not the sum |
| a reader thread keeps 6 x 8 MiB chunks ahead of the hasher (`pread`, `FADV_SEQUENTIAL`, recycled buffers) | `model-format/src/readahead.rs`, used by `VerifiedGgufFile::open` and the archive scan | I/O and hashing overlap |
| archive scan: SHA-256 on one thread, per-section CRC-32 on another | `kar.rs` `verify_integrity_pipelined`; same verdicts and precedence (SHA mismatch before CRC failure), tested against the stream scan | the 55 GB pass costs the slower of the two |
| **verification stamps**: a file that matched its pinned digest and is unchanged (device, inode, size, mtime, **ctime**) is not hashed again | `model-format/src/verify_stamp.rs`, `leleka-inference --verify-stamps DIR` (the supervisor passes `STATE/stamps/engine`) | a restart hashes nothing that did not change |
| the supervisor copies the archive into the memfd with several threads and checks that the source did not change while it was copied | `sealed.rs` `seal_file_with_identity` | the fill runs at memory bandwidth |
| a sealed memfd that this supervisor already had verified (an earlier engine) or that was copied from a file whose `kar-source` stamp matched is not hashed again: `--kar-attested-by-stamp` | `supervisor.rs`, `verify_stamp::set_attested_archive` | engine restarts and service restarts skip the 55 GB hash |
| on the first start, a CPU-only `--verify-only` hashes the shards while the supervisor fills the memfd | `supervisor.rs` `spawn_shard_preverify` | the two big reads overlap |
| `leleka verify` | `app.rs` | hashes shards and archive in full, in parallel, renews every stamp |
Stamp rules (fail closed). A stamp is one line per (kind, pinned digest) in a directory that must be owned by the service account and closed to
group and others; any difference in any field, an unreadable, malformed or extra-long stamp, a symlink, or a stamp directory that is not private means
"hash in full". `ctime` changes on every write, truncate, chmod, chown and rename and cannot be set from user space, so a rewritten file does not match even
when its `mtime` is restored (unit-tested). A stamp is recorded only if the file's identity is the same before and after the full hash, and it is keyed by the pinned
digest, so it never replaces the pin. A changed file is hashed in full and refused if it no longer matches. What a stamp cannot defend against is someone who can write both the stamp
directory and the model file as the service account; that account also owns the archive the engine maps. `--verify-rehash` / `leleka verify` ignore existing stamps; `"verify_stamps": false` in
`STATE/leleka.json` turns the whole mechanism off (every start hashes everything, in parallel).
Measured so far (CPU-only `--verify-only`, laptop i9-11900H, WSL2 ext4, shards and archive evicted from the guest page cache first; the host may still cache the virtual disk):
| run | shard 0 | shard 1 | archive | wall |
| --- | --- | --- | --- | --- |
| before: sequential, `read` + `update` in one thread | 115 s | 64 s | 95 s | 265 s (a first run with a colder host cache: 400 s) |
| after: parallel + read-ahead, no stamps | 74 s | 57 s | 74 s | 72 s |
| after: parallel, second sample (warmer host cache) | 47 s | 28 s | 47 s | 45-51 s |
| after: stamps current | 0.02 s | 0.01 s | 0.00 s | 0.02 s |
The laptop reads at about 1 GB/s at best; the 5090 server numbers are in the holder jobs `9g1`-`9g6` (section 10).
## 7. Container image
[`deploy/Containerfile.rust-runtime`](../deploy/Containerfile.rust-runtime): Ubuntu 24.04 (glibc 2.39, the floor of the binaries) + the six binaries + cuBLAS 12.9.1.4
(downloaded by BuildKit with `ADD --checksum`, only `libcublas.so.12*` and `libcublasLt.so.12*` kept) + the manifest/provenance. The sealed PTX is inside the binaries; `ldd` shows only libc, libm
and libgcc_s, and the engine `dlopen`s `libcuda.so.1` (injected by the NVIDIA Container Toolkit) and `libcublas.so.12`. Not in the image, by design: the model, the driver, any secret. Non-root (uid 10001), volumes `/models` and `/state`,
`HEALTHCHECK` = `leleka status`.
```sh
tar -xJf leleka-VERSION-linux-x86_64.tar.xz && cd leleka-VERSION-linux-x86_64
docker build -f /path/to/repo/deploy/Containerfile.rust-runtime --build-arg VERSION=VERSION -t leleka-runtime:VERSION .
# pin the base for a release: docker buildx imagetools inspect ubuntu:24.04 then --build-arg BASE=ubuntu:24.04@sha256:...
docker run -d --name leleka --gpus all --restart unless-stopped \
-v /data/leleka-models:/models -v leleka-state:/state -p 127.0.0.1:8081:8081 \
leleka-runtime:VERSION # default command: up --foreground --no-install-cublas --api-bind 0.0.0.0
docker logs -f leleka # first start: hours (download, verification, archive build); later starts: minutes
docker exec leleka cat /state/api-key
```
The memfd profile needs the host to give the container ~60 GB of RAM (no `--memory` below that; memfd is shmem charged to the container, not limited by `--shm-size`). Docker's default seccomp
profile allows `memfd_create`. Build is not run in CI; see section 10 for what was checked.
## 8. Build a release tarball
On Linux/WSL, from a tree with the toolchain pinned by `rust-toolchain.toml` (no CUDA toolkit is needed; the PTX is checked in):
```sh
cargo build --release --locked -p strata-desktop-core --features sm86 \
--bin leleka-inference --bin leleka-daemon --bin leleka-cli --bin leleka-seal-exec
cargo build --release --locked -p strata-control --bin strata-next
cargo build --release --locked -p leleka-deploy --bin leleka
# provenance is made where git exists (an exported tree has no .git); the tree must be clean or --allow-dirty marks it
python3 scripts/package-release.py provenance --repo . --out provenance.json
python3 scripts/package-release.py package --repo . --target-dir target --provenance provenance.json --out dist
```
`dist/leleka-VERSION-COMMIT12-linux-x86_64.tar.xz` (+ `.sha256`) contains `bin/` (six binaries), `share/leleka/ptx/{sm_120,sm_86}` (the sealed PTX and `SHA256SUMS`), `share/leleka/{profiles,templates,docs}`,
`MANIFEST.json` (version, commit, `features`, SHA-256 of every binary, rustc/glibc of the builder), `PROVENANCE.json`, `SHA256SUMS` for every file, and `install.sh`. `--no-ptx` omits the PTX files (they are embedded anyway);
`--with-cublas DIR` bundles cuBLAS (NVIDIA's redistribution terms apply).
`PROVENANCE.json` records the git commit, whether the tree was dirty (and a digest of the diff), the `Cargo.lock` digest, and for `engine/strata`: the upstream URL and commit from [`upstream.md`](upstream.md),
the subtree tree id, the import commit, every later commit touching the subtree, and the diff since import (shortstat + digest). The diff against the upstream tree itself is computed only when the upstream commit is present
in the repository (`git fetch strata-upstream`); otherwise the record says so. `engine/strata` is not modified by this work.
## 9. Troubleshooting
| message (preflight / run) | cause and fix |
| --- | --- |
| `NVIDIA GPU: nvidia-smi was not found` | no driver. Linux: install the NVIDIA driver >= 595. WSL2: install the Windows driver (never a Linux driver inside WSL), `wsl --shutdown`, retry |
| `driver version: 580.x is older than 595` | the sealed PTX needs ISA 9.2 (CUDA 13.2): update the driver |
| `GPU memory: N MiB free but the engine needs M MiB` | another process holds VRAM (`nvidia-smi`); stop it or lower `--gpu-budget-gib` |
| `architecture: ... built WITHOUT the sm86 feature` | an RTX 30-series card needs a release made with `--features sm86` |
| `memory: ... available is below ...` | the sealed archive copy needs the whole 55 GB in RAM. Free memory, or use the file profile if the GPU fits it. On WSL2 put `[wsl2] memory=32GB swap=8GB` in `%UserProfile%\.wslconfig` and `wsl --shutdown` |
| `WSL2 file system: ... is on a Windows/network mount` | `/mnt/c` is 9p: far too slow for mapped reads. Use a path on the WSL ext4 disk |
| `cuBLAS 12: libcublas.so.12 ... not found` | let `up` download the pinned 12.9.1.4 (needs curl or wget, tar, xz), or `--cublas-dir DIR`, or `apt install libcublas12` |
| `disk space: assets ...: N GiB free, M needed` | nothing was downloaded yet; point `--assets` at a larger volume |
| `loopback ports: already in use` | another listener; `--api-port` / `--engine-port` / `--daemon-port` |
| `permission denied` on `/dev/nvidia*` in the system unit | the device nodes are not world-accessible: add the service user to the `video` (or `render`) group and restart the unit |
| `systemd: not running` | WSL2 without systemd or a container: `--foreground`, or enable systemd in `/etc/wsl.conf` |
| `step mtp-pack is blocked` | the MTP pack has no automated producer yet; copy `data/mtp-rt` from a machine that has it (`--mtp-pack` takes a directory or tarball) |
| `... has N bytes but the engine only admits the pinned 55295529472-byte level-2 archive` | the archive was built with another level or policy; the engine would refuse it. Rebuild with `--levels 2` |
| `step model failed: ... 401/403` | the repository needs a token: `export HF_TOKEN=...` (sent only to huggingface.co) |
| `load-mtp was refused` | read `STATE/logs/engine.log` (the engine prints a fixed code, never a path or a secret) |
| `the model was not ready within 1800 s` | the engine verifies 84 GB of shards and 55 GB of archive at load; a cold disk can need longer: raise `load_timeout_s` in `STATE/leleka.json` |
| a stale `Another supervisor is running for ...` | `leleka down` (systemd) or stop the other process; `STATE/run/status.json` names its pid |
## 10. What was run and what was not
All of this is bring-up evidence, not a performance or quality result: no paired A/B, one request, no token statistics beyond what is quoted.
### Findings that the real run produced
1. **The production `Load` of the Original path could not succeed.** `leleka-inference ... --backend-mode original` never admitted a routed-expert bank
(the serve smokes call `load_resident_expert_source()` themselves; `backend.rs` did that only for the `--experimental-optimized-*` modes), so the first real `load-mtp`
through the daemon failed in `OriginalServeStack::open` with `MoeWeightCache::new_original_prompt_arena: InputRead` (`leleka-load phase=OriginalStack class=BackendUnavailable` in
`engine.log`) and the engine process stayed up. Fixed here: `OriginalServeOptions.expert_source` and `--expert-source resident|mapped` (default `resident`, the smoke form);
`backend.rs` admits the chosen bank before the driver, as it does for the optimized modes. The profile files select `resident` (server) and `mapped` (laptop).
2. **The supervisor waited out the load timeout for a refused load.** The engine does not exit on a failed load; `leleka` now reads the operation record
(`leleka-cli operation`, state FAILED/INDETERMINATE) and stops with the last lines of `engine.log`.
3. `leleka-inference` had no way to take the archive as a read-only file (only the 55 GB sealed memfd); `--kar-archive-file` is new and was exercised on the laptop.
### Real runs
| where | what | result |
| --- | --- | --- |
| WSL2 laptop, RTX 3080 Laptop 16 GB, driver 617.42, Ubuntu 24.04 with systemd, RAM 40 GB (`.wslconfig`) | `leleka up` from the unpacked release (commit `e03d97d`, 30.7 MB tarball, sm86 build), user unit, real shards and archive (copied to the WSL ext4 disk), profile `rtx3080-16g` chosen by `auto` | preflight 13 ok / 1 warning (cuBLAS missing); cuBLAS 12.9.1.4 unpacked from the pinned archive (SHA-256 checked; **the download itself was not exercised**: the archive was placed in `PREFIX/lib` beforehand); fetch + verify of the real shards about 3 min (hash reuse, no download); tokens, configs, tokenizer, `systemctl --user enable/start`; **model loaded in 198 s, `/ready` 200**; one `POST /v1/responses` (59 input tokens, 16 output tokens, 21.4 s wall, stopped by `max_output_tokens`, text is the model's reasoning preamble) |
| same | peak during that request | VRAM 13,971 MiB; engine RSS 26.4 GB (anon 2.6, file-backed 19.9, shmem 4.0); the engine log shows 3,133 VRAM expert slots (the expert tier was on because `expert-profile.bin` had the pinned digest) |
| same | idempotence | a second `up` against the running service: 0.27 s, same systemd `MainPID`, every step `done`; `leleka down`: 1.9 s, no process left, VRAM back to 0 |
| same | engine killed with `kill -9` | phase `engine_restarting`, `/ready` false, the engine restarted and reloaded: ready again 293 s after the kill (load 286 s), restart counter 1, gateway and API processes unchanged, one request served afterwards |
| RTX 5090 server (Ubuntu 26.04, driver 595.99.02, 121 GB RAM) | `leleka up --dry-run` with the real assets and the real preflight | 12 checks ok; the plan names the exact engine command; nothing created. The real-model jobs `930-deploy-prepare.sh` and `931-deploy-serve.sh` are in the holder queue (they inherit the holder's sealed descriptor with `--kar-fd`); see "Server job" below for their state |
### Tests (no GPU, no model)
* `cargo test -p leleka-deploy --features test-fakes` (71 unit, 11 end-to-end, 4 recipe tests, all passing in WSL): unit tests (profiles, facts parsers, preflight on synthetic hosts - server, laptop under default WSL2 memory, old driver, busy GPU,
no cuBLAS, full disk, `/mnt/c`, no systemd -, plan, units, CLI, sealed memfd, stamps, HTTP), `tests/e2e.rs` against a test double of the five programs
(supervisor lifecycle with an inherited sealed descriptor and with a read-only file: ready, SIGKILL of the engine -> restart with API/gateway unchanged -> SIGTERM drain with every child gone;
an engine that cannot start; a refused load fails fast; weak tokens are exit code 2; `up` is idempotent, resumable after a deleted archive, never rotates secrets, `--trust-archive`, wrong-size archive refused;
`--dry-run` creates nothing; a failing preflight changes nothing), `tests/recipe.rs` (the Containerfile is non-root, has a health check, copies no model or secret; the cuBLAS pin agrees in three places; `install.sh` verifies before it runs).
`cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` are clean.
* `cargo test -p strata-desktop-core --bin leleka-inference` (14 argument-parsing tests, including `--kar-archive-file` and `--expert-source`).
* Linux only for the process tests; the portable parts also run on Windows (`cargo test -p leleka-deploy`), where the POSIX-path tests are not meaningful.
### Not done / open
* **No container image was built.** Docker Desktop on this laptop does not start: its backend aborts on stale `AF_UNIX` socket files (`%LOCALAPPDATA%\Docker
un\dockerInference`,
`userAnalyticsOtlpHttp.sock`, dated 2025-06) that Windows refuses to delete without elevation (`Error 1920`). The recipe is checked statically (`tests/recipe.rs`) and by simulation: the `COPY` layout
rebuilt under `/opt/leleka` in WSL, `env -i`, the container's environment variables: `ldd` resolves every library from the base alone (libc, libm, libgcc_s), `libcublas.so.12` is found in
`PREFIX/lib/cublas`, `leleka status` answers in 2 ms; the content is 167 MB of binaries + 815 MB of cuBLAS = 982 MB before the Ubuntu base layer (no image digest exists).
Build it on a machine with a working engine (section 7) and record the digest and size.
* The **system-scope** unit (`useradd`, chown of state and assets, `/etc/systemd/system`) and the `curl` branch of the cuBLAS download have unit tests / renders but were not run for real.
* No clean Ubuntu 24.04 / 26.04 VM was installed from nothing; the first-ever archive build (`ensure-sharded-streamed` creating 55 GB) was not repeated.
* The MTP pack has no producer in the repository (`mtp_pack`); `up` needs it in `ASSETS/data/mtp-rt` or via `--mtp-pack`.
* Not measured: the load time of the server profile under the supervisor, the RAM peak of 55 GB memfd + 50 GB bank, anything about throughput.
* Native Windows is not a target. TLS and remote access are not part of this: use an SSH tunnel.
### Server job (RTX 5090)
Two holder jobs are queued on `rnr5090` (`~/work/gpu-runs/holder2/jobs/`), written to run after each other and to inherit the holder's sealed descriptor, so nothing is copied or downloaded:
* `930-deploy-prepare.sh`: `up --dry-run`, then `up --mode none --kar-fd $LELEKA_STRA169_KAR_FD --trust-archive` against `~/leleka-gates/assets` (real `model fetch`/`verify` of the existing shards by hash reuse,
tokens, configs, tokenizer extraction into `assets/tokenizer-assets`), then a second dry-run and a second `up` to show that nothing is redone.
* `931-deploy-serve.sh`: `up --foreground --kar-fd ...` with the real model (typed load, `/ready`), one request through the API, an unauthenticated request (must be refused), SIGTERM, the logs and a check that no process is left.
The release is unpacked at `~/work/deploy-run/rel`, state is `~/work/deploy-run/state`. At the time of writing the holder was busy with earlier queue entries (the holder takes a snapshot of the job list per pass, so entries added later run in the next pass), so
**these two jobs had not run**; read `930-deploy-prepare.log` and `931-deploy-serve.log` next to the scripts. The strict re-verification of the existing archive (`ensure-sharded-streamed` without `--trust-archive`) was deliberately not queued:
it re-derives the 708 GB virtual F32 stream (the analysis tool was stopped after 13 minutes at the same step, `build-validation.md`).
### Startup profile jobs (RTX 5090, queued)
`~/work/gpu-runs/holder2/jobs/9g1`-`9g6` (templates in `scripts/startup-profile/`) measure the phases of a
supervised start on the real assets with the holder's sealed descriptor: `9g1` verification only, baseline binaries (warm, cold shards, warm); `9g2`/`9g3` a full start with the baseline binaries
(warm / shards evicted); `9g4` verification only, new binaries (without stamps, with stamps first and second run, `--verify-rehash`); `9g5`/`9g6` two consecutive starts with the new binaries
(the second one is the restart that uses the stamps), warm / cold. Each prints the `leleka-load-time` lines, the governor's load ledger of the stack opening, the supervisor's
`start_to_ready` seconds and two requests (the second shows the warm-up cost of the first). They are FIFO behind the other queue entries; at the time of writing none had run.
The baseline binaries are the commit `cceb4b4` build (phase lines and `--verify-only`, sequential verification); the new ones the final build of this branch.
+18
View File
@@ -173,6 +173,24 @@ summary. A request that resumes from a tail reads its suffix with the neutral cu
* Tools: per-request stage marks (`REPLAY-MARKS`: resume, prefill, assemble, first round), the short-suffix cost sweep
(`backend::original_serve_ttft::original_serve_ttft_sweep`), jobs `9d0`-`9d2` of claude/ttft.
## Session retention (60 minutes)
A pool serves many agent sessions; each one's next request should find its own checkpoint as it would in a slot. The store therefore keeps
every node for a **retention time of wall-clock minutes since its last use** (`retention_ms`, default 60 minutes; 0 = no limit):
* **Expiry:** a node unused for longer than the retention time is dropped with the blocks only it covered (`expired=` in the stats line,
`leleka-serve prefix retention: expired N ...` in the log). The serve loop sweeps every 15 s while idle and each request refreshes
the clock of the node it resumed from, so an active session never expires and an abandoned one gives its host RAM back after an hour.
* **Displacement:** when the budget runs out (or the memory governor sheds), the value of a node is multiplied by a recency factor that
falls linearly from 1 (just used) to `recency_floor` (0.1) at the end of the retention window, so the session idle longest is displaced
first; a fresh session is never refused because an hour-old one still sits there.
* Tests: `a_session_is_kept_for_the_retention_time_and_dropped_after_it`, `retention_zero_never_expires`,
`when_the_budget_runs_out_the_session_idle_longest_is_displaced_first` (the policy takes the wall time from the caller, so they are exact).
`--prefix-cache-tail reply` is the slot-equivalent resume (the checkpoint stands where the agent's next turn continues, built from the
decode-produced cells exactly as the Original's live continuation); it is still EXPERIMENTAL pending the agreement gate and the large-budget
A/B (job 9d3: arms G/P/R with a 20 GiB budget, because the 4.6 GiB budget of job 9d2b made `reply` evict useful nodes).
## Pool protocol
A front router across many runtimes places a request on the runtime that holds the longest prefix of its prompt. Nothing but