messages/request.rs (the Messages request types and Request::into_responses, CountRequest, text and block helpers) and
messages/reply.rs (message, stop reason, tool_use block, usage, the error type table and envelope as functions of the
status number) are in crates/gateway-domain. strata-control keeps the route layers, the SSE adaptation and the HTTP errors;
error_value(StatusCode, ..) is a wrapper over the domain function. The adapter tests stay where they are and pass on the
moved code (same test ids). The long functions are added to docs/architecture/tech-debt.md, the continuation is recorded in
docs/experiments/stra-338-gateway-track.md (90 golden cases; an earlier commit message says 96, which was a miscount).
harmony_conversation (the Responses input as Harmony messages), harmony_render (developer message, tools, rendering through
leleka-harmony, the date given by the caller) and prompt_date (PromptDate, its parser, civil_date) are in
crates/gateway-domain/src/responses/. strata-control keeps the process-wide prompt date, today() and render(request) in
responses/harmony_prompt.rs with the inline tests, so the byte-exact Harmony prompt tests keep their ids and pass on the
moved code. render_at lost its cfg(test) because the tests live in the other crate. Function texts are unchanged; the long
ones are added to docs/architecture/tech-debt.md.
CreateRequest, TextOptions, TextFormat, its validation and tool-choice rules, OutputItem, Usage, ResponseTrace with its
event stream, the prompt rendering (render_request_with), the output parsing and reasoning split (parse_output_items_with,
decode_generation_noted), reasoning_effort and the schema checks now live in crates/gateway-domain/src/responses/.
strata-control re-exports the types under responses::* and keeps thin wrappers with the old signatures for the places that
need a process flag, a stage span or a log line. The text of the moved functions is unchanged; the edits are listed in
docs/architecture/tech-debt.md (S21 wider).
Evidence: the golden fixture committed just before this (control-plane/tests/fixtures/golden/responses_pure.json, recorded
from the old code, 96 cases of render, validate, trace and parse) passes on the new code, and the Linux test ids of
strata-control, strata-desktop-core, leleka-gateway-text and leleka-gateway-domain are unchanged (0 changed, 0 missing).
Gate: --update-baseline --allow-increase was used for two entries. process-global:leleka-gateway-domain 0 -> 3 is the
memo of tool_schema_accepted moving with its function (process-global:strata-control fell 14 -> 11, the sum is unchanged).
render.rs is a new moved file of 405 lines (one 385-line legacy function), listed as debt.
generate takes any ServeDevice (the stack delegates to its own methods, once per request); FakeStack/FakeDevice implement RequestOwners, ServeDevice, OriginalServePort and PrefixDevice over a ManualClock script. 14 lifecycle tests: completion, length, eos, partial acceptance, cancel, deadline, device errors, refusal, timing, prefix reuse. S15 notes and the S19 design in tech-debt.md.
Generation (generate, generate_mtp), the terminal and event publication, the source verification, the measurement
recorder, the Original serve loop (request deadline, idle sweep, reconfigure), the TTFT marks, the seed plan, the prefix
device phases and the prefix cache (retention scale and phase timers, now per cache instead of a process OnceLock) take a
Clock; the composition roots hand them SystemClock. emit_event is one function in utf8.rs instead of two copies. Hot
loops keep comparing against the reading taken at the start of the request. Tests on a manual clock: terminal and event
backpressure limits, prefill/decode accounting, source verification reads, the idle sweep cadence and the prefix
retention.
Clock (SystemClock, ManualClock, AnyClock) lives in leleka_obs::time. The governor reads the host through MemoryPressure
(ProcPressure over the real /proc or Win32 text, ScriptedPressure for tests) and times itself, its ledger, the
telemetry window and the nvidia-smi rate limit on a Clock. Governor::new and the telemetry entry points keep their
signatures. Tests: rising, falling and flapping pressure, the one-second shed step and the stale-sampler fallback on
a manual clock.
The CPU pool fields of the memory topic move into MemorySettings::pool (CpuPoolSettings) so each constructor
stays short; no key and no spelling changes.
Golden tests for the parsers that read the captured namespace: the speculative engine (the numeric and the
set-ness reading of LELEKA_SPEC, clamps, the adaptive switch, arm lists, adaptive constants, legacy policy),
the NaN guard, the conversation cache policy (including a value that is not unicode), and the memory
governor keys. Long test tables carry #[rustfmt::skip] so each test stays within 30 lines.
docs/architecture/tech-debt.md: what S13 left outside the port and why (settings::process(), the other crates'
readers), the keys whose spellings differ on purpose, the reads that became snapshots, the functions this step
touched that were already over the limits.
Diagnostics topic of Settings: the bring-up trace, the driver-error trace (the nine driver_error functions
share crate::driver_errors_traced), the PLE, prefill-residual, seed and prefix traces, the serve profile
and the prefill profile sync. A set-ness switch is on for any value, as before; the serve profile and the
spec traces stay off for 0 and the empty string. The OnceLock readers are gone.
measure.py: a module declared inside a file that is itself compiled only for tests (for example
fivecase_frames.rs under native_down_candidate_only.rs, through #[path]) is test-only too. Unit test added.
Accounting only; env-read of leleka-runtime is now 1 (ProcessEnv::get_os, the one place that calls std::env),
instant-now 45 to 42, path-include 102 to 101, process-global 69 to 61.
Test-only: crates/leleka-runtime/src/qwen_forward/original_spec_controller/tests/golden.rs and golden/*.txt. Each scenario records the port operations, draft plans, max_end and the emitted tokens; re-record with LELEKA_UPDATE_GOLDEN=1. All 5 pass in a second run without the flag (Linux). No production code changed. Baseline raised by 2 lines (--allow-increase): the one oversize tests.rs gained the declaration of the golden child module.
lib.rs 3508 -> 938 lines, ffi.rs 1897 -> small, qwen_dispatch.rs 2003 and qwen_ffi.rs 1696 lose their inline test and installed-proof modules (scripts/dev/extract_modules.py, 5 self-tests; split_module.py --allow-root for lib.rs). Module paths, visibility and test ids are unchanged: 544 test ids before and after, cuda-driver tests 433 passed / 78 ignored before and after (Linux), host check clean. GPU identity and A/B follow with the combined batch 1+2 gate.
Kv topic of Settings: the prefill switches (stream, stream threshold, MoE span cache, GDN pool and mirror,
staged input), the dense slab, the prompt embedding alias, the legacy footprint, the PLE read-ahead and its
verification, the prefix retention and the checkpoint re-read. Every on-by-default switch keeps its own
spelling: on unless exactly 0 for the prefill group, packed unless 0 or off for the dense slab, trimmed
words for the footprint, an explicit word or the platform default for the read-ahead.
alias_requested, legacy_footprint_from and the draft-after-commit check remain as test-only helpers over
the same spelling tables that Settings uses, so the tests that exist for them still pin the production
spellings. The OnceLock readers of these keys are gone.
Memory topic of Settings: tail-skip rank and its cache limit, span cache, refill defer, swap wait, PCIe
locked-only and auto modes, the adaptive tier numbers (min count, margin, decay text), routing dump, per-layer
sizing, the fault-injection count of the expert cache, and the CPU pool switches (pool path, fence, lookahead,
open cache, prefetch word, eager admission, prefetch-off file).
ExpertTierConfig::from_environment keeps its signature and delegates to from_source(&impl EnvSource), the
strict parser (a value that does not parse is refused); tier_env_tests.rs pins its spellings, defaults and
refusals. LELEKA_ADAPT_DECAY stays text so its range check and log line still run, once, where they did.
LELEKA_CPU_PREFETCH_OFF_FILE keeps the path from the settings and still asks the file system on every call.
OnceLock readers of these keys are gone (process-global 93 to 81, env-read 59 to 37).
Adds the Settings port to leleka-runtime (src/settings.rs): an EnvSource trait with a ProcessEnv adapter
(the only std::env user) and a MapEnv adapter for tests, and a Settings value that captures the operator
namespace (LELEKA_*, STRATA_*) once, parses the plain switches and numbers into typed topic structs, and
hands the captured namespace to the parsers that report errors themselves. settings::process() is the
instance of the process; the load path carries it as LoadEnv::settings.
Serve topic: GGUF-PLE switch, public evaluation, profile name and digest, capture dir, the GiB budgets of
the memory plan, CPU worker count and pool plan, prefill loan tiers. The conversation cache policy, the PLE
reader policy, the memory governor config and the sampler path read the captured namespace.
Decode topic: coupled, overlap, draft-after-commit, serial publish, adapt defer, suffix reset, spec trace
and stats, logprob/draft/residual traces. The speculative engine, arm list, adaptive config and NaN guard
parsers take the captured namespace instead of calling std::env. LELEKA_SPEC keeps both of its readings:
the numeric one (a malformed value is ignored) and the set-ness one that decides whether the adaptive
window is the default (a malformed value still counts as set).
Parse semantics are unchanged per key; settings/*_tests.rs pin each spelling with a MapEnv. The cached
OnceLock readers of these keys are gone (process-global 113 to 93, env-read 93 to 59).
serve_load (about 1000 lines, 1170 after rustfmt) becomes load.rs (a 20-line order of
the phases) plus: load_admit (every refusal that needs no model byte, the memory
governor start), load_sources + load_bind (verify, bind, identity digest chain, expert
bank), load_identity, load_cuda (driver, context, probes, hand-over to the Original
serve stack), load_weights + load_moe + load_moe_gates (output head, KAR PLE, dense and
MoE caches; the adaptive and learned-main witness gates), serve_loop + serve_generate +
serve_run + serve_report (the command loop and one Generate), serve_close (teardown).
owner() is split the same way. Each phase takes a small context (LoadEnv, Bound,
Identity, Weights, Serving, Exchange) and returns a typed result.
Order and side effects are kept: the admission checks, the env reads
(LELEKA_ORIGINAL_SERVE_GGUF_PLE is still read in gguf_ple_load and in the refusal
detail line), the log texts (including the load-gate detail line and the
KAR_MTP_PROFILE / NATIVE_MTP_PROFILE logic of the kar-off-ab branch), the cancellation
checks, the lap marks, and the drop order of the CUDA objects (Weights drops dense, MoE,
KAR PLE, output head; the context is closed after the weights and outlives the binding).
The three conditions of the former execution gates are one match, the policy flags one
PolicyFlags::of. No GPU or numerical path was touched.
New tests (backend/load_tests.rs): PolicyFlags against the former expressions, the
execution gates against the former three sequential checks for all 6 executions x 8
boolean combinations, and the weight-cache log line against its exact text and the
saturating subtraction. Test ids: 689 before the S5 work, 694 now (the five added), the
same 2 environment-dependent failures and 58 ignored; cargo check --all-targets for
leleka-runtime and leleka-deploy gives the same warning counts, clippy reports nothing
in backend/. All new and changed functions are within 30 lines, complexity 10, nesting 4,
except one 127-column line that is a 119-character MoeWeightCache constructor name
(docs/architecture/tech-debt.md, which also lists what S5a moved verbatim and still misses
the limits). moe_weight_cache.rs gains three pub(crate) use lines for the witness types.
The architecture baseline loses the transient backend/load.rs entry.
Eight digest functions repeated the same SHA-256 loop (field, newline, hex "sha256:"
suffix) and three repeated the hex rendering. lines_digest(fields) now hashes a list of
fields each followed by a newline and hex_digest(digest) renders a finished digest;
optimized, queued owners, adaptive slots, resident owners, retained scratch, streamed
spill, original serve, execution mode and mtp mode use the first, kar expert mode and
kar mode (which hash raw bytes) use the second. The field lists and their order are
untouched. identity_digests_match_their_golden_values (added before this change, from
the old code) passes, as do the older distinctness tests of backend::tests.
backend/digests.rs: 300 -> 209 lines.
backend.rs (3797 lines) becomes a 258-line parent that keeps the imports, the
#[path] children (original serve, measurement, prompt, GPU proofs) and the two
policy test modules, plus backend/{config, spawn, spawn_optimized, spawn_original,
sources, proxy, owner, load, validate, digests, probes, request, session, generate,
generate_mtp, utf8, errors, tests}.rs. Every public path stays: the children are
re-exported with `use child::*`, so leleka_runtime::backend::* and crate::backend::*
resolve as before, and the code that used `super::name` from the #[path] children
still finds its names.
Items moved verbatim by the lexer-based item parser of scripts/dev/rustsplit; only
visibility changed (pub(super) on moved private items, struct fields and inherent
methods) and the new files were run through rustfmt. Two lints of the moved code
(a needless borrow of `config` in serve_load, a useless `.into()` in the context
admission error) were removed; both are value-neutral.
Test ids: 689 before, 690 after (the one added is the digest golden test of the
previous commit); the same 2 tests fail before and after in this WSL setup
(model_binding::qwen4exp_input::mtp::backing, unrelated), 58 ignored both times.
cargo check --all-targets -p leleka-runtime -p leleka-deploy: same warning counts
(runtime lib 80, lib test 64), none in backend files.
Architecture gate: the baseline entry of backend.rs (3770) is replaced by one for the
new child backend/load.rs (1170 lines). load.rs holds serve_load unchanged and is
decomposed in the S5b commits that follow, which remove the entry again. The 8
remaining gate errors are not from this change (deploy file sizes, backend_original_serve.rs,
env-read ratchet 261 vs 256, all introduced by the kar-off-ab integration).
identity_digests_match_their_golden_values fixes the output of the twelve digest
functions of backend.rs (optimized with and without profile, queued owners, streamed
spill, retained scratch, resident owners, adaptive slots, original serve, kar expert,
execution mode, mtp mode, kar mode) on fixed small inputs. The values were produced by
the unmodified functions; the test lives in backend/digests_golden.rs, the first child
module of the directory the split fills next.
New crate crates/gateway-domain, the first member of layer L2 in architecture.json (L2 is now a pure layer: tokio, axum,
reqwest, libc and the other adapter crates are forbidden dependencies there). It depends on serde, serde_json,
leleka-sampler-ref and leleka-tokenizer only. Moved out of control-plane/src with git mv, content unchanged apart from
paths: sampling (request sampling extensions, validation) and EngineTune (was in wire.rs), reasoning_budget (the budget
driver and its tests), codec (Family, TextCodec, TokenDecoder, QwenCodec), json_order, and the Chat Completions
translation (chat_completions: Request -> Responses request, reply fields; the axum handlers stay in chat.rs).
strata-control re-exports codec, json_order, reasoning_budget and sampling under their old paths, and wire.rs re-exports
EngineTune, so no caller and no test outside the moved modules changed. 4 new tests cover the chat translation.
Architecture gate: layer entry added; dyn-trait:leleka-gateway-domain = 5 appears because the five dyn in the moved
code (Box<dyn TokenDecoder>, Box<dyn Iterator> in the budget driver, &dyn Fn, ...) change crate; dyn-trait:strata-control
fell 21 -> 16 in the same step, so the total is unchanged (--allow-increase was needed for the new per-crate key only).
Test outcomes: 597 ok / 2 ignored before, 615 ok / 2 ignored after (18 new tests); the 13 moved tests keep their ids in the
new crate and their outcome.
The splitter now cuts an inherent impl longer than its target into several impl blocks of the same type between associated items (the generics and where clause repeated, the doc comment kept on the first block), so the giant impls left by S12b/S12c (up to 2,000 lines) split too. 53 further module files of the cold and hot crates are split; the baseline drops to 127 oversize files holding 109,000 lines (329 files and 303,000 lines on main). Types, constants, macros, tests and the files kar-off-ab edits stay; crate roots and bins are untouched.
The same lexer-based splitter as S12b, now with explicit re-exports: every moved free fn comes back to its module under its old name and old visibility (cfg attributes carried), so a name can never clash with another glob import. 162 module files of leleka-runtime (68), cuda-driver (84), deploy (10), cpu-sys, igpu and leleka-memory are split into groups of about 250 lines; types, constants, macros, nested modules and tests stay. Not touched: the files kar-off-ab edits, crate roots (lib.rs, main.rs, bin/*), and giant single impl blocks (next). This changes codegen-unit placement of engine code, so it is covered by the bitwise replay and the paired A/B on the 5090, not by a binary comparison.
scripts/dev/split_module.py (lexer-based, with 16 self-tests) moves the top-level fn and impl items of 59 oversize module files in control-plane, desktop-core, model-format, gateway-text, leleka-memory, experimental-ref, context, serving-policy, tokenizer, backend-api, quant-core, harmony, igpu, libc-shim, npu-service and runtime-client into foo/<name>.rs groups of about 250 lines; types, constants, macros, nested modules and tests stay, every path stays valid through pub use re-exports, restricted visibilities keep their scope one level down, include paths and super:: paths are shifted. Not touched: leleka-runtime, cuda-driver, native-cpu-expert, sampler-ref and cpu-* (hot path, next wave) and the files kar-off-ab edits.
The baseline drops from 311 to 263 oversize files and from 273,600 to about 233,000 lines; the path-include ratchet ignores dir/name.rs child declarations.
The dedent by four spaces changed how rustfmt wraps some test lines; the 25 affected tests.rs files (strata-control, desktop-core, runtime-client, deploy, gateway-text and the strict crates) are formatted so cargo fmt --check stays clean for the crates that CI gates on. Only test files change.
scripts/dev/extract_tests.py moves a trailing cfg(test) mod tests block into foo/tests.rs for 118 files of leleka-runtime, cuda-driver, control-plane, gateway-text, deploy and nine smaller crates (31,000 lines), leaving production code and test ids untouched; 22 files that are themselves loaded through a path attribute carry an explicit path to their tests file. Not touched: the files the kar-off-ab branch edits (backend.rs, backend_original_serve.rs, backend_original_serve_replay.rs, qwen4exp_resident_expert_source.rs and seven deploy files).
Verified: cargo check --all-targets for the whole workspace on x86_64 Linux and on the Windows host; the 2429 library unit-test ids of the workspace are identical before and after (Linux listing diff empty); the loadable sections of leleka-inference, leleka-daemon, leleka-cli and strata-next are byte-identical between a release build before and after (scripts/dev/elf-sections-equal.sh), so the shipped code is the same. The architecture ratchets exclude tests.rs from the path-include count; the baseline drops from 329 to 311 oversize files and from 302,000 to 273,600 lines.