From 8890db316bcd64858fc2580dc7a0f26ef776374a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 11:57:26 +0100 Subject: [PATCH] STRA-338 S26: docs/architecture/hexagonal.md (layers, ports, how to add an engine family, gates, evidence rules, state after S22); tech-debt.md records S19 to S22 and corrects statements they made stale; AGENTS.md and README.md link the page --- AGENTS.md | 1 + README.md | 4 +- docs/architecture/gateway-ports.md | 2 + docs/architecture/hexagonal.md | 227 +++++++++++++++++++++++++++++ docs/architecture/tech-debt.md | 75 ++++++++-- 5 files changed, 298 insertions(+), 11 deletions(-) create mode 100644 docs/architecture/hexagonal.md diff --git a/AGENTS.md b/AGENTS.md index 1f7e759b..7efd29de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,7 @@ reference (the "Original"); the product is the Rust/CUDA port of its Original mo (CUDA Driver API, sealed PTX, NVML sampler), `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. diff --git a/README.md b/README.md index c3f2c9b5..735c635f 100644 --- a/README.md +++ b/README.md @@ -74,11 +74,11 @@ What the service is doing, and why a request was slow or failed, is in its logs; ## Repository layout -- `crates/` — the runtime: `leleka-runtime` (engine), `cuda-driver` (CUDA Driver API, sealed PTX), `leleka-memory` (memory governor), `obs` (logging), `deploy` (the `leleka` binary), model-format, tokenizer, sampler and CPU kernels. +- `crates/` — the runtime: `engine-qwen35-cuda` (the engine; `leleka-runtime` is its facade), `engine-core` (pure engine domain), `cuda-driver` (CUDA Driver API, sealed PTX), `leleka-memory` (memory governor), `obs` (logging), `deploy` (the `leleka` binary), model-format, tokenizer, sampler and CPU kernels. - `control-plane/`, `desktop-core/` — the HTTP/Responses gateway (`strata-next`) 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. +- `PROJECT_CHARTER.md`, `docs/` — requirements, provenance, decisions, gates and measurements. Architecture: `docs/architecture/hexagonal.md`. Model weights, request captures, credentials, logs and generated artifacts stay outside Git. diff --git a/docs/architecture/gateway-ports.md b/docs/architecture/gateway-ports.md index 96fa6379..b7fd797f 100644 --- a/docs/architecture/gateway-ports.md +++ b/docs/architecture/gateway-ports.md @@ -1,5 +1,7 @@ # Gateway ports (STRA-338 S16) +The layers, the engine-side ports and the architecture gates are on `hexagonal.md`; this page is the gateway half. + The HTTP/Responses gateway (`strata-control`, binary `strata-next`) talks to everything outside the request through five small traits in `control-plane/src/ports/`. `AppState` holds `Arc` (type aliases `SharedClock`, `SharedEngine`, `SharedResponseStore`, `SharedToolHub`, `SharedVisionEncoder`), never a concrete adapter. The real diff --git a/docs/architecture/hexagonal.md b/docs/architecture/hexagonal.md new file mode 100644 index 00000000..9b71cc01 --- /dev/null +++ b/docs/architecture/hexagonal.md @@ -0,0 +1,227 @@ +# Hexagonal architecture of the Leleka runtime and gateway (STRA-338) + +One page: the layers, the ports, how to add an engine family, what the gates check, and what the verification asked for. +Every statement was read from the code, `architecture.json`, `architecture-baseline.json` or the commits it names. +Detail pages: `gateway-ports.md` (the five gateway ports), `tech-debt.md` (what a step moved but did not fix), +`../experiments/stra-338-gateway-track.md` (the gateway track report). + +## Layers + +The policy is `architecture.json`. A normal dependency points to the same or a lower layer. L0 to L2 are the pure layers: they +may not use `tokio`, `axum`, `tonic`, `tonic-prost`, `reqwest`, `hyper`, `libc`, `rustix`, `windows-sys`, `sysinfo` or `wgpu`. +Inside L3 a crate may use another L3 crate only through an edge listed in `adapter_edges`. Every workspace package is in exactly one layer. + +| Layer | Role | Crates (package names) | +|---|---|---| +| L0 contract | wire and trait contracts | `leleka-backend-api` (the `Backend` trait), `leleka-worker-protocol` | +| L1 leaf libraries | pure or std-only libraries | `leleka-obs` (`Clock`), `leleka-memory` (`MemoryPressure`), `leleka-context`, `leleka-sampler-ref`, `leleka-quant-core`, `leleka-serving-policy`, `leleka-harmony`, `leleka-tokenizer`, `leleka-gguf`, `leleka-kar-codec`, `leleka-experimental-ref`, `leleka-cpu-sys`, `leleka-cpu-kernels`, `leleka-shm`, `leleka-openvino`, `leleka-gateway-text` | +| L2 domain | pure domain of one side | `leleka-engine-core` (prefix cache, conversation policy, prompt plan, speculative-decoding policies, request lifecycle, `EngineFamily`), `leleka-gateway-domain` (sampling, reasoning budget, codec, Responses and Messages protocol) | +| L3 adapters | OS, device, process and file access | engine: `leleka-engine-qwen35-cuda`, `leleka-engine-fake`, `leleka-cuda-driver`, `leleka-model-format` (`WeightSource`), `leleka-native-cpu-expert`, `leleka-libc-shim`; gpt-oss workers: `leleka-gptoss`, `leleka-gptoss-igpu`, `leleka-gptoss-npu`, `leleka-cpu-worker`, `leleka-igpu-worker`, `leleka-npu-worker`, `leleka-gpu-npu-worker`, `leleka-npu-service`, `leleka-igpu`; also `leleka-offline-tools`, `leleka-runtime-client` (gRPC client) | +| L4 hosts | composition roots and facades | `leleka-runtime` (facade), `strata-desktop-core` (the `leleka-inference` binary), `strata-control` (gateway, binary `strata-next`), `leleka-deploy` (the `leleka` binary), `leleka-native-parity-bench` | + +`leleka-runtime` is one line, `pub use leleka_engine_qwen35_cuda::*;` (S22), so the binaries keep importing `leleka_runtime::...`. +`leleka-engine-fake` is a dev-dependency of `strata-desktop-core` only; no production crate depends on it. + +## Dependency picture + +Selected edges of `python scripts/check-architecture.py --report`; every arrow points to a lower or equal layer. The dotted edge is a dev-dependency. + +```mermaid +flowchart TB + subgraph L4[L4 hosts] + ctl[strata-control
gateway root] + dcore[strata-desktop-core
engine process root] + rt[leleka-runtime
facade] + end + subgraph L3[L3 adapters] + q35[engine-qwen35-cuda] + fake[engine-fake] + cuda[cuda-driver] + mfmt[model-format
WeightSource] + cpux[native-cpu-expert] + rtc[runtime-client
gRPC] + end + subgraph L2[L2 domain] + core[engine-core
EngineFamily, run_request,
prefix cache, conversation] + gdom[gateway-domain] + end + subgraph L1[L1 leaf libraries] + obs[obs
Clock] + mem[leleka-memory
MemoryPressure] + gtext[gateway-text, harmony,
tokenizer, ...] + end + subgraph L0[L0 contract] + api[backend-api
Backend] + end + dcore --> rt --> q35 + dcore --> core + dcore --> rtc + dcore -.-> fake + ctl --> gdom + ctl --> rtc + q35 --> core + q35 --> cuda + q35 --> mfmt + q35 --> cpux + q35 --> mem + q35 --> obs + fake --> core + core --> api + fake --> api + rtc --> api + gdom --> gtext + cuda --> mfmt +``` + +`engine-qwen35-cuda` reaches `cuda-driver`, `model-format` and `native-cpu-expert` through three declared adapter edges. `engine-core` +depends on `leleka-backend-api` and `serde` only. `strata-desktop-core` is the composition root of the engine process; `strata-control` +is the composition root of the gateway process (`serve()` in `control-plane/src/serve.rs`). + +## Ports and seams + +| Seam | Trait or type, and where | Dispatch | Why | +|---|---|---|---| +| Clock (engine) | `leleka_obs::time::Clock`; `SystemClock`, `ManualClock`, `AnyClock`, `Stopwatch` (`crates/obs/src/time/clock.rs`) | generic (`C = SystemClock` by default); `AnyClock` is an enum for owners that cannot be generic | read at coarse points (request, decision, tick); hot loops take one reading and compare it | +| Settings / EnvSource | `EnvSource`, `ProcessEnv`, `MapEnv`, `Settings` (`crates/engine-qwen35-cuda/src/settings/`, crate-private) | generic (`&impl EnvSource`) | the operator namespace is captured once; parsers are tested with `MapEnv` | +| MemoryPressure | `leleka_memory::pressure_port::MemoryPressure`; `ProcPressure`, `ScriptedPressure` | `Arc` inside `Governor` | read at sampler and admission cadence, never per token | +| WeightSource | `leleka_model_format::weight_source::WeightSource`; file, shard, resident-tensor and KAR adapters, an in-memory double | generic (`S: WeightSource + ?Sized`) | opened once per load; no method returns an owning copy of the bytes | +| ServeDevice | `ServeDevice` (`crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs`, crate-private), implemented by `OriginalServeStack` | generic (`&mut impl ServeDevice`) | one call per request; tests drive the real `generate` over a scripted device | +| Lifecycle / run_request | `leleka_engine_core::request::{Lifecycle, run_request, ServeError, admit}` | generic, no trait object | admission, reset or resume, prefill, decode, finish: the order and the failure classes run over any owners | +| EngineFamily + `spawn::` | `leleka_engine_core::family::{EngineFamily, spawn}`; families `Qwen35Cuda` and `EngineFake` | `F` is generic; the result is `Box` | the root is monomorphised over the family; the trait object is the process boundary | +| Backend | `leleka_backend_api::Backend` (`crates/backend-api/src/lib.rs`) | `Box` in `RuntimeServer` (`desktop-core`) | methods are request-level (`load`, `start_generation`, `cancel`, `unload`, reports); tokens travel in the `GenerationStream` | +| Gateway ports | `EngineClient`, `ResponseStore`, `Clock`, `ToolHub`, `VisionEncoder` (`control-plane/src/ports/`) | `Arc` in `AppState`, boxed futures | called once per request or per process; streaming loops read the plain `mpsc` receiver | + +Inside the Qwen3.5 adapter there are three more device traits, all crate-private: `RequestOwners` (admission to finish), `PrefixDevice` +(the prefix cache) and `OriginalServePort` (the verify round). The rule behind the table is the `dyn-trait` pattern in +`architecture.json`: dynamic dispatch is for start-up composition and request-level boundaries, not for a round, a chunk or a token. +Two carve-outs are counted by the ratchet instead of hidden: `RequestOwners::prefill` and `decode` take `&mut dyn FnMut` callbacks, and the +`conversation` code in `engine-core` takes `&mut dyn StateMemory` and `&mut dyn SessionEngine`. + +There are two `Clock` traits on purpose: the engine one (std `Instant`, `leleka-obs`) and the gateway one (tokio `Instant`, `control-plane/src/ports/clock.rs`). + +## What is deliberately not a port + +* Kernels and their launch order, and CUDA graph capture and replay. They stay concrete in `leleka-cuda-driver` and the adapter. The STRA-338 + item says not to abstract graph capture until it is measured; nothing here measures it. +* The glue `prefill_actions` and `decode_phase` of `OriginalServeStack`. They hold the CUDA owners, the verifier assembly and the expert-tier + hooks, so they stay in the adapter; the test device mirrors them (`tech-debt.md`, S15). +* Shard open and bind, KAR verification and the CPU expert bank are not behind `WeightSource` yet; each is its own step (`tech-debt.md`, S18). +* The gpt-oss CPU/iGPU/NPU runtime is reached through the worker line protocol (`leleka-worker-protocol`, L0) and `codec::TextCodec` in the + gateway, not through `EngineFamily`. +* `RECONFIGURING`, `INSTANCE`, `settings::process()` and `Governor::global()` are still process-wide in the adapter (`tech-debt.md`, S13 and S14). + +## How to add an engine family + +Today `spawn::` is the only registered family of the engine process: `desktop-core/src/bin/leleka-inference.rs` calls it for the +Original and native paths, and its experimental paths still call the `spawn_backend_*` functions directly. There is no family `enum`; the root +chooses by its own logic, and a second family adds a second arm there. + +1. **Crate.** Create `crates/engine--` (package `leleka-engine--`), add it to `[workspace] members` in `Cargo.toml` + and to layer `L3` in `architecture.json`. Depend on `leleka-engine-core`, `leleka-backend-api` and L1 libraries. Another L3 crate only through an + `adapter_edges` pair that is a real port (the Qwen3.5 crate has three: `cuda-driver`, `model-format`, `native-cpu-expert`). Never depend on L4. +2. **Domain first.** Take policy from `leleka-engine-core` (`prefix_cache`, `conversation`, `prompt`, `spec`, `request`). Anything that needs the OS, + a device, `std::env` or `Instant::now()` goes behind the existing ports (`EnvSource`, `Clock`, `MemoryPressure`, `WeightSource`). +3. **Implement the seam.** A zero-sized marker `struct Family;` with `impl EngineFamily for Family { type Config = ..; const NAME: &'static str = ..; + fn spawn(config) -> Result, BackendError> }`, and `Backend` for the engine it returns. For the request path implement + `Lifecycle` on the family's owners and call `run_request`. Models: `crates/engine-fake/src/lib.rs` (smallest) and + `crates/engine-qwen35-cuda/src/backend/family.rs`. +4. **Register.** Add the crate to `desktop-core/Cargo.toml` and call `spawn::(config)` where the root picks the engine; the result goes to + `RuntimeServer::new` unchanged. +5. **Fake-engine test.** A GPU-free test that starts the family through `spawn::` and drives a request, in the style of + `crates/engine-fake/src/tests.rs`; for lifecycle behaviour implement `Lifecycle` on a scripted owner, as the `lifecycle_fake` device of the + Qwen3.5 adapter does. `desktop-core/tests/api_over_runtime.rs` is the full-chain test (real API router, real `RuntimeServer`, scripted engine). +6. **Gates** (next section): `python scripts/check-architecture.py`, `python scripts/check_architecture_test.py`, `python scripts/check-ci-coverage.py` + (add the package to `scripts/ci-coverage.json` and name it with `-p` in `scripts/check-local.sh`), `cargo test -p `, clippy with `-D warnings`. +7. **GPU rule (AGENTS.md).** A non-lossy change compares greedy output or tensor values with the defined baseline and records the tolerances. Nothing + is called a performance change without paired A/B measurements on the same workload, a quality result, and the hardware, software, model digest, + configuration, cache state, token counts and distributions the charter asks for. Lossy modes stay off by default and are marked experimental. + +## What the gates check + +`scripts/check-local.sh --product` (CI workflow `Product`, `.github/workflows/product.yml`) runs `scripts/check-ci-coverage.py`, +`scripts/check_architecture_test.py` (22 self-tests) and `scripts/check-architecture.py`. Run the last one alone for a local answer. + +| Check | Rule | Source | +|---|---|---| +| layers | every package has one layer; an edge to a higher layer is an error | `architecture.json` `layers` | +| adapter edges | L3 to L3 only through a listed pair | `adapter_edges` | +| purity | L0 to L2 use none of the `forbidden_in_pure` crates | `forbidden_in_pure` | +| size ratchet | no `.rs` file over 400 lines; a file already over may not grow past its baseline entry; a shrunk file is reported stale | `max_lines`, baseline `oversize` | +| source ratchets | per-crate counts of `env-read`, `instant-now`, `path-include`, `process-global`, `dyn-trait` over production code in `src/`; a count may only fall | `source_patterns`, baseline `source` | +| baselined violations | the two known `leleka-memory` dependencies (`libc`, `windows-sys`) | baseline `violations` | + +Commands: `python scripts/check-architecture.py` (0 errors expected), `--report` (layer graph, oversize census, ratchets), `--update-baseline` +(lowers numbers, refuses to raise one), `--update-baseline --allow-increase` (raising needs a reason in review). Test-only modules (a `mod x;` +under a test cfg, `tests.rs`, `*_tests.rs`, `tests/`) are not counted by the ratchets. + +Limits gate and Clippy ratchet (STRA-367). Function at most 30 lines, complexity 10, nesting 4, line 120 columns for new and changed code, a falling +census for legacy, and an opt-in Clippy ratchet (`too_many_lines`, `cognitive_complexity`, `too_many_arguments`). The files are +`scripts/check-limits.py`, `scripts/check-clippy-limits.sh` and `docs/architecture/limits-gate.md`, and `check-local.sh --product` runs the gate. +At the time of writing they exist on branch `claude/hexagonal-integ-lints` (commits `334af80d3`, `054b57bec`, `48b2ce9f4`) and not in this tree; their +census predates S19 to S22. After that branch is merged: `python scripts/check-limits.py`, and `scripts/check-local.sh --clippy-limits` for the Clippy side. + +## Verification evidence rules + +* **Identity is bitwise.** A step that must not change behaviour is compared with the reference binary on the teacher-forced replay of the + `night5-long-256k` capture: 5 requests, 240 forced tokens each, top-16 logprobs of every row and the draft trace. The reference A/A noise floor is + measured first (2057 logprob rows and 1036 draft-trace lines identical, 0 argmax flips), so any difference seen for a candidate is real. Recorded in + the LeaseVibe comments of STRA-344 as `HX-ID1`, `HX-ID2`, `HX-ID3`, `HX-ID-C2` and `HX-GATE2`. +* **Speed is paired.** A/B at 245k, 5 turns, each arm alone on the GPU, order alternating by block, block-paired differences with a confidence + interval. n = 10 blocks can exclude a slowdown of about 1% and shows nothing smaller; the charter's bar for claiming 1% is n >= 30. The records + (`HX-AB`, `HX-AB-C2`, `HX-GATE2`) state non-regression bounds, not speed-ups, and name what they do not cover (other workloads, sampling paths + other than greedy, the laptop 3080). +* **GPU-free steps** are covered by `cargo test`, clippy, `cargo fmt --check`, the architecture gate and, where one was recorded first, a golden + fixture (S21 `responses_pure.json`, the S5a digest goldens, the S2 round transcripts). +* **Not yet recorded.** The STRA-344 thread as read for this page ends with `HX-GATE2` at `17296a58f` (S14, S15, S18), with a note that the commits + after it up to `fc591f4e9` do not touch the engine process. It holds no identity or A/B record for S19 to S22 (`38eb771a4` to `a4ceeab69`), which + move code inside the engine process. The decision comment on STRA-338 puts that batch behind "A/B n=10 first, n=30 only with spare GPU time", with the + identity gate never dropped. Until that run exists, these four steps are verified by the compiler and the GPU-free tests only. + +## State after S22 + +`python scripts/check-architecture.py --report` on `a4ceeab69` (the S22 tip) against the first recorded baseline, commit `55dbadc43` (S1), whose +message states "3 layer violations, 329 oversize files, 65 ratchets" and which was built on `main` `731f060b7`. The two are not strictly comparable: +from S13 the ratchets count production code only, and the `path-include` pattern now skips `tests.rs` and `dir/name.rs`. + +| Measure | main `731f060b7` (S1 baseline) | S22 tip | +|---|---|---| +| `.rs` files over 400 lines | 329 | 121 | +| lines in those files | 303,231 | 96,649 | +| layer violations | 3 | 2 (`leleka-memory` to `libc`, `windows-sys`) | +| ratchet keys | 65 | 73 | +| `env-read` (total) | 492 | 205 | +| `instant-now` | 294 | 201 | +| `process-global` | 303 | 265 | +| `dyn-trait` | 229 | 219 | +| `path-include` | 205 | 231 (cause not analysed here) | + +Where the runtime went (oversize files and their lines, from the two baselines, and the ratchets per crate): + +| Crate | oversize files / lines | `env-read` | `instant-now` | `process-global` | `dyn-trait` | `path-include` | +|---|---|---|---|---|---|---| +| `leleka-runtime` at S1 | 87 / 82,652 | 239 | 74 | 102 | 71 | 94 | +| `leleka-runtime` now (facade) | 0 / 0 | 0 | 0 | 0 | 0 | 0 | +| `leleka-engine-qwen35-cuda` | 17 / 14,089 | 1 | 17 | 59 | 52 | 100 | +| `leleka-engine-core` | 4 / 3,714 | 0 | 0 | 0 | 19 | 0 | +| `leleka-engine-fake` | 0 / 0 | 0 | 0 | 0 | 1 | 0 | +| `leleka-gateway-domain` | 1 / 405 | 0 | 0 | 3 | 5 | 0 | +| `leleka-cuda-driver`, S1 to now | 97 / 91,850 to 30 / 19,617 | 126 to 76 | 44 to 31 | 108 to 110 | 51 to 48 | 102 to 115 | +| `strata-control`, S1 to now | 40 / 42,971 to 10 / 10,764 | 21 to 19 | 37 to 23 | 16 to 11 | 29 to 16 | 0 | + +Size of the new crates (all `.rs` under `src/`, tests included): `engine-core` 11,245 lines, `engine-qwen35-cuda` 113,374, `engine-fake` 92. +`engine-core` has no environment, clock or global in its code, which the zero counts reflect. The largest oversize file of the workspace is +`crates/native-cpu-expert/examples/kernel_ab.rs` (3,347 lines); the largest in the engine crates is +`crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs` (1,648). + +## Commits of the engine recut (S19 to S22) + +| Step | Commit | What | +|---|---|---| +| S19a | `38eb771a4` | prefix cache and pure memory admission to `leleka-engine-core` (L2) | +| S19b | `d717c6977` | Original prompt plan to `engine-core::prompt` | +| S19c | `93afb07bf` | conversation policy to `engine-core::conversation`; 17 `dyn` uses and 3 oversize test files moved with it | +| S19d | `8987e9ab0` | draft policy and adaptive window policy to `engine-core::spec`; `LELEKA_SPEC_*` parsing stays in the adapter | +| S19e | `58e3d864e` | admission, stop set, `ServeError`, `run_request` over `Lifecycle` to `engine-core::request` | +| S20 | `e049e24fe` | `EngineFamily` and `spawn::`, `Qwen35Cuda`, `leleka-engine-fake`; `leleka-inference` and the full-chain test start engines through the seam | +| S21 | `ff6cb3dcb` and later | `leleka-gateway-domain` (gateway track) | +| S22 | `a4ceeab69` | the engine moves to `leleka-engine-qwen35-cuda` (L3); `leleka-runtime` becomes the facade | diff --git a/docs/architecture/tech-debt.md b/docs/architecture/tech-debt.md index b131d819..79198818 100644 --- a/docs/architecture/tech-debt.md +++ b/docs/architecture/tech-debt.md @@ -1,12 +1,17 @@ # Architecture tech debt (STRA-367) Debt that a hexagonal step moved but did not remove. A line here names the file, the limit it misses, and what -removes it. The size and ratchet numbers themselves live in `architecture-baseline.json`. +removes it. The size and ratchet numbers themselves live in `architecture-baseline.json`; the overview is `hexagonal.md`. Limits for new and changed code: function at most 30 lines, cyclomatic complexity at most 10, nesting at most 4, line at most 120 columns, file at most 400 lines. -## crates/leleka-runtime `backend/` (STRA-338 S5a, S5b) +Crate names after S22: the sections below that say `leleka-runtime` describe code that now lives in `crates/engine-qwen35-cuda` (package +`leleka-engine-qwen35-cuda`); `leleka-runtime` is a one-line facade. The sections keep the wording they had when they were written, paths such as +`backend/` and `settings/` are relative to the new crate, and the ratchet keys read `...:leleka-engine-qwen35-cuda`. The layers, the ports and the +numbers after S22 are on `docs/architecture/hexagonal.md`; the S19 to S22 section below says what the engine recut moved and what it left. + +## crates/engine-qwen35-cuda `backend/` (formerly leleka-runtime; STRA-338 S5a, S5b) `backend.rs` (3797 lines) is a parent of 258 lines plus responsibility-named children. `serve_load` is decomposed into `load.rs` (the order of the phases) and `load_admit`, `load_sources`, `load_identity`, `load_bind`, `load_cuda`, @@ -17,7 +22,7 @@ limits except the one line named first. What was moved verbatim in S5a and is st | Where | Misses | Removed by | | --- | --- | --- | | `load_moe_gates.rs`, the `learned_main_lru` constructor call | one line of 127 columns: the method name of `MoeWeightCache` is 119 characters | renaming the constructor in `qwen_forward/moe_weight_cache` (its own step) | -| `generate_mtp.rs` `generate_mtp_resume` | 250 lines, complexity 44 | splitting the MTP window loop into phases (engine-core step; GPU identity and A/B gates apply) | +| `generate_mtp.rs` `generate_mtp_resume` | 250 lines, complexity 44 | splitting the MTP window loop into phases (still open after S19: the loop holds CUDA owners and stayed in the adapter; GPU identity and A/B gates apply) | | `generate.rs` `prefill_chunk`, `generate`, `step`, `target_step` | 90, 60, 55, 34 lines; complexity 14 and 10 | same step as above | | `spawn.rs` `spawn_backend_configured` | 100 lines; recomputes the policy flags that `PolicyFlags::of` now owns | use `PolicyFlags::of`, split the owner hand-over | | `spawn_optimized.rs` | seven factories of 32 to 39 lines repeating one precondition block | one `OptimizedSelection` check shared by the factories | @@ -34,7 +39,7 @@ Process-wide state and reads that the policy file `architecture.json` counts and `qwen_forward/moe_weight_cache.rs` gained three `pub(crate) use` lines (`AdaptiveWitness`, `LearnedMainWitness`, `SharedPermanentWitness`) so the witness gates in `load_moe_gates.rs` can name the types; no code changed there. -## crates/leleka-runtime `settings/` (STRA-338 S13) +## crates/engine-qwen35-cuda `settings/` (formerly leleka-runtime; STRA-338 S13) Production code in leleka-runtime no longer calls `std::env`. `settings.rs` holds the port (`EnvSource`, with the `ProcessEnv` adapter and the `MapEnv` fixture) and `Settings`: the operator namespace (`LELEKA_*`, `STRATA_*`) is @@ -42,7 +47,7 @@ captured once, the plain switches and numbers are typed fields of five topic str `kv`, `diagnostics`), and the parsers that report errors (conversation cache, PLE reader, expert tier, memory governor, the speculative engine, adaptive config, NaN guard, sampler path) read the capture through `Settings::env()`. Each topic has golden tests with a `MapEnv` (`settings/*_tests.rs`, `tier_env_tests.rs`, -`original_serve_engine/env_tests.rs`). The `env-read:leleka-runtime` ratchet is 1: `ProcessEnv::get_os` is the only +`original_serve_engine/env_tests.rs`). The `env-read:leleka-engine-qwen35-cuda` ratchet (`env-read:leleka-runtime` when this was written) is 1: `ProcessEnv::get_os` is the only `std::env::var_os` left (`vars_os` in `entries_with_prefix` does not match the pattern). The ratchets now count production code only: a file declared under a test cfg, and everything it declares, is skipped. @@ -50,7 +55,7 @@ What is still outside the port, and why: | Where | What | Removed by | | --- | --- | --- | -| `settings::process()` | one `OnceLock`: leaf code (the nine `driver_error` functions, the GDN/prefill switches, the serve loop traces) cannot take a parameter without threading it through hundreds of `map_err(driver_error)` calls; `LoadEnv::settings` carries it on the load path, the rest asks `process()` | injecting the settings (and the clock, S14) into the executors and the stack when the engine core is extracted (S19) | +| `settings::process()` | one `OnceLock`: leaf code (the nine `driver_error` functions, the GDN/prefill switches, the serve loop traces) cannot take a parameter without threading it through hundreds of `map_err(driver_error)` calls; `LoadEnv::settings` carries it on the load path, the rest asks `process()` | injecting the settings (and the clock, S14) into the executors and the stack. S19 extracted the pure policy only and `engine-core` takes no `Settings`, so this is still open | | `leleka-cuda-driver` (76 reads, 96 keys) | the driver parses its own options (`OriginalStagerOptions`, `OriginalResidentOptions`, the draft vocabulary, `logpos_topk_from_environment` and others); runtime never calls them, the driver does | a settings crate below the driver (L1) that both crates use, then the same capture-and-topic move | | `leleka-native-cpu-expert` (19), `leleka-gptoss` (6), `leleka-model-format` (5), `leleka-libc-shim` (4), `leleka-memory` (3), `leleka-deploy` (41), `strata-control` (19), `strata-desktop-core` (15) and the other CPU/iGPU/NPU crates | same pattern in their own crates; deploy sets the child's environment on purpose | follow-up steps per crate, after the settings crate exists | | `memory_governor`, `ResidentPolicy::from_environment` | public or crate-wide entry points keep their signature and read `settings::process().env()` | callers pass the capture once the load path owns a `Settings` reference everywhere | @@ -117,7 +122,7 @@ Where it is injected: Still on `std::time::Instant` on purpose: the per-window and per-miss timers of the CPU expert pool, lookahead, residency lag and the verify engine, the prefill/GDN profile spans, `owner_wall_profile` (diagnostics inside the -decode loop, one reading per kernel or per miss: a clock parameter there is the engine-core step, S19); `load_clock.rs` +decode loop, one reading per kernel or per miss: a clock parameter there is a later step: S19 extracted the pure policy only and `engine-core` has no clock); `load_clock.rs` (a process-wide lap printer behind a `Mutex`); `DBG_T0` (debug trace epoch); `open_tier_fn` (one startup log line); `smi::query` (a subprocess wait loop, real I/O). The gateway and control-plane crates keep their own sites for the gateway track. @@ -137,7 +142,7 @@ Process globals: `GPU_ORDINAL` is gone (the ordinal travels in `Run`, the value `Shared` would make concurrent backends independent, which is a behaviour change for a process that hosts two), `INSTANCE` (the owner id counter that `spawn_backend_configured` draws from; it needs a spawner object that the callers do not have), `Governor::global()` (about twenty calls in the runtime; they need a memory handle on the stack, the -conversation manager and the prefix cache, the same S19 move as `settings::process()`), `serving_cells()` (30 reads of +conversation manager and the prefix cache, the same open move as `settings::process()`, which S19 did not make), `serving_cells()` (30 reads of one validated constant), the two `std::cell::OnceCell` fields (per-instance lazy cells that the pattern also matches), `NO_TRIM_FILE`, `heap::OFF` and `TUNING` (environment caches that belong to the Settings follow-up). @@ -146,7 +151,7 @@ leleka-obs 0 -> 3 for the three adapters), `process-global` 267 -> 265, `dyn-tra touched that were already over the limits and are not made worse: `Governor::with_parts` (35 lines, the old `new` had 34), `seed_residency` (34, as before), `guard_archive_extents`, `residency_tick`, `telemetry::render`, the Original serve `generate` and `run`, `decode_phase`, `OriginalServeStack::open`. -Follow-ups: thread one clock and one memory handle through the engine core when it is extracted (S19), after which +Follow-ups: thread one clock and one memory handle through the engine stack (S19 extracted the pure policy only, so this is still open), after which `StackConfig::clock` and `LoadEnv::clock` become the generic parameter of the stack; a settings crate for the environment caches above; `RECONFIGURING` and `INSTANCE` with a spawner object. @@ -209,6 +214,12 @@ of sharing it (see "What the fake mirrors"). | telemetry and the `PREVIOUS_TIER` static written by `generate` | process-wide, tests assert nothing on them | S19: pass a request sink to `generate` | | `generate` (about 140 lines), `OriginalServeStack::open` | unchanged | S19 | +**Status after S19e, S20 and S22.** The design below was not carried out as drawn. S19e moved the sequencing of one request into +`leleka-engine-core::request` (`Lifecycle`, `run_request`, generic); the adapter's `RequestOwners` reach it through the wrapper struct `Owners` +(`original_serve_request.rs`). `PromptDevice`, `DecodeDevice`, `read_prompt` and `decode_request` do not exist in the code, `prefill_actions` and +`decode_phase` are still methods of `OriginalServeStack`, and `FakeStack` still mirrors them (`lifecycle_fake/stack.rs`), so the gaps in the table +above are open. The design text is kept as the plan for that step. + **S19 design: one generic lifecycle for the stack and the fake.** Move the glue out of `OriginalServeStack` into `qwen_forward/original_serve_lifecycle.rs`, generic over the device (monomorphised, called once per request or per chunk, never per token): @@ -330,6 +341,52 @@ clippy on both crates reports nothing in the new or changed files; the architect moved (`dyn-trait` unchanged: the port is generic); no `unsafe` was added (the only mapping owner stays `FileSpan`). Functions touched and already over the limits, not made worse: `verify_sources_parallel` (42 lines, not edited). +## Engine core, family seam and adapter crate (STRA-338 S19 to S22) + +Layer picture, ports and numbers: `docs/architecture/hexagonal.md`. This section records what each step moved, what it left, and why. + +**What moved to `leleka-engine-core` (L2; depends on `leleka-backend-api` and `serde` only).** Each step is one commit; the old paths +are re-exported by the adapter (`pub use leleka_engine_core::...` in `crates/engine-qwen35-cuda/src/lib.rs` and `crates/engine-qwen35-cuda/src/conversation/mod.rs`). + +| Step | Commit | Module in `engine-core` | Left in the adapter | +|---|---|---|---| +| S19a | `38eb771a4` | `prefix_cache` (hash chain, budget, store, summary), `memory` (pure admission, `memory_admit`) | `PrefixServe` and `PrefixDevice` (`qwen_forward/original_serve_prefix`): they drive the CUDA state | +| S19b | `d717c6977` | `prompt` (`PromptPlan`, `PromptOptions`) | the serving-context cell bound is a separate constructor the adapter calls (it needs `leleka-context`) | +| S19c | `93afb07bf` | `conversation` (cache, manager, snapshot, kv, state, model, binding, retention) | the CUDA-owner bindings (`conversation/original.rs`, `conversation/resident`) | +| S19d | `8987e9ab0` | `spec` (draft policy, adaptive window policy) | `LELEKA_SPEC_*` parsing (a free function reading `Settings`), the controller and the device round | +| S19e | `58e3d864e` | `request` (`admit`, the stop set, `ServeError`, `Lifecycle`, `run_request`) | `RequestOwners` and the `Owners` wrapper that implements `Lifecycle` over them | +| S20 | `e049e24fe` | `family` (`EngineFamily`, `spawn::`) | `Qwen35Cuda` (`backend/family.rs`) wraps `spawn_backend` and `spawn_backend_original_serve` | + +**Why the rest stayed in `leleka-engine-qwen35-cuda`.** It holds CUDA owners and the owner thread (`backend/`, `qwen_forward/`), reads the process +environment through `Settings`, uses `Instant::now()` (17 sites) and process globals (59), includes files with `#[path]` (100), and calls the +driver, the model-format reader and the native CPU expert. None of that can be in a crate that is built and tested without a GPU. The fake lifecycle +device (`lifecycle_fake`, S15) keeps mirroring the glue `prefill_actions` and `decode_phase`. + +**What S19 did not do.** `settings::process()` (a `OnceLock` read by leaf code), `Governor::global()`, `RECONFIGURING`, `INSTANCE`, +`StackConfig::clock` and `LoadEnv::clock` are all still in the adapter, and `engine-core` takes no `Settings`, clock or memory handle. The S13 and S14 +follow-ups that said "when the engine core is extracted (S19)" are therefore open. `generate_mtp_resume` (250 lines, complexity 44) and `generate` +did not move either. + +**The `dyn-trait` increase of S20 (+4).** The commit message of `e049e24fe` says the ratchets were raised by the `Box` signatures of the +seam; the baseline diff of that commit shows `dyn-trait:leleka-engine-core` 17 to 19, `dyn-trait:leleka-engine-fake` 0 to 1 and +`dyn-trait:leleka-runtime` 51 to 52. The four lines are `EngineFamily::spawn` and the free function `spawn` in `crates/engine-core/src/family.rs`, +`EngineFake::spawn`, and `Qwen35Cuda::spawn`. The same commit raised the size baseline of `desktop-core/tests/api_over_runtime.rs` from 644 to 646 +lines (the "2 test lines": the full-chain test starts its engine through `spawn::`); that is a size entry, not a `dyn` count. `Backend` +is the trait object the process already had at its boundary: `RuntimeServer` holds `Box` (`desktop-core/src/runtime_rpc.rs`) and the +existing `spawn_backend*` factories return it. Its methods are request-level and the tokens travel in the returned stream, so the seam adds no +dynamic dispatch per round or per token; the four lines are signatures. S22 renamed the five ratchet keys of `leleka-runtime` to `leleka-engine-qwen35-cuda` with the +same values (`dyn-trait` 52, `env-read` 1, `instant-now` 17, `path-include` 100, `process-global` 59). + +**Found after S22 and fixed in S26 (docs and scripts only).** `scripts/ci-coverage.json` named neither the three engine crates nor +`leleka-gateway-domain`, so `scripts/check-ci-coverage.py` failed on the S22 tip; `scripts/chain/build_rt.sh`, `scripts/decode-sm120/build_rt.sh` and +`scripts/profile/build_rt.sh` still looked for a test binary called `leleka_runtime-`; the bring-up scripts (`remote_sync.sh`, `regress_3080.sh`, +`run_gpu_smokes.sh`, `linux-tests/run.sh`) and the smoke inventory (`smoke_inventory.py`, `smoke-groups.json`) named `leleka-runtime`, whose lib target +has no tests since S22. Several documented commands did too (`docs/memory-safety.md`, `docs/original-serve.md`, `docs/windows.md`, +`docs/prefix-cache.md`, `docs/gpu-bringup.md`). Left on purpose: dated measurement records (`docs/ci-audit.md`, `docs/experiments/`, +`docs/prefill-throughput.md`, `docs/rope-and-memory-plan.md`, `docs/sampler-reference.md`, `docs/memory-safety-unsafe.md`, `docs/port-remaining.md` section 8) +and the doc comments in `crates/` (`crates/engine-core/src/family.rs` names `leleka_runtime::backend::Qwen35Cuda`; the `#[ignore]` text of +`crates/engine-core/src/prefix_cache/store/tests.rs` gives `-p leleka-runtime`). Those are code and stay for a code step. + ## leleka-gateway-domain `responses/` (STRA-338 S21, wider scope) The pure Responses protocol moved from `strata-control` to `crates/gateway-domain/src/responses/` with the code text