Files
leleka/docs/architecture/tech-debt.md
T

46 KiB

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; 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.

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, load_weights, load_moe, load_moe_gates, serve_loop, serve_generate, serve_run, serve_report, serve_close; all of them are inside the limits except the one line named first. What was moved verbatim in S5a and is still outside the limits:

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 (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
sources.rs verify_sources_parallel 42 lines splitting the scoped verification (the profile read moved to the WeightSource port in S18 and is within the limits)
proxy.rs start_generation, validate.rs validate_handle 44 lines; 46 lines and complexity 14 splitting the checks into predicates
config.rs the *_EXECUTION identity strings are single lines of 120 to 200 columns string continuation, with the golden digest test as the guard

Process-wide state and reads that the policy file architecture.json counts and that this directory still holds: RECONFIGURING and INSTANCE (process atomics that config.rs still owns, see S14 below), and the Box<dyn Backend> returned by the factories (startup composition only). The Instant::now() sites of generate*.rs, utf8.rs, sources.rs and GPU_ORDINAL moved in S14. The environment reads that were here (LELEKA_ORIGINAL_SERVE_GGUF_PLE, LELEKA_PUBLIC_EVALUATION) now read Settings (S13, below).

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/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 captured once, the plain switches and numbers are typed fields of five topic structs (serve, decode, memory, 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-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.

What is still outside the port, and why:

Where What Removed by
settings::process() one OnceLock<Settings>: 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
replay and GPU proof modules (backend_original_serve_replay.rs, gpu_proofs/) read their operator inputs from std::env test-only, not counted

Keys whose spellings differ on purpose (kept as they were, not unified):

  • LELEKA_SPEC is read twice: as a number (trimmed, malformed ignored) and as set-ness (decides whether the adaptive window is the default, so a malformed value still switches it off).
  • On-by-default switches use three families: off only for exactly 0 (prefill group, per-layer sizing), off for off or 0 (overlap, adapt defer, span cache, swap wait, eager admission), packed unless 0 or off (dense slab). Opt-in switches use exact words: 1, on (loan tiers, refill defer, locked-only), 1|on|yes (embed alias), trimmed 1|on|yes|true (legacy footprint), on|1 (draft after commit), serial, full, lag.
  • Trimming differs per number: trimmed for LELEKA_SPEC*, tail skip, prefix retention, STRATA_PREFILL_STREAM_MIN; untrimmed for the CPU worker count, the GiB budgets, the cache-fail count, the logprob depth and the adaptive tuning.
  • Set-ness switches (LELEKA_BRINGUP_TRACE, the trace group, STRATA_CKPT_REREAD) are on for any value, 0 and the empty string included; LELEKA_SPEC_TRACE, _STATS and LELEKA_SERVE_PROFILE are off for 0 and empty.
  • LELEKA_PCIE_AUTO selects two modes by two words (lag, on); LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED accepts NaN; LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB only counts over a file-mapped bank (the check stays at the call site).
  • A malformed value is refused (conversation cache, PLE reader, expert tier, memory governor), logged and replaced by the default (NaN guard, adapt decay), or ignored (everything else), exactly where it was before.

No key is re-read at run time through the port. Reads that used to happen per request, per chunk or per error and are now fields of the capture: LELEKA_CAPTURE_DIR, STRATA_OLD_SAMPLER and STRATA_SAMPLER_ONE_BLOCK (per request), LELEKA_PREFILL_STREAM, STRATA_PREFILL_STREAM_MIN, LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED, LELEKA_TRACE_PREFILL_R, LELEKA_PLE_AHEAD_VERIFY (per prefill chunk or batch), LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED (per decode phase), LELEKA_TRACE_DRIVER_ERRORS (per error). Nothing in the process sets an environment variable after start, so the values are the same. The one live toggle is the file named by LELEKA_CPU_PREFETCH_OFF_FILE: the path is a setting, its existence is still asked of the file system on every call. The replay harness overrides (set_span_cache_override, set_pool_override, set_sized_override, set_tail_skip_arm, PREFILL_STREAM_OVERRIDE) keep their atomics; with no override they follow the settings.

Functions this step touched that were already over the limits (a few lines changed inside each, not made worse): memory_governor::startup (63 lines), backend_original_serve::{generate, run}, OriginalServeStack::open (259 lines), OriginalPromptExecutor::forward, KarPleCache::stage_batch, DirectTier::with_path, ExpertTierConfig::from_source (67 lines, 16 branches: it was from_environment), seed_residency, spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots, and three lines of 144 to 173 columns that were already there (impl_default_for_ttftmarks.rs header, impl_originalservestack_2.rs arm lines, backend_original_serve.rs capture call).

Clock and MemoryPressure (STRA-338 S14)

Clock (leleka_obs::time, time/clock.rs): trait Clock { fn now(&self) -> Instant; fn since(&self, earlier: Instant) -> Duration } with SystemClock (zero-sized, the only production Instant::now() of the port), ManualClock (shared timeline, advance, and ticking(step) which moves after every reading so a polling loop with a deadline ends in a known number of rounds), AnyClock (an enum of the two, for the owner that cannot be generic) and Stopwatch<C> (a clock plus its start: "milliseconds since"). The reading stays a plain Instant, so values from either clock are stored and compared as before. Rule: a clock is read at coarse points (a request, a tile, a decision, a sampling tick); hot loops compare against the reading taken at their start (run.clock.since(start) is a statically dispatched call on a generic C that is SystemClock in production).

Where it is injected:

Place How
Generation<C = SystemClock> (generate.rs, generate_mtp.rs) the request start and the per-step deadline checks; LoadEnv::clock hands SystemClock to build_run
emit_terminal, emit_event (utf8.rs; the second one replaces two identical copies in generate.rs and the Original serve loop) the 30 s backpressure limit
verify_sources_parallel one reading per phase, passed to load_clock::span
measurement::Recorder<C = SystemClock> prefill and decode durations of an observed request
Original serve loop (backend_original_serve.rs, Run::clock) request deadline, telemetry instants, reconfigure duration, idle_sweep::IdleSweep (the 15 s housekeeping cadence, its own tested type)
StackConfig::clock: AnyClock TTFT marks, the seed plan timers, the prefix device phase timers, and the clock of PrefixServe
PrefixServe::with_clock (a Stopwatch<AnyClock>) the retention scale (wall_ms, now milliseconds since the cache was built instead of a process OnceLock<Instant>: only differences are used) and the lookup, import and park timers
leleka-memory: Governor::with_parts, Ledger::with_clock, telemetry::start_with_clock, request_started_at/tokens_delivered_at, smi::probe_with_clock uptime and shed cadence, stage timing, the sampler tick, the in-flight request clocks (the old entry points call the same code with SystemClock)

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 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.

MemoryPressure (leleka_memory::pressure_port): trait MemoryPressure: ProcSource + Send + Sync { fn facts(&self) -> HostFacts }. ProcPressure<S: ProcSource> is the production adapter (/proc and /sys on Linux, the Win32 text renderings of winproc.rs on Windows, parsed by HostFacts::probe exactly as before); ScriptedPressure hands out one scripted reading per probe, the last one repeating (available_mib(&[..])). The governor reads the host only through it (probe, available_now, the sample, the lock allowance and the heal check); it is also a ProcSource because the residency guard and the census still read single files (smaps). Governor::new(cfg, Arc<dyn ProcSource>) keeps its signature; with_pressure and with_parts(cfg, pressure, AnyClock) are the composition points. Tests drive rising, falling and flapping pressure, the once-a-second shed step, the stale-sampler fallback and the admission decisions without a sleep (governor/pressure_tests.rs).

Process globals: GPU_ORDINAL is gone (the ordinal travels in Run, the value it always had), and the retention OnceLock<Instant> with it. Left, and why: RECONFIGURING (one flag for every backend of the process; moving it into 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 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).

Ratchets (totals over the workspace): instant-now 242 -> 209 (leleka-runtime 42 -> 17, leleka-memory 12 -> 1, leleka-obs 0 -> 3 for the three adapters), process-global 267 -> 265, dyn-trait 215 -> 215. Functions this step 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 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.

Request lifecycle seams and the FakeDevice (STRA-338 S15)

What was found. The engine already has a device seam at every granularity the lifecycle needs, each a trait that the real CUDA path implements and that production code is generic over (no dyn per round, chunk or token):

Granularity Trait (file) Real implementer Driven by (production code)
request RequestOwners (original_serve_request.rs): is_fresh, reset, resume, prefill, decode, finish OriginalServeStack run_request: admission, cancel, resume or reset, finish
request layer ServeDevice (same file, new in S15): serve, reused_tokens, last_timing, expert_tier_stats OriginalServeStack (delegates to its inherent methods) generate of the Original serve loop: events, usage, deadline, telemetry
prefix cache PrefixDevice (original_serve_prefix.rs): position, park_*, import, restore_draft OriginalServeStack PrefixServe, PromptPlan
verify round OriginalServePort (original_serve_engine.rs): run_window, commit_window, draft_committed, checkpoints NativeServePort OriginalServeEngine, OriginalSpecController, serve_request

S15 added only ServeDevice: generate took &mut OriginalServeStack and now takes &mut impl ServeDevice; the four calls it makes (one per request) go through the trait, the stack's methods are the same functions called by the same code. serve is generic over the two closures (no dyn was added). The runner module is pub(super) so the tests can call generate. Nothing in the hot decode loop, the kernels, the launch order, the log text or the environment reads changed, so the production path is the same code as before (checked: the lib test ids and the warning count are unchanged, see below; no GPU run was possible).

Decision: the CUDA path was not moved onto a new trait. It is already on the four above. What stays concrete is the glue between them, prefill_actions and decode_phase of OriginalServeStack, because both hold CUDA owners (executor, session, the verifier assembly with its fallback, the expert tier lend/refill/seed). Making that glue generic touches the decode phase (engine construction, settle_state, tail checkpoint) and the prefill phase (tier hooks), which is the S19 step and needs the GPU identity and A/B gates. So the test device mirrors the glue instead of sharing it (see "What the fake mirrors").

FakeDevice (qwen_forward/original_serve_stack/lifecycle_fake*.rs, cfg(test)):

  • FakeDevice implements OriginalServePort and PrefixDevice over one scripted state: a positional buffer of one token per cell, a digest of the tokens read in order (the recurrent state), the committed branch, an asynchronous commit published by wait_commit, and a log of what the lifecycle asked of it.
  • The model is a fixed permutation of the printable ASCII range (model), so the text of any request is known whatever the acceptance pattern. Script says how long a chunk and a round take on a ManualClock, how many drafted tokens each draft call gets accepted (accept, the last entry repeats), and where one chunk or one round fails or the client cancels (fail_chunk, fail_round, cancel_in_round; each fires once).
  • FakeStack implements RequestOwners and ServeDevice over it, with the prefix cache on a 256-token grid when asked.
  • Tests (backend/lifecycle_tests.rs, lifecycle_tests/ends.rs, lifecycle_tests/prefix.rs) drive the real generate and run_request, PromptPlan, PrefixServe, OriginalServeEngine, OriginalSpecController and serve_request: normal completion and the order of resume, prefill, rounds and finish; the length limit at exactly max_new for three acceptance patterns; an EOS inside a round (counted, no text); partial acceptance (the committed rows per round 1, 3, 1, 2, 4 for the script 2, 0, 1, 3, windows of 1 then 4 rows, text unchanged); client cancel in a decode round, then the next request after a reset; the 24 h deadline expiring between rounds and between prompt chunks (a ManualClock, no sleep); a device error mid-prefill and mid-round (both checkpoints restored, the next request served); a request refused by admission and one cancelled before the first owner call (no owner touched); prefill_ms and decode_ms and the number of rounds against the clock; a prefix hit (deepest grid point, reuse of 512 tokens, the cells written back after another session, the resumed read ending in the full read's digest); a cancelled request keeping the checkpoints and a failed one dropping them.

What the fake mirrors, and what it does not cover (the list S19 and S20 work from):

Gap Where Removed by
FakeStack::read_prompt/serve_rounds repeat the plan, cancel, chunk and prefix bookkeeping of prefill_actions and the engine/controller/serve-loop part of decode_phase lifecycle_fake/stack.rs (about 100 lines) S19, below
text stop sequences the gateway, not the engine: the engine stops on the EOS ids, max_new and the context gateway track
TailMode::Reply (after_decode), the conversation cache (ResumeDevice), the lend/refill/seed hooks of the expert tier fake has no decoded cells, no ServeConversation, no tier S19 hooks below
NaN guard retry, adaptive window, the broken poison of the stack Script has no non-finite output, FakeStack has no mark_broken Script::nonfinite_round, then the stack's broken once the owners are behind a trait
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):

/// Condition prompt[resume..n-1] into the session, one chunk per action (prefill_actions without the CUDA setup).
pub(crate) trait PromptDevice: PrefixDevice {
    fn position(&self) -> Result<u64>;                 // session.target_origin()?.next_position()
    fn read_chunk(&mut self, prompt: &[i32], first: usize, count: usize, cancel: &mut impl FnMut() -> bool) -> Result<()>;
    fn after_action(&mut self, prompt: &[i32], action: &PromptAction);   // conversation cache hook
}
pub(crate) fn read_prompt<D: PromptDevice>(
    dev: &mut D, prefix: Option<&mut PrefixServe<D::State, D::Block>>, plan: PromptPlan<'_>, prompt: &[i32],
    cancel: &mut impl FnMut() -> bool,
) -> Result<(), SpecError>;

/// Open the decode side for one request and close it again (decode_phase: assemble ... settle_state/disassemble).
pub(crate) trait DecodeDevice {
    type Port: OriginalServePort;
    fn open(&mut self, request: &ServeRequest) -> Result<Self::Port, SpecError>;
    fn close(&mut self, port: Self::Port, result: &Result<ServeOutcome, SpecError>, want_tail: bool);
}
pub(crate) fn decode_request<D: DecodeDevice>(
    dev: &mut D, controller: &mut OriginalSpecController, settings: &OriginalServeSettings, request: &ServeRequest,
    emit: &mut impl FnMut(&[i32]) -> Result<()>, cancel: &mut impl FnMut() -> bool, clock_ms: impl FnMut() -> f64,
) -> Result<ServeOutcome, SpecError>;   // OriginalServeEngine::new(port, ..), set_min_p, serve_request, close

OriginalServeStack::prefill_actions and decode_phase become thin wrappers that build the plan options, call the two functions and keep the tier lend/refill/seed, the verifier assembly and settle_state in open/close; FakeStack calls the same two functions with the FakeDevice and the 100 mirrored lines go. The serve loop itself (serve_request) and OriginalServePort are untouched, so the per-round path keeps its shape. Gates for that step: GPU identity (greedy output and tensor values against the baseline) and a paired A/B on the 5090 before it is merged.

Checked for S15 (WSL, no GPU): leleka-runtime lib test ids 767 -> 781 (14 added, none missing; the two known failures failed_cleanup_or_replaced_inode_never_deletes_unowned_file and frozen_same_fd_hash_owner_and_source_independence fail on both sides); cargo check --all-targets -p leleka-runtime -p leleka-deploy warnings unchanged (243 lines starting with warning); clippy on leleka-runtime --all-targets gives the same warning set as the S14 tip and none in the new files; the architecture gate reports 0 errors and no ratchet moved (dyn-trait stays at 68: ServeDevice::serve is generic over the closures). Functions touched and already over the limits, not made worse: generate (about 140 lines).

WeightSource (STRA-338 S18)

The port (leleka_model_format::weight_source, layer L3 next to the code that owns the files; no new crate edge):

pub trait WeightSource {
    fn identity(&self) -> WeightIdentity;                      // sha256, bytes, Verification, BackingKind
    fn region(&self, range: Range<u64>) -> Result<Region<'_>, WeightError>;
    fn len(&self) -> u64;  fn live_len(&self) -> Result<u64, WeightError>;   // live_len: did the store grow or shrink?
}
pub enum Region<'a> {
    Resident(&'a [u8]),                                        // addressable store: the slice, the same address every call
    Positional { file: &'a File, offset: u64, len: u64 },      // file / sealed memfd: read_at(..) fills the CALLER's buffer
}
pub fn sha256_of<S: WeightSource + ?Sized>(source: &S, scratch: &mut [u8]) -> Result<[u8; 32], WeightError>;

BackingKind is Memory | HugePages | MappedFile | File | SealedMemfd; Verification is Unverified | FullPass | Stamp | AttestedMemfd | SparseExtents (From<KarTrust>). The trait has no Send/Sync bound (a mapped tensor owns a raw mapping). It is generic, not dyn: callers write S: WeightSource + ?Sized, so &dyn WeightSource also works, and the dyn-trait ratchet did not move. A source is opened once per load and read at load time; nothing is on the decode path.

No second copy by accident. A source lends borrowed views of its single backing store and has no method that returns an owner of the bytes. The only owned buffers are the caller's: the scratch of sha256_of / for_each_chunk, the staging packet of stage_window, the profile buffer of read_ranked_expert_profile, each created and sized by the caller. Tests: memory_source_..., mapped_tensor_source_... and retained_tensor_source_returns_the_same_address_for_every_call (the same pointer on every call, and sub-ranges are offsets into the first), positional_sources_expose_no_address_... (a file or memfd region has no slice, only read_at into the caller's buffer), every_adapter_reports_the_same_digest_for_the_same_bytes (mem double, file, verified shard, all against Sha256::digest, with scratch sizes 1, 7, 33 and 4096), and the_production_port_has_no_owning_copy_method, which scans the production files of the port for to_vec, to_owned, into_boxed_slice, Vec<u8>, Box<[u8]>, Arc<[u8]>, Rc<[u8]> and Cow< (only the double in mem.rs owns bytes).

Adapters (all wrap existing code; none changes what a load maps, copies or reads):

Adapter Over Backing, verification
FileWeightSource<F: Borrow<File>> any open file or sealed memfd, owned or borrowed (&File) File or SealedMemfd; the identity the caller gives, unverified(..) or hashed(..)
impl WeightSource for VerifiedGgufFile (gguf/impl_verifiedgguffile/port.rs) the retained verified descriptor of a shard, positional File, FullPass (matched at open, by hash or by a current stamp: the stamp case is not recorded, see below)
ResidentWeightSource (VerifiedGgufFile::{mapped,retained}_tensor_source) the ResidentTensor the bank already owns MappedFile, Memory or HugePages; digest of the artifact, bytes of the tensor
impl WeightSource for KarInspection the archive descriptor of the KAR reader File, Unverified with a zero digest (inspection checks structure and CRCs, the pin lives with the verifier)
InheritedKarArchive::weight_source() (runtime) the admitted sealed memfd or read-only file, borrowed SealedMemfd or File, Unverified, the pinned archive digest (the digest of the extents when sparse)
MemWeightSource an owned Vec or &'static [u8] Memory, FullPass; the test double
WeightRange<'a, S> any source as a kar_levels::RangeSource the refusals of KarInspection::read_exact_at (range, overflow, changed length)

Migrated: read_ranked_expert_profile (load phase read_profile, once per load) opens the pinned profile through FileWeightSource and reads it with read_pinned_profile<S: WeightSource + ?Sized>; same refusal texts in the same order (unrecognized, unavailable, extent mismatch, exhausted, read failed, digest mismatch, domain mismatch), same buffer (try_reserve_exact(len + 1), one Vec of len), same digest; a file that ended early or grew after the length check is the digest refusal, as when the profile was read to its end (live_len). Tests in backend/profile_tests.rs. stage_window (the KAR expert staging) accepts any source through WeightRange; KarExpertSource still passes its two KarInspections, which keep their own RangeSource impl, so its behaviour did not move.

Deferred, and why (each is a step with its own gates; none is half-done):

  1. Shard open and bind. VerifiedGgufFile::open(path, digest) hashes and indexes by path, and Qwen4ExpArtifact::bind takes the concrete files; stream_tensor / read_tensor_into read through the retained descriptor with a seek and a 16 MiB stream buffer. Moving them onto Region::read_at changes syscalls (seek+read to pread) and on Windows the shared file cursor (seek_read moves it; read_exact_at of the port documents that), and bind reads the metadata with the cursor. Plan: (a) give VerifiedGgufFile a StreamSource seam in the same file that the port impl uses, keep the stream buffer; (b) switch stream_tensor to the port with an strace/read-count comparison on the laptop file; (c) let ExpertFileOwner and the bank keep a ResidentWeightSource instead of a ResidentTensor (same value, the type rename); (d) record stamp-vs-hash in VerifiedGgufFile so identity().verification can say Stamp.
  2. KAR verification and row reads. load_pinned_inherited_archive re-opens the admitted descriptor into an owned File that KarInspection::inspect consumes, and verify* hashes with bulk_read (O_DIRECT, many threads: it needs the File, not slices); KarPleRowReader duplicates 16 handles. Plan: Region::file() for the bulk strategy, verify* taking &impl WeightSource, the row reader taking the port; the 55 GB hash time and the leleka-kar-startup line are the A/B guard. sparse archives need an extents() accessor on the identity (a hole reads as zeros through the port).
  3. CPU expert tier (leleka-native-cpu-expert, ExpertFileOwner): the bank is C++-owned memory filled from the GGUF by native code, so the port would have to lend raw pointers across FFI. Needs its own review of lifetimes; left alone.
  4. The memory governor's mappings (archive_handle(), guard_archive*) still take the File; they map, they do not read.

Checked for S18 (WSL, no GPU): leleka-runtime lib test ids 781 -> 787 (6 added, none missing; the two known failures failed_cleanup_or_replaced_inode_never_deletes_unowned_file and frozen_same_fd_hash_owner_and_source_independence fail on both sides); leleka-model-format lib 155 -> 166 passed (11 added; the three qwen4exp tests that replace files under /mnt/c fail with "size changed after verification" on the S15 tip and on this one alike); cargo check --all-targets -p leleka-runtime -p leleka-deploy warnings unchanged (243 lines starting with warning); clippy on both crates reports nothing in the new or changed files; the architecture gate reports 0 errors and no ratchet 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<E>, Lifecycle, run_request) RequestOwners and the Owners wrapper that implements Lifecycle over them
S20 e049e24fe family (EngineFamily, spawn::<F>) 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<Settings> 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<dyn Backend> 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<F> 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::<EngineFake>); that is a size entry, not a dyn count. Backend is the trait object the process already had at its boundary: RuntimeServer holds Box<dyn api::Backend> (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-<hash>; 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 unchanged; only what the compiler or the gate forced was edited. The functions below keep the shape they had and miss the limits (function 30 lines, complexity 10, nesting 4, 120 columns). A line count is the function as measured by scripts/dev style counting (signature to closing brace).

File Function Lines Complexity Removes it
responses/render.rs render_request_with 385 58 one function per input item kind (message, reasoning, function_call, *_output) and a small state struct for calls, outputs, custom_calls, reasoning; the file is also over 400 lines (baseline entry 405)
responses/trace.rs ResponseTrace::build_with_terminal 246 40 split the checks, the item loop (one function per OutputItem variant) and the usage block
responses/validate.rs CreateRequest::validate 159 46 one function per field group (text.format, tools, tool_choice, limits)
responses/tool_calls.rs decode_generation_noted 72 8 the two token-count loops into one helper; nesting 5
responses/tool_calls.rs parse_output_items_with 35 3 segment to item mapping into a function
responses/effort.rs reasoning_effort 39 5 field checks and the effort table as two functions
messages/request.rs Request::into_responses 156 28 turn merging, block flushing, tool and choice mapping as separate functions; nesting 6
messages/reply.rs message 22 10 content blocks of an output item as a function; nesting 6
responses/harmony_conversation.rs conversation 142 22 one function per input item kind; nesting 7
responses/harmony_render.rs instruction_texts, render_dated 43, 51 13, 5 the constraint sentences and the tool list as separate functions (the sentences repeat render.rs; keep the two in step)

Lines wider than 120 columns remain in the json! bodies of trace.rs, in render.rs (string literals and a json!), and in the doc comment of tool_schema_accepted; they are moved text.

What changed in the move, apart from pub(super) becoming pub:

  • render_request -> render_request_with(request, marks, template_span): the render_template stage span is created by the closure the caller passes (strata-control keeps render_request with the old signature and passes stage_trace::span), so the domain does not read the stage trace global.
  • parse_output_items_after -> parse_output_items_with(.., options) -> (items, notes) and decode_generation_with -> decode_generation_noted(.., natural_options, on_call_in_reasoning): the recovery flag is the caller's (TOOL_CALL_RECOVERY stays in strata-control) and so are the log lines (elog!). strata-control keeps both old names as wrappers. The log line for a call written inside the reasoning is now emitted by a closure at the same point.
  • CreateRequest::apply_defaults(&Settings) -> apply_defaults(&MergedDefaults, &SharedDefaults); the one caller passes settings.merged() and settings.shared() in that order, as the method did.
  • codec::decode_all is generic over C: TextCodec + ?Sized (it took &dyn TextCodec), so the dyn-trait count of the domain crate did not rise.
  • tool_schema_accepted keeps its process-wide memo (a coding agent sends the same tool schemas on every request and the schema is validated three times per request). It moved with the function, so process-global:leleka-gateway-domain is 3 and process-global:strata-control fell from 14 to 11 (--allow-increase was used for the new key only; the sum is unchanged). Removing it needs the memo owned by the gateway state and passed to validate, which changes every caller.

strata-control responses/ (STRA-338 S6, rest)

responses.rs is 97 lines (module list and re-exports); its children are named for what they do: route, create, intake, render, reasoning, tool_recovery, stream/, history, history_adapter, resources, errors, harmony_prompt. The text of every function is unchanged (moved only); the fields and constants that siblings read became pub(super). Functions that still miss the limits (30 lines, complexity 10, nesting 4):

File Function Lines Complexity Removes it
responses/create.rs create 391 29 admission, history lookup, prompt preparation, command build, buffered answer and stream start as separate functions
responses/intake.rs prepare_input_tokens 99 7 text prompt, picture expansion and context check as three functions
responses/intake.rs expand_images, parse_request, count_input_tokens 62, 53, 34 2..5 one step per function
responses/history.rs StoredResponse::input_page 76 18 cursor parsing, order and limit as helpers (nesting 6)
responses/history.rs ResponseHistory::open, insert_with_limit 63, 55 19, 9 snapshot decode and entry check as functions

Limits gate and the legacy sites listed here (STRA-367)

The limits of this page are enforced by scripts/check-limits.py (rules, measures, allowlist and census: limits-gate.md). The sites listed in the sections above and below are legacy that was moved verbatim: none of them is in limits-allowlist.json today, because the allowlist is empty on the default base (the tip of the integration branch) and the census total in limits-baseline.json already counts them. They become allowlist entries the moment a change touches or relocates them (scripts/check-limits.py --allowlist-add --reason ... --owner STRA-338), with the numbers below as the starting point. Measures are the gate's own (? and the boolean operators count, so complexity is higher than the hand counts above):

Gate key (path, name) Lines Complexity Nesting Wide lines Listed in
crates/leleka-runtime/src/backend/generate_mtp.rs generate_mtp_resume 250 70 4 0 S5a
crates/leleka-runtime/src/backend/generate.rs Generation::prefill_chunk 91 24 3 0 S5a
crates/leleka-runtime/src/backend/generate.rs generate 60 19 2 0 S5a
crates/leleka-runtime/src/backend/generate.rs Generation::step 55 10 2 0 S5a
crates/leleka-runtime/src/backend/generate.rs Generation::target_step 34 7 1 0 S5a
crates/leleka-runtime/src/backend/spawn.rs spawn_backend_configured 100 11 1 0 S5a
crates/leleka-runtime/src/backend/sources.rs verify_sources_parallel 42 1 3 0 S5a
crates/leleka-runtime/src/backend/proxy.rs Backend for Proxy::start_generation 44 10 1 0 S5a
crates/leleka-runtime/src/backend/validate.rs validate_handle 46 17 2 0 S5a
control-plane/src/responses/create.rs create 391 35 2 5 S21
control-plane/src/responses/intake.rs prepare_input_tokens 99 9 2 0 S21
control-plane/src/responses/intake.rs expand_images 62 7 2 1 S21
control-plane/src/responses/intake.rs parse_request 53 6 1 0 S21
control-plane/src/responses/intake.rs count_input_tokens 34 4 2 0 S21
control-plane/src/responses/history.rs StoredResponse::input_page 76 21 6 0 S21
control-plane/src/responses/history.rs ResponseHistory::open 63 25 3 0 S21
control-plane/src/responses/history.rs ResponseHistory::insert_with_limit 55 12 2 0 S21
crates/gateway-domain/src/responses/render.rs render_request_with 385 93 6 4 S21
crates/gateway-domain/src/responses/trace.rs ResponseTrace::build_with_terminal 246 51 4 15 S21
crates/gateway-domain/src/responses/validate.rs CreateRequest::validate 159 51 3 0 S21
crates/gateway-domain/src/responses/harmony_conversation.rs conversation 142 42 5 0 S21
crates/gateway-domain/src/responses/tool_calls.rs decode_generation_noted 72 11 5 1 S21
crates/gateway-domain/src/responses/tool_calls.rs parse_output_items_with 35 6 1 0 S21
crates/gateway-domain/src/responses/effort.rs reasoning_effort 39 13 2 0 S21
crates/gateway-domain/src/messages/request.rs Request::into_responses 156 41 5 2 S21
crates/gateway-domain/src/messages/reply.rs message 22 11 6 1 S21

The wide lines the sections list (the learned_main_lru call of load_moe_gates.rs, the *_EXECUTION strings of config.rs) are covered, when a change touches them, by the width number of the entry of their function, or by the <file> entry when they are in a constant outside any function. scripts/check-limits.py --report prints the same measures for the worst functions of the whole tree.