Merge codex/leleka-arxiv-paper into main: docs/ moved to MCP, 120-column formatting, CI fixes, hooks; conflicts resolved on main's side and re-formatted
Linux / keyless-cuda-gate (push) Skipped
Rust port / port-typecheck (push) Successful in 1m27s
Rust port / port-linux-tests (push) Failing after 4m34s
Rust port / port-fast (push) Successful in 5m56s
Desktop foundation / core (ubuntu-latest) (push) Successful in 5m7s
Linux / verify (push) Failing after 8m49s
Linux / keyless-cuda (push) Skipped
Linux / static-cuda-package (push) Skipped
Linux / hosted-cuda-package (push) Skipped
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Product / product (push) Failing after 16m46s
Rust port / port-oracles (push) Successful in 11m11s

This commit is contained in:
Pavlo Ratushnyi
2026-11-23 09:42:41 +01:00
1159 changed files with 9766 additions and 56239 deletions
+59
View File
@@ -0,0 +1,59 @@
{
"hooks": {
"PreCompact": [
{
"matcher": "auto",
"hooks": [
{
"type": "command",
"command": "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"$CLAUDE_PROJECT_DIR/.claude/hooks/precompact-permit.ps1\"",
"timeout": 30
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"$CLAUDE_PROJECT_DIR/.claude/hooks/stop-advisory.ps1\" > /dev/null 2>&1",
"timeout": 60
}
]
}
],
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-crr3-guard.ps1\"",
"timeout": 30
}
]
},
{
"matcher": "mcp__leasevibe__spec_delete|mcp__leasevibe__spec_import|mcp__leasevibe__memory_retire",
"hooks": [
{
"type": "command",
"command": "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-crr3-guard.ps1\"",
"timeout": 30
}
]
},
{
"matcher": "PowerShell",
"hooks": [
{
"type": "command",
"command": "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"$CLAUDE_PROJECT_DIR/.claude/hooks/pretooluse-crr3-guard.ps1\"",
"timeout": 30
}
]
}
]
}
}
-1
View File
@@ -13,7 +13,6 @@ engine/strata/*
engine/strata/serve/*
!engine/strata/serve/chat_template.jinja
benchmarks/
docs/
target/
dist/
**/target/
+3 -3
View File
@@ -8,9 +8,9 @@ scripts/gpu-bringup/**/*.py text=auto eol=lf
scripts/e2e/codex/tasks/** -text
scripts/e2e/codex/delta/** text eol=lf
# Release reproducibility (docs/release/5090-v0.1-checklist.md): the sealed PTX files are pinned by SHA-256 in the sources, so the bytes in the
# Release reproducibility: the sealed PTX files are pinned by SHA-256 in the sources, so the bytes in the
# working tree must be the bytes in the index on every platform. Without this line a Windows checkout with core.autocrlf=true turns 212 of the
# 273 .ptx files into CRLF (the other 61 end in a NUL byte, which git treats as binary) so the embedded PTX is not the sealed one (a CRLF checkout built a binary 9 MB smaller than every earlier one, docs/experiments/baseline-pair-5090.md part d).
# 273 .ptx files into CRLF (the other 61 end in a NUL byte, which git treats as binary) so the embedded PTX is not the sealed one (a CRLF checkout built a binary 9 MB smaller than every earlier one).
*.ptx -text
# The release packager and the files it copies into the tarball are POSIX shell and systemd text: LF everywhere.
scripts/release/** text eol=lf
@@ -19,7 +19,7 @@ deploy/rust-runtime/** text eol=lf
# The embedded expert profile is pinned by SHA-256 in the sources: the bytes in the working tree must be the bytes in the index on every platform.
crates/deploy/data/expert-profile.bin -text binary
# CI entry points run on Linux runners: LF whatever the checkout host's autocrlf says (docs/ci-audit.md).
# CI entry points run on Linux runners: LF whatever the checkout host's autocrlf says.
scripts/ci/** text eol=lf
scripts/check-local.sh text eol=lf
scripts/check-clippy-limits.sh text eol=lf
+1 -1
View File
@@ -29,7 +29,7 @@ jobs:
- name: Tests
run: cargo test --locked --manifest-path desktop-core/Cargo.toml
- name: Lints
# --no-deps: the path dependencies (leleka-model-format, leleka-cuda-driver, leleka-runtime) carry reported Clippy debt of their own (docs/ci-audit.md)
# --no-deps: the path dependencies (leleka-model-format, leleka-cuda-driver, leleka-runtime) carry reported Clippy debt of their own
run: cargo clippy --locked --manifest-path desktop-core/Cargo.toml --all-targets --no-deps -- -D warnings
- name: Hardware smoke (no inference)
# desktop-core ships six binaries and no default-run: name the one this smoke test runs
+22 -3
View File
@@ -1,6 +1,6 @@
name: Rust port
# Checks for the Rust port of the Original engine (docs/port-status.md). Everything here runs without a GPU, model
# Checks for the Rust port of the Original engine. Everything here runs without a GPU, model
# weights or tokens. The existing "Linux" workflow is unchanged; the jobs below add the port-specific gates:
# port-fast fmt, Clippy and tests on the host-buildable crates (scripts/check-local.sh --fast)
# port-typecheck Linux-only crates (cuda-driver with the cuda-driver feature, leleka-runtime) type-checked, not run
@@ -54,7 +54,7 @@ jobs:
cargo clippy --locked --target x86_64-unknown-linux-gnu --no-deps -p leleka-cuda-model -p leleka-cuda-driver --features cuda-driver -p leleka-engine-qwen35-cuda -p leleka-runtime --all-targets -- -D warnings
port-oracles:
# CPU oracle differentials: the Rust side against the UNMODIFIED Python tools (docs/offline-port.md) and the
# CPU oracle differentials: the Rust side against the UNMODIFIED Python tools and the
# sampler host shim. Optional until it has run green on the hosted runner; the committed goldens are replayed by
# port-fast regardless.
runs-on: ubuntu-latest
@@ -66,9 +66,22 @@ jobs:
- name: Install pinned Rust
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Oracle Python environment (no model data)
# numpy 2.5.x needs Python >= 3.12 and the runner's distro Python is older, so the numpy pin follows the
# interpreter exactly as engine/strata/requirements.txt does (2.5.4 on 3.12+, 2.4.6 on 3.11, 2.2.6 below).
# The oracle differentials compare against recorded goldens with tolerances, not against a numpy build.
run: |
python3 -m venv "$RUNNER_TEMP/oracle-venv"
"$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check numpy==2.5.4 PyYAML==6.0.3 tqdm==4.70.1 Jinja2==3.1.6 regex==2026.9.10
cat > "$RUNNER_TEMP/oracle-requirements.txt" <<'EOF'
numpy==2.5.4; python_version >= "3.12"
numpy==2.4.6; python_version == "3.11"
numpy==2.2.6; python_version < "3.11"
PyYAML==6.0.3
tqdm==4.70.1
Jinja2==3.1.6
regex==2026.9.10
EOF
"$RUNNER_TEMP/oracle-venv/bin/python" --version
"$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check -r "$RUNNER_TEMP/oracle-requirements.txt"
- name: Fetch the pinned llama.cpp gguf-py
run: |
commit="$(sed -n 's/^LLAMA_CPP_COMMIT = "\(.*\)"$/\1/p' engine/strata/setup.py)"
@@ -104,7 +117,13 @@ jobs:
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io
- name: Linux test harness
if: steps.present.outputs.present == 'true'
# The job runs in a container and uses the host's Docker daemon: the checkout path does not exist on that host,
# so the harness copies the source into the test container instead of bind-mounting it.
env:
LELEKA_TEST_COPY_SOURCE: '1'
run: scripts/linux-tests/run.sh
- name: Fake-libcuda mock gates (CPU-only ELF protocol tests of the driver)
if: steps.present.outputs.present == 'true'
env:
LELEKA_TEST_COPY_SOURCE: '1'
run: scripts/linux-tests/run.sh --mocks
+3 -3
View File
@@ -1,6 +1,6 @@
name: Product
# Builds and tests what actually ships (docs/ci-audit.md). The other workflows cover the legacy Strata-Next static CLI (linux.yml),
# Builds and tests what actually ships. The other workflows cover the legacy Strata-Next static CLI (linux.yml),
# the host-buildable port crates (port.yml) and desktop-core (desktop.yml); none of them built the `leleka` deploy binary, ran the
# tests of leleka-deploy, leleka-memory, leleka-runtime-client, leleka-runtime or leleka-cuda-driver, or compiled the six release
# binaries. This job runs `scripts/check-local.sh --product`, the same command a developer runs locally:
@@ -8,12 +8,12 @@ name: Product
# - scripts/check-architecture.py: dependency direction between layers, adapter edges, no new .rs over 400 lines, source ratchets
# (architecture.json is the policy, architecture-baseline.json the debt that may only fall; self-tests in check_architecture_test.py)
# - cargo build --locked (every default-member) and the release build of leleka, leleka-api, leleka-inference, leleka-daemon,
# leleka-cli, leleka-seal-exec (docs/deploy.md section 8)
# leleka-cli, leleka-seal-exec
# - cargo check of the CUDA-feature crates (leleka-cuda-driver --features cuda-driver, leleka-runtime)
# - cargo test of the product crates; the deploy end-to-end tests run against scripts/ci/nvidia-smi, a hermetic stand-in
# - rustfmt and Clippy -D warnings on the shipped crates; the known debt is reported (STRICT_DEBT=1 makes it fatal)
# No GPU, model weights or token is used. A green run proves the product compiles, links and passes its CPU-side tests; it does not
# prove any GPU kernel, model quality or speed (docs/ci-audit.md, section "What CI cannot prove").
# prove any GPU kernel, model quality or speed.
on:
push:
+5
View File
@@ -45,3 +45,8 @@ dist/
# The one binary kept in Git: upstream Strata's ranked expert profile (196,632 B, MIT, sha256 8f59b4aa...388975baf), embedded in `leleka`
# (crates/deploy/src/expert_profile.rs; attribution in crates/deploy/data/expert-profile.NOTICE). Every other *.bin stays ignored.
!crates/deploy/data/expert-profile.bin
# LeaseVibe (generated, host-local)
/AGENTS.md
/.leasevibe.yaml
/.claude/hooks/
-58
View File
@@ -1,58 +0,0 @@
# Repository instructions
Read `PROJECT_CHARTER.md` before changing architecture, performance policy, or scope. The charter is the source of truth for goals and milestones.
## Priorities
1. Preserve protocol correctness and successful task completion.
2. Preserve model quality and tool-call integrity.
3. Improve end-to-end agent throughput, then decode/prefill throughput.
## Change rules
- Keep production serving independent of Python. Python is allowed for offline conversion, calibration, experiments, and evaluations.
- Keep model weights, request captures, credentials, logs, and generated artifacts out of Git. Use external volumes or ignored local paths. Sanitize any fixture committed to the repository.
- Do not enable lossy optimizations by default until their separate quality gate passes. Mark experimental modes explicitly. Recorded exception: the 5090 profiles run the lossy route tail skip by default, an explicit owner decision of 2026-11-13 that overrode the open points of its quality gate (`docs/deploy.md` section 4).
- For non-lossy changes, compare greedy output or tensor values against the defined baseline and record numerical tolerances.
- Do not label a change as a performance improvement without paired A/B measurements on the same workload and a quality result. Record hardware, software, model digest, configuration, cache state, token counts, and distributions as required by the charter.
- Do not conflate a synthetic kernel gain with an end-to-end agent workload gain. Report both when relevant.
- Dependency direction, file sizes and source patterns are gated by `scripts/check-architecture.py` (policy `architecture.json`, debt `architecture-baseline.json`, run by `scripts/check-local.sh --product`). A number in the baseline may only fall; lower it with `--update-baseline`, never raise it without `--allow-increase` and a reason in review.
- Keep the Strata upstream commit and local changes traceable. Do not overwrite or silently replace the upstream provenance record.
## Repository state
The Strata source is present under `engine/strata/` at the commit recorded in `docs/upstream.md` and is not modified. `engine/strata` is the
reference (the "Original"); the product is the Rust/CUDA port of its Original mode17 serve path:
* `crates/engine-qwen35-cuda` (the Qwen3.5 CUDA engine family: prefill, MTP speculative decode, expert tiers, KV streaming; `crates/leleka-runtime` is its facade), `crates/engine-core` (the pure engine domain: prefix cache, conversation policy, prompt plan, speculative-decoding policies, request lifecycle, the `EngineFamily` seam), `crates/engine-fake` (the scripted engine family for GPU-free tests), `crates/cuda-driver`
(CUDA Driver API, sealed PTX, NVML sampler; its pure host-side models are `crates/cuda-model`), `crates/leleka-memory` (memory governor, pressure gate, telemetry), `desktop-core` and
`crates/runtime-client` (the gRPC contract between the engine process and the gateway), `control-plane` (HTTP/Responses gateway), `crates/deploy`
(the `leleka` binary: `up/run/status/verify`, memory profiles, resource presets).
* The layers (L0 to L4), the ports, how to add an engine family and what the architecture gates check: `docs/architecture/hexagonal.md`.
* Measured on an RTX 5090 server with real Codex CLI sessions (`docs/e2e-run.md`, `docs/ledger.md`, `docs/quality-gate.md`, `docs/prefix-cache.md`,
`docs/deploy.md`, `docs/roofline.md`); the RTX 3080 laptop is a secondary, experimental target (`docs/laptop-profile.md`).
* The port is complete for the 5090 serve path; open work is listed in `docs/port-remaining.md` and the ledger.
* The CPU/iGPU/NPU runtime for gpt-oss (`crates/cpu-*`, `gptoss*`, `harmony`, `igpu*`, `npu-*`, `gguf`, `kar-codec`; `docs/cpu-runtime.md`) is served through the same
control plane: `codec::TextCodec` selects the family (Qwen3.5 or gpt-oss/Harmony) and `engine.extra_workers` runs a worker pool (`docs/worker-pool.md`).
The pool, `lazy_load`/`idle_unload_s`, `vision` and the `runtime` block are separate modes; the config rejects combining them (`docs/api-contract.md`).
## Worktrees
- Create worktrees inside the main repository's git directory, never as sibling folders of `~/work`: `scripts/dev/worktree.sh new <name> [<branch>]` makes `.git/wt/<name>`. The files are ordinary; only the location is hidden from the file listing.
- Clean up when a branch has been merged: `scripts/dev/worktree.sh clean` lists the clean, merged worktrees and `--yes` removes them. Uncommitted changes block the removal; commit them to the branch first. Do this at the end of every task that created a worktree and before starting a new batch, so no more than a handful exist at a time.
- Build output (`target/`, `dist/`) lives in the worktree and goes with it; a removed worktree never deletes its branch.
## Workspace layout
One folder per machine (owner rule, 2026-10-29). Outside it, read only: no creating, moving, renaming or deleting anything, and no relocating other people's files.
- Laptop: `C:\Users\pavel\work\leleka` (worktrees, build output and run directories under `.git/wt`). Never create, list or clean sibling folders of the repository, and keep WSL builds inside it too (`CARGO_TARGET_DIR` inside the worktree).
- 5090 server (`rnr5090`): `~/work/leleka/` only, the same name as on the laptop. It is a symlink to `/data/leleka-e2e/` because the root disk is small; the data lives on `/data`. Do not add anything to `~/work` itself or to any other folder. Known exception until the holder is re-homed: the GPU queue (`~/work/gpu-runs/holder2/jobs/` stubs and `PRIORITY`) is written there, nothing else.
- Models live inside the work folder too (owner decision, 2026-10-29): server `~/work/leleka/models/{leleka-gates,deepseek-v41-flash}/` (absolute `/home/para/work/leleka/models/...`), laptop `C:\Users\pavel\work\leleka\models\`. Scripts, profiles and docs name those paths; a model path outside the work folder is a bug.
- Name each path after its task (`<task-id>` or `<task-id>-<purpose>`); one directory per task, not one per attempt.
- Clean up your own paths at the end of the task. Do not hard-delete: anything deletable goes into the `garbage/` folder inside the work folder (laptop `leleka/garbage`, server `~/work/leleka/garbage`) with a line in `garbage/LOG.txt`. The owner empties it.
- Evidence cited in a task record keeps its path until the cited change is merged; after a move, update the record with the new path.
- An agent's final report lists every path it created, and any path outside the places above is moved in before the task is closed.
- Measurement inputs are not scratch: a corpus, expert profile, prompt set, binary or helper script that a measurement depends on lives in one named directory (server: `/data/leleka-e2e/decode/` or the task's own directory), is frozen read-only, and is recorded with its sha256 in a manifest and in the run metadata. A run refuses to start when an input is missing or its digest differs. Never read an input from `~/work`, a home directory or a sibling folder that nobody owns. The 2026-10-29 incident: the 245k corpus lived in an unowned folder, a cleanup removed it, and the "256k" session silently became ~300 tokens.
Read `engine/strata/AGENTS.md` before modifying imported engine code.
+1 -1
View File
@@ -14,7 +14,7 @@ unsafe_code = "forbid"
[workspace.lints.clippy]
all = "warn"
# Opt-in profile for paired A/B builds (STRA-245 parity audit, docs/experiments/parity-audit-5090.md item 10). The workspace has no
# Opt-in profile for paired A/B builds (STRA-245 parity audit). The workspace has no
# [profile] section, so every shipped binary (bin-e2e4, crates/deploy) is the cargo release default: opt-level 3, no LTO,
# 16 codegen units, panic=unwind, no RUSTFLAGS and no target-cpu (the last on purpose: the CPU kernels select their GGML
# arithmetic branches with cfg!(target_feature), see crates/native-cpu-expert/src/rust_ggml_native.rs, so target-cpu would change bits).
+2 -2
View File
@@ -10,7 +10,7 @@ This is a bounded core-path ledger, not a whole-project completion certificate.
| Original source / function | Current Rust boundary | Required completion |
| --- | --- | --- |
| `src/core/mtp.cpp:143` `MtpDrafter::load`; `:380` `bind`; `:677` `kv_restore`; `include/strata/core/mtp.hpp` `idle/device/tensor_*` | SOURCE-COMPLETE, NOT GPU-RUN (2026-10-14, branch `claude/port-mtp-loader`). `original_mtp_rt.rs` reads dense.txt/dense.bin/experts.bin/draft_vocab.bin; `original_mtp_bank.rs` places them (Original order, nine-name check last); `original_mtp_loader.rs` plans geometry/session/KV/coupled and admits the retained ring; `original_mtp_draft_head.rs` gathers the subset head; `original_mtp_actor_loaded.rs` adopts the genuine drafter and links `idle/device/kv_restore/set_*/draft*/coupled`. Runtime: `RetainedOriginalMtpWeights::from_rt_bank`, `OriginalMtpFullOwner::assemble_rt`, `OriginalPromptExecutor::select_rt_mtp` and the actor-driven `draft_committed_mtp`/`draft_first_committed_mtp`. | Remaining is GPU-only evidence: run the ignored `original_mtp_bank_gpu` tests (`LELEKA_MTP_RT_BANK_GPU=yes`), a real-pack load, and compare drafts with the Original. `OriginalServeStack::open` (`qwen_forward/original_serve_stack.rs`) now calls `select_rt_mtp` (option `--mtp-rt-dir`) or the pinned-pack assembly, and the serve loop drives `draft_committed_mtp` (`OriginalServeHost::draft_committed`); `draft_first` stays CLI-only (the serve loop never reaches it). Not repeated: Original `cudaMemset(cring_, 0xff)`; the Original single-allocation `dense_` (each indexed tensor is its own allocation, same total bytes); `tensor_f32/bf16/q8` host accessors (roles are the retained `Rc<DeviceBuffer>` bank). |
| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. The concrete aggregate is `OriginalVerifyWindowResources` (`original_verify_window_ops.rs`). | `OriginalVerifyWindowOps` now has capture-time producers for every former `UNBOUND_PRODUCERS` entry (pure planners over SHA-pinned sealed PTX: projections/head, GR, GDN, QSA, MoE; unit-tested against verify.cpp order). Still open: seal `original_verify_window_moe_experts.ptx` and `original_verify_window_qsa_gate.ptx` (`docs/cuda-seal-plan-additions-window.json`; the window fails closed with those names until then), GPU smokes/golden comparisons per kernel and for a whole window, the fast-math re-seal question listed in that JSON, and the hardware run. The runtime-side wiring (weights, QSA/PLE journals, CPU pool callbacks, graph registration before `run`) is SOURCE-WIRED, NOT GPU-RUN on `claude/port-serve-host`: `original_serve_verifier::assemble` builds the canonical GDN image, the QSA journal over the prompt executor's twelve resident owners, the PLE history and the window/commit aggregates per decode phase; `original_serve_pool` is the CPU callback (all-CPU expert tier: the driver publishes the empty plan). The asset probe (`original_serve_asset_status`) lists the unsealed assets and any producer still unbound, so `--backend-mode auto` stays on the preview path until they are sealed and `original` refuses naming them. |
| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. The concrete aggregate is `OriginalVerifyWindowResources` (`original_verify_window_ops.rs`). | `OriginalVerifyWindowOps` now has capture-time producers for every former `UNBOUND_PRODUCERS` entry (pure planners over SHA-pinned sealed PTX: projections/head, GR, GDN, QSA, MoE; unit-tested against verify.cpp order). Still open: seal `original_verify_window_moe_experts.ptx` and `original_verify_window_qsa_gate.ptx` (`crates/cuda-driver/seal-plans/cuda-seal-plan-additions-window.json`; the window fails closed with those names until then), GPU smokes/golden comparisons per kernel and for a whole window, the fast-math re-seal question listed in that JSON, and the hardware run. The runtime-side wiring (weights, QSA/PLE journals, CPU pool callbacks, graph registration before `run`) is SOURCE-WIRED, NOT GPU-RUN on `claude/port-serve-host`: `original_serve_verifier::assemble` builds the canonical GDN image, the QSA journal over the prompt executor's twelve resident owners, the PLE history and the window/commit aggregates per decode phase; `original_serve_pool` is the CPU callback (all-CPU expert tier: the driver publishes the empty plan). The asset probe (`original_serve_asset_status`) lists the unsealed assets and any producer still unbound, so `--backend-mode auto` stays on the preview path until they are sealed and `original` refuses naming them. |
| `mtp.cpp` `draft/draft_first` and `verify.cpp` `run/commit/wait_commit`, used together by mode17 generation | SOURCE-WIRED, NOT GPU-RUN. `OriginalServeEngine` implements `OriginalSpecEngine` over `NativeServePort`, which binds the driver `OriginalVerifier`; `OriginalServeHost` (`original_serve_host.rs`) supplies the owners (window PLE rows, penalty-history sampling, expert pool, lineage ledger, session publication of the accepted prefix, MTP history/restore/drain) and `OriginalServeStack` drives prompt + decode. `OriginalServeSettings::controller` is called by the stack; `--backend-mode` selects it in the serving owner. Commit and draft are serialized (the commit event completes and the session is published before the draft launches), so the Original's commit/draft overlap is not reproduced. | Hardware run of `backend_original_serve_smoke.rs` (`LELEKA_ORIGINAL_SERVE_SMOKE=yes`), then parity and a keep-the-overlap pass. |
| `include/strata/core/verify.hpp` `set_stage/set_next`; `src/core/verify.cpp:191,1054,1382,1412`; `core/on_device.hpp` | `OriginalVerifier` loops all 48 layers, has no next-stage owner or stage handoff fields. Context identity exists, but the unselected MTP actor cannot infer an actual current CUDA device ordinal. | Port stage bounds, mapped portable R+pending-bo+inject handoff, next-user CPU dispatch and last-stage head/sampling/final_R/commit forwarding. This is an absent multi-GPU mode17 leaf, not a single-device quality defect. |
| `verify.cpp:137,158,899,1323,1422` public release/diag/profile/logprob/logit APIs | Internal Rust bounded wait release, commit event and completed-row bridge are present. No equivalent public diagnostic/watchdog registry, profile report, window_logprobs or copy_logits API was found in the inspected Original Rust modules. | Expose the actual live verifier release/diagnostic owner; port literal GPU-stage stamps and completed logit/logprob readout (including LOGPOS_TOPK). Keep capture-only graphs inadmissible for readout. Do not call the existing internal release absent. |
@@ -21,7 +21,7 @@ This is a bounded core-path ledger, not a whole-project completion certificate.
mapped/fallback embedding, T1..8 head rows, request sampling/history and MTP
head-weight loans. `model-format/src/gguf_native_head.rs` has shard/architecture
and `strata-embd` override parsing. The owners are bound by `OriginalServeStack`/`OriginalServeHost`
(see docs/original-serve.md); the remaining gap is the unbound window producers and the GPU run.
(see spec node original-serve.md); the remaining gap is the unbound window producers and the GPU run.
- NativeHead's earlier penalties-off empty-history refusal is already corrected
in current `native_head.rs:140..158`; do not reopen that stale finding.
- Verifier GDN/QSA accepted-prefix journals, stream release and async commit event
+10 -10
View File
@@ -3,11 +3,11 @@
Leleka is a Rust/CUDA inference runtime for coding agents. Release **0.1** serves one model, **Qwen3.8-Flash-Next IQ3_S** (KAR level-2 PLE, MTP speculative
decode), on **one RTX 5090 (32 GB)** at **262,144 tokens of context**, to Codex CLI and other clients over the Responses, Chat Completions and Messages APIs.
It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (reference copy in `engine/strata/`, pinned at
upstream `41cf05a0`, see `docs/upstream.md`). Serving needs no Python and no CUDA toolkit on the host.
upstream `41cf05a0`, see `engine/upstream.md`). Serving needs no Python and no CUDA toolkit on the host.
**Status of 0.1.** It runs real Codex sessions to completion and decodes about 155 tok/s on the 245k-token benchmark of the 5090 server (section "Numbers").
It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `docs/release/RELEASE-NOTES-5090-v0.1.md`;
every gate and its evidence: `docs/release/5090-v0.1-checklist.md`.
It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `spec node release/RELEASE-NOTES-5090-v0.1.md`;
every gate and its evidence: `spec node release/5090-v0.1-checklist.md`.
## Requirements
@@ -30,21 +30,21 @@ curl -H "Authorization: Bearer $(cat STATE/api-key)" http://127.0.0.1:8081/v1/mo
```
The API listens on loopback only (use an SSH tunnel); the key is in `STATE/api-key`. Codex CLI: `wire_api = "responses"`, `base_url = "http://127.0.0.1:8081/v1"`, `web_search = "disabled"`.
Details, every flag, upgrade and rollback: `docs/deploy.md`, `docs/unattended.md` (running it as a boot-time service: `scripts/ops/`, installed by the owner of the machine, never by the release).
Details, every flag, upgrade and rollback: `spec node deploy.md`, `spec node unattended.md` (running it as a boot-time service: `scripts/ops/`, installed by the owner of the machine, never by the release).
Upgrade: stop the service, keep a copy of `STATE/*.json`, unpack the new release, run its `install.sh` with the same flags. Rollback: restore the copies and run the previous release's `install.sh`.
## Numbers (measured, paired, one workload)
Decode tok/s on the frozen 245k-token corpus (5 turns x 300 output tokens, greedy, RTX 5090, Ryzen 9 9950X3D), ours against vanilla Strata 0.2.6 on fresh boots, vanilla in its good
huge-page state (`docs/experiments/baseline-pair-5090.md`, section 10, 3 balanced blocks): **ours 155.4** (sd 2.4), vanilla v1 (its shipped lossy defaults) 137.0 (ahead of it in 3 of 3 blocks, +13.5 %),
huge-page state (`spec node experiments/baseline-pair-5090.md`, section 10, 3 balanced blocks): **ours 155.4** (sd 2.4), vanilla v1 (its shipped lossy defaults) 137.0 (ahead of it in 3 of 3 blocks, +13.5 %),
vanilla v2 (lossless-comparable) 144.7 (ahead in **2 of 3** blocks, +9.2 %; vanilla v2 is bimodal and ran 171.2 once, 10.8 % faster than ours). Later changes: the faster draft attention is bitwise identical and
shortens a round by 2.7 % (tok/s +0.5 % +- 0.6 %, not significant); the window policy default +1.1 % +- 1.2 % (not resolved, no speedup claimed); the single-copy memory layout
(`docs/kar-sparse-memfd.md`) is identical in output (2057/2057 logprob rows, 1036/1036 draft traces) and frees 36.6 GiB of RAM at 245k (MemAvailable 8.5 to 45.1 GiB; tok/s +0.58 %, n.s.).
(`spec node kar-sparse-memfd.md`) is identical in output (2057/2057 logprob rows, 1036/1036 draft traces) and frees 36.6 GiB of RAM at 245k (MemAvailable 8.5 to 45.1 GiB; tok/s +0.58 %, n.s.).
These are decode speeds of a benchmark, not agent-task times.
## Quality and limits
* Not bit-identical to the Original; deviations are inside the Original's own rounding envelope where tested (`docs/quality-gate.md`), and **there is no 245k port-versus-Original equality gate yet** (STRA-337).
* Not bit-identical to the Original; deviations are inside the Original's own rounding envelope where tested (`spec node quality-gate.md`), and **there is no 245k port-versus-Original equality gate yet** (STRA-337).
KAR level-2 PLE, chain kernels, prefill chunk 8192, request-end prefix checkpoints and the adaptive expert tier have no 256k gate. All evidence is greedy.
* Lossy modes are **off**: route tail skip gave +15 % decode but failed its quality gate; keyless KV failed too. Tool calls are the model's: malformed ones are refused, not repaired.
* One generation at a time (queue of 16); images and `reasoning_budget_tokens` are refused; RTX 3080 and Windows are not part of 0.1; no multi-hour soak on the release commit (post-release feedback).
@@ -78,7 +78,7 @@ What the service is doing, and why a request was slow or failed, is in its logs;
- `control-plane/`, `desktop-core/` — the HTTP/Responses gateway (`leleka-api`) and the engine/daemon processes.
- `engine/strata/` — the pinned upstream Strata, the reference (unmodified by Leleka).
- `deploy/`, `scripts/` — profiles, service templates, release packager (`scripts/release/`), test and measurement tooling (Python is allowed there, never in serving).
- `PROJECT_CHARTER.md`, `docs/` — requirements, provenance, decisions, gates and measurements. Architecture: `docs/architecture/hexagonal.md`.
- `PROJECT_CHARTER.md`, the LeaseVibe spec (imported repository documentation) — requirements, provenance, decisions, gates and measurements. Architecture: spec node `architecture/hexagonal.md`.
Model weights, request captures, credentials, logs and generated artifacts stay outside Git.
@@ -87,9 +87,9 @@ Model weights, request captures, credentials, logs and generated artifacts stay
```sh
cargo test --workspace --locked
cargo clippy --workspace --all-targets --all-features -- -D warnings
scripts/release/package-5090.sh check # the release gates; `package` builds the release set (docs/release/5090-v0.1-checklist.md)
scripts/release/package-5090.sh check # the release gates; `package` builds the release set (spec node release/5090-v0.1-checklist.md)
```
## Licence
MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `docs/release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`).
MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`).
@@ -1,5 +1,5 @@
# ttt browser checks (Chromium 1148 via playwright 1.49.1, software GL, laptop; each page one run at a time, 2026-11-05)
# first column: check_ttt.mjs (thirds probe, scripts/e2e/codex/tasks/ttt/hidden), second: check_ttt_v2.mjs (gap-clustering probe, docs/e2e-data/codex-compare)
# first column: check_ttt.mjs (thirds probe, scripts/e2e/codex/tasks/ttt/hidden), second: check_ttt_v2.mjs (gap-clustering probe)
LELK-r1 check_ttt.mjs rc=0 6 pass, 0 fail, SUMMARY 6/6
LELK-r1 check_ttt_v2.mjs rc=1 3 pass, 3 fail, SUMMARY 3/6
LELK-r2 check_ttt.mjs rc=0 6 pass, 0 fail, SUMMARY 6/6
+1 -1
View File
@@ -1,4 +1,4 @@
# Laptop profile paired prompts (docs/laptop-profile.md): one user turn per line, thinking off, 128 new tokens.
# Laptop profile paired prompts: one user turn per line, thinking off, 128 new tokens.
Write a Python function that converts an ISO-8601 duration string such as P3DT4H12M5S into a total number of seconds. Reject years and months with a clear ValueError, validate the whole input with one regular expression, and add three short doctest examples. After the code, explain in two sentences which edge cases you considered and why.
Explain to a junior engineer how a write-ahead log makes a database safe against crashes. Cover what is written before the data pages change, how recovery replays or discards log records after a power loss, why the order of fsync calls matters, and one common performance trade-off. Use a short numbered list followed by a one-paragraph summary.
You are reviewing a pull request that changes a Rust HTTP server to stream responses as server-sent events. List the five most important things to check for correctness, including client cancellation, backpressure, errors that happen after the first byte was sent, and the terminal event. For each item, describe one concrete test you would write.
@@ -44,9 +44,9 @@ build) much larger than 0.005 mean KL is suspect.
`cargo run --release -p leleka-gptoss-igpu --example dump_logprobs_gpu -- <model.gguf> ids.txt gpu.jsonl 20`
prefills the ids on the integrated GPU (every position's hidden state), projects each on the CPU and writes the
same format. Against `llama-reference.jsonl` (two kernel variants, see the table in `docs/igpu-prefill.md`): 97.1% / mean KL 0.0100 and 95.3% / 0.0121; first variant: best token agrees 97.1% (372/383), mean KL 0.0100, NLL 1.2976 vs
same format. Against `llama-reference.jsonl` (two kernel variants, see the table in `spec node igpu-prefill.md`): 97.1% / mean KL 0.0100 and 95.3% / 0.0121; first variant: best token agrees 97.1% (372/383), mean KL 0.0100, NLL 1.2976 vs
1.2828. Against the CPU decoder's own dump: 97.4% (373/383), mean KL 0.0067, NLL 1.2976 vs 1.2979. Details and
caveats in `docs/igpu-prefill.md`.
caveats in `spec node igpu-prefill.md`.
## Longer reference set (`set2/`, 2026-10-15)
@@ -1,7 +1,7 @@
# paired prefill A/B (warm)
model: gpt-oss-20b-MXFP4.gguf (12109565632 bytes, sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB)
cpu: 14 threads, kernels avx-vnni; gpu: Intel(R) Graphics (Vulkan), batch 512; context capacity = prompt + 1
date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see docs/igpu-prefill.md)
date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see spec node igpu-prefill.md)
## 512 prompt tokens, 5 pairs
pair first cpu s gpu s speed-up next tokens
@@ -28,7 +28,7 @@ paired speed-up cpu/gpu: mean 3.40x, 95% CI [2.77, 4.04], median 3.26x (5 pairs)
# paired prefill A/B (warm)
model: gpt-oss-20b-MXFP4.gguf (12109565632 bytes, sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB)
cpu: 14 threads, kernels avx-vnni; gpu: Intel(R) Graphics (Vulkan), batch 512; context capacity = prompt + 1
date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see docs/igpu-prefill.md)
date: 2026-10-15 00:50 (hardware/driver/power state are not controlled; see spec node igpu-prefill.md)
## 2048 prompt tokens, 3 pairs
pair first cpu s gpu s speed-up next tokens
@@ -1,7 +1,7 @@
# real KAR codec roundtrip, teacher-forced against llama.cpp (benchmarks/quality/gpt-oss-20b-teacher-forced/set2/table-igpu, 770 positions)
model: gpt-oss-20b-MXFP4.gguf (sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB); dump_logprobs 14 threads, top 20; avx-vnni
codec: crates/kar-codec (moved unchanged from control-plane/src/kar_codec.rs), group 32, codebook fitted per tensor to 65,536 evenly sampled values; reconstruction stored as Q8_0
baseline (8-bit attention/output, MXFP4 experts): 93.4% agreement, mean KL 0.016 (docs/cpu-runtime.md)
baseline (8-bit attention/output, MXFP4 experts): 93.4% agreement, mean KL 0.016 (spec node cpu-runtime.md)
date: 2026-10-16; the first table was built in the shared checkout and reproduced exactly (4 levels, all tensors) from a clean worktree build
## attention + output weights, LELEKA_EXPERIMENTAL_KAR_LEVELS=3..6
@@ -1,7 +1,7 @@
# paired prefill A/B (warm)
model: gpt-oss-20b-MXFP4.gguf (12109565632 bytes, sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB)
cpu: 14 threads, kernels avx-vnni; npu service device: Intel(R) AI Boost, batch 2048; context capacity = prompt + 1
date: 2026-10-15 12:22 (hardware/driver/power state are not controlled; see docs/npu-service.md)
date: 2026-10-15 12:22 (hardware/driver/power state are not controlled; see spec node npu-service.md)
## 1024 prompt tokens, 3 pairs
pair first cpu s npu s speed-up next tokens
+1 -1
View File
@@ -4,7 +4,7 @@
.DESCRIPTION
Read-only. Uses the same locale-independent forms as the command catalogue in
docs/reference-hardware/win-core-ultra-7-265u-npu.md (C04, C07, C08, C09, C11, C13, C14, C15, C17, C18):
spec node reference-hardware/win-core-ultra-7-265u-npu.md (C04, C07, C08, C09, C11, C13, C14, C15, C17, C18):
CIM classes, setting GUIDs and ISO-8601 UTC times, no parsing of translated labels. Every benchmark run
calls this before and after and stores both objects with its results.
+1 -1
View File
@@ -1,4 +1,4 @@
# Thresholds of the Clippy limits ratchet (STRA-367, lawbook 301, docs/architecture/limits-gate.md).
# Thresholds of the Clippy limits ratchet (STRA-367, lawbook 301).
# too_many_lines and cognitive_complexity are allow-by-default lints: these two numbers change nothing for the default
# `cargo clippy ... -D warnings` gates, and no source enables the lints. scripts/check-clippy-limits.sh turns them on as
# warnings and ratchets the count per crate.
+1 -1
View File
@@ -19,4 +19,4 @@ cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-respons
cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-responses -- --sse benchmarks/fixtures/responses/structured-tool.json
```
See [API contract](../docs/api-contract.md) for the supported subset and remaining integration work.
See API contract (spec node `api-contract.md`) for the supported subset and remaining integration work.
+6 -23
View File
@@ -26,11 +26,8 @@ fn main() {
type BuildResult<T> = Result<T, Box<dyn std::error::Error>>;
/// The three variables that configure an embedded engine: all unset, or all set.
const ENGINE_VARS: [&str; 3] = [
"STRATA_EMBED_ENGINE_PATH",
"STRATA_EMBED_ENGINE_SHA256",
"STRATA_EMBED_ENGINE_REVISION",
];
const ENGINE_VARS: [&str; 3] =
["STRATA_EMBED_ENGINE_PATH", "STRATA_EMBED_ENGINE_SHA256", "STRATA_EMBED_ENGINE_REVISION"];
fn embed_engine() -> BuildResult<()> {
use std::{env, fs, path::PathBuf};
@@ -70,16 +67,8 @@ fn write_payload(
return Ok((String::new(), String::new()));
}
let file = open_engine(values)?;
let digest = values[1]
.as_ref()
.unwrap()
.to_str()
.ok_or("digest must be ASCII")?;
let revision = values[2]
.as_ref()
.unwrap()
.to_str()
.ok_or("revision must be ASCII")?;
let digest = values[1].as_ref().unwrap().to_str().ok_or("digest must be ASCII")?;
let revision = values[2].as_ref().unwrap().to_str().ok_or("revision must be ASCII")?;
embedded_spec::copy_verified(
file,
fs::File::create(payload_path)?,
@@ -141,11 +130,7 @@ fn engine_assembly(path: &str) -> String {
}
/// Assembles the payload into the crate and returns the Rust declaration of `BYTES` for it.
fn payload_declaration(
output: &std::path::Path,
payload_path: &std::path::Path,
size: u64,
) -> BuildResult<String> {
fn payload_declaration(output: &std::path::Path, payload_path: &std::path::Path, size: u64) -> BuildResult<String> {
// Keep large verified payloads out of Rust constant evaluation/LLVM IR.
// The target assembler copies the bytes into an immutable ELF section.
let path = payload_path.to_str().ok_or("payload path must be UTF-8")?;
@@ -155,9 +140,7 @@ fn payload_declaration(
let path = path.replace('\\', "\\\\").replace('"', "\\\"");
let assembly = output.join("embedded-engine.S");
std::fs::write(&assembly, engine_assembly(&path))?;
cc::Build::new()
.file(assembly)
.compile("strata_embedded_payload");
cc::Build::new().file(assembly).compile("strata_embedded_payload");
Ok(format!(
"unsafe extern \"C\" {{ static strata_embedded_engine_bytes: [u8; {size}]; }}\n\
// SAFETY: build.rs emits exactly {size} verified bytes in read-only storage.\n\
+2 -10
View File
@@ -33,11 +33,7 @@ fn compare_blocks(source: &mut File, blocks: u64) -> Result<(), Failure> {
source.read_exact(&mut block)?;
let rust = iq3_s::decode_block(&block)?;
ggml_bridge::decode_into(21, &block, &mut ggml)?;
if let Some(position) = rust
.iter()
.zip(&ggml)
.position(|(left, right)| left.to_bits() != right.to_bits())
{
if let Some(position) = rust.iter().zip(&ggml).position(|(left, right)| left.to_bits() != right.to_bits()) {
return Err(format!(
"block {number}, value {position}: Rust={:#010x}, ggml={:#010x}",
rust[position].to_bits(),
@@ -53,11 +49,7 @@ fn main() -> Result<(), Failure> {
let (path, requested) = parse_args()?;
let path = Path::new(&path);
let index = gguf::tensor_index(path)?;
let tensor = index
.tensors
.iter()
.find(|tensor| tensor.kind == 21)
.ok_or("GGUF has no IQ3_S tensor")?;
let tensor = index.tensors.iter().find(|tensor| tensor.kind == 21).ok_or("GGUF has no IQ3_S tensor")?;
let blocks = requested.min(tensor.bytes / iq3_s::BLOCK_BYTES as u64);
let mut source = File::open(path)?;
source.seek(SeekFrom::Start(index.summary.data_start + tensor.offset))?;
+2 -12
View File
@@ -45,13 +45,7 @@ fn parse_args() -> Result<Args, Failure> {
if args.next().is_some() || count == 0 || count > 1_000_000 {
return Err(USAGE.into());
}
Ok(Args {
source_path,
archive_path,
level,
start,
count,
})
Ok(Args { source_path, archive_path, level, start, count })
}
/// `(elements, bytes)` of one block of the supported source kinds.
@@ -94,11 +88,7 @@ impl ErrorSums {
}
fn relative_l2(&self) -> f64 {
if self.reference == 0.0 {
self.error.sqrt()
} else {
(self.error / self.reference).sqrt()
}
if self.reference == 0.0 { self.error.sqrt() } else { (self.error / self.reference).sqrt() }
}
}
+18 -66
View File
@@ -13,9 +13,7 @@ pub(super) static MAX_OUTPUT: AtomicU64 = AtomicU64::new(0);
pub(super) static STORE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub(super) fn unix_ms() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis())
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis())
}
pub(super) fn number_after(text: &[u8], key: &[u8]) -> u64 {
@@ -31,39 +29,22 @@ pub(super) fn number_after(text: &[u8], key: &[u8]) -> u64 {
pub(super) fn find(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
let start = from.saturating_sub(needle.len());
haystack[start.min(haystack.len())..]
.windows(needle.len())
.position(|w| w == needle)
.map(|p| p + start)
haystack[start.min(haystack.len())..].windows(needle.len()).position(|w| w == needle).map(|p| p + start)
}
const FIRST_DELTA_EVENTS: [&[u8]; 3] = [
b"response.reasoning_text.delta",
b"response.output_text.delta",
b"response.function_call_arguments.delta",
];
const FIRST_DELTA_EVENTS: [&[u8]; 3] =
[b"response.reasoning_text.delta", b"response.output_text.delta", b"response.function_call_arguments.delta"];
const TERMINAL_EVENTS: [&str; 3] = [
"response.completed",
"response.incomplete",
"response.failed",
];
const TERMINAL_EVENTS: [&str; 3] = ["response.completed", "response.incomplete", "response.failed"];
/// The first terminal event name found in the body (empty when there is none).
fn terminal_event(text: &[u8]) -> String {
TERMINAL_EVENTS
.into_iter()
.find(|name| find(text, 0, name.as_bytes()).is_some())
.unwrap_or("")
.to_owned()
TERMINAL_EVENTS.into_iter().find(|name| find(text, 0, name.as_bytes()).is_some()).unwrap_or("").to_owned()
}
/// `input_tokens` / `cached_tokens` of the terminal event's usage.
fn usage_of(tail: &[u8]) -> (u64, u64) {
(
number_after(tail, b"\"input_tokens\":"),
number_after(tail, b"\"cached_tokens\":"),
)
(number_after(tail, b"\"input_tokens\":"), number_after(tail, b"\"cached_tokens\":"))
}
/// What has arrived of one response so far, with the instants the replay measures.
@@ -120,16 +101,10 @@ impl ReplyScan {
};
self.header_end = Some(end + 4);
let head = String::from_utf8_lossy(&self.data[..end]).to_ascii_lowercase();
self.status = head
.split_whitespace()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0);
self.status = head.split_whitespace().nth(1).and_then(|s| s.parse().ok()).unwrap_or(0);
self.chunked = head.contains("transfer-encoding: chunked");
self.content_length = head
.lines()
.find_map(|l| l.strip_prefix("content-length: "))
.and_then(|v| v.trim().parse::<usize>().ok());
self.content_length =
head.lines().find_map(|l| l.strip_prefix("content-length: ")).and_then(|v| v.trim().parse::<usize>().ok());
true
}
@@ -137,10 +112,7 @@ impl ReplyScan {
fn mark_events(&mut self, before: usize, start: usize) {
if self.t_first_delta == 0 {
let from = self.scanned.max(start).min(before.max(start));
if FIRST_DELTA_EVENTS
.iter()
.any(|name| find(&self.data, from, name).is_some())
{
if FIRST_DELTA_EVENTS.iter().any(|name| find(&self.data, from, name).is_some()) {
self.t_first_delta = now_ns();
}
}
@@ -148,10 +120,7 @@ impl ReplyScan {
if self.t_created == 0 && find(&self.data, from, b"response.created").is_some() {
self.t_created = now_ns();
}
if self.t_completed == 0
&& TERMINAL_EVENTS
.iter()
.any(|name| find(&self.data, from, name.as_bytes()).is_some())
if self.t_completed == 0 && TERMINAL_EVENTS.iter().any(|name| find(&self.data, from, name.as_bytes()).is_some())
{
self.t_completed = now_ns();
}
@@ -188,8 +157,7 @@ impl ReplyScan {
t_first_delta: self.t_first_delta,
t_completed: self.t_completed,
saw_function_call: find(text, 0, b"\"type\":\"function_call\"").is_some(),
saw_completed: terminal == "response.completed"
|| find(text, 0, b"\"status\":\"completed\"").is_some(),
saw_completed: terminal == "response.completed" || find(text, 0, b"\"status\":\"completed\"").is_some(),
sent_unix_ms: self.sent_unix_ms,
done_unix_ms: unix_ms(),
usage: usage_of(tail),
@@ -199,19 +167,12 @@ impl ReplyScan {
}
async fn send_request(conn: &mut TcpStream, path: &str, body: &[u8], stream: bool) {
let auth = AUTH
.get()
.map(|value| format!("Authorization: Bearer {value}\r\n"))
.unwrap_or_default();
let auth = AUTH.get().map(|value| format!("Authorization: Bearer {value}\r\n")).unwrap_or_default();
let head = format!(
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\n\
Content-Length: {}\r\nAccept: {}\r\n{auth}\r\n",
body.len(),
if stream {
"text/event-stream"
} else {
"application/json"
}
if stream { "text/event-stream" } else { "application/json" }
);
conn.write_all(head.as_bytes()).await.unwrap();
conn.write_all(body).await.unwrap();
@@ -263,12 +224,7 @@ pub(super) fn load_session(path: &str) -> Session {
instructions: doc["instructions"].as_str().unwrap().to_owned(),
tools: doc["tools"].as_array().unwrap().clone(),
items: doc["items"].as_array().unwrap().clone(),
rounds: doc["rounds"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_u64().unwrap() as usize)
.collect(),
rounds: doc["rounds"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap() as usize).collect(),
capture_items: doc["capture_items"].as_u64().unwrap_or(0) as usize,
capture_ids: doc["capture_prompt_ids"]
.as_array()
@@ -309,16 +265,12 @@ pub(super) async fn token_count(conn: &mut TcpStream, session: &Session, round:
let bytes = serde_json::to_vec(&body).unwrap();
// reuse the sender, response is small JSON
let reply = request_raw(conn, "/v1/responses/input_tokens", &bytes).await;
let value: Value =
serde_json::from_str(&reply).unwrap_or_else(|_| panic!("input_tokens reply: {reply}"));
let value: Value = serde_json::from_str(&reply).unwrap_or_else(|_| panic!("input_tokens reply: {reply}"));
value["input_tokens"].as_u64().unwrap() as usize
}
pub(super) async fn request_raw(conn: &mut TcpStream, path: &str, body: &[u8]) -> String {
let auth = AUTH
.get()
.map(|value| format!("Authorization: Bearer {value}\r\n"))
.unwrap_or_default();
let auth = AUTH.get().map(|value| format!("Authorization: Bearer {value}\r\n")).unwrap_or_default();
let head = format!(
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\n{auth}\r\n",
body.len()
@@ -19,8 +19,7 @@ pub struct EngineMarks {
pub last_prompt: Mutex<Option<String>>,
}
pub(super) static KEEP_PROMPT: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
pub(super) static KEEP_PROMPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// How long the instant engine waits after taking the prompt before its first token (a real engine needs far longer;
/// the wait lets the response's opening events leave first, as they do in production).
@@ -55,12 +54,8 @@ pub(super) fn reply_text() -> String {
/// Stamps the arrival of the prompt and records its size, hash and (for `--verify`) text.
fn record_request(marks: &EngineMarks, request: &GenerationRequest) {
marks.received.store(now_ns(), Ordering::SeqCst);
marks
.prompt_bytes
.store(request.prompt.len() as u64, Ordering::SeqCst);
marks
.prompt_hash
.store(fnv(request.prompt.as_bytes()), Ordering::SeqCst);
marks.prompt_bytes.store(request.prompt.len() as u64, Ordering::SeqCst);
marks.prompt_hash.store(fnv(request.prompt.as_bytes()), Ordering::SeqCst);
if KEEP_PROMPT.load(Ordering::Relaxed) {
*marks.last_prompt.lock().unwrap() = Some(request.prompt.clone());
}
@@ -78,21 +73,14 @@ fn spawn_reply(reply: Vec<String>, marks: Arc<EngineMarks>, sink: GenerationSink
} else if gap > 0 {
std::thread::sleep(Duration::from_micros(gap));
}
if sink
.emit(GenerationEvent::TextDelta { text: piece })
.is_err()
{
if sink.emit(GenerationEvent::TextDelta { text: piece }).is_err() {
return;
}
}
marks.terminal.store(now_ns(), Ordering::SeqCst);
let _ = sink.complete(
FinishReason::Stop,
Usage {
input_tokens: input,
output_tokens: 420,
reused_input_tokens: input * 97 / 100,
},
Usage { input_tokens: input, output_tokens: 420, reused_input_tokens: input * 97 / 100 },
);
});
}
+7 -25
View File
@@ -4,20 +4,11 @@ use super::*;
/// The key (read from a file, never printed), the model name and the output cap of the `--live` requests.
fn set_live_credentials(args: &[String]) {
let key = std::fs::read_to_string(arg(args, "--key-file").expect("--key-file"))
.expect("key file")
.trim()
.to_owned();
let key =
std::fs::read_to_string(arg(args, "--key-file").expect("--key-file")).expect("key file").trim().to_owned();
AUTH.set(key).ok();
MODEL
.set(arg(args, "--model").unwrap_or_else(|| "qwen-iq3".into()))
.ok();
MAX_OUTPUT.store(
arg(args, "--max-output-tokens")
.and_then(|v| v.parse().ok())
.unwrap_or(48),
Ordering::Relaxed,
);
MODEL.set(arg(args, "--model").unwrap_or_else(|| "qwen-iq3".into())).ok();
MAX_OUTPUT.store(arg(args, "--max-output-tokens").and_then(|v| v.parse().ok()).unwrap_or(48), Ordering::Relaxed);
}
async fn connect_all(urls: &[String]) -> Vec<TcpStream> {
@@ -32,18 +23,11 @@ async fn connect_all(urls: &[String]) -> Vec<TcpStream> {
}
/// `--first-round R`, or the round whose prompt is closest to `--size N` tokens.
async fn first_live_round(
conn: &mut TcpStream,
session: &Session,
args: &[String],
turns: usize,
) -> usize {
async fn first_live_round(conn: &mut TcpStream, session: &Session, args: &[String], turns: usize) -> usize {
match arg(args, "--first-round").and_then(|v| v.parse::<usize>().ok()) {
Some(round) => round,
None => {
let size: usize = arg(args, "--size")
.and_then(|v| v.parse().ok())
.unwrap_or(60000);
let size: usize = arg(args, "--size").and_then(|v| v.parse().ok()).unwrap_or(60000);
closest_round(conn, session, size, turns).await
}
}
@@ -76,9 +60,7 @@ pub(super) async fn live(targets: &str, session: Session, args: &[String]) {
let names: Vec<String> = arg(args, "--names")
.map(|v| v.split(',').map(str::to_owned).collect())
.unwrap_or_else(|| (0..urls.len()).map(|i| format!("arm{i}")).collect());
let turns: usize = arg(args, "--turns")
.and_then(|v| v.parse().ok())
.unwrap_or(24);
let turns: usize = arg(args, "--turns").and_then(|v| v.parse().ok()).unwrap_or(24);
let mut conns = connect_all(&urls).await;
let first = first_live_round(&mut conns[0], &session, args, turns).await;
let first = first.min(session.rounds.len().saturating_sub(turns));
+17 -59
View File
@@ -1,4 +1,4 @@
//! Host-side latency replay (`docs/cp-latency.md`): Codex-shaped Responses requests with a growing history sent over
//! Host-side latency replay: Codex-shaped Responses requests with a growing history sent over
//! real loopback HTTP to the real router, the real worker adapter and the real tokenizer, in front of an *instant*
//! engine that returns a canned reply the moment it has the prompt. Everything this prints is therefore the cost of the
//! control plane outside the engine, per stage; it says nothing about the engine.
@@ -34,6 +34,7 @@ use live::*;
mod verify;
use verify::*;
use leleka_control_plane::app::{EngineLink, ModelView};
use std::{
collections::BTreeMap,
io::Write as _,
@@ -44,14 +45,11 @@ use std::{
},
time::{Duration, Instant},
};
use leleka_control_plane::app::{EngineLink, ModelView};
use leleka_backend_api::{
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent,
GenerationRequest, GenerationSink, GenerationStream, InferenceMode, LoadedModel, RuntimeConfig,
SupportedModelTuple, Usage,
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent, GenerationRequest,
GenerationSink, GenerationStream, InferenceMode, LoadedModel, RuntimeConfig, SupportedModelTuple, Usage,
};
use serde_json::{Value, json};
use leleka_control_plane::{
app::{AppState, router},
backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker},
@@ -59,6 +57,7 @@ use leleka_control_plane::{
tokenizer::Tokenizer,
worker::{WorkerState, WorkerStatus},
};
use serde_json::{Value, json};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
@@ -66,18 +65,13 @@ use tokio::{
};
fn arg(args: &[String], name: &str) -> Option<String> {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1).cloned())
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
}
#[allow(dead_code)]
#[tokio::main]
async fn main() {
run(std::env::args().collect(), async |marks| {
Box::new(InstantBackend::new(marks)) as Box<dyn Backend>
})
.await;
run(std::env::args().collect(), async |marks| Box::new(InstantBackend::new(marks)) as Box<dyn Backend>).await;
}
/// The command-line choices of the plain replay.
@@ -94,17 +88,10 @@ fn replay_plan(args: &[String]) -> ReplayPlan {
.split(',')
.map(|s| s.parse().unwrap())
.collect();
let turns: usize = arg(args, "--turns")
.and_then(|v| v.parse().ok())
.unwrap_or(24);
let turns: usize = arg(args, "--turns").and_then(|v| v.parse().ok()).unwrap_or(24);
let stream = !args.iter().any(|a| a == "--json-response");
let label = arg(args, "--label").unwrap_or_else(|| "run".into());
ReplayPlan {
sizes,
turns,
stream,
label,
}
ReplayPlan { sizes, turns, stream, label }
}
/// `--store`, `--engine-delay-ms` and `--delta-gap-us` reach the client and the instant engine through statics.
@@ -121,9 +108,7 @@ fn set_load_flags(args: &[String]) {
}
fn exit_with_usage() -> ! {
eprintln!(
"usage: cp_replay TOKENIZER_DIR SESSION.json [--sizes a,b] [--turns n] [--out file] [--json-response]"
);
eprintln!("usage: cp_replay TOKENIZER_DIR SESSION.json [--sizes a,b] [--turns n] [--out file] [--json-response]");
std::process::exit(2);
}
@@ -172,13 +157,7 @@ async fn connect(addr: std::net::SocketAddr) -> TcpStream {
}
/// Replays one history size: finds its round, then measures `turns` consecutive rounds on a fresh stack.
async fn replay_size<F>(
tokenizer_dir: &Path,
session: &Session,
make: &F,
plan: &ReplayPlan,
size: usize,
) -> Value
async fn replay_size<F>(tokenizer_dir: &Path, session: &Session, make: &F, plan: &ReplayPlan, size: usize) -> Value
where
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
{
@@ -198,12 +177,7 @@ where
}
/// Picks the round whose prompt is closest to `size` tokens (counted by the server itself).
async fn closest_round(
conn: &mut TcpStream,
session: &Session,
size: usize,
turns: usize,
) -> usize {
async fn closest_round(conn: &mut TcpStream, session: &Session, size: usize, turns: usize) -> usize {
let (mut low, mut high) = (0usize, session.rounds.len() - 1);
while low < high {
let mid = (low + high) / 2;
@@ -232,10 +206,7 @@ async fn replay_turns(
let body = body_at(session, round, plan.stream);
let reply = request(conn, "/v1/responses", &body, plan.stream).await;
assert_eq!(reply.status, 200, "turn {turn}");
assert!(
reply.saw_completed && reply.saw_function_call,
"turn {turn}: incomplete reply"
);
assert!(reply.saw_completed && reply.saw_function_call, "turn {turn}: incomplete reply");
rows.push(turn_row((turn, round), body.len(), &stack.marks, &reply));
}
rows
@@ -250,12 +221,7 @@ fn stages_json() -> serde_json::Map<String, Value> {
stage_json
}
fn turn_row(
(turn, round): (usize, usize),
body_len: usize,
marks: &EngineMarks,
reply: &Reply,
) -> Value {
fn turn_row((turn, round): (usize, usize), body_len: usize, marks: &EngineMarks, reply: &Reply) -> Value {
let received = marks.received.load(Ordering::SeqCst);
let first_delta = marks.first_delta.load(Ordering::SeqCst);
let terminal = marks.terminal.load(Ordering::SeqCst);
@@ -290,10 +256,7 @@ fn print_summary(label: &str, size: usize, first: usize, rows: &[Value]) {
rows[0]["prompt_bytes"].as_f64().unwrap() / 1024.0,
warm.len()
);
println!(
"{:<22} {:>9} {:>9} {:>9}",
"metric (ms)", "cold", "p50", "p95"
);
println!("{:<22} {:>9} {:>9} {:>9}", "metric (ms)", "cold", "p50", "p95");
for key in ["pre_engine_ms", "first_event_ms", "tail_ms", "wall_ms"] {
println!(
"{:<22} {:>9.2} {:>9.2} {:>9.2}",
@@ -310,19 +273,14 @@ fn print_stage_rows(cold: &Value, warm: &[&Value]) {
let mut stage_names: BTreeMap<String, Vec<f64>> = BTreeMap::new();
for row in warm {
for (name, value) in row["stages"].as_object().unwrap() {
stage_names
.entry(name.clone())
.or_default()
.push(value["ms"].as_f64().unwrap());
stage_names.entry(name.clone()).or_default().push(value["ms"].as_f64().unwrap());
}
}
for (name, values) in &stage_names {
println!(
" stage {:<18} {:>9.2} {:>9.2} {:>9.2}",
name,
cold["stages"]
.get(name)
.map_or(f64::NAN, |v| v["ms"].as_f64().unwrap()),
cold["stages"].get(name).map_or(f64::NAN, |v| v["ms"].as_f64().unwrap()),
percentile(values, 0.5),
percentile(values, 0.95)
);
+3 -14
View File
@@ -47,9 +47,7 @@ fn app_state(
},
model: ModelView {
name: Some("fixture".into()),
tokenizer: Some(Arc::new(leleka_control_plane::codec::qwen_codec_shared(
tokenizer.clone(),
))),
tokenizer: Some(Arc::new(leleka_control_plane::codec::qwen_codec_shared(tokenizer.clone()))),
..Default::default()
},
..Default::default()
@@ -101,10 +99,7 @@ fn spawn_worker(
config,
status,
stop_rx,
WorkerInbox {
requests: requests_rx,
control: control_rx,
},
WorkerInbox { requests: requests_rx, control: control_rx },
));
(stop, requests, control, worker)
}
@@ -122,13 +117,7 @@ where
let state = app_state(&status, requests, control, &tokenizer);
let (addr, server) = serve(router(state)).await;
await_ready(&status).await;
Stack {
addr,
marks,
stop,
worker,
server,
}
Stack { addr, marks, stop, worker, server }
}
impl Stack {
+5 -20
View File
@@ -6,19 +6,9 @@ use super::*;
fn check_prompt_ids(reference: &Tokenizer, round: usize, prompt: &str, counted: usize) -> Vec<u32> {
let fast = reference.encode(prompt, true).unwrap();
let slow = reference.encode_reference(prompt, true).unwrap();
assert_eq!(
fast, slow,
"round {round}: fast path ids differ from the reference"
);
assert_eq!(
fast.len(),
counted,
"round {round}: input_tokens differs from the ids"
);
assert!(
reference.decodes_to(&fast, prompt.as_bytes()),
"round {round}: ids do not decode to the prompt"
);
assert_eq!(fast, slow, "round {round}: fast path ids differ from the reference");
assert_eq!(fast.len(), counted, "round {round}: input_tokens differs from the ids");
assert!(reference.decodes_to(&fast, prompt.as_bytes()), "round {round}: ids do not decode to the prompt");
fast
}
@@ -84,10 +74,7 @@ async fn verify_round(
return false;
}
check_capture(reference, session, round, &fast);
println!(
"CAPTURE round={round} tokens={} identical to the captured prompt ids",
fast.len()
);
println!("CAPTURE round={round} tokens={} identical to the captured prompt ids", fast.len());
true
}
@@ -103,9 +90,7 @@ where
{
KEEP_PROMPT.store(true, Ordering::Relaxed);
let reference = Tokenizer::from_assets(tokenizer_dir).expect("tokenizer assets");
let step: usize = arg(args, "--verify-step")
.and_then(|v| v.parse().ok())
.unwrap_or(1);
let step: usize = arg(args, "--verify-step").and_then(|v| v.parse().ok()).unwrap_or(1);
let stack = start_stack(tokenizer_dir, make).await;
let mut conn = connect(stack.addr).await;
let mut checked = 0;
+6 -26
View File
@@ -1,30 +1,19 @@
//! Model-free routed-expert fixture, using the production KAR writer.
use leleka_control_plane::kar_writer::{self, SourceIdentity, Tensor, TensorData};
use sha2::{Digest, Sha256};
use std::path::Path;
use leleka_control_plane::kar_writer::{self, SourceIdentity, Tensor, TensorData};
const H: u64 = 64;
const F: u64 = 32;
const E: u64 = 2;
const ROLE_BYTES: usize = (H * F * E * 4) as usize;
const NAMES: [&str; 3] = [
"blk.0.ffn_gate_exps.weight",
"blk.0.ffn_up_exps.weight",
"blk.0.ffn_down_exps.weight",
];
const NAMES: [&str; 3] = ["blk.0.ffn_gate_exps.weight", "blk.0.ffn_up_exps.weight", "blk.0.ffn_down_exps.weight"];
/// The three raw F32 tensors: expert 0 is 1/32 everywhere and expert 1 is -1/32.
fn raw_source() -> Vec<u8> {
(0..3)
.flat_map(|_| {
(0..H * F * E).flat_map(|i| {
(if i < H * F {
1.0f32 / 32.0
} else {
-1.0f32 / 32.0
})
.to_le_bytes()
})
(0..H * F * E).flat_map(|i| (if i < H * F { 1.0f32 / 32.0 } else { -1.0f32 / 32.0 }).to_le_bytes())
})
.collect()
}
@@ -54,15 +43,7 @@ fn expert_tensor<'a>(
source_dtype: 0,
source_digest: Sha256::digest(&raw[role * ROLE_BYTES..(role + 1) * ROLE_BYTES]).into(),
source_offset: (role * ROLE_BYTES) as u64,
data: TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 1,
scales,
books,
planes,
},
data: TensorData::Nested { group: 32, nesting: 0, planes_min: 1, planes_max: 1, scales, books, planes },
}
}
@@ -80,9 +61,8 @@ fn main() -> Result<(), String> {
let raw = raw_source();
let source = source_identity(&raw);
let dims = [[H, F, E], [H, F, E], [F, H, E]];
let tensors: Vec<_> = (0..3)
.map(|role| expert_tensor(role, &raw, &dims[role], (&scales, &books, &planes)))
.collect();
let tensors: Vec<_> =
(0..3).map(|role| expert_tensor(role, &raw, &dims[role], (&scales, &books, &planes))).collect();
kar_writer::write_archive(Path::new(&args[1]), &source, &tensors)?;
Ok(())
}
+5 -17
View File
@@ -3,30 +3,20 @@
use std::{collections::BTreeMap, env, fs::File, path::Path};
use sha2::{Digest, Sha256};
use leleka_control_plane::{gguf, gguf_f32_stream};
use sha2::{Digest, Sha256};
type Failure = Box<dyn std::error::Error>;
fn all_finite(values: &[u8]) -> bool {
values
.as_chunks::<4>()
.0
.iter()
.all(|word| f32::from_le_bytes(*word).is_finite())
values.as_chunks::<4>().0.iter().all(|word| f32::from_le_bytes(*word).is_finite())
}
/// Decodes the first block of `tensor` and prints its element count and the SHA-256 of the decoded values.
fn scan_kind(
source: &mut File,
data_start: u64,
(kind, tensor): (u32, &gguf::TensorInfo),
) -> Result<(), Failure> {
fn scan_kind(source: &mut File, data_start: u64, (kind, tensor): (u32, &gguf::TensorInfo)) -> Result<(), Failure> {
let (expected_elements, bytes) =
gguf::block_geometry(kind).ok_or_else(|| format!("unsupported source kind {kind}"))?;
let absolute = data_start
.checked_add(tensor.offset)
.ok_or("GGUF tensor offset overflow")?;
let absolute = data_start.checked_add(tensor.offset).ok_or("GGUF tensor offset overflow")?;
let mut hasher = Sha256::new();
let decoded_bytes = gguf_f32_stream::visit(source, absolute, kind, bytes, |_, values| {
if !all_finite(values) {
@@ -48,9 +38,7 @@ fn scan_kind(
}
fn main() -> Result<(), Failure> {
let path = env::args()
.nth(1)
.ok_or("usage: scan-quant-blocks FILE.gguf")?;
let path = env::args().nth(1).ok_or("usage: scan-quant-blocks FILE.gguf")?;
let path = Path::new(&path);
let index = gguf::tensor_index(path)?;
let mut first_by_kind = BTreeMap::new();
+3
View File
@@ -0,0 +1,3 @@
# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line.
max_width = 120
use_small_heuristics = "Max"
+3 -15
View File
@@ -22,10 +22,7 @@ impl ChannelEngine {
}
/// A command channel of `capacity` places and its engine; the worker side reads the receiver.
pub fn channel(
capacity: usize,
clock: SharedClock,
) -> (SharedEngine, mpsc::Receiver<GenerationCommand>) {
pub fn channel(capacity: usize, clock: SharedClock) -> (SharedEngine, mpsc::Receiver<GenerationCommand>) {
let (sender, receiver) = mpsc::channel(capacity);
(Arc::new(Self::new(sender, clock)), receiver)
}
@@ -37,17 +34,8 @@ impl ChannelEngine {
}
impl EngineClient for ChannelEngine {
fn submit(
&self,
command: GenerationCommand,
budget: Option<Duration>,
) -> BoxFuture<'_, Result<(), Error>> {
Box::pin(queue::enqueue_with(
&self.sender,
command,
budget,
self.clock.clone(),
))
fn submit(&self, command: GenerationCommand, budget: Option<Duration>) -> BoxFuture<'_, Result<(), Error>> {
Box::pin(queue::enqueue_with(&self.sender, command, budget, self.clock.clone()))
}
fn queue_capacity(&self) -> usize {
+2 -8
View File
@@ -8,10 +8,7 @@ use crate::{
};
impl VisionEncoder for Vision {
fn encode_all<'a>(
&'a self,
sources: &'a [String],
) -> BoxFuture<'a, Result<Vec<Encoded>, VisionError>> {
fn encode_all<'a>(&'a self, sources: &'a [String]) -> BoxFuture<'a, Result<Vec<Encoded>, VisionError>> {
Box::pin(async move {
// Encode only while the engine is idle: the gate is also taken for every engine generation.
let _turn = self.gate.lock().await;
@@ -23,10 +20,7 @@ impl VisionEncoder for Vision {
})
}
fn combine<'a>(
&'a self,
images: &'a [Encoded],
) -> BoxFuture<'a, Result<(PathBuf, Keep), VisionError>> {
fn combine<'a>(&'a self, images: &'a [Encoded]) -> BoxFuture<'a, Result<(PathBuf, Keep), VisionError>> {
Box::pin(Vision::combine(self, images))
}
}
+4 -15
View File
@@ -16,10 +16,7 @@ pub(super) async fn lifecycle_status(State(state): State<AppState>) -> Json<serd
&& lifecycle.requests_in_flight == 0
&& lifecycle.generation_jobs == 0
&& worker.metrics.active_since.is_none()
&& matches!(
worker.state,
WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded
);
&& matches!(worker.state, WorkerState::Ready | WorkerState::Unconfigured | WorkerState::Unloaded);
Json(
serde_json::json!({"service":"leleka-control-plane", "server_pid":std::process::id(), "model":state.model.name,
"draining":lifecycle.draining,
@@ -75,17 +72,9 @@ pub(super) async fn resume(State(state): State<AppState>, headers: HeaderMap) ->
/// `GET /metrics`: the native JSON document, or its Prometheus text exposition (`?format=prometheus`, or an `Accept`
/// that asks for `text/plain` / OpenMetrics, as a Prometheus scraper sends). `?requests=all` lists every kept
/// generation, not the last 12.
pub(super) async fn metrics(
State(state): State<AppState>,
RawQuery(query): RawQuery,
headers: HeaderMap,
) -> Response {
let accept = headers
.get(axum::http::header::ACCEPT)
.and_then(|v| v.to_str().ok());
let all = query
.as_deref()
.is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
pub(super) async fn metrics(State(state): State<AppState>, RawQuery(query): RawQuery, headers: HeaderMap) -> Response {
let accept = headers.get(axum::http::header::ACCEPT).and_then(|v| v.to_str().ok());
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
+11 -35
View File
@@ -23,9 +23,7 @@ impl Gathered {
let memory = state.model.memory.status();
let (hardware, hardware_static, telemetry, history) = state.model.memory.hardware();
let busy = generation.active_since.is_some();
let elapsed_ms = generation
.active_since
.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64);
let elapsed_ms = generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64);
Self {
worker,
busy,
@@ -41,22 +39,14 @@ impl Gathered {
/// The value while a request is running, `null` otherwise.
fn while_busy(&self, value: &serde_json::Value) -> serde_json::Value {
if self.busy {
value.clone()
} else {
serde_json::Value::Null
}
if self.busy { value.clone() } else { serde_json::Value::Null }
}
fn engine_state(&self, phase: Option<&str>) -> serde_json::Value {
if self.worker.state != WorkerState::Ready {
serde_json::to_value(self.worker.state).unwrap_or(serde_json::Value::Null)
} else if self.busy {
serde_json::json!(if phase == Some("prefill") {
"reading"
} else {
"generating"
})
serde_json::json!(if phase == Some("prefill") { "reading" } else { "generating" })
} else {
serde_json::json!("idle")
}
@@ -92,16 +82,8 @@ impl Gathered {
/// Identity, queue and memory gate of the process.
fn process_block(&self, state: &AppState) -> serde_json::Value {
let queue_capacity = state
.engine
.client
.as_ref()
.map(|engine| engine.queue_capacity());
let queue_used = state
.engine
.client
.as_ref()
.map(|engine| engine.queue_used());
let queue_capacity = state.engine.client.as_ref().map(|engine| engine.queue_capacity());
let queue_used = state.engine.client.as_ref().map(|engine| engine.queue_used());
serde_json::json!({
"schema_version": 1,
"scope": "control_plane_process",
@@ -122,8 +104,7 @@ impl Gathered {
fn generation_block(&self, state: &AppState) -> serde_json::Value {
let generation = self.worker.metrics;
let decode_rate =
crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms);
let decode_rate = crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms);
serde_json::json!({
"generation": generation,
"done_decode_tokens_per_second": decode_rate,
@@ -134,11 +115,9 @@ impl Gathered {
fn requests_block(&self, state: &AppState, all_requests: bool) -> serde_json::Value {
let (requests, requests_kept, totals) = match self.worker.metrics.history {
Some(history) => (
history.requests((!all_requests).then_some(RECENT_REQUESTS)),
history.kept(),
history.totals(),
),
Some(history) => {
(history.requests((!all_requests).then_some(RECENT_REQUESTS)), history.kept(), history.totals())
}
None => (Vec::new(), 0, serde_json::Value::Null),
};
serde_json::json!({
@@ -182,8 +161,7 @@ pub async fn metrics_document(state: &AppState, all_requests: bool) -> serde_jso
/// Seconds since the API started, on the state's clock.
pub(crate) fn uptime_s(state: &AppState) -> u64 {
let now = state.services.clock.system_time();
now.duration_since(state.services.started_at)
.map_or(0, |d| d.as_secs())
now.duration_since(state.services.started_at).map_or(0, |d| d.as_secs())
}
/// The supervisor's own account (`LELEKA_STATUS_FILE`, set by `leleka run`): restarts and uptime of the service.
@@ -198,9 +176,7 @@ pub(super) fn supervisor_block() -> serde_json::Value {
let Ok(status) = serde_json::from_str::<serde_json::Value>(&text) else {
return serde_json::Value::Null;
};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
serde_json::json!({
"phase": status["phase"],
"restarts_total": status["restarts_total"],
+3 -14
View File
@@ -9,15 +9,8 @@ pub(super) async fn ready(State(state): State<AppState>) -> (StatusCode, Json<St
&& state.model.tokenizer.is_some()
&& state.engine.client.is_some()
&& !state.lifecycle.snapshot().draining;
let code = if inference_ready {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
code,
Json(status_body(worker, inference_ready, state.model.name)),
)
let code = if inference_ready { StatusCode::OK } else { StatusCode::SERVICE_UNAVAILABLE };
(code, Json(status_body(worker, inference_ready, state.model.name)))
}
pub(super) async fn status(State(state): State<AppState>) -> Json<StatusResponse> {
@@ -40,11 +33,7 @@ pub(super) async fn pool_ready(state: &AppState) -> bool {
true
}
pub(super) fn status_body(
worker: WorkerStatus,
inference_ready: bool,
model: Option<String>,
) -> StatusResponse {
pub(super) fn status_body(worker: WorkerStatus, inference_ready: bool, model: Option<String>) -> StatusResponse {
StatusResponse {
service: "leleka-control-plane",
server_pid: std::process::id(),
+15 -53
View File
@@ -10,10 +10,7 @@ type Routes = Router<AppState>;
/// The handler behind the admission gate of the lifecycle (drain and the in-flight limit).
fn admitted(state: &AppState, handler: MethodRouter<AppState>) -> MethodRouter<AppState> {
handler.layer(middleware::from_fn_with_state(
state.lifecycle.clone(),
crate::lifecycle::admit,
))
handler.layer(middleware::from_fn_with_state(state.lifecycle.clone(), crate::lifecycle::admit))
}
/// The handler with its request captured for the monitor and recorded in the request log.
@@ -23,14 +20,8 @@ fn recorded(
handler: MethodRouter<AppState>,
) -> MethodRouter<AppState> {
handler
.layer(middleware::from_fn_with_state(
state.services.monitor.clone(),
crate::request_monitor::capture,
))
.layer(middleware::from_fn_with_state(
observe.clone(),
crate::request_log::observe,
))
.layer(middleware::from_fn_with_state(state.services.monitor.clone(), crate::request_monitor::capture))
.layer(middleware::from_fn_with_state(observe.clone(), crate::request_log::observe))
}
/// Health, status, metrics, the llama.cpp style endpoints, settings and model loading.
@@ -47,10 +38,7 @@ fn server_routes(router: Routes) -> Routes {
.route("/v1/prefix_match", post(crate::server_api::v1_prefix_match))
.route("/v1/reconfigure", post(crate::server_api::v1_reconfigure))
.route("/mcp", get(crate::server_api::mcp_status))
.route(
"/settings",
get(crate::server_api::settings_get).post(crate::server_api::settings_post),
)
.route("/settings", get(crate::server_api::settings_get).post(crate::server_api::settings_post))
.route("/load", post(crate::server_api::load_post))
.route("/unload", post(crate::server_api::unload_post))
.route("/v1/load", post(crate::server_api::v1_load))
@@ -64,18 +52,11 @@ fn model_routes(router: Routes) -> Routes {
.route("/v1/models/{id}", get(crate::models_api::retrieve))
}
fn response_routes(
router: Routes,
state: &AppState,
observe: &crate::request_log::Observe,
) -> Routes {
fn response_routes(router: Routes, state: &AppState, observe: &crate::request_log::Observe) -> Routes {
let create = admitted(state, post(responses::create_route));
router
.route("/v1/responses", recorded(state, observe, create))
.route(
"/v1/responses/input_tokens",
admitted(state, post(responses::count_input_tokens)),
)
.route("/v1/responses/input_tokens", admitted(state, post(responses::count_input_tokens)))
}
fn chat_routes(router: Routes, state: &AppState, observe: &crate::request_log::Observe) -> Routes {
@@ -83,18 +64,11 @@ fn chat_routes(router: Routes, state: &AppState, observe: &crate::request_log::O
router.route("/v1/chat/completions", recorded(state, observe, create))
}
fn message_routes(
router: Routes,
state: &AppState,
observe: &crate::request_log::Observe,
) -> Routes {
let count = admitted(state, post(crate::messages::count_tokens))
.layer(middleware::from_fn(crate::messages::protocol));
let create = admitted(state, post(crate::messages::create))
.layer(middleware::from_fn(crate::messages::protocol));
router
.route("/v1/messages/count_tokens", count)
.route("/v1/messages", recorded(state, observe, create))
fn message_routes(router: Routes, state: &AppState, observe: &crate::request_log::Observe) -> Routes {
let count =
admitted(state, post(crate::messages::count_tokens)).layer(middleware::from_fn(crate::messages::protocol));
let create = admitted(state, post(crate::messages::create)).layer(middleware::from_fn(crate::messages::protocol));
router.route("/v1/messages/count_tokens", count).route("/v1/messages", recorded(state, observe, create))
}
/// The request monitor, the lifecycle, the stored responses.
@@ -102,14 +76,8 @@ fn admin_routes(router: Routes) -> Routes {
router
.route("/api/requests", get(crate::server_api::api_requests))
.route("/admin/lifecycle", get(lifecycle_status))
.route(
"/v1/responses/{id}",
get(responses::retrieve).delete(responses::delete),
)
.route(
"/v1/responses/{id}/input_items",
get(responses::input_items),
)
.route("/v1/responses/{id}", get(responses::retrieve).delete(responses::delete))
.route("/v1/responses/{id}/input_items", get(responses::input_items))
.route("/admin/drain", post(drain))
.route("/admin/resume", post(resume))
}
@@ -125,14 +93,8 @@ pub fn router(state: AppState) -> Router {
admin_routes(message_routes(routes, &state, &observe))
.fallback(crate::server_api::not_found)
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(
state.http.api_key.clone(),
crate::auth::authorize,
))
.layer(middleware::from_fn_with_state(state.http.api_key.clone(), crate::auth::authorize))
// Outermost: a browser's credential-less preflight is answered before authentication.
.layer(middleware::from_fn_with_state(
state.http.cors.clone(),
crate::server_api::cors_layer,
))
.layer(middleware::from_fn_with_state(state.http.cors.clone(), crate::server_api::cors_layer))
.with_state(state)
}
+3 -10
View File
@@ -64,8 +64,7 @@ pub struct ModelView {
pub vision: Option<SharedVisionEncoder>,
/// The engine's prefix-cache summary for a pool router (`GET /v1/status`, `POST /v1/prefix_match`).
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`
/// (`docs/memory-safety.md`).
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`.
pub memory: Arc<crate::memory_view::MemoryView>,
}
@@ -107,11 +106,7 @@ impl Default for EngineLink {
impl Default for HttpPolicy {
fn default() -> Self {
Self {
api_key: None,
cors: Arc::new(Default::default()),
trusted_origins: Arc::new(Vec::new()),
}
Self { api_key: None, cors: Arc::new(Default::default()), trusted_origins: Arc::new(Vec::new()) }
}
}
@@ -133,9 +128,7 @@ impl Default for Services {
fn default() -> Self {
let clock = SystemClock::shared();
Self {
responses: responses::HistoryResponseStore::shared(
responses::ResponseHistory::default(),
),
responses: responses::HistoryResponseStore::shared(responses::ResponseHistory::default()),
monitor: Arc::new(Default::default()),
mcp: None,
settings: Arc::new(crate::settings::Settings::default()),
+12 -46
View File
@@ -19,17 +19,9 @@ async fn assert_wrong_pids_refused(
state: &AppState,
(path, initial): (&str, bool),
) {
for (value, status) in [
("0".to_string(), 400),
("bad".into(), 400),
((std::process::id() + 1).to_string(), 409),
] {
let response = client
.post(format!("{url}/admin/{path}"))
.header("x-strata-expected-pid", value)
.send()
.await
.unwrap();
for (value, status) in [("0".to_string(), 400), ("bad".into(), 400), ((std::process::id() + 1).to_string(), 409)] {
let response =
client.post(format!("{url}/admin/{path}")).header("x-strata-expected-pid", value).send().await.unwrap();
assert_eq!(response.status().as_u16(), status);
assert_eq!(state.lifecycle.snapshot().draining, initial);
}
@@ -59,8 +51,7 @@ async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let value: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
let value: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(value["server_pid"], std::process::id());
assert_eq!(value["service"], "leleka-control-plane");
assert_eq!(value["draining"], !initial);
@@ -70,13 +61,8 @@ async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation()
}
async fn assert_drain_twice(client: &reqwest::Client, url: &str) {
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/drain"))
.send()
.await
.unwrap();
let data: serde_json::Value =
serde_json::from_str(&response.text().await.unwrap()).unwrap();
let response = client.post(format!("{url}/admin/drain")).send().await.unwrap();
let data: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_eq!(data["draining"], true);
assert_eq!(data["drained"], true);
}
@@ -98,25 +84,15 @@ async fn assert_draining_refuses_unparsed(client: &reqwest::Client, url: &str, s
async fn assert_not_drained_while_busy(state: &AppState) {
let job = state.lifecycle.generation();
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
assert_eq!(lifecycle_status(State(state.clone())).await.0["drained"], false);
drop(job);
state.engine.worker.write().await.state = WorkerState::Restarting;
assert_eq!(
lifecycle_status(State(state.clone())).await.0["drained"],
false
);
assert_eq!(lifecycle_status(State(state.clone())).await.0["drained"], false);
}
async fn assert_resume_is_idempotent(client: &reqwest::Client, url: &str) {
for _ in 0..2 {
let response = client
.post(format!("{url}/admin/resume"))
.send()
.await
.unwrap();
let response = client.post(format!("{url}/admin/resume")).send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}
@@ -151,11 +127,7 @@ async fn queue_one_command(sender: &tokio::sync::mpsc::Sender<GenerationCommand>
.send(GenerationCommand {
queue: None,
activity: None,
request: crate::wire::Generate {
token_ids: vec![10],
max_new: 1,
..Default::default()
},
request: crate::wire::Generate { token_ids: vec![10], max_new: 1, ..Default::default() },
result: crate::worker::GenerationResult::Buffered(result),
})
.await
@@ -175,10 +147,7 @@ fn assert_busy_metrics(body: &serde_json::Value) {
async fn metrics_expose_activity_without_changing_discovery() {
let (sender, mut receiver) = tokio::sync::mpsc::channel(2);
let state = AppState {
engine: EngineLink {
client: Some(ChannelEngine::shared(sender.clone())),
..Default::default()
},
engine: EngineLink { client: Some(ChannelEngine::shared(sender.clone())), ..Default::default() },
..Default::default()
};
let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap();
@@ -193,10 +162,7 @@ async fn metrics_expose_activity_without_changing_discovery() {
assert_eq!(response.headers()["content-type"], "application/json");
let body: serde_json::Value = serde_json::from_str(&response.text().await.unwrap()).unwrap();
assert_busy_metrics(&body);
assert_eq!(
serde_json::to_value(status(State(state.clone())).await.0).unwrap(),
initial_status
);
assert_eq!(serde_json::to_value(status(State(state.clone())).await.0).unwrap(), initial_status);
receiver.recv().await.unwrap();
assert_eq!(metrics_document(&state, false).await["queue_used"], 0);
server.abort();
+6 -19
View File
@@ -26,16 +26,13 @@ pub fn validate(bundles: &[AssetBundle]) -> Result<()> {
for path in [&bundle.manifest, &bundle.directory] {
if !path.is_absolute()
|| path.file_name().is_none()
|| path
.components()
.any(|part| matches!(part, Component::ParentDir))
|| path.components().any(|part| matches!(part, Component::ParentDir))
{
return Err("asset paths must be absolute, non-root paths without '..'".into());
}
}
if bundles[..index].iter().any(|other| {
other.directory.starts_with(&bundle.directory)
|| bundle.directory.starts_with(&other.directory)
other.directory.starts_with(&bundle.directory) || bundle.directory.starts_with(&other.directory)
}) {
return Err("asset bundle destinations must not overlap".into());
}
@@ -58,15 +55,9 @@ pub async fn provision(bundles: &[AssetBundle]) -> Result<()> {
}
async fn ensure(bundle: &AssetBundle, manifest: &model::Manifest) -> Result<()> {
let parent = bundle
.directory
.parent()
.ok_or("asset directory has no parent")?;
let parent = bundle.directory.parent().ok_or("asset directory has no parent")?;
fs::create_dir_all(parent)?;
let name = bundle
.directory
.file_name()
.ok_or("asset directory has no name")?;
let name = bundle.directory.file_name().ok_or("asset directory has no name")?;
let sibling = |suffix: &str| sibling_path(parent, name, suffix);
let _lock = lock_destination(&sibling(".strata-lock"))?;
if directory_exists(&bundle.directory)? {
@@ -119,9 +110,7 @@ fn lock_destination(path: &Path) -> Result<File> {
if !lock.metadata()?.is_file() {
return Err("asset lock must be a regular file".into());
}
lock.try_lock().map_err(
|_| "asset bundle is busy or cannot be locked; retry after preparation finishes",
)?;
lock.try_lock().map_err(|_| "asset bundle is busy or cannot be locked; retry after preparation finishes")?;
Ok(lock)
}
@@ -153,9 +142,7 @@ async fn verify_bundle(manifest: &model::Manifest, directory: &Path) -> Result<(
for entry in fs::read_dir(directory)? {
let name = entry?.file_name();
if !manifest.files.iter().any(|file| name == file.name.as_str()) {
return Err(
"asset bundle contains files absent from its manifest; use a new directory".into(),
);
return Err("asset bundle contains files absent from its manifest; use a new directory".into());
}
}
model::verify(manifest, directory).await
+13 -56
View File
@@ -87,9 +87,7 @@ pub(crate) fn read_token(path: &Path) -> Result<String, Box<dyn std::error::Erro
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
return Err(
"API key file must not grant group/other permissions (use chmod 600)".into(),
);
return Err("API key file must not grant group/other permissions (use chmod 600)".into());
}
}
let mut bytes = Vec::new();
@@ -101,36 +99,20 @@ pub(crate) fn parse_token(bytes: &[u8]) -> Result<String, Box<dyn std::error::Er
if bytes.len() > 514 {
return Err("API key file exceeds 514 bytes".into());
}
let value = std::str::from_utf8(bytes)
.map_err(|_| "API key must contain printable ASCII")?
.trim_end_matches(['\r', '\n']);
let value =
std::str::from_utf8(bytes).map_err(|_| "API key must contain printable ASCII")?.trim_end_matches(['\r', '\n']);
ApiKey::from_token(value)?;
Ok(value.to_owned())
}
pub async fn authorize(
State(key): State<Option<Arc<ApiKey>>>,
request: Request,
next: Next,
) -> Response {
let messages = matches!(
request.uri().path(),
"/v1/messages" | "/v1/messages/count_tokens"
);
pub async fn authorize(State(key): State<Option<Arc<ApiKey>>>, request: Request, next: Next) -> Response {
let messages = matches!(request.uri().path(), "/v1/messages" | "/v1/messages/count_tokens");
if !matches!(request.uri().path(), "/health" | "/api/health")
&& key.as_ref().is_some_and(|key| {
if messages {
!key.accepts_messages(request.headers())
} else {
!key.accepts(request.headers())
}
if messages { !key.accepts_messages(request.headers()) } else { !key.accepts(request.headers()) }
})
{
return (
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
Json(invalid_key_body(messages)),
)
return (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer")], Json(invalid_key_body(messages)))
.into_response();
}
next.run(request).await
@@ -168,14 +150,8 @@ mod tests {
headers.insert(header::AUTHORIZATION, value.parse().unwrap());
assert!(!key.accepts(&headers));
}
headers.insert(
header::AUTHORIZATION,
format!("Bearer {KEY}").parse().unwrap(),
);
headers.append(
header::AUTHORIZATION,
format!("Bearer {KEY}").parse().unwrap(),
);
headers.insert(header::AUTHORIZATION, format!("Bearer {KEY}").parse().unwrap());
headers.append(header::AUTHORIZATION, format!("Bearer {KEY}").parse().unwrap());
assert!(!key.accepts(&headers));
}
@@ -191,12 +167,7 @@ mod tests {
"/admin/lifecycle",
"/unknown",
] {
let response = client
.post(format!("{url}{path}"))
.body("not json")
.send()
.await
.unwrap();
let response = client.post(format!("{url}{path}")).body("not json").send().await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
assert_eq!(response.headers()[header::WWW_AUTHENTICATE], "Bearer");
assert!(!response.text().await.unwrap().contains(KEY));
@@ -204,12 +175,7 @@ mod tests {
}
async fn assert_authorized_requests_pass(client: &reqwest::Client, url: &str) {
let response = client
.get(format!("{url}/status"))
.bearer_auth(KEY)
.send()
.await
.unwrap();
let response = client.get(format!("{url}/status")).bearer_auth(KEY).send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(!response.text().await.unwrap().contains(KEY));
let response = client
@@ -234,19 +200,10 @@ mod tests {
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let server =
tokio::spawn(async move { axum::serve(listener, crate::app::router(state)).await });
let server = tokio::spawn(async move { axum::serve(listener, crate::app::router(state)).await });
let client = reqwest::Client::new();
assert_protected_paths_are_unauthorized(&client, &url).await;
assert_eq!(
client
.get(format!("{url}/health"))
.send()
.await
.unwrap()
.status(),
StatusCode::OK
);
assert_eq!(client.get(format!("{url}/health")).send().await.unwrap().status(), StatusCode::OK);
assert_authorized_requests_pass(&client, &url).await;
server.abort();
}
+1 -4
View File
@@ -39,10 +39,7 @@ use tokio::{
use crate::{
tokenizer::Tokenizer,
wire::{Done, Event, Finish, Generate},
worker::{
Control, GenerationCommand, LoadReply, WorkerState, WorkerStatus, deliver, finish,
send_failure, update,
},
worker::{Control, GenerationCommand, LoadReply, WorkerState, WorkerStatus, deliver, finish, send_failure, update},
};
/// Literals that end the text, as the ids `<|im_end|>` / `<|endoftext|>` do on the stdio wire.
+22 -67
View File
@@ -1,12 +1,11 @@
//! The attach loop of the backend worker: wait for the engine to load the model, serve requests and control
//! messages while it is there, and attach again when it is lost.
use crate::{adapters::SystemClock, ports::Clock};
use super::{
Arc, BackendWorkerConfig, Context, Control, Engine, GenerationCommand, LoadReply, RwLock, Served,
WorkerInbox, WorkerState, WorkerStatus, api, mpsc, on_engine, refresh_prefix_view, send_failure, serve_one, update,
watch,
Arc, BackendWorkerConfig, Context, Control, Engine, GenerationCommand, LoadReply, RwLock, Served, WorkerInbox,
WorkerState, WorkerStatus, api, mpsc, on_engine, refresh_prefix_view, send_failure, serve_one, update, watch,
};
use crate::{adapters::SystemClock, ports::Clock};
/// How a stretch of serving ended.
pub(super) enum Flow {
@@ -78,11 +77,7 @@ impl AttachLoop {
pub(super) async fn run(&mut self) {
loop {
let state = if self.attached_before {
WorkerState::Restarting
} else {
WorkerState::Starting
};
let state = if self.attached_before { WorkerState::Restarting } else { WorkerState::Starting };
update(&self.status, state, None).await;
// Fail what queued up while the engine was away; nothing is replayed.
while let Ok(command) = self.requests.try_recv() {
@@ -114,26 +109,14 @@ impl AttachLoop {
let model = self.config.model.clone();
let runtime = self.config.runtime.clone();
match on_engine(&self.engine, move |backend| backend.load(model, runtime)).await {
Ok(Ok(loaded))
if loaded
.validate_for_load(&self.config.model, &self.config.runtime)
.is_ok() =>
{
Ok(Ok(loaded)) if loaded.validate_for_load(&self.config.model, &self.config.runtime).is_ok() => {
return Some(loaded);
}
Ok(Ok(_)) => {
crate::elog!("the engine returned a load result that does not match the request")
}
Ok(Err(error)) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
Err(error) => leleka_obs::info(
"api",
"engine_wait",
&[("reason", error.to_string().as_str().into())],
),
Ok(Err(error)) => leleka_obs::info("api", "engine_wait", &[("reason", error.to_string().as_str().into())]),
Err(error) => leleka_obs::info("api", "engine_wait", &[("reason", error.to_string().as_str().into())]),
}
None
}
@@ -161,10 +144,9 @@ impl AttachLoop {
fn on_control_detached(&mut self, message: Option<Control>) {
match message {
Some(Control::Load { reply }) => self.waiting.push(reply),
Some(Control::Reconfigure { reply, .. }) => crate::worker::reconfigure_unavailable(
reply,
"the worker is not attached to the engine",
),
Some(Control::Reconfigure { reply, .. }) => {
crate::worker::reconfigure_unavailable(reply, "the worker is not attached to the engine")
}
Some(Control::Unload { reply, .. }) => {
let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded);
}
@@ -192,12 +174,7 @@ impl AttachLoop {
/// The status of a worker whose engine holds the model.
async fn publish_ready_status(&self) {
update(
&self.status,
WorkerState::Ready,
Some(self.config.max_context),
)
.await;
update(&self.status, WorkerState::Ready, Some(self.config.max_context)).await;
self.status.write().await.output_cap = Some(self.config.max_output_tokens);
self.status.write().await.text_level_engine = true;
self.status.write().await.last_activity = Some(SystemClock.now());
@@ -250,10 +227,7 @@ impl AttachLoop {
/// Ask the engine whether the configured model is still loaded.
async fn engine_reports_model(&self) -> bool {
let wanted = self.config.model.clone();
let present = on_engine(&self.engine, move |backend| {
backend.capabilities().supports(&wanted)
})
.await;
let present = on_engine(&self.engine, move |backend| backend.capabilities().supports(&wanted)).await;
present == Ok(true)
}
@@ -273,9 +247,7 @@ impl AttachLoop {
Some(Control::Load { reply }) => {
let _ = reply.send(Ok(()));
}
Some(Control::Reconfigure { settings, reply }) => {
self.reconfigure(settings, reply).await
}
Some(Control::Reconfigure { settings, reply }) => self.reconfigure(settings, reply).await,
Some(Control::Unload { reply, .. }) => {
// The runtime's lifecycle belongs to its operator (leleka-cli), not to HTTP.
let _ = reply.send(leleka_serving_policy::idle::Outcome::Unsupported);
@@ -284,28 +256,19 @@ impl AttachLoop {
}
}
async fn reconfigure(
&self,
settings: String,
reply: tokio::sync::oneshot::Sender<Result<String, (u16, String)>>,
) {
async fn reconfigure(&self, settings: String, reply: tokio::sync::oneshot::Sender<Result<String, (u16, String)>>) {
// Requests that arrive meanwhile wait in the queue: the engine reopens its serve stack in tens of seconds.
let answer =
match on_engine(&self.engine, move |backend| backend.reconfigure(&settings)).await {
Ok(Ok(effective)) => Ok(effective),
Ok(Err(error)) => Err((error_status(error.code), error.message)),
Err(message) => Err((500, message)),
};
let answer = match on_engine(&self.engine, move |backend| backend.reconfigure(&settings)).await {
Ok(Ok(effective)) => Ok(effective),
Ok(Err(error)) => Err((error_status(error.code), error.message)),
Err(message) => Err((500, message)),
};
let _ = reply.send(answer);
refresh_prefix_view(&self.engine, &self.config).await;
}
/// One queued request; `Some` ends the serving stretch.
async fn on_request(
&mut self,
command: Option<GenerationCommand>,
loaded: &api::LoadedModel,
) -> Option<Flow> {
async fn on_request(&mut self, command: Option<GenerationCommand>, loaded: &api::LoadedModel) -> Option<Flow> {
let Some(mut command) = command else {
self.requests_closed = true;
return None;
@@ -317,18 +280,10 @@ impl AttachLoop {
}
/// Serve a request nobody has abandoned and decide how the serving stretch goes on.
async fn serve_claimed(
&mut self,
mut command: GenerationCommand,
loaded: &api::LoadedModel,
) -> Option<Flow> {
async fn serve_claimed(&mut self, mut command: GenerationCommand, loaded: &api::LoadedModel) -> Option<Flow> {
self.status.write().await.last_activity = Some(command.request.obs.now());
let _activity = command.activity.take();
let ctx = Context {
engine: &self.engine,
config: &self.config,
status: &self.status,
};
let ctx = Context { engine: &self.engine, config: &self.config, status: &self.status };
let served = serve_one(ctx, &mut self.shutdown, &mut command, loaded).await;
self.after_request(served, &command).await
}
+5 -26
View File
@@ -118,26 +118,15 @@ impl Ending<'_> {
}
async fn failed(&mut self, message: String, code: api::ErrorCode) {
let message = if message.is_empty() {
format!("engine generation failed ({code:?})")
} else {
message
};
let message = if message.is_empty() { format!("engine generation failed ({code:?})") } else { message };
self.fail(message).await;
}
}
/// How long the generation waited for its first text and how long it then decoded, in milliseconds.
fn timings(state: &Conclusion<'_>, ended: Instant) -> (f64, f64) {
let prompt_ms = state
.first_delta
.unwrap_or(ended)
.duration_since(state.started)
.as_secs_f64()
* 1000.0;
let decode_ms = state
.first_delta
.map_or(0.0, |at| ended.duration_since(at).as_secs_f64() * 1000.0);
let prompt_ms = state.first_delta.unwrap_or(ended).duration_since(state.started).as_secs_f64() * 1000.0;
let decode_ms = state.first_delta.map_or(0.0, |at| ended.duration_since(at).as_secs_f64() * 1000.0);
(prompt_ms, decode_ms)
}
@@ -151,19 +140,9 @@ pub(super) async fn conclude(
) -> Served {
let (prompt_ms, decode_ms) = timings(&state, command.request.obs.now());
let disconnected = matches!(state.cancel, Some(Cancel::Client)) || command.result.is_closed();
let mut ending = Ending {
command,
status,
buffered,
state,
prompt_ms,
decode_ms,
disconnected,
};
let mut ending = Ending { command, status, buffered, state, prompt_ms, decode_ms, disconnected };
match terminal {
api::GenerationTerminal::Completed { reason, usage } => {
ending.completed(reason, usage).await
}
api::GenerationTerminal::Completed { reason, usage } => ending.completed(reason, usage).await,
api::GenerationTerminal::Cancelled => ending.cancelled().await,
api::GenerationTerminal::Failed { message, code, .. } => ending.failed(message, code).await,
}
@@ -17,9 +17,7 @@ pub(super) async fn on_engine<T: Send + 'static>(
) -> Result<T, String> {
let engine = Arc::clone(engine);
tokio::task::spawn_blocking(move || {
let mut guard = engine
.lock()
.map_err(|_| "engine state is poisoned".to_owned())?;
let mut guard = engine.lock().map_err(|_| "engine state is poisoned".to_owned())?;
Ok(call(&mut **guard))
})
.await
@@ -29,15 +27,13 @@ pub(super) async fn on_engine<T: Send + 'static>(
/// The prompt as text, or why the engine would not see exactly these tokens.
pub(super) fn prompt_text(tokenizer: &Tokenizer, ids: &[u32]) -> Result<String, String> {
let bytes = tokenizer.decode_bytes(ids).map_err(|e| e.to_string())?;
let text = String::from_utf8(bytes)
.map_err(|_| "the prompt tokens do not decode to valid UTF-8 text".to_owned())?;
let text =
String::from_utf8(bytes).map_err(|_| "the prompt tokens do not decode to valid UTF-8 text".to_owned())?;
let again = tokenizer.encode(&text, true).map_err(|e| e.to_string())?;
if again != ids {
return Err(
"the prompt tokens are not the canonical encoding of their text, so a text-level engine \
return Err("the prompt tokens are not the canonical encoding of their text, so a text-level engine \
would tokenize the prompt differently; refusing to serve different tokens than were counted"
.to_owned(),
);
.to_owned());
}
Ok(text)
}
@@ -65,16 +61,10 @@ fn refuse_unsupported(request: &Generate) -> Result<(), String> {
.to_owned());
}
if request.tune.is_some() {
return Err(
"strata_tune is an engine-process setting and is not part of the engine contract"
.to_owned(),
);
return Err("strata_tune is an engine-process setting and is not part of the engine contract".to_owned());
}
if request.cvec.is_some() {
return Err(
"experimental_speed_projection (control vectors) is not part of the engine contract"
.to_owned(),
);
return Err("experimental_speed_projection (control vectors) is not part of the engine contract".to_owned());
}
Ok(())
}
@@ -112,9 +102,7 @@ async fn marked_or_decoded_prompt(
tokio::task::spawn_blocking(move || match marked {
Some(text)
if tokenizer.marks().has_marks(&text)
&& tokenizer
.encode_marked(&text)
.is_ok_and(|encoded| encoded == ids) =>
&& tokenizer.encode_marked(&text).is_ok_and(|encoded| encoded == ids) =>
{
Ok(text.to_string())
}
@@ -130,13 +118,7 @@ async fn engine_prompt(config: &BackendWorkerConfig, request: &Generate) -> Resu
let prompt = match &request.prompt_text {
// The HTTP layer produced the ids from this very text; the engine is given the text if the ids still
// decode to it (a table walk over the ids, well under a millisecond for a whole conversation).
Some(text)
if config
.tokenizer
.decodes_to(&request.token_ids, text.as_bytes()) =>
{
text.to_string()
}
Some(text) if config.tokenizer.decodes_to(&request.token_ids, text.as_bytes()) => text.to_string(),
// Control-token text inside a message travels marked (`LiteralMarks`), and the engine reads the marks
// (`encode_marked`): the text is handed over if that encoding is exactly the ids that were counted.
// Anything else is decoded and must be the canonical encoding of its own text, or it is refused.
@@ -1,12 +1,12 @@
//! The loop of one generation: what wakes the worker (the engine's events, the deadlines, the client going away,
//! the shutdown) and what each wake-up does, ending with the terminal event for the HTTP layer.
use crate::{adapters::SystemClock, ports::Clock};
use super::{
BackendWorkerConfig, Cancel, Conclusion, Duration, Engine, Event, GenerationCommand, Instant, RwLock,
STOP_LITERALS, Served, WorkerStatus, api, conclude, deliver, fail_command, mpsc, text_tokens, trigger_cancel,
watch,
};
use crate::{adapters::SystemClock, ports::Clock};
type Item = Option<Result<api::GenerationEvent, api::StreamError>>;
@@ -143,10 +143,7 @@ impl<'a> Run<'a> {
first_delta: None,
delivered: 0,
last_progress: SystemClock.now(),
deadline: ctx
.config
.generation_timeout
.map(|limit| request.started + limit),
deadline: ctx.config.generation_timeout.map(|limit| request.started + limit),
drain_deadline: None,
}
}
@@ -282,9 +279,7 @@ impl<'a> Run<'a> {
}
async fn deliver_text(&mut self, emit: &str) -> Result<(), String> {
let ids = crate::stage_trace::time("delta_retokenize", || {
text_tokens(&self.ctx.config.tokenizer, emit)
})?;
let ids = crate::stage_trace::time("delta_retokenize", || text_tokens(&self.ctx.config.tokenizer, emit))?;
for id in ids {
self.delivered += 1;
deliver(self.command, &mut self.buffered, Event::Token(id)).await;

Some files were not shown because too many files have changed in this diff Show More