Files
leleka/docs/unattended.md
T
Pavlo RatushnyiandClaude Sonnet 5.5 fb10bf0e70 observability: structured bounded logs, per-request record, metrics, leleka logs / report
* crates/obs (leleka-obs, std only): one event per line (JSON under `leleka run`, key=value on a terminal, the lab's plain lines when a
  binary is started by hand into a file), UTC ms timestamp, level, component, event, flat fields; prompt/completion text and credentials
  never appear (key classes + value scrub + registered secrets), per-event token buckets with a `suppressed` count, value and line caps,
  histogram with Prometheus exposition, size-capped file sink for requests.log.
* control-plane: `observe` middleware gives every generation request an id (x-leleka-request-id header) and a session tag (hash of the
  client's session header); the worker marks engine start / first token / terminal / error on it and one record is written at request end
  (tokens, cached prefix, queue wait, TTFT, prefill/decode tok/s, finish, error class, engine restart, GPU clock/temp/throttle). All
  elog! lines go through the log layer (sampled per call site). /metrics?format=prometheus gains request counters and histograms, engine
  lost/attached counters, uptime and supervisor restarts, PCIe, memory clock, throttle reasons, speculative tokens per round, expert-tier
  entries by tier and hit ratio.
* engine: one structured line per request with the same id (rounds, tokens per round, expert-tier share served from VRAM/PCIe/CPU for that
  request); telemetry gains spec / expert_tier / last_request; NVML sampler reads PCIe throughput, memory clock, throttle reasons.
* supervisor: structured events (engine exit, health, restarts), secrets registered with the log layer, children get LELEKA_REQUEST_LOG,
  LELEKA_STATUS_FILE, LELEKA_PROFILE and JSON logging; runtime-client and gateway log connect/probe failures as sampled events.
* leleka logs (--tail/--since/--level/--component/--source/--request/--follow), leleka report (sanitized support bundle, written only with
  --yes, nothing sent anywhere), request statistics in leleka status / verify --quick.
* generation, sampling and kernels are untouched; the lab scripts keep their plain lines (LELEKA_LOG_FORMAT=legacy or a hand-started binary).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-02 23:25:24 +01:00

20 KiB

Leleka as an unattended service on the 5090 server

Branch claude/unattended (base f9003b7ce). Goal: the owner uses Leleka as the thinking system for daily work (Codex CLI through the control-plane HTTP/Responses gateway) and never has to babysit it: it starts at boot, starts fast, restarts itself when the engine dies or hangs, answers a failing request with an error instead of a hang, keeps its logs small, and exposes nothing beyond loopback.

Everything here is about operations. No kernel, sampler or model path changed; the one engine-side change (how the expert bank is read from disk) is bitwise-identical by construction and is checked by the replay gate in section 9. Nothing here is a throughput claim.

Contents: 1 what runs; 2 owner steps (exact commands); 3 lab mode; 4 fast cold load; 5 supervision; 6 logs; 7 security defaults; 8 the soak test (harness, criteria, multi-day command); 9 what was run and what happened; 10 open items.

1. What runs

systemd: leleka.service  (User=para, Restart=on-failure, starts at boot)
  `- leleka run --config STATE/leleka.json        the supervisor ("the holder": it owns the sealed archive)
       |- seals the 55 GB KAR archive into a memfd ONCE (O_DIRECT, 32 x 8 MiB blocks; 2.5 min cold)
       |- leleka-daemon      gateway, 127.0.0.1:18080
       |- leleka-inference   engine, gRPC 127.0.0.1:18766 (gets a duplicate of the memfd)
       `- strata-next serve  the API Codex talks to, 127.0.0.1:8081, bearer key in STATE/api-key

The service replaces the lab infrastructure for daily use: the Python KAR holder (run_holder2.sh), gpu.lock and the job stubs in ~/work/gpu-runs/holder2/jobs are not involved (nothing in the product reads them). They are mutually exclusive with the service (both want the GPU and 51 GB of RAM); section 3 says how to hand the machine from one to the other.

Layout on rnr5090 (all inside the work folder, which is a symlink to /data/leleka-e2e):

path content
/data/leleka-e2e/service/prefix/bin/ leleka, leleka-inference, leleka-daemon, leleka-cli, leleka-seal-exec, strata-next
/data/leleka-e2e/service/state/ leleka.json (run configuration), runtime.env + api-key (mode 0600), run/status.json, logs/, stamps/
/home/para/work/leleka/models/leleka-gates/assets/ shards, archive, MTP pack, tokenizer (read only; unchanged)
/data/leleka-e2e/service/ops/ install-leleka-service.sh, leleka.service (copies of scripts/ops/)

2. Owner steps

Everything below is run by the owner; the agent that wrote this did not run any of it on the server (no sudo, no system settings).

2.1 Binaries. Built in WSL from this branch (commit named in section 9) and copied; the server never builds. The agent left a build in /data/leleka-e2e/unattended/bin-12d1d71/ (the six binaries). To install them as the service prefix:

ssh rnr5090
mkdir -p /data/leleka-e2e/service/prefix /data/leleka-e2e/service/state

2.2 Prepare (as para, no sudo; the GPU must be free and the lab holder stopped, section 3). One command creates the state, tokens, API key, configs, verification stamps and installs the binaries; it starts nothing:

/data/leleka-e2e/unattended/bin-12d1d71/leleka up --mode none \
  --assets /home/para/work/leleka/models/leleka-gates/assets \
  --state-dir /data/leleka-e2e/service/state --prefix /data/leleka-e2e/service/prefix \
  --bin-src /data/leleka-e2e/unattended/bin-12d1d71 \
  --cublas-dir /home/para/cuda-toolkits/cublas-12.9.1.4/lib --trust-archive

It prints the preflight (13 checks), the resource plan and the exact engine command. If the profile came out as the file/mapped form instead of memfd/resident, the host did not have the 109 GiB it needs free at that moment (the lab holder is the usual reason; preflight now says so): stop it and run the command again.

2.3 Install and start (sudo, once).

The two files (install-leleka-service.sh, leleka.service) are in scripts/ops/ of the repository; there is no repository on the server, so the agent left a copy in /data/leleka-e2e/service/ops/ (same directory: the script looks for the unit next to itself).

sudo /data/leleka-e2e/service/ops/install-leleka-service.sh --install     # copies leleka.service, daemon-reload, enable, start
/data/leleka-e2e/service/ops/install-leleka-service.sh --status           # no sudo

--install refuses when the state is not prepared, when the lab holder runs (--force overrides), or when a binary is missing; --no-start installs and enables without starting; --remove stops, disables and deletes the unit (state, logs and models stay). The first start after a boot is the archive copy (2.6 min cold, section 4) plus the engine load (section 9); a later restart of the engine alone takes the load time only (the supervisor keeps the archive).

2.4 Use it. The API is http://127.0.0.1:8081; the key is in /data/leleka-e2e/service/state/api-key. For Codex on the server: base_url = "http://127.0.0.1:8081/v1", key from that file. From the laptop use an SSH tunnel (ssh -L 8081:127.0.0.1:8081 rnr5090); the service never listens on anything but loopback (section 7).

2.5 Look at it.

STATE=/data/leleka-e2e/service/state; LELEKA=/data/leleka-e2e/service/prefix/bin/leleka
$LELEKA status --state-dir $STATE        # ready?, supervisor phase and age, uptime, restarts and why, health, logs, GPU/RAM/throughput
$LELEKA verify --quick --state-dir $STATE --assets /home/para/work/leleka/models/leleka-gates/assets   # health without reading the model; exit 0 = OK
systemctl status leleka ; journalctl -u leleka -n 50
tail -n 30 $STATE/logs/leleka.log        # the supervisor's own log: every restart, every health finding

2.6 Update. Copy new binaries to a new directory, sudo systemctl stop leleka, run 2.2 again with --bin-src NEW (idempotent: it replaces the binaries by rename and keeps tokens and key), sudo systemctl start leleka.

3. Lab mode (hand the machine to the queue and back)

The lab queue (kar_holder2.py, gpu.lock, job stubs) and the service want the same GPU and the same 51 GB of RAM.

scripts/ops/install-leleka-service.sh --lab on     # creates STATE/lab-mode: the unit will not start while it exists (boot included)
sudo systemctl stop leleka                         # if it runs; then start the lab holder as before (run_holder2.sh)
...
touch ~/work/gpu-runs/holder2/jobs/STOP            # lab holder: stop between jobs; wait until its process is gone
scripts/ops/install-leleka-service.sh --lab off && sudo systemctl start leleka

leleka up and the install script both recognise a running kar_holder process and say so instead of failing with a bare memory number.

4. Fast cold load

Problem (docs/experiments/baseline-pair-5090.md, section 9). After a reboot the holder read the 55 GB archive with plain read() at 8-35 MB/s (2003.8 s for the first holder). The drive (Lexar NM610PRO, DRAM-less, max_sectors_kb 128) serves a 128 KiB request at a time to a sequential reader; it needs many requests in flight to be fast. The product's own copy (sealed.rs, 8 threads of buffered 32 MiB reads) was better but not enough, and the expert bank load (50 GB from shard 0) used one sequential read_exact loop.

Change. crates/model-format/src/bulk_read.rs: 32 threads each read 8 MiB blocks with O_DIRECT into aligned bounce buffers (the file is re-opened through its own /proc/self/fd entry; no unsafe), so the page cache is never touched: nothing to evict, and the free-memory state that vanilla's huge-page guard looks at stays as it was. Used by the sealed-archive copy, by the expert-bank read (spans >= 64 MiB) and, as a WILLNEED readahead, by the hashing passes. O_DIRECT falls back to WILLNEED/DONTNEED readahead where the file system refuses it. Knobs for A/B in one binary: LELEKA_LOAD_READ=direct|advise|plain|legacy, LELEKA_LOAD_THREADS, LELEKA_LOAD_CHUNK_MIB.

Measured (page cache of the span evicted with posix_fadvise(DONTNEED), never drop_caches; the drive is shared with other agents' jobs, so every number carries the other traffic; bulk_read_bench, /data/leleka-e2e/unattended/*.out):

MB/s 55 GB in
whole KAR file, new default (direct, 32 x 8 MiB), two runs 362, 346 153 s, 160 s
one thread, 16-32 MiB reads (the holder's pattern), four cold slices 65, 86, 105, 154 6-14 min
the recorded holder after a reboot 27 2003.8 s
8 threads x 32 MiB buffered (old sealed.rs), sharing the drive 240 3.8 min

Risk and lever. This host's root NVMe has stopped answering for minutes before (server-hang-autoreboot.sh; kernel.hung_task_panic=1, timeout 120 s). A deeper queue raises the bytes in flight (32 threads x 8 MiB = 256 MiB; at the worst rate seen, 8 MB/s, a block waits about 30 s, well under 120 s). dmesg (read only, sudo -n dmesg) showed no NVMe timeout or abort during any of the cold-read tests of this work (about 700 GB read, boot 06:07 to 20:26). If a timeout ever shows during a load, lower the depth without a rebuild: LELEKA_LOAD_THREADS=8 in STATE/runtime.env (the supervisor passes its environment on) and restart the unit.

The drive's speed varies up to 10x between regions and moments whatever the strategy (the same config measured 113 and 1133 MB/s), so the multi-thread strategies are not told apart by the 4x7 matrix in the commit message; all beat one thread; direct is the default because it leaves the cache alone. Target < 5 min: met for the archive copy (2.6 min). The engine's own load (verify stamps, bank copy, CUDA setup) is measured in section 9.

5. Supervision (what happens when something breaks)

event what the service does
engine process dies the API answers not-ready / errors at once; after 5 s (then 10, 20, ... up to 300 s) the supervisor starts the engine again with the same sealed archive (no 55 GB copy) and loads the model; a start that fails counts as an attempt and is retried; 6 attempts in a row (the counter resets after 10 ready minutes) end the service with exit 1 and systemd starts everything afresh (30 s, growing to 10 min, never gives up)
engine hangs (alive, not working) a request that gets no event for 600 s is cancelled by the API with an error to the client (stall_timeout_s); an engine that does not take the cancellation is declared lost by the API; after 120 s of "worker not ready" the supervisor SIGKILLs it and restarts it; a request still active after 3900 s (the API's own 3600 s deadline + 300) does the same
API process hangs or dies dies: restarted after 2 s (5 times); hangs (no answer to /metrics for 120 s): killed and restarted
gateway dies restarted after 2 s (3 times); serving does not depend on it
supervisor dies systemd restarts the unit; the sealed archive is copied again (2.6 min cold) and everything starts in order
a request fails HTTP 5xx / response.failed with a message, never an open connection: engine death mid-stream ends the stream with a failure event; a stall or an overlong generation is cancelled by the API (above)
SIGTERM / systemctl stop the API drains first, then gateway and engine (SIGINT, SIGKILL after the grace), exit 0; TimeoutStopSec=180
host reboot the unit is enabled; it starts after network.target once /data is mounted; lab mode (STATE/lab-mode) keeps it down

The judgement is crates/deploy/src/watchdog.rs (pure, unit-tested) over GET /metrics (the control plane's own view). The engine's telemetry is not used for it: the API refreshes it only between requests, so mid-request it is stale (a finding of this work; leleka status shows machine: null during a request longer than 30 s for the same reason).

Not covered: a process stuck in uninterruptible driver sleep cannot be killed (the supervisor says so and exits; only a reboot helps; the host already has server-hang-autoreboot.sh); GPU or driver faults that corrupt output without hanging.

6. Logs and disk

  • STATE/logs/{leleka,engine,gateway,api,preverify}.log, written by the children themselves in append mode. Every 10 s the supervisor copy-truncates any *.log over 16 MiB into .1 ... .3 (oldest dropped): at most 16 MiB x 4 x 5 files = 320 MiB, written in 16 MiB pieces (no stream of small writes). The engine is quiet by default (a few lines per request); trace switches stay off.
  • leleka.json logs: {limit_mib, keep} changes the bound. The status file reports log_bytes.
  • systemd: LimitCORE=0 (no 100 GB core dump on the root NVMe), journal rate limit 1000 messages / 30 s for the unit.
  • No request capture, transcript or response history is written by default (api_monitor is off; history is memory only).
  • Per-request telemetry: history stays in memory, and since claude/observability each request also leaves one numbers-only JSON line in requests.log (about 0.5 KB; no prompt, no output, no key; same rotation), the engine one line of its own for the same request id, and every process logs JSON lines under leleka run. leleka logs, leleka report and the README section "Observability" describe them.

7. Security defaults

  • The API binds 127.0.0.1:8081 (--api-bind only for containers); engine and gateway are loopback-only and refuse anything else in leleka.json validation. Remote access: SSH tunnel. No TLS inside the machine.
  • Every route except /health needs Authorization: Bearer <key>; the key is generated by strata-next api-key init (random, file 0600, never rotated by up); the two internal tokens live in runtime.env (0600) and reach children through their environment, never argv. HF_TOKEN is removed from every child. The unit runs with UMask=0077 and NoNewPrivileges=yes as the unprivileged user para.
  • No secret in a log: the supervisor never logs a command line with a token; the soak harness scans every log for the key and the tokens and fails if one appears (section 9).
  • leleka status --json and status.json hold no secret.

8. The soak test

scripts/soak/soak.py (Python, offline tooling; stdlib only) plays a Codex-style session against the running service and breaks it:

  • session: one conversation at a time, grown turn by turn from the frozen 782-file source corpus (/data/leleka-e2e/decode/corpus, digest checked; a toy corpus is refused) up to 200k tokens, then a new one; streamed POST /v1/responses, store:false, a shell function tool whose calls are answered; after an error it retries with backoff like a real client.
  • faults, injected while a request is in flight: engine (kill -9), hang (SIGSTOP the engine), api (kill -9), gateway (kill -9) and gateway-term, supervisor (kill -9 the holder), abort (client disconnects mid-stream), logs (64 MiB flood into three logs), burst (8 parallel requests).
  • criteria (all must hold; soak-result.json lists each with its measurement):
    1. every fault recovers within its bound (engine 900 s, hang stall + 900 s, API / gateway 120 s, supervisor 1500 s);
    2. no request ends improperly: every request ends with a completed response, an HTTP error or an SSE failure event; none hangs or is cut off silently; a request hit by a crash ends within 90 s, one hit by a hang within stall timeout + 150 s;
    3. a fixed greedy probe returns the same text before the first fault, after every fault and at the end (the state after recovery is sound);
    4. the log directory stays under 400 MiB through the log flood;
    5. no secret in any log; 6. supervisor descriptors stay bounded; 7. the session keeps completing requests; 8. the service is ready at the end.
  • scripts/soak/test_soak.py tests the harness against a fake service (no GPU).

Short run on the GPU (queue job, 1.5-2 h): scripts/soak/soak-job.sh as a holder job (it inherits the holder's memfd, takes gpu.lock, prepares the service state from nothing with leleka up --mode none, A/B-measures the cold load, then soaks under a restart loop that plays systemd including its cgroup kill of the children). The identity gate is scripts/soak/identity-job.sh.

Multi-day run (owner or agent, with the service installed, lab mode off):

python3 /data/leleka-e2e/unattended/soak/soak.py --state-dir /data/leleka-e2e/service/state --out /data/leleka-e2e/unattended/soak-long-1 \
  --duration-s 259200 \
  --faults "engine@every:7200,api@every:5400,gateway@every:9000,abort@every:1800,burst@every:4000,logs@every:21600,hang@every:43200,supervisor@every:86400"

(72 h; ~12 engine kills, 6 hangs, 3 supervisor kills with a cold re-seal each; the harness competes with real Codex use for the single engine slot, so run it when you are away. soak-result.json and events.jsonl (capped at 50 MiB) stay in the --out directory.)

9. What was run, what happened

Done without the GPU (laptop and server, 2026-11-02):

  • Cold read of the whole 51.5 GiB KAR file with the new reader: 153 s and 160 s; its block-digest chain 2ad20b40e676...a5a884 equals an independent plain sequential pass in Python (whole-digest-python.out, 7 min), so the copy is bit-exact for the whole file. leleka seal-probe (the service's own memfd copy) on two real files: dense.bin (1.5 GB) and experts.bin (0.7 GB), both read strategies, SHA-256 of memfd == SHA-256 of file (IDENTICAL).
  • leleka-deploy: 136 unit tests; e2e with the fake runtime: hang kill and restart, backoff and give-up, log rotation, killed API/gateway restarted in place, verify --quick, the existing lifecycle tests. Six e2e tests fail on this laptop exactly as on the base commit (environment: real GPU, a stale 3080 profile assertion).
  • soak.py against the fake service (test_soak.py): passes.
  • systemd-analyze verify (unprivileged) of leleka.service on the server: only "command not executable" because the prefix is not installed yet.

Identity gate on the GPU, run 2026-11-02 21:06-21:20Z (unattended-id, /data/leleka-e2e/unattended/id-1/, job log ~/work/gpu-runs/holder2/jobs/unattended-id.log): teacher-forced replay of night5-long-256k (5 requests, 240 forced decode tokens each, production shape, adaptive tier swaps on, seed off), ONE test binary (bin-rt/rt-unattended, sha256 309c2157..., built at 12d1d71d8), process 1 with LELEKA_LOAD_READ=legacy (the old sequential bank read), process 2 with the default (O_DIRECT, 32 x 8 MiB), two arms in each. Result: 2057 / 2057 top-16 logprob rows identical between the two processes in both arms (and A/A exact in each), 1036 / 1036 draft-trace lines identical ("DRAFT VERDICT: IDENTICAL"), 0 argmax flips, q_tail_gate PASS for both. The expert bank therefore holds the same bytes whichever way it is read. (The test binary prints no load laps, so the bank-load time is measured by the soak job's A/B below.)

Queued on the GPU, NOT run when this was written:

  • unattended-soak.sh -> /data/leleka-e2e/unattended/soak-run-1/ (job.log, soak/soak-result.json): seal-probe, leleka up from nothing, cold-load A/B (the leleka-load-time ... expert_bank_admission laps with LELEKA_LOAD_READ=legacy against the default), then 90 minutes of soak with the eight faults. Read soak/soak-result.json (criteria, faults). What recovered and what did not is whatever that file says; nothing is claimed here before it exists.

Until those two logs exist, the engine-side identity and the end-to-end recovery of the real stack are unverified.

10. Open items

  • The soak was run for 1.5 h, not for days; the multi-day command above is for the owner or the next agent.
  • LELEKA_ORIGINAL_SERVE_PCIE_FRAC is not set by the profile (the lab jobs pin 0.45); the adaptive-window defaults are being changed on claude/window-policy. The service runs the profile as committed; reconcile when that branch lands.
  • leleka status shows no machine telemetry while a request longer than 30 s runs (control plane refreshes it between requests).
  • The sealed memfd is in RAM only: a supervisor crash costs a 2.6 min re-copy (previously 25-55 min).
  • The e2e suite of leleka-deploy has 6 environment-dependent failures on the laptop (and one flaky lifecycle test) that exist on the base commit.