Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
20 KiB
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),
output-event.md (the canonical model output of the gateway, S23), ../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, leleka-cuda-model (the pure host-side models peeled out of leleka-cuda-driver: Error, projection formats and geometries, serving context, schedules and kernel specifications) |
| 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, OutputEvent and the output decoders, 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.
leleka-engine-qwen35-cuda has a default-on cargo feature preview-path (S25) for the legacy Rust-native "preview" decoder chain
(docs/original-serve.md): its spawn tier, Qwen35CudaStart::Native and the native serve loop. Off, the crate serves the Original path only
and refuses --backend-mode preview and the auto fallback with a clear error; the feature adds no edge between crates.
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.
flowchart TB
subgraph L4[L4 hosts]
ctl[strata-control<br/>gateway root]
dcore[strata-desktop-core<br/>engine process root]
rt[leleka-runtime<br/>facade]
end
subgraph L3[L3 adapters]
q35[engine-qwen35-cuda]
fake[engine-fake]
cuda[cuda-driver]
mfmt[model-format<br/>WeightSource]
cpux[native-cpu-expert]
rtc[runtime-client<br/>gRPC]
end
subgraph L2[L2 domain]
core[engine-core<br/>EngineFamily, run_request,<br/>prefix cache, conversation]
gdom[gateway-domain]
end
subgraph L1[L1 leaf libraries]
obs[obs<br/>Clock]
mem[leleka-memory<br/>MemoryPressure]
gtext[gateway-text, harmony,<br/>tokenizer, ...]
cudam[cuda-model<br/>Error, shapes, schedules]
end
subgraph L0[L0 contract]
api[backend-api<br/>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
cuda --> cudam
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<C> (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<S>, ScriptedPressure |
Arc<dyn MemoryPressure> 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<E>, admit} |
generic, no trait object | admission, reset or resume, prefill, decode, finish: the order and the failure classes run over any owners |
EngineFamily + spawn::<F> |
leleka_engine_core::family::{EngineFamily, spawn}; families Qwen35Cuda and EngineFake |
F is generic; the result is Box<dyn Backend> |
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<dyn Backend> 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<dyn Port> in AppState, boxed futures |
called once per request or per process; streaming loops read the plain mpsc receiver |
| OutputDecoder | leleka_gateway_domain::output::{LiveDecoder, AtEndDecoder, OutputEvent}, made by TextCodec::live_decoder and at_end_decoder (output-event.md) |
enum over the families (Qwen, Harmony) behind two decoder types; no virtual call per token |
one decoder per generation; the adapters of the families produce the canonical OutputEvent that the Responses answers consume |
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-driverand the adapter. The STRA-338 item says not to abstract graph capture until it is measured; nothing here measures it. - The glue
prefill_actionsanddecode_phaseofOriginalServeStack. 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
WeightSourceyet; 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) andcodec::TextCodecin the gateway, not throughEngineFamily. RECONFIGURING,INSTANCE,settings::process()andGovernor::global()are still process-wide in the adapter (tech-debt.md, S13 and S14).
How to add an engine family
Today spawn::<Qwen35Cuda> 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.
- Crate. Create
crates/engine-<family>-<device>(packageleleka-engine-<family>-<device>), add it to[workspace] membersinCargo.tomland to layerL3inarchitecture.json. Depend onleleka-engine-core,leleka-backend-apiand L1 libraries. Another L3 crate only through anadapter_edgespair that is a real port (the Qwen3.5 crate has three:cuda-driver,model-format,native-cpu-expert). Never depend on L4. - Domain first. Take policy from
leleka-engine-core(prefix_cache,conversation,prompt,spec,request). Anything that needs the OS, a device,std::envorInstant::now()goes behind the existing ports (EnvSource,Clock,MemoryPressure,WeightSource). - Implement the seam. A zero-sized marker
struct Family;withimpl EngineFamily for Family { type Config = ..; const NAME: &'static str = ..; fn spawn(config) -> Result<Box<dyn Backend>, BackendError> }, andBackendfor the engine it returns. For the request path implementLifecycleon the family's owners and callrun_request. Models:crates/engine-fake/src/lib.rs(smallest) andcrates/engine-qwen35-cuda/src/backend/family.rs. - Register. Add the crate to
desktop-core/Cargo.tomland callspawn::<Family>(config)where the root picks the engine; the result goes toRuntimeServer::newunchanged. - Fake-engine test. A GPU-free test that starts the family through
spawn::<Family>and drives a request, in the style ofcrates/engine-fake/src/tests.rs; for lifecycle behaviour implementLifecycleon a scripted owner, as thelifecycle_fakedevice of the Qwen3.5 adapter does.desktop-core/tests/api_over_runtime.rsis the full-chain test (real API router, realRuntimeServer, scripted engine). - Gates (next section):
python scripts/check-architecture.py,python scripts/check_architecture_test.py,python scripts/check-ci-coverage.py(add the package toscripts/ci-coverage.jsonand name it with-pinscripts/check-local.sh),cargo test -p <crate>, clippy with-D warnings. - 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 |
| mechanical file names | no new .rs file named by a mechanical split: impl_*.rs, *_fn.rs, *_<N>.rs / *_<N>_<M>.rs (a name must say what the module is and what it is for); the baseline lists the existing 964 files (mechanical_names) and an entry goes away when the file is renamed; scripts/dev/rustsplit now names the modules it creates after what they hold (foo, thing_methods, display_for_thing, thing_methods_from_<method>) and disambiguates with a word (_more), never a number |
mechanical_names, baseline mechanical_names |
| 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-256kcapture: 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 asHX-ID1,HX-ID2,HX-ID3,HX-ID-C2andHX-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 (S21responses_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-GATE2at17296a58f(S14, S15, S18), with a note that the commits after it up tofc591f4e9do not touch the engine process. It holds no identity or A/B record for S19 to S22 (38eb771a4toa4ceeab69), 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<E>, run_request over Lifecycle to engine-core::request |
| S20 | e049e24fe |
EngineFamily and spawn::<F>, 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 |