Author SHA1 Message Date
Pavlo Ratushnyi 5310d7042f Merge claude/debt-final-ctx5: the architecture gate reads past cfg(test) mod declarations and finds static cells by type; 49 needless allow(unused_imports) and dead glob re-exports removed; exceptions carry kept:/debt: reasons (STRA-338)
Rust port / port-typecheck (push) Successful in 1m4s
Rust port / port-linux-tests (push) Failing after 2m52s
Rust port / port-oracles (push) Successful in 4m34s
Rust port / port-fast (push) Successful in 4m36s
Linux / verify (push) Failing after 5m14s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Product / product (push) Failing after 14m51s
2026-11-24 08:53:08 +01:00
Pavlo Ratushnyi 75e28ca110 deploy: drop the HIDDEN flag of the supervisor, a process cell that was written by --hidden and never read (STRA-338)
The console is hidden by winsys::hide_console right where the flag was stored; nothing in the workspace loads supervisor::HIDDEN, so the cell and its exception entry go. cargo check -p leleka-deploy --all-targets passes.
2026-11-24 08:51:58 +01:00
Pavlo Ratushnyi 219238cd08 architecture gate: read the whole file after a cfg(test) mod declaration, find static cells by type, 64 new exceptions with reasons (STRA-338)
The scanner stopped at the first '#[cfg(test)] mod x;' of a file, so the code below was invisible. It now skips only the item under a test-only cfg (an inline mod body, a declaration, a fn, a use; any(test, feature) is not test-only) and reads on.

process-global counted the type name OnceLock/LazyLock/OnceCell, which also matched instance fields (six exceptions existed only for that) and missed Atomic*, Mutex, RwLock, Once, Cell and RefCell statics, thread_local! included. It now counts a static whose type is a cell or a workspace type that holds one (derived per crate and its dependencies), and static mut. Eight exceptions that only excused instance fields go; the rest of the file's hits are re-judged.

Newly visible: 123 static cells in 58 files, 15 allow(unused_imports) in 6 files and the engine settings::process() cell (read at about 78 sites). Each gets an exception whose reason starts kept: (the boundary that forces it) or debt: (what removes it); the settings cell is the largest debt and is not removed here because the engine does not compile on Windows. Entries 173 -> 229, baseline stays empty. 11 new self-tests (39 in all).
2026-11-24 08:51:58 +01:00
Pavlo Ratushnyi d9c0c87dcf Narrow the dead glob re-exports of the module splits: pub use x::* becomes use x::* or pub(crate) use x::* (STRA-338)
Where the split left pub use x::* over items that no outside module can name, the compiler said the glob re-exports nothing pub. The glob now has the visibility its items really have: plain use where they are pub(self), pub(crate) where siblings reach them (model.rs file_download, libc-shim launch_interposers). One glob of backend-api scripted.rs was dead and is deleted. 7 globs of control-plane stay with their allow: the compiler calls them unused in the lib build and the lib test build of control-plane cannot be built on Windows, so a test use cannot be ruled out.

cargo check --all-targets on backend-api, control-plane, gateway-domain, gateway-text and libc-shim: no new warning, no new error (the one control-plane lib test error is the pre-existing std::os::unix use).
2026-11-24 08:51:58 +01:00
Pavlo Ratushnyi e79179a255 cuda-driver: the copy ring asks its arena for the stage slot count by static dispatch, not through a dyn view (STRA-338)
admitted_slots coerced the read lease to &dyn RingArena only to call stage_slots on it. RingArena::stage_slots(read) is the same method of the same impl without the vtable; the Ring keeps its own dyn field, which has its exception entry.
2026-11-24 08:51:57 +01:00
Pavlo Ratushnyi c1734bc7c4 cuda-driver: the expert tier probe names what it takes from its parent instead of use super::* (STRA-338)
The probe module is compiled under cfg(any(test, feature = "expert-tier-probe")), so it is production code of that feature and the glob import counts for the gate. The 16 names it uses are listed; cargo check --all-targets with features cuda-driver,expert-tier-probe and with cuda-driver alone gives no new warning.
2026-11-24 08:51:57 +01:00
Pavlo Ratushnyi 651ed44e90 Drop 49 allow(unused_imports) that no compiler warning needs (STRA-338)
The re-exports left by the mechanical module splits carried a blanket allow(unused_imports). 49 of them cover nothing: cargo check --all-targets on backend-api, control-plane, gateway-domain, gateway-text and libc-shim gives no new unused-import or glob-import warning without them. 39 others in those crates still silence a real warning and stay; the 8 in desktop-core (engine-host) could not be checked because that crate needs the engine, which does not build on Windows (STRA-390), and stay too.
2026-11-24 08:51:57 +01:00
Pavlo Ratushnyi 682c582f8a Merge claude/debt-final-ctx4: request counters, adaptive-tier tuning and the VRAM ledger leave the process cells; vague exception reasons fixed (STRA-338)
Rust port / port-typecheck (push) Successful in 1m46s
Rust port / port-linux-tests (push) Failing after 3m30s
Rust port / port-fast (push) Successful in 6m23s
Linux / verify (push) Failing after 7m48s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Rust port / port-oracles (push) Successful in 5m34s
Desktop foundation / core (ubuntu-latest) (push) Successful in 5m6s
Product / product (push) Failing after 30m51s
2026-11-24 07:52:28 +01:00
Pavlo Ratushnyi 4619a91367 architecture.json: the engine timer exceptions say what each reading is for (STRA-338)
Eight exceptions of the instant-now ratchet in leleka-engine-qwen35-cuda ended in a deferral ("which is the S14 follow-up"), and one of them was wrong: pcie_share_controllers.rs does not feed a log line, because PcieLag and PcieAuto read the wall-clock duration of the PCIe leg and of a round as the input of their control law. Seven reasons now say that the reading is a measurement that only feeds a log line or a counter, and the controller entry says that its timing is the control input, that both controllers are opt-in (LELEKA_PCIE_AUTO=lag|on, set by no shipped profile) and that their unit tests drive the control law through round() without the clock.
2026-11-24 03:56:38 +01:00
Pavlo Ratushnyi 4ef84275b1 cuda-driver: the VRAM allocation ledger belongs to the Context, not a process cell (STRA-338)
The per-call-site ledger of LELEKA_VRAM_LEDGER is now part of what a Context retains: Context::allocate and the DeviceBuffer free note into the ledger of their own context, and the engine reports through Context::report_vram_ledger, so the OnceLock singleton of vram_ledger.rs and its architecture.json exception are gone. The operator switch stays an EnvSwitch and the default is unchanged (off: one cached bool read per allocation); with the switch on, each context now accounts for its own allocations instead of every context of the process sharing one table.
2026-11-24 03:53:15 +01:00
Pavlo Ratushnyi 47d831ec62 engine: the adaptive-tier tuning is a field of the tier configuration, not a process cell (STRA-338)
ExpertTierConfig now carries AdaptTuning (minimum routed count, margin, decay) parsed once with the tier switches; the residency pool, the cross-layer estimate and the seed ranking take it as a value, so the OnceLock of split_group_pcie.rs and its architecture.json exception are gone. The production default is unchanged (the values still come from LELEKA_ADAPT_MIN_COUNT, _MARGIN and _DECAY with the same fallbacks), and the line for an invalid LELEKA_ADAPT_DECAY is now printed when the tier configuration is read instead of at the first adaptation.

Provenance of two comments that left ExpertTierConfig::off() so that the function stays within the 30-line limit. decode_reserve_mib 300: measured (jobs 989/990/988), the per-request verifier needs about 450 MiB, so 1024 left about 550 MiB idle (180k smoke included); 300 gives the auto-sized cache about 330 more slots. On the 5090, 5 x 245k session (speedtrain-ab), with 300 the card never had less than 563 MiB free (vanilla runs down to 315), so 130 would be safe on the card (+87 slots), but the first slots-footprint A/B showed the Context budget is a second ceiling the planner respects (usable_room); 130 stays an opt-in (LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130) until its own arm measures it. pcie_frac 0.45: the PCIe share that equalises the legs when the CPU pool and the DMA share the host's memory ceiling (P/(P+C) = 0.45, job 987-b/909; 0.45 against 0.55 gave +0.5 % / +4.7 % at the auto-sized cache and was equal at 2048 slots).
2026-11-24 03:50:37 +01:00
Pavlo Ratushnyi 51a4eceff0 control-plane: the request counters of /metrics belong to Services, not a process cell (STRA-338)
The request middleware, the backend worker and the metrics handler now share one RequestMetrics value that Services holds, so the LazyLock registry of request_log.rs and its architecture.json exception are gone. The middleware gets it through Observe, the worker through BackendWorkerConfig, and prometheus::render takes it as an argument; the counters, histograms, labels and log lines are unchanged, and the unit tests now count into a registry of their own instead of one shared by the whole test process.
2026-11-24 03:44:23 +01:00
Pavlo Ratushnyi 128a6fb18b Merge claude/debt-final-ctx3: the serving context is a value from the composition root, not a process cell; unused expert layout and GPU-wait hook removed; every remaining process-global exception says why (STRA-338) 2026-11-24 03:26:37 +01:00
Pavlo Ratushnyi e9107fe43c comments: the serving context is no longer called process-wide (STRA-338) 2026-11-24 02:01:08 +01:00
Pavlo Ratushnyi c1fa88db87 architecture.json: every remaining process-global exception says why that site keeps its cell (STRA-338)
The 32 remaining process-global exceptions are classified: instance-local OnceCell/OnceLock fields
that the gate pattern only matches by type name, pure memos of constants or embedded sealed
images, ambient immutable environment read below the Settings owner, FFI and logger-facade
boundaries, diagnostics, and three entries marked "kept for now, NOT a boundary" (request_log
counters, split_group_pcie tuning, vram_ledger) that can still take the value by argument.
2026-11-24 01:04:59 +01:00
Pavlo Ratushnyi 52abe0a21a control-plane: the gpt-oss prompt date is a field of the model view, not a process cell (STRA-338)
PromptDate was set once by serve into a process OnceLock and read by harmony_prompt::render.
It is now ModelView::prompt_date, built from the config in build_state, and prepare_input_tokens
hands it to render_prompt/render. The default of a bare AppState is still Utc, as the unset cell was.
One process-global exception deleted.
2026-11-24 01:04:43 +01:00
Pavlo Ratushnyi 5951540336 native-cpu-expert: drop the process expert layout and the GPU-wait hook nobody installs (STRA-338)
install_layout/expert_layout (a process RwLock cell) and install_release_gpu_waits (a process
OnceLock hook read on a pool stall) have no caller anywhere in the workspace, so the cells were
never written and the hook never ran. They are deleted instead of injected; the origin of the
pool's diagnostic millisecond clock is now a field of the pool's shared state (Shared::origin)
instead of a process OnceLock. Three process-global exceptions deleted.
2026-11-24 01:00:07 +01:00
Pavlo Ratushnyi 79765ac804 engine: the serving context is a value from the composition root, not a process cell (STRA-338)
ServingContext::new(cells, rope) replaces configure_serving_context and the process cell of
cuda-model; serving_context() is gone. The backend spawn makes the value once (serving::
admit_context_tokens) and hands it down: OwnerThread -> LoadEnv -> ServedArtifact (the
model binding captures it, ModelBinding::serving()) and Device::create_context_serving
(every Context of the Load). Device::create_context stays the trained default for tools and
tests. contract::serving_cells, the QSA index context()/device_peak() reads, the
native-resources size read, the memory governor, the stack config and the RoPE constants
read the binding or the Context instead; the stack open refuses a binding and a Context
made for different serving contexts. The two laptop tools build their own value.

Five process-global exceptions deleted (cuda-model serving_context, engine contract,
binding_identity, qsa_index/context, qsa_native_resources).
2026-11-24 00:59:18 +01:00
Pavlo Ratushnyi 1faee20402 Merge claude/debt-final-ctx2: positions, the resident KV window and the serving geometry belong to the model binding and the Context, not to the process (STRA-338) 2026-11-23 23:14:40 +01:00
Pavlo Ratushnyi f43aacd77d Merge claude/strata-scrub: no stale engine/strata paths in comments, sealed sources and fixtures; pins re-sealed (STRA-407) 2026-11-23 22:55:36 +01:00
Pavlo Ratushnyi a736aa03fa UPSTREAM.md: keep the checkout hint in its own paragraph (STRA-407) 2026-11-23 22:51:23 +01:00
Pavlo Ratushnyi 6c88bbc65e sm86_table: say that the digest was recomputed (STRA-407) 2026-11-23 22:37:37 +01:00
Pavlo Ratushnyi bb8ff44667 Sealed PTX: scrub engine/strata from four PTX header comments and their sm_86 companions, re-pin (STRA-407)
bf16_f32_mmvf, iq3_s_q8_1, moe_group_iq3_s, moe_group_iq3_s_nc4 (sm_120 in src/, sm_86 in ptx-sm86/) change in // header comments only (proof: identical after comment
stripping, no .file/.loc directive or string carries the path). The sm_86 companions are re-derived with sm86_assets.retarget + ptxas -arch=sm_86 (== the edited files);
MANIFEST.json (sm120/sm86 sha256 and byte counts of the four, the -I flags of the one recompiled companion) and the five-part sm86_table rows (new keys, re-sorted, same 27/27/27/27/23
layout) follow; FORMER_TABLE_DIGEST is recomputed with the algorithm of its test (reproduces the old value on main). Rust pins that cover the changed bytes:
bf16_receipt_types.rs BF16_RECEIPT (.cu source_sha256 and bf16_f32_mmvf.ptx ptx_sha256; a Receipt, not a PtxPin, so patched token by token), the frozen-artifact hash of
iq3_s_q8_1.ptx in context_handle.rs and in scripts/test-cuda-projection-family-driver.sh. Instruction streams, entry names and pinned symbol names are untouched.
2026-11-23 22:37:24 +01:00
Pavlo Ratushnyi 5e963eada5 Sealed sources: scrub engine/strata from .cu/.cuh comments, move the source pins that cover them (STRA-407)
21 .cu/.cuh files change in comments only (proof: identical after comment stripping; where the file compiles without the removed headers, nvcc 13.2.86 gives the same PTX
modulo the content-hashed symbol names, which nvcc derives from the source text and which the committed PTX keeps as sealed). Every pin that covered such a file moves:
cu_pin sha256+bytes in the seal plans of mmq_original_prefill_misc, s_gemv_legacy, experimental_keyless, experimental_cvec (no repo tool writes cu_pin; computed with sha256),
experimental.rs PINS[3] and PINS[5] and closed_kernels.rs PINS[1] .source_sha256 (rustpins.apply_field, then rustfmt as seal_pins.py does). The four experimental sources
that were already pending a reseal stay pending. Seal-plan prose and -I flags follow the same wording as the gpu-bringup data.
2026-11-23 22:37:17 +01:00
Pavlo Ratushnyi da8c974f68 Drop the stale engine/strata paths and retired generator names from comments, doc strings and generated fixtures (STRA-407)
Rust comments that named scripts/offline/*, gen_goldens.py, oracle/gen_*.{sh,cpp,py}, build_oracle.sh and similar retired generators now say where the data
came from (the Original's code, Strata 41cf05a0) or drop the sentence. The path/generator text of seven generated fixtures (sampler_oracle.json, sampling_keys.json,
memory_plan_golden.json, rope_golden.json, cvec_oracle.json, stra161 fixtures.json, commentary-tool-prompt.json) is reworded; no test reads those fields and no pin
covers their bytes. cmd_time/doc.rs: the two path texts in the format string; its lines are re-broken so they stay within 120 columns (the string is unchanged
otherwise). Comment-only except those data/string spots; no behaviour change.
2026-11-23 22:37:17 +01:00
Pavlo Ratushnyi a4afb2a182 gpu-bringup: name the include dirs of an upstream checkout strata-41cf05a0/ instead of the removed engine/strata (STRA-407)
The recipe data (sm86-recipes.json, extra-seal-plan.json, rope-regeneration.json), STANDARD_INCLUDES, the sm86 include list and the one test that asserts them
now spell the include directories as strata-41cf05a0/{include,src,third_party/ggml}; prose that named engine/strata/CMakeLists.txt or the retired
build-original-verify-ptx.sh now says Strata 41cf05a0 or the precise flags. UPSTREAM.md records where to place a restored checkout.
No pin covers these files; behaviour of the tools is unchanged (the directories did not exist before either).
2026-11-23 22:29:08 +01:00
Pavlo Ratushnyi 920be477ee Merge claude/strata-removal: remove the vendored Strata tree, keep LICENSE and the files Rust embeds in third_party/strata (STRA-406)
Rust port / port-typecheck (push) Successful in 1m10s
Rust port / port-linux-tests (push) Failing after 3m0s
Rust port / port-fast (push) Successful in 4m26s
Rust port / port-oracles (push) Successful in 4m28s
Linux / verify (push) Failing after 5m16s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Product / product (push) Failing after 14m14s
2026-11-23 21:44:36 +01:00
Pavlo Ratushnyi 966c3fc233 cuda-driver: a Context captures the serving context it is created for, and the qsa sites read it from the Context (STRA-338)
Device::create_context_serving fixes the ServingContext (cell count and RoPE constants) of one Context in Retained.serving; create_context takes the process value once, at creation. Context::serving() / serving_geometry() replace the ~55 reads of cuda-model geometry() / serving_context() in qsa_prompt_index, qsa_prompt_kv, qsa_index_ffi (Arguments::for_launch takes the ServingContext), qsa_prompt_host_ffi (MappedAllocation::new takes the geometry), the resolver and qsa_fixed_kernels. cuda-model geometry() is deleted; the KV window file becomes context_serving.rs; ServingContext::resident_pages_for carries the window arithmetic. The engine call site OriginalQsaMappedPrefix::validate_retained(context) takes the Context (this signature change completes the call-site edit that commit 1 already carries, so commit 1 alone does not compile: merge the branch as a whole).

Behaviour notes for review: the ScoreTC reach check against max_blocks moves from launch time to argument-build time (same error value). OriginalQsaMappedSnapshot::logical_payload_eq no longer re-checks end against the serving cells (a diagnostic comparison; the owner validates snapshots on every use). The old process-wide guards only fired for a second load with different values in one process.
2026-11-23 21:16:57 +01:00
Pavlo Ratushnyi 1e5e5e14c6 cuda-driver: the resident KV window belongs to the Context its owners are made from, not to the process (STRA-338)
Context::configure_kv_resident fixes the window of one Context (Retained.kv_resident) and streamed QSA owners size their pool from c.kv_resident_pages(). The process cell KV_RESIDENT and configure_kv_resident / kv_resident_cells / kv_resident_pages leave cuda-model and the driver exports; the serve stack open phase configures the window on its Context (that call site already changed in the previous commit). Behaviour note: the old process-wide guard "resident KV window already configured differently" fired only for a second load with another window in the same process; a fresh Context after Unload now accepts another window.
2026-11-23 21:12:58 +01:00
Pavlo Ratushnyi e3209650b5 engine: every Position takes its dimension from the model binding it belongs to, not from the process serving context (STRA-338)
BindingIdentity and ModelBinding carry position_dimension(), built from the serving cells the binding captured when the model was bound. contract::position_dimension() (a read of the driver's process serving context) is deleted; the ~50 call sites in production code use the binding they already hold, tests use a cfg(test) trained_dimension() (262144 cells). No behaviour change: production binds the model after the context is admitted, so both values are the same.
2026-11-23 21:10:55 +01:00
295 changed files with 2672 additions and 2293 deletions
+94 -51
View File
@@ -49,11 +49,9 @@
"patterns": ["^impl_.*\\.rs$", "_fn\\.rs$", "_[0-9]+(_[0-9]+)*\\.rs$"],
"allow": ["^(quantize_)?q[0-9]_[0-9k]\\.rs$"]
},
"_exceptions": "Sites that must stay, so the ratchet is zero outside this list (STRA-338 stage 10). Each entry: crate, file (relative to the crate directory), ratchet (a source_patterns id), reason. The file's hits of that ratchet are not counted; an entry that excuses nothing is an error.",
"_exceptions": "Sites that must stay, so the ratchet is zero outside this list (STRA-338 stage 10). Each entry: crate, file (relative to the crate directory), ratchet (a source_patterns id), reason. The reason starts with `kept:` (the site must stay, and the boundary that forces it) or `debt:` (a real remaining owner problem, and what removes it). The file's hits of that ratchet are not counted; an entry that excuses nothing is an error.",
"exceptions": [
{"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "env-read", "reason": "EnvSwitch is the one reader of the operator environment in this crate: it reads one named variable on the first get() and applies a typed rule"},
{"crate": "leleka-cuda-model", "file": "src/env_switch.rs", "ratchet": "process-global", "reason": "the OnceLock inside EnvSwitch caches the switch position for the process life (an immutable operator setting; a hot path pays one atomic load)"},
{"crate": "leleka-cuda-model", "file": "src/serving_context.rs", "ratchet": "process-global", "reason": "the serving context and the resident KV window are fixed once at engine start (configure_*) and read by every kernel geometry; injecting them through every owner is the settings follow-up of S13"},
{"crate": "leleka-cpu-worker", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-tokenizer", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
{"crate": "leleka-gptoss-npu", "file": "src/settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment in this crate: it returns the operator's switches as typed values"},
@@ -71,7 +69,7 @@
{"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "env-read", "reason": "platform adapter (glibc heap): reads its own LELEKA_MEMORY_NO_TRIM switch once"},
{"crate": "leleka-native-parity-bench", "file": "src/lib.rs", "ratchet": "env-read", "reason": "benchmark host (L4): reads the operator's STRATA_IQ_MT_MIN override to report which value it measured"},
{"crate": "leleka-npu-worker", "file": "src/main.rs", "ratchet": "env-read", "reason": "worker binary (composition root): reads LELEKA_OPENVINO_ROOT into its configuration"},
{"crate": "leleka-memory", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cached LELEKA_NO_TRIM_FILE path: an immutable operator setting read once by the crate's one environment reader"},
{"crate": "leleka-memory", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_NO_TRIM_FILE path is ambient process environment, immutable after start (a cached read equals a fresh one); this crate is below the engine Settings owner and MemoryServices carries the governor, not the environment, so no settings value reaches the reader"},
{"crate": "leleka-memory", "file": "src/governor.rs", "ratchet": "dyn-trait", "reason": "port boundary: the Governor holds its MemoryPressure adapter as Arc<dyn MemoryPressure>, chosen at start-up (hexagonal.md, ports table)"},
{"crate": "leleka-memory", "file": "src/governor/operations/setup.rs", "ratchet": "dyn-trait", "reason": "port boundary: Governor::new takes the host as Arc<dyn ProcSource + Send + Sync> (the adapter is chosen by the composition root) and source() hands it back"},
{"crate": "leleka-memory", "file": "src/lock/page_locking.rs", "ratchet": "dyn-trait", "reason": "port boundary: SharedPageLocking = Arc<dyn PageLocking>, the OS adapter of mmap/mlock chosen by the composition root"},
@@ -99,12 +97,12 @@
{"crate": "leleka-model-format", "file": "src/ple_reader/read_queue.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: readings of the per-row read queue's latency window, inside the reader loop"},
{"crate": "leleka-model-format", "file": "src/ple_reader/row_reading.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: latency measurement of one PLE row read, inside the reader loop"},
{"crate": "leleka-obs", "file": "src/time/clock.rs", "ratchet": "instant-now", "reason": "the clock adapter itself: SystemClock, AnyClock and ManualClock are the one place that reads the monotonic clock"},
{"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "process-global", "reason": "platform adapter (glibc heap): the LELEKA_MEMORY_NO_TRIM switch is read once and cached"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "process-global", "reason": "Windows interposer (FFI): the CUDA call tracer is process-wide state behind C-ABI hooks that carry no context pointer"},
{"crate": "leleka-obs", "file": "src/lib.rs", "ratchet": "process-global", "reason": "the logger is process-wide: its Settings, rate limiter and request sink are built once from the environment"},
{"crate": "leleka-obs", "file": "src/write_stderr.rs", "ratchet": "process-global", "reason": "the request-log sink of the process-wide logger (see lib.rs)"},
{"crate": "leleka-tokenizer", "file": "src/lib.rs", "ratchet": "process-global", "reason": "immutable constant tables built once: the pre-tokenizer regex and the character classes"},
{"crate": "leleka-gptoss-npu", "file": "src/half.rs", "ratchet": "process-global", "reason": "immutable constant table: the half-to-float conversion table, built once"},
{"crate": "leleka-memory-os", "file": "src/heap.rs", "ratchet": "process-global", "reason": "kept: platform adapter over the glibc heap, which is itself process-wide; the LELEKA_MEMORY_NO_TRIM switch is ambient immutable environment read once, and the adapter is below the Settings owner"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace/trace_state.rs", "ratchet": "process-global", "reason": "kept: FFI interposer boundary. The CUDA call tracer is state behind C-ABI hooks that the dynamic loader calls with no context pointer and no way to carry an argument; the process is the only scope that exists there"},
{"crate": "leleka-obs", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: the logger facade, like the `log` crate, is process-wide by contract: elog! and request logging are called from every crate without a handle; its Settings, rate limiter and request sink are built once from the environment"},
{"crate": "leleka-obs", "file": "src/write_stderr.rs", "ratchet": "process-global", "reason": "kept: the request-log sink of the process-wide logger facade of lib.rs (same reason: written by every thread, no handle at the call sites)"},
{"crate": "leleka-tokenizer", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: immutable constant tables (the pre-tokenizer regex and the character classes) compiled on first use; a pure function of constants, a memo no caller can observe"},
{"crate": "leleka-gptoss-npu", "file": "src/half.rs", "ratchet": "process-global", "reason": "kept: immutable constant table (half-to-float conversion), a pure function of constants built once; no caller can observe the memo"},
{"crate": "leleka-cuda-model", "file": "src/original_prefill_schedule.rs", "ratchet": "dyn-trait", "reason": "parameter struct SourceView borrows three residency queries (resident, pinned, transient) from the caller's tables; a generic parameter per closure would make the type unnameable in the callers' signatures"},
{"crate": "leleka-experimental-ref", "file": "src/remote_experts.rs", "ratchet": "dyn-trait", "reason": "parameter struct Candidates borrows the primary's residency test from the caller's table; generic parameters would leak into every caller's signature"},
{"crate": "leleka-cpu-worker", "file": "src/engine.rs", "ratchet": "dyn-trait", "reason": "port boundary: the engine holds the prefill accelerator (iGPU, NPU or split) as Box<dyn PrefillAccelerator + Send>, chosen by the worker binary"},
@@ -124,10 +122,9 @@
{"crate": "leleka-model-format", "file": "src/qwen4exp/binding_topology.rs", "ratchet": "dyn-trait", "reason": "std::error::Error::source() returns &(dyn Error + 'static) by the trait's own signature"},
{"crate": "leleka-model-format", "file": "src/ple_reader.rs", "ratchet": "dyn-trait", "reason": "port boundary: the PLE reader holds its PageSource (file, direct-IO file or test double) as Arc<dyn PageSource>"},
{"crate": "leleka-model-format", "file": "src/ple_reader/row_reading.rs", "ratchet": "dyn-trait", "reason": "port boundary: PleReader::open takes the PageSource as Arc<dyn PageSource>"},
{"crate": "leleka-model-format", "file": "src/huge_pages.rs", "ratchet": "process-global", "reason": "the huge-page mode is an operator setting parsed once from LELEKA_HUGEPAGES and cached for the process"},
{"crate": "leleka-model-format", "file": "src/kar/independent_handles.rs", "ratchet": "process-global", "reason": "the identity-recheck switch is an operator setting parsed once and cached for the process"},
{"crate": "leleka-model-format", "file": "src/kar.rs", "ratchet": "process-global", "reason": "a per-instance lazily opened set of file handles (a OnceLock field of the archive), not a process global"},
{"crate": "leleka-model-format", "file": "src/kar/verified_kar_ple_artifact.rs", "ratchet": "process-global", "reason": "constructs the per-instance lazy handle cell of kar.rs, not a process global"},
{"crate": "leleka-model-format", "file": "src/huge_pages.rs", "ratchet": "process-global", "reason": "kept: ambient environment and the mapping registry. The huge-page mode (LELEKA_HUGEPAGES, MODE) is immutable after start so the cache equals a fresh read, and model-format is below the engine Settings owner (dependency direction); LIVE is the registry of the live huge-page mappings that the release path needs, a process-wide fact of the allocator"},
{"crate": "leleka-model-format", "file": "src/kar/independent_handles.rs", "ratchet": "process-global", "reason": "kept: ambient environment. The identity-recheck switch is immutable after start so the cache equals a fresh read; model-format is below the engine Settings owner (dependency direction)"},
{"crate": "leleka-model-format", "file": "src/kar.rs", "ratchet": "process-global", "reason": "kept: COLD_SKIP, the number of upcoming calls that read in parallel without probing after a cold verdict (a cold file would pay the probe's latency each time); a read-path heuristic of the process's one archive reader, output-neutral. The OnceLock field of the archive is an instance field and no longer counted"},
{"crate": "leleka-control-plane", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (number, path, flag, mode)"},
{"crate": "leleka-deploy", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate: every variable is parsed here into a typed value (path, flag, text)"},
{"crate": "leleka-engine-host", "file": "src/env_settings.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the crate and its binaries: credentials by name, the evaluation switches, the inherited child variables"},
@@ -151,20 +148,18 @@
{"crate": "leleka-engine-host", "file": "src/node.rs", "ratchet": "dyn-trait", "reason": "tonic server-streaming response type: the generated trait wants a boxed stream"},
{"crate": "leleka-engine-host", "file": "src/runtime_rpc.rs", "ratchet": "dyn-trait", "reason": "tonic server-streaming response type: the generated trait wants a boxed stream"},
{"crate": "leleka-backend-api", "file": "src/scripted.rs", "ratchet": "dyn-trait", "reason": "the scripted test engine stores the test's responder closure"},
{"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "pure cache: the validity of a tool schema by its compact text, so the dozen schemas of a coding agent are compiled once, not three times per request"},
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "the compiled pinned chat template: immutable, built on first use, read by every request"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "the process-wide request counters and histograms that /metrics renders; written by every request"},
{"crate": "leleka-control-plane", "file": "src/responses/harmony_prompt.rs", "ratchet": "process-global", "reason": "the gpt-oss prompt date: configuration set once by serve before the first request"},
{"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "diagnostic stage table of the replay harness and STRATA_STAGE_TRACE: one table per process by design"},
{"crate": "leleka-gateway-domain", "file": "src/responses/schema.rs", "ratchet": "process-global", "reason": "kept: pure memo (not state): the validity of a tool schema keyed by its compact text, so the dozen schemas of a coding agent compile once, not three times per request; the result depends on the key alone, so no caller can observe the cache; a per-request owner would defeat it"},
{"crate": "leleka-gateway-text", "file": "src/prompt/renderer.rs", "ratchet": "process-global", "reason": "kept: the compiled pinned chat template is an immutable constant of the build, compiled on first use and read by every request; a pure memo of a constant"},
{"crate": "leleka-control-plane", "file": "src/stage_trace.rs", "ratchet": "process-global", "reason": "kept: diagnostic stage table of the replay harness and STRATA_STAGE_TRACE; time() and span() are called from deep helpers (render, tokenize) that carry no state argument, and the output is diagnostic only, never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/settings/source.rs", "ratchet": "env-read", "reason": "the one reader of the process environment of the engine: ProcessEnv is the adapter of the EnvSource port, and Settings parses every variable into typed fields there (S13)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per traced port call, only when the bring-up trace is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per routing prediction on the lookahead thread); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_group_steps.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per CPU expert group of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_tier.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per eager admission, once at start-up); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per pool phase lap of a decode round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/pcie_share_controllers.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per PCIe lag probe and adaptation round); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per prefill stage span, only when the profile switch is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prompt_device_rows/prompt_device_read/produce_original_gdn.rs", "ratchet": "instant-now", "reason": "measurement timer in a hot loop (one reading per GDN layer producer lap, only when the command profile is on); a Clock parameter would add a generic to every owner on the path, which is the S14 follow-up; the reading is a Duration that only feeds a log line or a counter"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_engine/round_tally/serve_rounds.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per traced port call, only when the bring-up trace is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_lookahead.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per routing prediction on the lookahead thread; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_group_steps.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per CPU expert group of a decode round; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool/direct_tier.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per eager admission, once at start-up; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per pool phase lap of a decode round; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/pcie_share_controllers.rs", "ratchet": "instant-now", "reason": "control input, not a log line: PcieLag spins until the PCIe copies of a group have landed and PcieAuto times a round from one apply_pending to the next, and the control law reads those wall-clock durations to move the PCIe share; both controllers are opt-in experiments (LELEKA_PCIE_AUTO=lag|on, off in every shipped profile) and their unit tests drive the control law through round() without the clock"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per prefill stage span, only when the profile switch is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prompt_device_rows/prompt_device_read/produce_original_gdn.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: one reading per GDN layer producer lap, only when the command profile is on; the reading is a Duration that only feeds a log line or a counter, never a decision"},
{"crate": "leleka-engine-core", "file": "src/family.rs", "ratchet": "dyn-trait", "reason": "EngineFamily::spawn returns Box<dyn Backend>: the family seam is the process boundary of the engine, called once at start-up"},
{"crate": "leleka-engine-fake", "file": "src/lib.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/family.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
@@ -174,16 +169,7 @@
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/spawn_preview.rs", "ratchet": "dyn-trait", "reason": "Box<dyn Backend> is the process boundary: the factory hands the composed engine to the host, which holds one Backend per process (startup composition only, never per round)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/measurement.rs", "ratchet": "dyn-trait", "reason": "the evaluation measurement sink is a stored callback handed in by the host (observer port, called once per request)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "dyn-trait", "reason": "the GPU telemetry probe is a stored callback handed in by the host at load (port, sampled by the telemetry tick, not per token)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/binding_identity.rs", "ratchet": "process-global", "reason": "the model binding captures the serving context in cells once, when it is made (the driver's context is configured before the engine binds a model); the validators read the bound from the binding, not from the process"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/contract.rs", "ratchet": "process-global", "reason": "the engine's one reader of the driver's serving context (cells): contract::serving_cells() is called where a model is bound (InputConstants::from_artifact) and by sizing code that has no binding; every validator takes the bound from the binding"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/split_group_pcie.rs", "ratchet": "process-global", "reason": "the adaptive-tier tuning constants, derived once from the settings capture (immutable after the first read)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "the epoch of the bring-up trace timestamps (DBG_T0), set once; diagnostics only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_index/context.rs", "ratchet": "process-global", "reason": "the QSA index owner bounds positions and sizes its pages by the process geometry in about ten places (validate_ids, pending rows, native state, max rows, index image sizes) that are reached without a model binding; carrying the bound in QsaOwner is the next step. Same value as the driver's serving context, read through the engine's contract::serving_cells"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/qsa_native_resources.rs", "ratchet": "process-global", "reason": "the byte sizes of a layer's host image come from the process geometry (QsaGeometry over the serving cells) when the resource set is built, before any binding is passed in; they follow the QSA owner's bound (see qsa_index/context.rs)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "instance-local lazy cell (std::cell::OnceCell), not a process global: the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack.rs", "ratchet": "process-global", "reason": "kept: DBG_T0, the epoch of the bring-up trace timestamps (dbg_el()); diagnostics only, called from trace macros in many files that hold no common owner, never read by serving logic"},
{"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: stall span of one timed drain, reported by the prefill stall trace"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/chunk_stream/chunk_issuing.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: span of one chunk issue, summed into the copy-ring profile"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/original_mmq_copy_schedule/stream_start.rs", "ratchet": "instant-now", "reason": "measurement timer, not decision logic: start of the copy-ring stream, read once per stream for the profile"},
@@ -223,25 +209,82 @@
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/gdn_native_batch/context.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_dispatch/moe_prefill_batch/moe_prefill_batch_lifecycle.rs", "ratchet": "dyn-trait", "reason": "the batch owner holds its GEMM provider (cuBLAS-backed in production, a host stand-in in the tests) as a trait object for the life of one batch; it is a port, chosen when the owner is opened"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "the verdict of the immutable MMQ artifact check, computed once"},
{"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "the usability of the kh recurrence on this device: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "the RoPE ABI of the loaded index module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "the resolver ABI of the loaded module: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/asset_admission.rs", "ratchet": "process-global", "reason": "per-operation memo of the PTX proof: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "the table of PTX proof memos, one cell per operation: immutable result of a probe or proof of a sealed image, computed once and cached"},
{"crate": "leleka-cuda-driver", "file": "src/vram_ledger.rs", "ratchet": "process-global", "reason": "the process-wide VRAM ledger (LELEKA_VRAM_LEDGER): a diagnostic singleton fed by every allocation site"},
{"crate": "leleka-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "the marker files of the A/B controls: the paths named by the operator are read once and the time of the first look is kept (OnceLock), so a hot path looks at the disk at most every 250 ms; one type serves the three controls"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "FFI: `static mut stdout` is libc's C stream, declared in an extern block"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_expert_layout.rs", "ratchet": "process-global", "reason": "the process-wide expert layout the pool threads read; it is set at load time by the engine"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool/job_default.rs", "ratchet": "process-global", "reason": "the origin instant of the pool's job timestamps"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_general_pool.rs", "ratchet": "process-global", "reason": "the hook that releases the GPU waits, installed once by the engine (a function pointer)"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "the cell of a Setting: the operator's switches and the CPU probes the kernels dispatch on are computed on the first read and kept for the process life (immutable; a hot path pays one atomic load, and kernel code carries no context to pass a settings value through)"}
{"crate": "leleka-cuda-driver", "file": "src/mmq/asset.rs", "ratchet": "process-global", "reason": "kept: pure memo of the verdict of the immutable embedded MMQ artifact check (a function of the embedded bytes alone), so no caller can observe the cache; a Context-owned copy would re-prove the same bytes per Context"},
{"crate": "leleka-cuda-driver", "file": "src/prefill_stage.rs", "ratchet": "process-global", "reason": "kept: pure memo of a proof about an embedded sealed image (usability of the kh recurrence), a result per device that no caller can observe as state; and two per-arm A/B overrides (GDN_OVERRIDE, NOSTORE_OVERRIDE) of the prefill GDN switches, written by the test harness for paired passes in one process"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_index_ffi.rs", "ratchet": "process-global", "reason": "kept: pure memo of the RoPE ABI proof of the embedded index module, a function of the embedded bytes alone"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_resolver.rs", "ratchet": "process-global", "reason": "kept: pure memo of the resolver ABI proof of the embedded module, a function of the embedded bytes alone"},
{"crate": "leleka-cuda-driver", "file": "src/qwen_ffi/n_types.rs", "ratchet": "process-global", "reason": "kept: the table of the PTX proof memos of asset_admission.rs, one cell per operation; pure functions of embedded bytes"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_bench_frontend.rs", "ratchet": "process-global", "reason": "kept: FFI. `static mut stdout` is libc's C stream, declared in an extern block; it is the C library's own global, not ours"},
{"crate": "leleka-native-cpu-expert", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: the cell of each `static Setting` (operator switches and the CPU probes the kernels dispatch on), computed on first read from the immutable environment and the CPU; the kernels are free functions called from pool worker threads that carry no context to pass a value through, and a hot path pays one atomic load"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "process-global", "reason": "kept: `tokio::task_local! CURRENT`, the request context (ReqCtx) of the running request, read without a request argument by code that holds no handle; it is scoped to one task, not to the process"},
{"crate": "leleka-control-plane", "file": "src/responses.rs", "ratchet": "process-global", "reason": "kept: NEXT_RESPONSE_ID, the counter in the `resp_<time>_<n>` id of a response: unique across every request of the process by definition, so it has no narrower owner than the process"},
{"crate": "leleka-control-plane", "file": "src/responses/tool_recovery.rs", "ratchet": "process-global", "reason": "debt: the EXPERIMENTAL tool_call_recovery flag, set once by `main` from the config file or STRATA_TOOL_CALL_RECOVERY and read by the response decoder. It belongs on the Services/config value the handlers already receive; it stays a cell until the decoder takes it by argument"},
{"crate": "leleka-control-plane", "file": "src/vision.rs", "ratchet": "process-global", "reason": "kept: NEXT_DIR numbers the scratch directories of vision requests so two requests of one process never share a directory; uniqueness across the process is its job"},
{"crate": "leleka-cuda-driver", "file": "src/arch_ptx.rs", "ratchet": "process-global", "reason": "debt: STREAM_K_AVOIDED, the fact that the sm_86 companion image was chosen so the stream-K kernels stay off, set in stream_k_off when the module loads and read by the same decision; a fact about the loaded device image that belongs on the Context"},
{"crate": "leleka-cuda-driver", "file": "src/compute_drain.rs", "ratchet": "process-global", "reason": "kept: the registry of every stream the crate creates (STREAMS) and the id of the registered background copy stream (BACKGROUND), which `Api::synchronize` consults in all of the crate's producers (blas, Original schedule, owned copy, swap) that have no common owner; plus the diagnostic counters and per-site table of the drains (SEEN, SHOWN, SITES, BLOCK_*, thread-local LOCAL_DRAINS) and two A/B overrides (ZERO_MEMSET, DEPTH_OVERRIDE). Moving the registry into the Context needs the Api handle in every producer"},
{"crate": "leleka-cuda-driver", "file": "src/deferred_status.rs", "ratchet": "process-global", "reason": "kept: per-thread queue of the deferred status read-backs, bound to the context that created it (the contexts are single-thread owners); one state per thread by design, like the thread that owns the Context"},
{"crate": "leleka-cuda-driver", "file": "src/mmq/resident/original_group/copy_ring/chunk_stream.rs", "ratchet": "process-global", "reason": "kept: the thread's active inline-mode chunk stream, which `prefetch_point` finds without a handle (its doc comment: the producers have no handle to the stream)"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule.rs", "ratchet": "process-global", "reason": "debt: SIDE_STREAMS_WANTED is stored by `set_side_streams_wanted` and read by the capture phases; the thread-local SUMS of `capture_timing` is the serve profile's per-thread diagnostic. The flag belongs on the schedule value; it stays a cell until the capture call takes it"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/abi/platform/api.rs", "ratchet": "process-global", "reason": "kept: WARMED, once per process: the first graph callback thread is started pinned (Linux); a failure is ignored and the first real callback creates the thread"},
{"crate": "leleka-cuda-driver", "file": "src/original_gpu_schedule/transport.rs", "ratchet": "process-global", "reason": "kept: SEEN counts the verifier-window graph instantiations of the process for the test hook LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT=N (the N-th instantiation of the process fails once); a process-wide count is what the hook means"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/chain.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/combine_head.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/diag.rs", "ratchet": "process-global", "reason": "kept: REGISTRY of the live verifier diagnostics, read by `original_verify_diagnostics` and the release hooks from the operator and shutdown paths that hold no verifier handle; diagnostics only"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gdn_fused.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gr/fused_down.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/gr/head_chain.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/qsa/fused_prelude.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/sm120.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/original_verify/window_ops/original_verifier.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_cluster.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_late.rs", "ratchet": "process-global", "reason": "debt: per-arm overrides (OVERRIDE, TOPK_OVERRIDE) for paired A/B passes in one process, plus a once-per-process notice (SAID). The overrides belong in the arm configuration handed to the recording call; they stay cells until it is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/qsa_prompt_kv/resident_transport.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-cuda-driver", "file": "src/settings.rs", "ratchet": "process-global", "reason": "kept: operator environment switches of the CUDA driver, one `static EnvSwitch/EnvSetting/LazySetting/MarkerFiles` per variable, computed on first read from the process environment, which cannot change after start, so a cached read equals a fresh one; they are read from free functions deep in the launch and prefill paths that carry no settings argument, and the driver sits below the engine Settings owner (dependency direction). A driver settings struct on the Context would remove them (follow-up of STRA-338)"},
{"crate": "leleka-cuda-model", "file": "src/bringup_trace.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_BRINGUP_TRACE switch, an `EnvSwitch` declared where it is read (same reason as env_switch.rs: immutable environment, and the crate is below the engine Settings owner)"},
{"crate": "leleka-cuda-model", "file": "src/command_profile.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_PREFILL_PROFILE_SYNC switch (an `EnvSwitch`, reason of env_switch.rs) and TOTALS, the table of per-command timings that the profile report prints; diagnostics only, recorded from command wrappers that hold no profile handle"},
{"crate": "leleka-cuda-model", "file": "src/host_profile.rs", "ratchet": "process-global", "reason": "kept: the LELEKA_SERVE_PROFILE switch (an `EnvSwitch`, reason of env_switch.rs) and the thread-local SUMS of the host profile; diagnostics only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/config.rs", "ratchet": "process-global", "reason": "kept: RECONFIGURING (a reconfigure is reopening the serve stack, new generations are refused and retryable meanwhile) and INSTANCE (the number of the backend instance, taken by each spawn). Both describe the one engine of the process and are touched from the control thread and the request threads; open item: move them next to the backend handle when the engine builds on Windows (STRA-390) and can be compiled"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve.rs", "ratchet": "process-global", "reason": "kept: PREFIX_SUMMARY, the prefix cache's pool summary that the owner thread publishes after each request and any status thread reads; its doc comment: one backend per process, so one cell"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner.rs", "ratchet": "process-global", "reason": "debt: PREVIOUS_TIER, the expert tier counters after the previous request, to turn stack-lifetime figures into a request's share; it belongs to the runner that reports each request, and stays a cell until the runner owns it (needs the engine to compile, STRA-390)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/backend/original_serve/runner/stack_reports.rs", "ratchet": "process-global", "reason": "kept: NEXT numbers the per-request id dump files of the process so that two dumps never share a name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/load_clock.rs", "ratchet": "process-global", "reason": "kept: CLOCK, the start and last-lap time of the one model load of the process, written by `lap` and `span` from the loading thread and the parallel verification threads; the output is the `leleka-load-time` log line only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/memory_governor.rs", "ratchet": "process-global", "reason": "debt: MAPPED_WORKING_SET is the RAM kept for the hot part of a file-mapped expert bank, set by `startup` and read when the prefix budget is resolved at open; a value that should travel in the memory settings handed to open. It stays a cell until the engine compiles on Windows (STRA-390) and the plumbing can be verified"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/kar_ple_source/private_copy.rs", "ratchet": "process-global", "reason": "kept: SEQUENCE numbers the temporary private copies of a source file, so two copies of one process never collide on a name (macOS and test builds only)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/mtp/backing.rs", "ratchet": "process-global", "reason": "kept: SERIAL numbers the temporary backing files of the process (`tiny-<pid>-<serial>`), so two never collide"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/gdn.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/moe_weight_cache/cache_original_prompt.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_cache_startup.rs", "ratchet": "process-global", "reason": "debt: per-arm override of one switch so a paired A/B pass can flip it inside one process (-1 none, 0 off, 1 on); written by the test and replay harness, read when a window graph is recorded. It belongs in the configuration value of the arm, handed to the recording call; it stays a cell until the arm configuration is threaded through"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_host/ple_on_chain.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_native/native_window.rs", "ratchet": "process-global", "reason": "kept: WINDOW_SEQ numbers the residual trace files of a window (diagnostic trace output, LELEKA trace directory only)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_pool.rs", "ratchet": "process-global", "reason": "kept: thread-local diagnostic accumulator of the serve profile (written from deep helpers that hold no profile handle, drained by the profile report on the same thread); never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_profile.rs", "ratchet": "process-global", "reason": "kept: thread-local diagnostic accumulator of the serve profile (written from deep helpers that hold no profile handle, drained by the profile report on the same thread); never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency.rs", "ratchet": "process-global", "reason": "debt: TAIL_SKIP_RANK, the route-tail skip rank resolved once from the settings and the cache on first use and read by the router each round. It belongs to the residency state of the serve stack; it stays a cell until that owner exists and the engine compiles on Windows (STRA-390)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/source_spans.rs", "ratchet": "process-global", "reason": "kept: once-per-process notice on the operator log (`std::sync::Once`) that a non-default kernel set is in use; output only, never read by serving logic, and the call sits in a function that has no owner object to hold the flag"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_residency/tail_skip_rank.rs", "ratchet": "process-global", "reason": "kept: ANNOUNCED, the effective tail-skip rank last printed, so the operator log prints a change once; output only"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/original_serve_stack/prompt_chunk.rs", "ratchet": "process-global", "reason": "kept: LOWEST_FREE, the low-water mark of the card's free VRAM over every note of the process (diagnostic print when the serve profile is on; the number the reserve must cover)"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/prefill_profile.rs", "ratchet": "process-global", "reason": "kept: thread-local diagnostic accumulator of the serve profile (written from deep helpers that hold no profile handle, drained by the profile report on the same thread); never read by serving logic"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/quality_force.rs", "ratchet": "process-global", "reason": "kept: FORCED, the teacher-forcing sequence of the model quality gate; production code never installs one (the only caller is the Original serve smoke) and with nothing installed `apply` is one uncontended lock and an empty check"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/settings.rs", "ratchet": "process-global", "reason": "debt (the largest remaining process cell): `settings::process()` holds the engine Settings in a OnceLock captured from the real environment on first ask, and is read at about 78 sites. It must become a value built once by the composition root and passed through the Context/ModelBinding/config structs, as the serving context was in phase 2c. Not done in phase 2e: leleka-engine-qwen35-cuda does not compile on Windows at the base (std::os::unix in model_binding/weight_binding/mtp, STRA-390), and no uncompiled code is committed"},
{"crate": "leleka-gptoss-npu", "file": "src/par.rs", "ratchet": "process-global", "reason": "debt: LIMIT, the thread budget of the parallel helpers, set once by the NPU prefill setup (`set_threads`) and read by every helper; it belongs to the setup value the helpers are called with"},
{"crate": "leleka-libc-shim", "file": "src/cuda_trace.rs", "ratchet": "process-global", "reason": "kept: FFI interposer boundary (same reason as trace_state.rs): the real entry points, launch counters and stream sync marks live in statics because the CUDA call wrappers are C-ABI functions the loader calls with no context pointer and no way to carry an argument"},
{"crate": "leleka-libc-shim", "file": "src/lib.rs", "ratchet": "process-global", "reason": "kept: the loader hook that registers the extra DLL directories is `Once`-guarded, once per process, because it changes the process-wide DLL search path"},
{"crate": "leleka-memory", "file": "src/telemetry.rs", "ratchet": "process-global", "reason": "kept: the telemetry state (STATE, PUBLISHED, SETTINGS): the serve loop calls the `record_*` functions from many places that hold no common handle, one sampler thread publishes once a second; process-wide by contract like the obs logger. Diagnostics only (rides the runtime snapshot), never read by serving logic"},
{"crate": "leleka-model-format", "file": "src/gguf/resident.rs", "ratchet": "process-global", "reason": "kept: NEXT_SOURCE_ID mints the private source-owner identity after an admitted file fill; unique across the process by definition, checked exhaustion refuses rather than wraps"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_legacy.rs", "ratchet": "process-global", "reason": "kept: ORACLE, the q8-zero oracle switch of the legacy kernel (`set_oracle_q8_zero`), a test hook read by the kernel free functions that pool worker threads call with no context argument"},
{"crate": "leleka-native-cpu-expert", "file": "src/rust_weight_iq.rs", "ratchet": "process-global", "reason": "kept: pure memo of the IQ quantizer grids (one slot per grid kind, built on first use from constant tables, dropped by the release call), shared by the pool worker threads that call the quantizers as free functions; no caller can observe the cache"},
{"crate": "leleka-obs", "file": "src/redact.rs", "ratchet": "process-global", "reason": "kept: the secret values registered for scrubbing: the logger facade is process-wide by contract (same reason as lib.rs) and `scrub` runs on every log line of every thread"},
{"crate": "leleka-control-plane", "file": "src/config.rs", "ratchet": "allow-unused-imports", "reason": "debt: two glob re-exports of the config split that the compiler reports unused in the lib build; they stay because the lib test build of control-plane cannot be compiled on Windows (std::os::unix), so a use from a test module cannot be ruled out. Delete or narrow them on a Linux compile"},
{"crate": "leleka-control-plane", "file": "src/mcp.rs", "ratchet": "allow-unused-imports", "reason": "debt: three glob re-exports of the mcp split that the compiler reports unused in the lib build; kept because the lib test build of control-plane cannot be compiled on Windows (std::os::unix) and a test use cannot be ruled out. Delete or narrow them on a Linux compile"},
{"crate": "leleka-control-plane", "file": "src/request_log.rs", "ratchet": "allow-unused-imports", "reason": "debt: one glob re-export (metrics_text) that the compiler reports unused in the lib build; kept because the lib test build of control-plane cannot be compiled on Windows and a test use cannot be ruled out"},
{"crate": "leleka-control-plane", "file": "src/request_monitor.rs", "ratchet": "allow-unused-imports", "reason": "debt: one glob re-export (record) that the compiler reports unused in the lib build; kept because the lib test build of control-plane cannot be compiled on Windows and a test use cannot be ruled out"},
{"crate": "leleka-engine-host", "file": "src/runtime_gateway.rs", "ratchet": "allow-unused-imports", "reason": "debt: four glob re-exports of the gateway split; not checked, because leleka-engine-host needs the engine, which does not compile on Windows (STRA-390). Narrow or delete them with the compiler once it does"},
{"crate": "leleka-engine-host", "file": "src/runtime_rpc.rs", "ratchet": "allow-unused-imports", "reason": "debt: four glob re-exports of the rpc split; not checked, because leleka-engine-host needs the engine, which does not compile on Windows (STRA-390). Narrow or delete them with the compiler once it does"}
],
"source_patterns": [
{"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"},
{"id": "instant-now", "regex": "\\bInstant::now\\(\\)", "why": "time must come from an injected Clock in core logic (S14)"},
{"id": "path-include", "regex": "#\\[path\\s*=\\s*\"(?![^\"]*tests\\.rs\")(?![A-Za-z0-9_]+/[A-Za-z0-9_]+\\.rs\")", "why": "a file compiled into two crates must be one crate (S8); a tests.rs or a child module file of the form dir/name.rs is not an include"},
{"id": "process-global", "ignore_imports": true, "regex": "\\b(OnceLock|LazyLock|OnceCell)\\b|\\bstatic\\s+mut\\b|Governor::global\\(|serving_cells\\(\\)", "why": "process globals make core logic untestable without a GPU (S14)"},
{"id": "process-global", "ignore_imports": true, "regex": "\\bstatic\\s+mut\\b|\\bstatic\\s+[A-Z_][A-Z0-9_]*\\s*:[^=;]*{cell_types}|\\blazy_static!|Governor::global\\(|serving_cells\\(\\)", "why": "process globals make core logic untestable without a GPU (S14). Counted: a `static` (also inside thread_local!) whose type is a cell (Atomic*, Mutex, RwLock, Once, OnceLock, LazyLock, Cell, RefCell, ...) or a workspace type that holds one, and `static mut`; an instance field of those types is not a global"},
{"id": "dyn-trait", "regex": "\\bdyn\\s+[A-Z]", "why": "no dynamic dispatch per round or token; dyn is for startup composition only"},
{"id": "glob-super-import", "regex": "^use super::\\*;", "why": "a glob import of the parent hides what a module needs; name the items (use super::{A, B}); scripts/dev/explicit_imports.py does it for the files rustsplit leaves"},
{"id": "allow-unused-imports", "regex": "#\\[allow\\(unused_imports\\)\\]", "why": "a blanket allow hides imports that are really unused; it belongs on re-exports and on names that only some cargo features use"}
@@ -1,5 +1,5 @@
{
"provenance": "Pinned engine/strata/serve/chat_template.jinja rendered with Jinja2 3.1.6; sanitized fixture",
"provenance": "Pinned third_party/strata/serve/chat_template.jinja rendered with Jinja2 3.1.6; sanitized fixture",
"request": {
"model": "strata-local",
"reasoning": {
@@ -29,6 +29,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
+2 -6
View File
@@ -38,14 +38,10 @@ mod tests;
mod state;
pub use state::{AppState, EngineLink, HttpPolicy, ModelView, Services};
mod routes;
#[allow(unused_imports)]
pub use routes::*;
mod admin_routes;
#[allow(unused_imports)]
pub use admin_routes::*;
use admin_routes::*;
mod readiness;
#[allow(unused_imports)]
pub use readiness::*;
use readiness::*;
mod metrics_document;
#[allow(unused_imports)]
pub use metrics_document::*;
+1 -1
View File
@@ -77,7 +77,7 @@ pub(super) async fn metrics(State(state): State<AppState>, RawQuery(query): RawQ
let all = query.as_deref().is_some_and(|q| q.split('&').any(|pair| pair == "requests=all"));
let document = metrics_document(&state, all).await;
if crate::prometheus::wanted(query.as_deref(), accept) {
let mut response = crate::prometheus::render(&document).into_response();
let mut response = crate::prometheus::render(&document, &state.services.request_metrics).into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static(crate::prometheus::CONTENT_TYPE),
+1
View File
@@ -87,6 +87,7 @@ pub fn router(state: AppState) -> Router {
model: state.model.name.clone(),
memory: state.model.memory.clone(),
clock: state.services.clock.clone(),
metrics: state.services.request_metrics.clone(),
};
let routes = model_routes(server_routes(Router::new()));
let routes = chat_routes(response_routes(routes, &state, &observe), &state, &observe);
+6
View File
@@ -66,6 +66,8 @@ pub struct ModelView {
pub prefix_cache: Arc<crate::prefix_view::PrefixView>,
/// The engine's memory-governor report: the pressure gate and the numbers behind `GET /v1/status` `memory`.
pub memory: Arc<crate::memory_view::MemoryView>,
/// What a gpt-oss system message says about the date (`prompt_date` in the config).
pub prompt_date: crate::responses::PromptDate,
}
/// Stores and process-wide services.
@@ -78,6 +80,8 @@ pub struct Services {
/// The MCP servers configured for the operator (`GET /mcp`).
pub mcp: Option<SharedToolHub>,
pub settings: Arc<crate::settings::Settings>,
/// The request counters and histograms that `/metrics` renders: written by the request middleware and the worker.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
/// Wall and monotonic time: queue deadlines, uptime, response timestamps.
pub clock: SharedClock,
pub started_at: SystemTime,
@@ -120,6 +124,7 @@ impl Default for ModelView {
vision: None,
prefix_cache: Arc::new(Default::default()),
memory: Arc::new(Default::default()),
prompt_date: crate::responses::PromptDate::Utc,
}
}
}
@@ -132,6 +137,7 @@ impl Default for Services {
monitor: Arc::new(Default::default()),
mcp: None,
settings: Arc::new(crate::settings::Settings::default()),
request_metrics: Arc::default(),
started_at: clock.system_time(),
clock,
}
+2
View File
@@ -74,6 +74,8 @@ pub struct BackendWorkerConfig {
/// Where the engine's memory-governor report is copied (health tick and after every request); `None` = not shown,
/// no gate.
pub memory_view: Option<Arc<crate::memory_view::MemoryView>>,
/// Where the worker counts the engine attaches and losses that `/metrics` renders.
pub request_metrics: Arc<crate::request_log::RequestMetrics>,
}
type Engine = Arc<Mutex<Box<dyn api::Backend>>>;
+2 -2
View File
@@ -167,7 +167,7 @@ impl AttachLoop {
/// The engine has the model: report ready and answer the `Load` requests that waited.
async fn become_ready(&mut self) {
self.attached_before = true;
crate::request_log::note_engine_attached();
self.config.request_metrics.note_engine_attached();
self.publish_ready_status().await;
self.answer_waiting_loads();
}
@@ -238,7 +238,7 @@ impl AttachLoop {
/// The engine is gone: record why and fail the worker.
async fn report_engine_lost(&self, reason: &str) {
crate::request_log::note_engine_lost(reason);
self.config.request_metrics.note_engine_lost(reason);
update(&self.status, WorkerState::Failed, None).await;
}
+2 -2
View File
@@ -35,7 +35,7 @@ fn single_commands(action: &str, rest: &[String]) -> Outcome {
fn batch_commands(action: &str, rest: &[String]) -> Outcome {
match (action, rest) {
// Batch forms for the differential harness (scripts/offline/diff_tokenizer.py): one JSON value per line.
// Batch forms for the differential harness: one JSON value per line.
("pre-tokenize-batch", []) => Some(pre_tokenize_batch()),
("tokenize-batch", [path, flags_rest @ ..]) if flags_rest.iter().all(|flag| flag == "--special") => {
Some(tokenize_batch(path, !flags_rest.is_empty()))
@@ -122,7 +122,7 @@ fn request_kwargs(request: &Json) -> Vec<(&str, Json)> {
}
/// JSON lines {"messages": [...], "tools": [...]|null, "add_generation_prompt": true, "kwargs": {...}} ->
/// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template, for scripts/offline/diff_chat_template.py.
/// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template.
fn render_chat() -> Result<(), BoxError> {
for line in std::io::stdin().lines() {
let request: Json = serde_json::from_str(&line?)?;
-2
View File
@@ -98,8 +98,6 @@ mod tests;
mod analyze;
mod previous;
mod sample;
#[allow(unused_imports)]
pub use analyze::*;
mod sample_records;
#[allow(unused_imports)]
pub use sample_records::*;
+3 -8
View File
@@ -103,17 +103,12 @@ mod tests;
mod archive_entry_points;
mod archive_file;
mod archive_plan;
#[allow(unused_imports)]
pub use archive_entry_points::*;
mod archive_write_steps;
#[allow(unused_imports)]
pub use archive_write_steps::*;
use archive_write_steps::*;
mod nested_layout;
#[allow(unused_imports)]
pub use nested_layout::*;
mod section_payload;
#[allow(unused_imports)]
pub use section_payload::*;
use section_payload::*;
mod directory_record;
#[allow(unused_imports)]
pub use directory_record::*;
use directory_record::*;
+4 -10
View File
@@ -146,17 +146,14 @@ pub struct Hub {
mod tests;
mod mcp_settings_errors;
#[allow(unused_imports)]
pub use mcp_settings_errors::*;
use mcp_settings_errors::*;
mod stdio_transport;
#[allow(unused_imports)]
pub use stdio_transport::*;
mod stdio_message_routing;
#[allow(unused_imports)]
pub use stdio_message_routing::*;
use stdio_message_routing::*;
mod http_transport;
#[allow(unused_imports)]
pub use http_transport::*;
use http_transport::*;
mod transport;
#[allow(unused_imports)]
pub use transport::*;
@@ -164,11 +161,8 @@ mod server;
#[allow(unused_imports)]
pub use server::*;
mod tool_result_text;
#[allow(unused_imports)]
pub use tool_result_text::*;
mod hub;
#[allow(unused_imports)]
pub use hub::*;
use hub::*;
mod parse_config;
#[allow(unused_imports)]
pub use parse_config::*;
+1 -4
View File
@@ -30,11 +30,8 @@ struct Events(mpsc::Receiver<Event>);
mod tests;
mod count_tokens;
#[allow(unused_imports)]
pub use count_tokens::*;
mod error_type;
#[allow(unused_imports)]
pub use error_type::*;
mod messages_stream;
#[allow(unused_imports)]
pub use messages_stream::*;
use messages_stream::*;
+1 -3
View File
@@ -44,8 +44,6 @@ pub struct ModelFile {
mod tests;
mod manifest_fetch;
#[allow(unused_imports)]
pub use manifest_fetch::*;
mod file_download;
#[allow(unused_imports)]
pub use file_download::*;
pub(crate) use file_download::*;
+5 -12
View File
@@ -70,23 +70,16 @@ pub struct Options {
mod tests;
mod pack_rules;
#[allow(unused_imports)]
pub use pack_rules::*;
use pack_rules::*;
mod expert_layout;
#[allow(unused_imports)]
pub use expert_layout::*;
use expert_layout::*;
mod convert_tensor;
#[allow(unused_imports)]
pub use convert_tensor::*;
use convert_tensor::*;
mod dense_files;
#[allow(unused_imports)]
pub use dense_files::*;
use dense_files::*;
mod pack_publication;
#[allow(unused_imports)]
pub use pack_publication::*;
mod pack_outputs;
#[allow(unused_imports)]
pub use pack_outputs::*;
mod same_bytes;
#[allow(unused_imports)]
pub use same_bytes::*;
use same_bytes::*;
+1 -1
View File
@@ -65,7 +65,7 @@ fn the_native_ple_key_encodings_are_the_originals() {
}
/// Numpy (`astype(float16)`) and gguf-py (`BF16.quantize_blocks`) answers for 4096 f32 bit patterns, from
/// `scripts/offline/gen_goldens.py`. The packer's F32 -> F16 / BF16 helpers must match bit for bit.
/// the Original's offline tooling (Strata 41cf05a0). The packer's F32 -> F16 / BF16 helpers must match bit for bit.
#[test]
fn f16_and_bf16_rounding_match_numpy_and_gguf_py() {
let vectors = include_bytes!("../../tests/fixtures/offline/f16_bf16_vectors.golden");
+4 -11
View File
@@ -79,26 +79,19 @@ struct StagingDir(PathBuf);
mod tests;
mod preview_entry_points;
#[allow(unused_imports)]
pub use preview_entry_points::*;
mod prepare_sharded;
#[allow(unused_imports)]
pub use prepare_sharded::*;
mod streamed_sharded_prepare;
#[allow(unused_imports)]
pub use streamed_sharded_prepare::*;
use streamed_sharded_prepare::*;
mod spool_raw_f32;
#[allow(unused_imports)]
pub use spool_raw_f32::*;
use spool_raw_f32::*;
mod prepare_single_file;
#[allow(unused_imports)]
pub use prepare_single_file::*;
use prepare_single_file::*;
mod tensor_encoding;
#[allow(unused_imports)]
pub use tensor_encoding::*;
mod derived_verification;
#[allow(unused_imports)]
pub use derived_verification::*;
use derived_verification::*;
mod preview_tensor_io;
use preview_tensor_io::*;
mod sharded_encode;
-1
View File
@@ -41,5 +41,4 @@ mod tests;
mod series;
use series::SERIES;
mod render;
#[allow(unused_imports)]
pub use render::*;
+2 -2
View File
@@ -35,7 +35,7 @@ pub(super) fn format_value(value: f64) -> String {
}
/// Render the `/metrics` document. `model` (when the document has one) labels `leleka_info`.
pub fn render(document: &Value) -> String {
pub fn render(document: &Value, requests: &crate::request_log::RequestMetrics) -> String {
let mut out = String::new();
let mut described: Vec<&str> = Vec::new();
for series in SERIES {
@@ -54,7 +54,7 @@ pub fn render(document: &Value) -> String {
let _ = writeln!(out, "# TYPE leleka_info gauge");
let model = document.get("model").and_then(Value::as_str).unwrap_or("");
let _ = writeln!(out, "leleka_info{{model=\"{}\"}} 1", escape(model));
crate::request_log::render_prometheus(&mut out);
requests.render_prometheus(&mut out);
out
}
+5 -4
View File
@@ -2,6 +2,7 @@
//! their fixed labels, unmeasured figures left out, and the choice of format by query or `Accept` header.
use super::*;
use crate::request_log::RequestMetrics;
use serde_json::json;
fn document() -> Value {
@@ -27,7 +28,7 @@ fn document() -> Value {
#[test]
fn counters_gauges_and_labels_render_in_the_text_format() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
assert!(text.contains("# TYPE leleka_generations_started_total counter\nleleka_generations_started_total 5\n"));
assert!(text.contains("leleka_prefill_seconds_total 2.5\n"));
assert!(text.contains("leleka_decode_seconds_total 1.25\n"));
@@ -85,7 +86,7 @@ const ENGINE_LINES: [&str; 16] = [
#[test]
fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
let text = render(&engine_document());
let text = render(&engine_document(), &RequestMetrics::default());
for expected in ENGINE_LINES {
assert!(text.contains(expected), "{expected} missing:\n{text}");
}
@@ -108,11 +109,11 @@ fn engine_gauges_counters_and_throttle_reasons_are_exposed_with_fixed_labels() {
#[test]
fn unmeasured_figures_are_not_exposed() {
let text = render(&document());
let text = render(&document(), &RequestMetrics::default());
// null in the document: no lifetime decode rate, no GPU clock, no swap
assert!(!text.contains("window=\"lifetime\""));
assert!(!text.contains("leleka_gpu_sm_clock_megahertz"));
let bare = render(&json!({"model": "m", "up": false}));
let bare = render(&json!({"model": "m", "up": false}), &RequestMetrics::default());
assert!(bare.contains("leleka_up 0\n"));
assert!(!bare.contains("leleka_gpu_") && !bare.contains("leleka_engine_phase"));
// every line is HELP, TYPE or a sample
+23 -19
View File
@@ -11,10 +11,10 @@
//! finalises the request, or, for a request that never reached the engine (a rejection, a client that left the queue),
//! when the last reference is dropped.
//!
//! The same moment feeds the Prometheus histograms and counters of [`render_prometheus`], whose labels are enums of
//! The same moment feeds the Prometheus histograms and counters of [`RequestMetrics`], whose labels are enums of
//! fixed size (endpoint x outcome, error class): there is no label whose value comes from a client.
use std::sync::{
Arc, LazyLock, Mutex,
Arc, Mutex,
atomic::{AtomicU64, Ordering},
};
@@ -85,6 +85,7 @@ struct Live {
pub struct ReqCtx {
state: Mutex<Live>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
}
/// What the request middleware leaves for the handler and the worker.
@@ -101,6 +102,7 @@ pub struct Observe {
pub model: Option<String>,
pub memory: Arc<crate::memory_view::MemoryView>,
pub clock: crate::ports::SharedClock,
pub metrics: Arc<RequestMetrics>,
}
/// Everything the line says, resolved.
@@ -128,7 +130,7 @@ pub struct Record {
pub hardware: Option<crate::memory_view::Brief>,
}
struct Registry {
pub struct RequestMetrics {
requests: Vec<AtomicU64>,
errors: Vec<AtomicU64>,
restarts: AtomicU64,
@@ -143,29 +145,31 @@ struct Registry {
prefill_tps: Histogram,
}
static REGISTRY: LazyLock<Registry> = LazyLock::new(|| Registry {
requests: (0..ENDPOINTS.len() * OUTCOMES.len()).map(|_| AtomicU64::new(0)).collect(),
errors: (0..ERROR_CLASSES.len()).map(|_| AtomicU64::new(0)).collect(),
restarts: AtomicU64::new(0),
engine_lost: AtomicU64::new(0),
engine_attached: AtomicU64::new(0),
ttft: Histogram::new(&[0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]),
duration: Histogram::new(&[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]),
queue: Histogram::new(&[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0]),
prompt_tokens: Histogram::new(&[256.0, 1024.0, 4096.0, 16384.0, 65536.0, 131072.0, 262144.0]),
output_tokens: Histogram::new(&[16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0]),
decode_tps: Histogram::new(&[5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0, 150.0]),
prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]),
});
impl Default for RequestMetrics {
fn default() -> Self {
Self {
requests: (0..ENDPOINTS.len() * OUTCOMES.len()).map(|_| AtomicU64::new(0)).collect(),
errors: (0..ERROR_CLASSES.len()).map(|_| AtomicU64::new(0)).collect(),
restarts: AtomicU64::new(0),
engine_lost: AtomicU64::new(0),
engine_attached: AtomicU64::new(0),
ttft: Histogram::new(&[0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0]),
duration: Histogram::new(&[0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0]),
queue: Histogram::new(&[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 15.0, 60.0]),
prompt_tokens: Histogram::new(&[256.0, 1024.0, 4096.0, 16384.0, 65536.0, 131072.0, 262144.0]),
output_tokens: Histogram::new(&[16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0]),
decode_tps: Histogram::new(&[5.0, 10.0, 20.0, 40.0, 60.0, 80.0, 100.0, 150.0]),
prefill_tps: Histogram::new(&[100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0]),
}
}
}
#[cfg(test)]
mod tests;
mod request_context;
#[allow(unused_imports)]
pub use request_context::*;
mod observation;
#[allow(unused_imports)]
pub use observation::*;
mod metrics_text;
#[allow(unused_imports)]
+97 -95
View File
@@ -1,107 +1,109 @@
//! The request metrics in the Prometheus text format (requests by endpoint and outcome, errors by class, engine lost,
//! attached and restart counters, time and token histograms) and the note that a worker attached to a loaded engine.
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, REGISTRY};
use super::{ENDPOINTS, ERROR_CLASSES, OUTCOMES, Ordering, RequestMetrics};
use std::fmt::Write as _;
/// The worker attached to a loaded engine (at start and after every restart).
pub fn note_engine_attached() {
let n = REGISTRY.engine_attached.fetch_add(1, Ordering::Relaxed) + 1;
leleka_obs::emit_always(leleka_obs::Level::Info, "api", "engine_attached", &[("attaches", n.into())]);
}
impl RequestMetrics {
/// The worker attached to a loaded engine (at start and after every restart).
pub fn note_engine_attached(&self) {
let n = self.engine_attached.fetch_add(1, Ordering::Relaxed) + 1;
leleka_obs::emit_always(leleka_obs::Level::Info, "api", "engine_attached", &[("attaches", n.into())]);
}
/// Append the request metrics in the Prometheus text format.
pub fn render_prometheus(out: &mut String) {
render_requests(out);
render_errors(out);
render_engine_counters(out);
render_histograms(out);
}
/// Append the request metrics in the Prometheus text format.
pub fn render_prometheus(&self, out: &mut String) {
self.render_requests(out);
self.render_errors(out);
self.render_engine_counters(out);
self.render_histograms(out);
}
/// `leleka_requests_total` by endpoint and outcome (a zero line when there is none).
fn render_requests(out: &mut String) {
let reg = &*REGISTRY;
leleka_obs::hist::header(
"leleka_requests_total",
"Generation requests by endpoint and how they ended.",
"counter",
out,
);
let mut any = false;
for (e, endpoint) in ENDPOINTS.iter().enumerate() {
for (o, outcome) in OUTCOMES.iter().enumerate() {
let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed);
if n > 0 {
any = true;
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}");
/// `leleka_requests_total` by endpoint and outcome (a zero line when there is none).
fn render_requests(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_requests_total",
"Generation requests by endpoint and how they ended.",
"counter",
out,
);
let mut any = false;
for (e, endpoint) in ENDPOINTS.iter().enumerate() {
for (o, outcome) in OUTCOMES.iter().enumerate() {
let n = reg.requests[e * OUTCOMES.len() + o].load(Ordering::Relaxed);
if n > 0 {
any = true;
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} {n}");
}
}
}
if !any {
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0");
}
}
if !any {
let _ = writeln!(out, "leleka_requests_total{{endpoint=\"responses\",outcome=\"stop\"}} 0");
/// `leleka_request_errors_total` by error class.
fn render_errors(&self, out: &mut String) {
let reg = self;
leleka_obs::hist::header(
"leleka_request_errors_total",
"Failed or rejected requests by error class.",
"counter",
out,
);
for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) {
let n = reg.errors[c].load(Ordering::Relaxed);
let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}");
}
}
/// The engine lost, attached and restart-request counters.
fn render_engine_counters(&self, out: &mut String) {
let reg = self;
let counters = [
(
"leleka_engine_lost_total",
"Times the API lost the engine (it restarted, hung or stopped answering).",
&reg.engine_lost,
),
(
"leleka_engine_attached_total",
"Times the API attached to a loaded engine (the first start counts).",
&reg.engine_attached,
),
("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", &reg.restarts),
];
for (name, help, value) in counters {
leleka_obs::hist::header(name, help, "counter", out);
let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed));
}
}
/// The time, token and rate histograms of the requests.
fn render_histograms(&self, out: &mut String) {
self.render_time_histograms(out);
self.render_size_histograms(out);
}
/// The time histograms: first token, duration and queue wait.
fn render_time_histograms(&self, out: &mut String) {
let reg = self;
reg.ttft.render("leleka_request_ttft_seconds", "Time from arrival to the first generated token.", out);
reg.duration.render("leleka_request_duration_seconds", "Time from arrival to the end of the request.", out);
reg.queue.render("leleka_request_queue_wait_seconds", "Time a request waited before the engine took it.", out);
}
/// The token-count and token-rate histograms.
fn render_size_histograms(&self, out: &mut String) {
let reg = self;
reg.prompt_tokens.render("leleka_request_prompt_tokens", "Prompt tokens per request.", out);
reg.output_tokens.render("leleka_request_output_tokens", "Output tokens per request.", out);
reg.decode_tps.render("leleka_request_decode_tokens_per_second", "Decode rate per request.", out);
reg.prefill_tps.render(
"leleka_request_prefill_tokens_per_second",
"Prefill rate per request (uncached prompt tokens).",
out,
);
}
}
/// `leleka_request_errors_total` by error class.
fn render_errors(out: &mut String) {
let reg = &*REGISTRY;
leleka_obs::hist::header(
"leleka_request_errors_total",
"Failed or rejected requests by error class.",
"counter",
out,
);
for (c, class) in ERROR_CLASSES.iter().enumerate().skip(1) {
let n = reg.errors[c].load(Ordering::Relaxed);
let _ = writeln!(out, "leleka_request_errors_total{{class=\"{class}\"}} {n}");
}
}
/// The engine lost, attached and restart-request counters.
fn render_engine_counters(out: &mut String) {
let reg = &*REGISTRY;
let counters = [
(
"leleka_engine_lost_total",
"Times the API lost the engine (it restarted, hung or stopped answering).",
&reg.engine_lost,
),
(
"leleka_engine_attached_total",
"Times the API attached to a loaded engine (the first start counts).",
&reg.engine_attached,
),
("leleka_requests_engine_restart_total", "Requests during which the engine was lost.", &reg.restarts),
];
for (name, help, value) in counters {
leleka_obs::hist::header(name, help, "counter", out);
let _ = writeln!(out, "{name} {}", value.load(Ordering::Relaxed));
}
}
/// The time, token and rate histograms of the requests.
fn render_histograms(out: &mut String) {
render_time_histograms(out);
render_size_histograms(out);
}
/// The time histograms: first token, duration and queue wait.
fn render_time_histograms(out: &mut String) {
let reg = &*REGISTRY;
reg.ttft.render("leleka_request_ttft_seconds", "Time from arrival to the first generated token.", out);
reg.duration.render("leleka_request_duration_seconds", "Time from arrival to the end of the request.", out);
reg.queue.render("leleka_request_queue_wait_seconds", "Time a request waited before the engine took it.", out);
}
/// The token-count and token-rate histograms.
fn render_size_histograms(out: &mut String) {
let reg = &*REGISTRY;
reg.prompt_tokens.render("leleka_request_prompt_tokens", "Prompt tokens per request.", out);
reg.output_tokens.render("leleka_request_output_tokens", "Output tokens per request.", out);
reg.decode_tps.render("leleka_request_decode_tokens_per_second", "Decode rate per request.", out);
reg.prefill_tps.render(
"leleka_request_prefill_tokens_per_second",
"Prefill rate per request (uncached prompt tokens).",
out,
);
}
+12 -9
View File
@@ -3,7 +3,7 @@
use super::{
Arc, CURRENT, Done, ENDPOINTS, ERROR_CLASSES, HeaderValue, Instant, Live, Next, OUTCOMES, ObsHandle, Observe,
Ordering, REGISTRY, REQUEST_ID_HEADER, Record, Registry, ReqCtx, ReqIdentity, Request, Response, State, V,
Ordering, REQUEST_ID_HEADER, Record, ReqCtx, ReqIdentity, Request, RequestMetrics, Response, State, V,
class_of_status, endpoint_index, session_tag,
};
@@ -69,7 +69,8 @@ pub async fn observe(State(observe): State<Observe>, request: Request, next: Nex
sid: session_tag(request.headers()),
model: observe.model.clone(),
};
let ctx = Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone()));
let ctx =
Arc::new(ReqCtx::new(identity, Some(observe.memory.clone()), observe.clock.clone(), observe.metrics.clone()));
let id = ctx.id();
let mut response = CURRENT.scope(ctx.clone(), next.run(request)).await;
ctx.set_http_status(response.status().as_u16());
@@ -224,13 +225,13 @@ impl Record {
}
}
pub(super) fn publish(&self) {
REGISTRY.observe(self);
pub(super) fn publish(&self, metrics: &RequestMetrics) {
metrics.observe(self);
leleka_obs::record("api", "request", &self.fields());
}
}
impl Registry {
impl RequestMetrics {
pub(super) fn observe(&self, r: &Record) {
let outcome = OUTCOMES.iter().position(|o| *o == r.outcome).unwrap_or(OUTCOMES.len() - 1);
self.requests[r.endpoint * OUTCOMES.len() + outcome].fetch_add(1, Ordering::Relaxed);
@@ -268,8 +269,10 @@ impl Registry {
}
}
/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`).
pub fn note_engine_lost(reason: &str) {
REGISTRY.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
impl RequestMetrics {
/// The worker lost the engine (a structured warning is logged; the count feeds `leleka_engine_lost_total`).
pub fn note_engine_lost(&self, reason: &str) {
self.engine_lost.fetch_add(1, Ordering::Relaxed);
leleka_obs::warn("api", "engine_lost", &[("reason", reason.into())]);
}
}
@@ -2,7 +2,8 @@
//! the classifiers that keep free text out of the line: endpoint index, session tag by digest, error class.
use super::{
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, SESSION_HEADERS, Sha256,
Arc, Digest, Done, DoneInfo, Finish, HeaderMap, Live, Mutex, ObsHandle, Record, ReqCtx, RequestMetrics,
SESSION_HEADERS, Sha256,
};
pub fn endpoint_index(path: &str) -> usize {
@@ -76,6 +77,7 @@ impl ReqCtx {
identity: ReqIdentity,
memory: Option<Arc<crate::memory_view::MemoryView>>,
clock: crate::ports::SharedClock,
metrics: Arc<RequestMetrics>,
) -> Self {
Self {
state: Mutex::new(Live {
@@ -96,6 +98,7 @@ impl ReqCtx {
memory,
}),
clock,
metrics,
}
}
@@ -171,7 +174,7 @@ impl ReqCtx {
Some(Record::from_state(s, self.clock.now()))
});
if let Some(Some(record)) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
@@ -186,7 +189,7 @@ impl Drop for ReqCtx {
_ => None,
};
if let Some(record) = record {
record.publish();
record.publish(&self.metrics);
}
}
}
+18 -14
View File
@@ -34,14 +34,14 @@ fn ctx() -> ReqCtx {
sid: Some("s-0123456789".into()),
model: Some("qwen-iq3".into()),
};
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared())
ReqCtx::new(identity, None, crate::adapters::SystemClock::shared(), Arc::default())
}
#[test]
fn the_record_stamps_come_from_the_injected_clock() {
let clock = crate::ports::fakes::ManualClock::new(1_700_000_000);
let identity = ReqIdentity { id: "rid".into(), endpoint: 0, sid: None, model: None };
let c = ReqCtx::new(identity, None, clock.clone());
let c = ReqCtx::new(identity, None, clock.clone(), Arc::default());
clock.advance(std::time::Duration::from_millis(40));
c.engine_start();
clock.advance(std::time::Duration::from_millis(60));
@@ -189,19 +189,20 @@ fn the_session_header_is_hashed_not_copied() {
assert_eq!(session_tag(&headers).unwrap(), tag);
}
fn counted(endpoint: &str, outcome: &str) -> u64 {
fn counted(metrics: &RequestMetrics, endpoint: &str, outcome: &str) -> u64 {
let mut text = String::new();
render_prometheus(&mut text);
metrics.render_prometheus(&mut text);
let prefix = format!("leleka_requests_total{{endpoint=\"{endpoint}\",outcome=\"{outcome}\"}} ");
text.lines().find_map(|l| l.strip_prefix(prefix.as_str())).and_then(|n| n.parse().ok()).unwrap_or(0)
}
/// A router whose handler asserts it sees the request's record and answers 503, behind the `observe` middleware.
fn rejecting_router() -> axum::Router {
fn rejecting_router(metrics: Arc<RequestMetrics>) -> axum::Router {
let observe = Observe {
model: Some("m".into()),
memory: Arc::new(Default::default()),
clock: crate::adapters::SystemClock::shared(),
metrics,
};
axum::Router::new()
.route(
@@ -217,8 +218,10 @@ fn rejecting_router() -> axum::Router {
}
/// Serves `rejecting_router` on a free port; returns its URL and the server task.
async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router();
async fn serve_rejecting_handler(
metrics: Arc<RequestMetrics>,
) -> (String, tokio::task::JoinHandle<std::io::Result<()>>) {
let app = rejecting_router(metrics);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/v1/chat/completions", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await });
@@ -227,10 +230,10 @@ async fn serve_rejecting_handler() -> (String, tokio::task::JoinHandle<std::io::
/// The rejected-chat count once it rises above `before`. The record is written when the last reference to it is gone,
/// just after the response.
async fn counted_after(before: u64) -> u64 {
async fn counted_after(metrics: &RequestMetrics, before: u64) -> u64 {
let mut after = before;
for _ in 0..50 {
after = counted("chat", "rejected");
after = counted(metrics, "chat", "rejected");
if after > before {
break;
}
@@ -241,14 +244,15 @@ async fn counted_after(before: u64) -> u64 {
#[tokio::test]
async fn the_middleware_names_the_request_hands_it_to_the_handler_and_records_a_rejection() {
let (url, server) = serve_rejecting_handler().await;
let before = counted("chat", "rejected");
let metrics = Arc::<RequestMetrics>::default();
let (url, server) = serve_rejecting_handler(metrics.clone()).await;
let before = counted(&metrics, "chat", "rejected");
let response = reqwest::Client::new().post(url).header("session_id", "conv-4417").body("{}").send().await.unwrap();
assert_eq!(response.status(), 503);
let id = response.headers()[REQUEST_ID_HEADER].to_str().unwrap().to_owned();
assert!(uuid::Uuid::parse_str(&id).is_ok(), "{id}");
assert!(!id.contains("4417"));
let after = counted_after(before).await;
let after = counted_after(&metrics, before).await;
assert!(after > before, "the rejection must be counted: {before} -> {after}");
server.abort();
}
@@ -259,9 +263,9 @@ fn the_prometheus_text_has_fixed_labels_and_valid_lines() {
c.engine_start();
c.first_token();
c.done(&done("DONE 10 100 5.0 100.0 length"), false);
record_of(&c).publish();
record_of(&c).publish(&c.metrics);
let mut text = String::new();
render_prometheus(&mut text);
c.metrics.render_prometheus(&mut text);
assert!(text.contains("leleka_requests_total{endpoint=\"responses\",outcome=\"length\"}"), "{text}");
assert!(text.contains("# TYPE leleka_request_ttft_seconds histogram"));
for line in text.lines() {
+1 -3
View File
@@ -93,11 +93,9 @@ struct Tap {
mod tests;
mod captured_text;
#[allow(unused_imports)]
pub use captured_text::*;
use captured_text::*;
mod record;
#[allow(unused_imports)]
pub use record::*;
mod capture;
#[allow(unused_imports)]
pub use capture::*;
+1 -1
View File
@@ -54,7 +54,7 @@ use serde_json::Map;
type SharedCodec = Arc<dyn TextCodec>;
static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0);
mod harmony_prompt;
pub use harmony_prompt::{PromptDate, set_prompt_date};
pub use harmony_prompt::PromptDate;
mod create;
pub use create::create;
mod errors;
+5 -13
View File
@@ -7,7 +7,6 @@
//! developer message; reasoning of earlier turns is not replayed (the template drops it), except for a
//! tool-call message where the template keeps it; custom tools are not supported.
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
pub use leleka_gateway_domain::responses::PromptDate;
@@ -19,22 +18,15 @@ use serde_json::Value;
use super::CreateRequest;
static PROMPT_DATE: OnceLock<PromptDate> = OnceLock::new();
/// Choose the date mode for the rest of the process (once, at start; later calls are ignored).
pub fn set_prompt_date(mode: PromptDate) {
let _ = PROMPT_DATE.set(mode);
}
pub(super) fn today() -> String {
civil_date(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs())
}
/// Render the Harmony prompt for `request` with today's date. The special markers are written as
/// sentinel characters, which the gpt-oss codec turns into the special tokens: text from the client can
/// never forge a marker.
pub(super) fn render(request: &CreateRequest) -> Result<String, String> {
match PROMPT_DATE.get().unwrap_or(&PromptDate::Utc) {
/// Render the Harmony prompt for `request` with the date `mode` says (the model view's `prompt_date`). The special
/// markers are written as sentinel characters, which the gpt-oss codec turns into the special tokens: text from the
/// client can never forge a marker.
pub(super) fn render(request: &CreateRequest, mode: &PromptDate) -> Result<String, String> {
match mode {
PromptDate::Utc => render_dated(request, Some(&today()), true),
PromptDate::Fixed(date) => render_dated(request, Some(date), true),
PromptDate::None => render_dated(request, None, true),
+1 -1
View File
@@ -90,7 +90,7 @@ pub(super) async fn prepare_input_tokens(
encode_images: bool,
) -> Result<Prepared, Box<Response>> {
resolve_previous(state, request).await?;
let (prompt, images) = render_prompt(&tokenizer, request)?;
let (prompt, images) = render_prompt(&tokenizer, request, &state.model.prompt_date)?;
let (token_ids, prompt) = tokenize_prompt(tokenizer.clone(), prompt).await?;
if images.is_empty() || !encode_images {
return Ok(Prepared {
@@ -74,13 +74,14 @@ pub(super) async fn resolve_previous(state: &AppState, request: &mut CreateReque
pub(super) fn render_prompt(
tokenizer: &SharedCodec,
request: &CreateRequest,
date: &crate::responses::PromptDate,
) -> Result<(String, Vec<String>), Box<Response>> {
let rendered = crate::stage_trace::time("render", || match tokenizer.family() {
Family::Qwen35 => {
let qwen = tokenizer.qwen().ok_or_else(|| "the Qwen family needs the Qwen tokenizer".to_owned())?;
render_request(request, qwen.marks())
}
Family::GptOss => harmony_prompt::render(request).map(|prompt| (prompt, Vec::new())),
Family::GptOss => harmony_prompt::render(request, date).map(|prompt| (prompt, Vec::new())),
});
rendered.map_err(|message| {
refuse(StatusCode::BAD_REQUEST, "invalid_request_error", "invalid_prompt", Some("input"), &message)
+1
View File
@@ -51,6 +51,7 @@ pub(super) fn worker_config(
cancel_drain_timeout: Duration::from_secs(20),
prefix_view: Some(state.model.prefix_cache.clone()),
memory_view: Some(state.model.memory.clone()),
request_metrics: state.services.request_metrics.clone(),
}
}
+1 -1
View File
@@ -48,6 +48,7 @@ pub(super) fn build_state(config: &Config, history: ResponseHistory) -> Result<a
model: app::ModelView {
name: config.model.clone(),
aliases: Arc::new(config.aliases.clone()),
prompt_date: config.prompt_date.clone(),
..Default::default()
},
services: services(config, history),
@@ -108,7 +109,6 @@ pub(super) fn apply_prompt_settings(config: &Config) {
config.prompt_date
);
}
leleka_control_plane::responses::set_prompt_date(config.prompt_date.clone());
if config.tool_call_recovery {
leleka_control_plane::elog!(
"tool_call_recovery is ON (experimental): a declared tool's call written in a drifted form is run as \
+1 -1
View File
@@ -2,7 +2,7 @@
//! that is not an inference API: `GET /props`, `GET /slots`, `GET /v1/status`, `GET /api/health`,
//! `GET|POST /settings`, `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload`, CORS and
//! the own-page guard. Behaviour is checked against the real Python handlers in
//! `tests/http_surface.rs` (fixtures from `tests/golden/gen_goldens.py http`).
//! `tests/http_surface.rs` (fixtures recorded from the Original's Python server).
//!
//! One engine at a time: `total_slots` is 1 and `/slots` lists one slot while the engine is loaded.
+1 -3
View File
@@ -28,8 +28,6 @@ mod unix;
mod tests;
mod command_line;
#[allow(unused_imports)]
pub use command_line::*;
use command_line::*;
mod control;
#[allow(unused_imports)]
pub use control::*;
+2 -5
View File
@@ -188,13 +188,10 @@ mod storage {
mod tests;
mod switch_profiles;
#[allow(unused_imports)]
pub use switch_profiles::*;
use switch_profiles::*;
mod run;
#[allow(unused_imports)]
pub use run::*;
mod reconcile;
#[cfg(unix)]
mod transaction;
#[allow(unused_imports)]
pub use reconcile::*;
use reconcile::*;
+1 -1
View File
@@ -184,7 +184,7 @@ mod tests {
}
/// Every GEN/GENI line equals what the Original's `StrataEngine.generate` writes to the pipe
/// (fixture from `tests/golden/gen_goldens.py`, which runs that real code with a fake pipe).
/// (fixture recorded by running that real code with a fake pipe).
#[test]
fn gen_lines_equal_the_python_servers_for_every_sampling_key() {
let fixture: serde_json::Value =
@@ -102,6 +102,7 @@ fn default_worker_config(tokenizer: Arc<Tokenizer>) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
@@ -32,6 +32,7 @@ fn worker_config(stack: &Stack) -> BackendWorkerConfig {
cancel_drain_timeout: Duration::from_secs(1),
prefix_view: None,
memory_view: None,
request_metrics: Default::default(),
}
}
+1 -2
View File
@@ -1,10 +1,9 @@
//! The native Jinja renderer against the Python server's `ChatTemplate` (jinja2) on generated conversations.
//!
//! `tests/fixtures/offline/chat_template_oracle.json` comes from `scripts/offline/gen_goldens.py chat_template_oracle`:
//! `tests/fixtures/offline/chat_template_oracle.json` was recorded from the Original's Python code (Strata 41cf05a0):
//! 90 renders (every role incl. developer and tool, list content with image/video parts, assistant `tool_calls`
//! with mapping arguments, tools, `enable_thinking` / `reasoning_effort` / `preserve_thinking`, no generation
//! prompt) and 25 conversations the template refuses, with the exact `raise_exception` message.
//! `scripts/offline/diff_chat_template.py` runs the same generator live over thousands of cases.
use leleka_control_plane::prompt::{ChatInput, Json, pinned};
use serde::Deserialize;
+2 -2
View File
@@ -1,8 +1,8 @@
//! Dequantization versus the pinned gguf-py (`quants.dequantize`, llama.cpp 3cf03257) and `tools/iq_fixture.py`.
//!
//! `tests/fixtures/offline/dequant_oracle.json` holds one seeded 256-value row of each of 23 block types and the
//! oracle's float32 bits (`scripts/offline/gen_goldens.py dequant_oracle`; `scripts/offline/diff_dequant.py` runs
//! 32 rows x 3 seeds live). The production visitor (`gguf_f32_stream::visit`: independent Rust decoders where they
//! oracle's float32 bits (recorded from the Original's Python code, Strata 41cf05a0). The production
//! visitor (`gguf_f32_stream::visit`: independent Rust decoders where they
//! exist, the pinned ggml C bridge otherwise) must reproduce every float bit for bit. Q8_K has no gguf-py
//! dequantizer; its reference is `d * qs`.
use leleka_control_plane::{gguf, gguf_f32_stream};
@@ -1,10 +1,9 @@
//! GGUF header reader versus `Strata 41cf05a0, tools/gguf_reader.py`.
//!
//! `tests/fixtures/offline/gguf_headers.json` is generated by `scripts/offline/gen_goldens.py` from the unmodified
//! `tests/fixtures/offline/gguf_headers.json` was recorded offline from the unmodified
//! Python reader: random GGUF v3 headers (all 13 metadata value types, arrays, unicode, alignment, split keys,
//! 1-4 dimensional tensors of every block geometry) with the metadata and tensor directory it parses from each, and
//! its `BLOCK_GEOMETRY` table. The live differential over thousands of files is
//! `scripts/offline/diff_gguf_header.py`.
//! its `BLOCK_GEOMETRY` table.
use leleka_control_plane::{gguf, gguf_json};
use serde_json::Value;
use std::{fs, path::PathBuf};
+1 -1
View File
@@ -2,7 +2,7 @@
//! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`,
//! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python
//! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from
//! `Strata 41cf05a0, serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here
//! `Strata 41cf05a0, serve/server.py`, and is replayed here
//! against the Rust router with a real worker supervisor and the mock engine.
//!
//! Deliberate differences, skipped in the comparison: the chat template text, the build/version
@@ -54,6 +54,7 @@ fn worker_config(tokenizer: Arc<Tokenizer>, memory: &Arc<MemoryView>) -> Backend
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: Some(memory.clone()),
request_metrics: Default::default(),
}
}
@@ -1,7 +1,7 @@
//! The reasoning-budget logic against the Python server's `Service.reasoning_budget` and `Service.run` (#123).
//!
//! `tests/fixtures/offline/reasoning_budget_oracle.json` comes from `scripts/offline/gen_goldens.py
//! reasoning_budget_oracle`: 247 budget lookups (request and configured values of every JSON type, with the message
//! `tests/fixtures/offline/reasoning_budget_oracle.json` was recorded from the Original's Python
//! code (Strata 41cf05a0): 247 budget lookups (request and configured values of every JSON type, with the message
//! of the 400) and 400 generations of the unmodified `Service.run` over a scripted engine and a byte-level toy
//! vocabulary, recording each engine call (prompt, max_new), the finish reason, the completion tokens and the text
//! the output parser was fed.
-22
View File
@@ -21,50 +21,28 @@ pub use recent_ids::{DEFAULT_RECENT_IDS, RecentIds};
mod tests;
mod backend_contract;
#[allow(unused_imports)]
pub use backend_contract::BACKEND_API_VERSION;
#[allow(unused_imports)]
pub use backend_contract::Backend;
#[allow(unused_imports)]
pub use backend_contract::BackendCapabilities;
#[allow(unused_imports)]
pub use backend_contract::BackendError;
#[allow(unused_imports)]
pub use backend_contract::BackendIdentity;
#[allow(unused_imports)]
pub use backend_contract::ContractError;
#[allow(unused_imports)]
pub use backend_contract::ErrorCode;
#[allow(unused_imports)]
pub use backend_contract::FinishReason;
#[allow(unused_imports)]
pub use backend_contract::GenerationEvent;
#[allow(unused_imports)]
pub use backend_contract::GenerationRequest;
#[allow(unused_imports)]
pub use backend_contract::GenerationSink;
#[allow(unused_imports)]
pub use backend_contract::GenerationTerminal;
#[allow(unused_imports)]
pub use backend_contract::LoadedModel;
#[allow(unused_imports)]
pub use backend_contract::MAX_OUTPUT_TOKENS;
#[allow(unused_imports)]
pub use backend_contract::ModelDescriptor;
#[allow(unused_imports)]
pub use backend_contract::RuntimeConfig;
#[allow(unused_imports)]
pub use backend_contract::SamplingOptions;
#[allow(unused_imports)]
pub use backend_contract::SupportedModelTuple;
#[allow(unused_imports)]
pub use backend_contract::Usage;
mod generation_stream;
#[allow(unused_imports)]
use generation_stream::EventSender;
#[allow(unused_imports)]
pub use generation_stream::GenerationStream;
#[allow(unused_imports)]
pub use generation_stream::StreamError;
mod contract_rules;
+2 -6
View File
@@ -103,12 +103,8 @@ pub struct ScriptedEngine {
mod tests;
mod scripted_handle;
#[allow(unused_imports)]
pub use scripted_handle::*;
use scripted_handle::*;
mod backend_port;
#[allow(unused_imports)]
pub use backend_port::*;
mod play;
#[allow(unused_imports)]
pub use play::*;
use play::*;
mod shared_ops;
+1 -1
View File
@@ -4,7 +4,7 @@
//! (`derived_factor`, `setup_resolve_rope`); this module holds the rest: which contexts the RAM allows
//! ([`ram_ctx`], [`ctx_ram_need`]), how many GiB of experts to keep resident ([`resident_budget_gib`]) and the
//! low-RAM mode's arithmetic (`low_ram_*`). Every function is checked against `import setup` over a grid by
//! `tests/setup_policy_oracle.rs` (golden from `scripts/offline/gen_goldens.py setup_policy`).
//! `tests/setup_policy_oracle.rs` (golden recorded from the Original's `setup.py`).
//!
//! Floating point is IEEE double on both sides, evaluated in the same order; Python's `round()` is round-half-even
//! (`f64::round_ties_even`).
+1 -1
View File
@@ -1,5 +1,5 @@
//! Golden tests for `rope_scaling` and `memory_plan` against fixtures produced by the ORIGINAL's host code
//! (see `rope_plan_golden/gen_rope_golden.sh` and `gen_plan_golden.sh`; clang++ on macOS, arm64).
//! (clang++ on macOS, arm64).
//!
//! Rope: the C++ side links `rope_scaling.hpp` unmodified and the two `build_rope_table` definitions extracted
//! verbatim from `rope.cu`, compiled `-O2 -ffp-contract=off`. Tables are checked bit-for-bit through FNV-1a 64
@@ -1,5 +1,5 @@
{
"generator": "strata-plan built from engine/strata/src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes",
"generator": "strata-plan built from Strata 41cf05a0, src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes",
"state_bytes_default": 117669888,
"cli": [
{
@@ -1,5 +1,5 @@
{
"generator": "gen_rope_golden.cpp over rope_scaling.hpp + rope.cu build_rope_table (verbatim)",
"generator": "host build over rope_scaling.hpp + rope.cu build_rope_table (verbatim)",
"cases": [
{
"name": "none_default", "desc": "default-constructed RopeScaling (today's engine)", "n_rot": 64,
+1 -1
View File
@@ -1,5 +1,5 @@
//! `setup.py` sizing rules versus `import setup` (the unmodified oracle), over the grid in
//! `tests/fixtures/setup_policy_oracle.json` (`scripts/offline/gen_goldens.py setup_policy`). Floats are compared
//! `tests/fixtures/setup_policy_oracle.json`. Floats are compared
//! bit for bit.
use leleka_context::{
rope_scaling::{RopeScalingType, derived_factor, setup_resolve_rope},
@@ -1,5 +1,5 @@
// Original Strata fetch_blobs_kernel; arithmetic-free uint4 copy.
// engine/strata/src/kernels/cuda/verify_kernels.cu, pinned upstream provenance.
// Strata 41cf05a0, src/kernels/cuda/verify_kernels.cu, pinned upstream provenance.
#include <cuda_runtime.h>
#include <cstdint>
extern "C" __global__ void fetch_blobs_kernel(const unsigned long long* __restrict__ src, const int32_t* __restrict__ n,
+19 -19
View File
@@ -124,13 +124,13 @@
"count": 3
}
],
"sm120_bytes": 5980,
"sm120_bytes": 5983,
"sm120_nvcc": null,
"sm120_path": "crates/cuda-driver/src/bf16_f32_mmvf.ptx",
"sm120_sha256": "044543f681bb23eb9cae602b1a16aa7b2386d6d5c3b15cc41987338bd613b1c3",
"sm120_sha256": "8b0d71f343f2b2b34b0e742e3bb08c2192be33e8016c2136e63fc7f34f477aaa",
"sm120_stored_nul": false,
"sm86_bytes": 5874,
"sm86_sha256": "54a33146558ef76c817fc8e556f709228f90e2ccd6565f57c4f8ec4646e6c442"
"sm86_bytes": 5877,
"sm86_sha256": "29e6a266d9608df5ff00c87ca8296c55f4ea53ed4d1fe01f0b785b76984d4318"
},
{
"entries": 19,
@@ -476,13 +476,13 @@
"count": 1
}
],
"sm120_bytes": 24712,
"sm120_bytes": 24718,
"sm120_nvcc": "13.0.88",
"sm120_path": "crates/cuda-driver/src/iq3_s_q8_1.ptx",
"sm120_sha256": "94f798c00813c2fb860b4bf77be9225767d408955e3421330ac34a4ebd43978f",
"sm120_sha256": "ebfcabd456b8cf16608c529b906849e4391096322a88e5a665ac87657a91dde6",
"sm120_stored_nul": false,
"sm86_bytes": 24711,
"sm86_sha256": "b19860070e69dccd5e98d1e6bc7cddcda2928efbd3f0bd21568fd1ae7d4ae927"
"sm86_bytes": 24717,
"sm86_sha256": "46a64e151bbdfe0e5b3a4b36e6abab396aeed026872b608e76b9a482bea8240a"
},
{
"entries": 1,
@@ -916,13 +916,13 @@
"count": 1
}
],
"sm120_bytes": 25114,
"sm120_bytes": 25120,
"sm120_nvcc": "13.0.88",
"sm120_path": "crates/cuda-driver/src/moe_group_iq3_s.ptx",
"sm120_sha256": "58d068ff3acc4211614f70ab04703a40858e148f9aef8503ed66f7640ae2e2aa",
"sm120_sha256": "46b0d5365a1529c65f478aa5335089e56eb624370f9c17c87e79b7369f0e7b8a",
"sm120_stored_nul": false,
"sm86_bytes": 25113,
"sm86_sha256": "36c2f68c0d3a3c524787ecf03a1f33e2da930a4917419ea5893ccaa28c33a88c"
"sm86_bytes": 25119,
"sm86_sha256": "0e5e0434421077516213079c02d9f98ff4bcfa46347903786e1decd520bbfd14"
},
{
"entries": 2,
@@ -936,13 +936,13 @@
"count": 1
}
],
"sm120_bytes": 36382,
"sm120_bytes": 36388,
"sm120_nvcc": "13.0.88",
"sm120_path": "crates/cuda-driver/src/moe_group_iq3_s_nc4.ptx",
"sm120_sha256": "be6ee907c0b370cb99894a03419466f1aa465ba9b8e2e8cf603887f534450d0c",
"sm120_sha256": "7a13911f998d38bba5c52862f92799d17a662e8427c1cdff24f01c1f30a7fd94",
"sm120_stored_nul": false,
"sm86_bytes": 36381,
"sm86_sha256": "23b702aaf1278dd3d436142b9c27321921f36dda7606d1f756973e5dfcbd4537"
"sm86_bytes": 36387,
"sm86_sha256": "e12dea8f921efd99c9483012f8da00c5ba1ba66b0444ff4ba98fed4903ed51e5"
},
{
"entries": 1,
@@ -1635,12 +1635,12 @@
"-std=c++17",
"--fmad=true",
"--ftz=false",
"-Iengine/strata/include",
"-Iengine/strata/third_party/ggml",
"-Istrata-41cf05a0/include",
"-Istrata-41cf05a0/third_party/ggml",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src",
"-Iengine/strata/src"
"-Istrata-41cf05a0/src"
],
"isa": "9.2",
"method": "recompile",
@@ -1,5 +1,5 @@
// Adapted from the pinned native operation:
// engine/strata/src/kernels/cuda/native_bf16.cu
// Strata 41cf05a0, src/kernels/cuda/native_bf16.cu
// SHA-256 70b44795528fb73d636be5914d60f0adaa849a48cc38f309d327a2976c3ed3da
// and exact BF16 bit expansion in bf16_bits.hpp
// SHA-256 813b51f17c5c264d642f4d77b3d6e5f35e7ea7310ba87b18b3a2a5bc9185198f.
+2 -2
View File
@@ -1,7 +1,7 @@
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -1,7 +1,7 @@
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -5,8 +5,8 @@
// Tail activation loads clamp to last genuine pointer; only live stores write.
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -1,6 +1,6 @@
{
"schema": 1,
"note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.",
"note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow Strata 41cf05a0, CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.",
"assets": [
{
"cu": "crates/cuda-driver/src/experimental_kv_q4.cu",
@@ -17,7 +17,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). FWHT-256 + Q4_0 append (step/batched) + gather; Original kv_q4.cu precise (default flags, not in the fast-math list); K8V4's Q4_0 V half and rotated INT8's FWHT",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/kv_q4.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/kv_q4.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -53,7 +53,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). INT8 append (K+V, K8V4 K half, V-only) + gather; Original kv_q8.cu precise",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/kv_q8.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/kv_q8.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -89,7 +89,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). CLOCK residency resolver, block copy, ring table, u4 copy; Original kv_stream.cu precise; integer only",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/kv_stream.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/kv_stream.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -113,8 +113,8 @@
{
"cu": "crates/cuda-driver/src/experimental_keyless.cu",
"cu_pin": {
"sha256": "77c50e5baff842e31f0d71624a5706f46ed74a56cdfc5e4211086d2ef08671c5",
"bytes": 1987
"sha256": "44304e967dc68e92233f6b78c25e6d80475ea4c0e94262cf928f7405cd553733",
"bytes": 1990
},
"ptx": "crates/cuda-driver/src/experimental_keyless.ptx",
"flags": [
@@ -125,7 +125,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). per-head query routing (fmaf-ordered 256x256); Original keyless.cu precise",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/keyless.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/keyless.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -161,7 +161,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). experimental attention modes 2/3/4 + merge; Original qsa_decode_attn.cu precise (expf/exp2f exact, not in the fast-math list)",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/qsa_decode_attn.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/qsa_decode_attn.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -185,8 +185,8 @@
{
"cu": "crates/cuda-driver/src/experimental_cvec.cu",
"cu_pin": {
"sha256": "d4fe221b11569db73247644bb79118b34d040b49c14897e0bac158dcd4ca356e",
"bytes": 4783
"sha256": "89038128664ea4688e20de69eb32f55dd17c3a51bb1d67ec7774cba97ec70686",
"bytes": 4786
},
"ptx": "crates/cuda-driver/src/experimental_cvec.ptx",
"flags": [
@@ -197,7 +197,7 @@
],
"policy": "EXPERIMENTAL, off by default (OptIn). control-vector apply; Original cvec.cu default flags (its own __expf in sigmoidf_ is explicit in the source)",
"direct_original_headers": [],
"original": "engine/strata/src/kernels/cuda/cvec.cu",
"original": "Strata 41cf05a0, src/kernels/cuda/cvec.cu",
"rust_consumers": {
"experimental.rs": {
"sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981",
@@ -1,7 +1,7 @@
{
"schema": 1,
"purpose": "Assets Root must seal for the literal Verifier window recorder (OriginalVerifyWindowOps). Everything not listed under new_sources is an already sealed asset that the window producers merely bind (SHA-256 pinned in the AssetSpec constants of crates/cuda-driver/src/original_verify_window_*.rs).",
"toolkit": "deploy/cuda-toolkit.lock.json (CUDA 13.0.88), built through scripts/build-original-verify-ptx.sh",
"toolkit": "deploy/cuda-toolkit.lock.json (CUDA 13.0.88), built with the precise nvcc flags (--fmad=true --ftz=false)",
"new_sources": [
{
"source": "crates/cuda-driver/src/original_verify_window_moe_experts.cu",
@@ -13,8 +13,8 @@
"-arch=sm_120",
"--fmad=true",
"--ftz=false",
"-Iengine/strata/include",
"-Iengine/strata/third_party/ggml",
"-Istrata-41cf05a0/include",
"-Istrata-41cf05a0/third_party/ggml",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src"
@@ -37,7 +37,7 @@
"window_moe_down_7",
"window_moe_down_8"
],
"derived_from": "engine/strata/src/kernels/cuda/iq_kernels.cu (native_gu_kernel, native_gu_multi_kernel, native_down_kernel, native_down_multi_kernel via native_expert_grouped / launch_gu / launch_down; textually includes crates/cuda-driver/src/mtp_original_full_head_iq.cu, the sealed copy of iq_kernels.cu; engine/strata/CMakeLists.txt gives iq_kernels.cu no per-source COMPILE_OPTIONS)",
"derived_from": "Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu (native_gu_kernel, native_gu_multi_kernel, native_down_kernel, native_down_multi_kernel via native_expert_grouped / launch_gu / launch_down; textually includes crates/cuda-driver/src/mtp_original_full_head_iq.cu, the sealed copy of iq_kernels.cu; Strata 41cf05a0, CMakeLists.txt gives iq_kernels.cu no per-source COMPILE_OPTIONS)",
"notes": "NEW source: no sealed PTX instantiates the grouped gate/up and down templates for the target's formats. The rest of native_expert_grouped (swiglu_entries_kernel, quantize_q8_1_kernel) is sealed in mtp_original_full_head_iq.ptx under mangled names. The PTX will also carry the unused head_* / dequant entries of the included file. Update EXPERTS.sha in original_verify_window_moe.rs after sealing; the build script's required-exports check should list the exports above.",
"install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL."
},
@@ -51,8 +51,8 @@
"-arch=sm_120",
"--fmad=true",
"--use_fast_math",
"-Iengine/strata/include",
"-Iengine/strata/third_party/ggml",
"-Istrata-41cf05a0/include",
"-Istrata-41cf05a0/third_party/ggml",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include",
"-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src"
@@ -60,8 +60,8 @@
"exports": [
"verify_window_qsa_gate"
],
"derived_from": "engine/strata/src/kernels/cuda/native_qsa.cu (kernel `gate`; CMakeLists.txt compiles native_qsa.cu with --use_fast_math)",
"nvcc_note": "--use_fast_math (as engine/strata/CMakeLists.txt compiles native_qsa.cu) implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true; --ftz=false is deliberately NOT passed.",
"derived_from": "Strata 41cf05a0, src/kernels/cuda/native_qsa.cu (kernel `gate`; CMakeLists.txt compiles native_qsa.cu with --use_fast_math)",
"nvcc_note": "--use_fast_math (as Strata 41cf05a0, CMakeLists.txt compiles native_qsa.cu) implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true; --ftz=false is deliberately NOT passed.",
"install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL."
}
],
@@ -160,7 +160,7 @@
"native_qsa_indexer",
"native_qsa_score"
],
"note": "engine/strata/CMakeLists.txt compiles these Original sources with --use_fast_math. The sealed Rust copies below were built with the precise flags of scripts/build-original-verify-ptx.sh (--fmad=true --ftz=false). Some copies reproduce the fast-math operations with explicit intrinsics in the .cu (e.g. mtp_original_full_shared.cu: __fdividef/__expf); the others are a numerics risk for bit-exact parity with the Original window until a per-kernel golden comparison on the GPU (or a re-seal with --use_fast_math) proves otherwise.",
"note": "Strata 41cf05a0, CMakeLists.txt compiles these Original sources with --use_fast_math. The sealed Rust copies below were built with the precise flags (--fmad=true --ftz=false). Some copies reproduce the fast-math operations with explicit intrinsics in the .cu (e.g. mtp_original_full_shared.cu: __fdividef/__expf); the others are a numerics risk for bit-exact parity with the Original window until a per-kernel golden comparison on the GPU (or a re-seal with --use_fast_math) proves otherwise.",
"candidate_resealed_assets": [
{
"ptx": "mtp_original_full_head_native.ptx / mtp_original_tail.ptx / mtp_original_full_checks.ptx",
@@ -204,7 +204,7 @@
}
],
"audit": {
"method": "For each Original source in the fast-math list that the window launches, the fast-math-sensitive operations (/ , expf, sqrtf, powf, sinf, cosf, logf) were listed from engine/strata/src/kernels/cuda/*.cu and compared with the instruction mix of the sealed PTX. A precise nvcc compile emits div.rn/rcp.rn/sqrt.rn and the multi-instruction expf sequence (fma.rn + ex2.approx.ftz + mul); --use_fast_math emits div.full, rcp.approx.ftz, sqrt.approx.ftz, ex2.approx.ftz(x*log2e), sin/cos.approx.ftz and .ftz on the arithmetic. Only qsa_decode_postops.ptx carries .ftz on its arithmetic.",
"method": "For each Original source in the fast-math list that the window launches, the fast-math-sensitive operations (/ , expf, sqrtf, powf, sinf, cosf, logf) were listed from Strata 41cf05a0, src/kernels/cuda/*.cu and compared with the instruction mix of the sealed PTX. A precise nvcc compile emits div.rn/rcp.rn/sqrt.rn and the multi-instruction expf sequence (fma.rn + ex2.approx.ftz + mul); --use_fast_math emits div.full, rcp.approx.ftz, sqrt.approx.ftz, ex2.approx.ftz(x*log2e), sin/cos.approx.ftz and .ftz on the arithmetic. Only qsa_decode_postops.ptx carries .ftz on its arithmetic.",
"sealed_precise_but_original_fast_math": [
{
"ptx": "mtp_original_full_head_native.ptx",
@@ -257,7 +257,7 @@
"original_verify.ptx, mtp_original_full_fused_gr.ptx, mtp_original_kv.ptx, qsa_prompt_select.ptx, qsa_prompt_resolver.ptx, mtp_original_full_element.ptx, mtp_original_full_s2.ptx, mtp_original_full_head_iq.ptx, mtp_original_full_router_legacy.ptx (all precise in the Original)"
],
"not_in_verify_window": "native_flash_attn.cu and native_qsa_score.cu are launched only by the single-token layer.cpp path, never by verify.cpp (qsa_decode_attn_batch / qsa_block_scores are precise)",
"action": "Re-seal the six assets above from their existing .cu with --use_fast_math (scripts/build-original-verify-ptx.sh compiles every source with the precise flags) and update their SHA pins; none of those sources contains hand-written intrinsics that a fast-math build would double-apply. The same assets back the MTP path, so the MTP golden comparisons must be redone after the re-seal."
"action": "Re-seal the six assets above from their existing .cu with --use_fast_math (every source was sealed with the precise flags) and update their SHA pins; none of those sources contains hand-written intrinsics that a fast-math build would double-apply. The same assets back the MTP path, so the MTP golden comparisons must be redone after the re-seal."
},
"not_candidates_original_is_precise": [
{
@@ -1,6 +1,6 @@
{
"schema": 1,
"note": "Additions to CUDA-SEAL-PLAN.json (schema 1, see stra169 plan) for the .cu assets added on claude/port-forward-leaves. Same fields; seal_sha256/seal_length are filled by the sealing session after nvcc. None of these needs -I/work/include (they include only cuda_fp16.h/cuda_runtime.h/libc headers). Verify each compiled entry list with `cuobjdump -sass`/`grep .entry` against `entries` before pinning. Flags follow engine/strata/CMakeLists.txt: --use_fast_math only for files in the native_* fast-math list.",
"note": "Additions to CUDA-SEAL-PLAN.json (schema 1, see stra169 plan) for the .cu assets added on claude/port-forward-leaves. Same fields; seal_sha256/seal_length are filled by the sealing session after nvcc. None of these needs -I/work/include (they include only cuda_fp16.h/cuda_runtime.h/libc headers). Verify each compiled entry list with `cuobjdump -sass`/`grep .entry` against `entries` before pinning. Flags follow Strata 41cf05a0, CMakeLists.txt: --use_fast_math only for files in the native_* fast-math list.",
"assets": [
{
"cu": "crates/cuda-driver/src/qsa_prompt_attention_variants.cu",
@@ -81,8 +81,8 @@
{
"cu": "crates/cuda-driver/src/mmq_original_prefill_misc.cu",
"cu_pin": {
"sha256": "da4cc72e19ca1ad694f4be807d6c0c1337ecfd8ca553fe31dd4c5185ed24cf4a",
"bytes": 3072
"sha256": "c5b2242dd01a48168052e4dd42ed5ab37bf44bd1bcc47a9bccb8f4ab7460faad",
"bytes": 3075
},
"ptx": "crates/cuda-driver/src/mmq_original_prefill_misc.ptx",
"flags": [
@@ -154,8 +154,8 @@
{
"cu": "crates/cuda-driver/src/s_gemv_legacy.cu",
"cu_pin": {
"sha256": "0922bb96ca3b2f1110509adab242cf76fa1f910cde859d1e4e4150c607b51952",
"bytes": 51423
"sha256": "0476de35304abd5149fc3b123e2a81855d79b37d36e0f4022433732fe94090ca",
"bytes": 51401
},
"ptx": "crates/cuda-driver/src/s_gemv_legacy.ptx",
"flags": [
@@ -211,7 +211,7 @@
}
],
"flags_policy_audit": {
"audited": "2026-10-14 with scripts/cuda-stubs/literal_diff.py (SOURCES=1) over every crates/cuda-driver/src/*.cu, against engine/strata/CMakeLists.txt",
"audited": "2026-10-14 with a literal-diff check (SOURCES=1) over every crates/cuda-driver/src/*.cu, against Strata 41cf05a0, CMakeLists.txt",
"cmake_policy": {
"per_source_use_fast_math": [
"native_mmvq",
@@ -229,7 +229,7 @@
"native_qsa_indexer",
"native_qsa_score"
],
"cmake_lines": "engine/strata/CMakeLists.txt:340-352 (strata_kernels), :965 (strata_mmq)",
"cmake_lines": "Strata 41cf05a0, CMakeLists.txt:340-352 (strata_kernels), :965 (strata_mmq)",
"strata_mmq_extended_lambda_use_fast_math": [
"src/prefill/moe_mmq.cu",
"src/prefill/ggml_cuda_host.cu",
@@ -320,6 +320,6 @@
"mtp_original_full_fused_gr (fused_gr)",
"mtp_original_full_s2 / mtp_original_full_shared / mtp_original_full_verify / mtp_original_full_element / mtp_original_full_gr_write / mtp_original_full_head_iq / mtp_original_full_head_sampler / mtp_original_full_coupled / mtp_original_full_quant80"
],
"stale_toolkit_comments": "kar_decode_levels.cu, experimental_*.cu, mmq_original_group_*.cu, mmq_original_formats*.cu say nvcc 12.8.93; deploy/cuda-toolkit.lock.json and scripts/build-original-verify-ptx.sh pin 13.0.88"
"stale_toolkit_comments": "kar_decode_levels.cu, experimental_*.cu, mmq_original_group_*.cu, mmq_original_formats*.cu say nvcc 12.8.93; deploy/cuda-toolkit.lock.json pins 13.0.88"
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
// Adapted from the pinned native operation:
// engine/strata/src/kernels/cuda/native_bf16.cu
// Strata 41cf05a0, src/kernels/cuda/native_bf16.cu
// SHA-256 70b44795528fb73d636be5914d60f0adaa849a48cc38f309d327a2976c3ed3da
// and exact BF16 bit expansion in bf16_bits.hpp
// SHA-256 813b51f17c5c264d642f4d77b3d6e5f35e7ea7310ba87b18b3a2a5bc9185198f.
@@ -4,6 +4,7 @@
use super::{
Cell, Context, Device, Driver, Error, PoisonCell, PromptSyncTrace, Rc, Result, RoutedGateUpQ8, ffi, qwen_dispatch,
};
use leleka_cuda_model::serving_context::ServingContext;
impl PromptSyncTrace {
pub fn enter() -> Self {
@@ -50,7 +51,13 @@ impl Driver {
}
}
impl<'driver> Device<'driver> {
/// A context of the trained serving context (262144 cells, identity RoPE); the serving engine creates its
/// contexts with [`Device::create_context_serving`].
pub fn create_context(&self, byte_budget: usize) -> Result<Context<'driver>> {
self.create_context_serving(byte_budget, ServingContext::trained())
}
/// A context whose buffers are sized and whose rotating kernels are parameterized for `serving`.
pub fn create_context_serving(&self, byte_budget: usize, serving: ServingContext) -> Result<Context<'driver>> {
valid_size(byte_budget)?;
let api = &self.driver.api;
let handle = api.create(self.handle)?;
@@ -64,7 +71,9 @@ impl<'driver> Device<'driver> {
}
return combine(Err(error), cleanup);
}
Ok(Context::fresh(self.driver, handle, self.ordinal, byte_budget))
let mut context = Context::fresh(self.driver, handle, self.ordinal, byte_budget);
context.retained.serving = serving;
Ok(context)
}
}
impl<'driver> Context<'driver> {
@@ -95,7 +104,7 @@ impl<'driver> Context<'driver> {
qwen_kernels: qwen_dispatch::Cache::new(),
kar_levels: Cell::new(None),
experimental: std::array::from_fn(|_| Cell::new(None)),
retained: crate::prompt_sync_trace_types::Retained::default(),
retained: crate::prompt_sync_trace_types::Retained::new(ServingContext::trained()),
}
}
}
+2 -2
View File
@@ -54,8 +54,8 @@ pub const PINS: [PtxPin; 3] = [
},
PtxPin {
source_sha256: [
9, 34, 187, 150, 202, 59, 47, 17, 16, 80, 154, 218, 178, 66, 207, 118, 250, 31, 145, 12, 222, 133, 157, 30,
78, 65, 80, 198, 7, 181, 25, 82,
4, 118, 222, 53, 48, 74, 189, 81, 73, 252, 59, 18, 62, 42, 129, 133, 93, 121, 179, 125, 54, 224, 244, 2,
36, 51, 115, 47, 233, 64, 144, 202,
],
ptx_sha256: [
58, 180, 209, 42, 94, 151, 196, 226, 244, 96, 44, 108, 135, 35, 114, 197, 192, 104, 93, 140, 241, 162, 2,
+6 -1
View File
@@ -54,6 +54,11 @@ impl Context<'_> {
}
Ok(CurrentGuard { context: self, active: true })
}
/// Print the allocation sites of this context that changed since the last report (nothing while
/// `LELEKA_VRAM_LEDGER` is off).
pub fn report_vram_ledger(&self, label: &str) {
vram_ledger::report(&self.retained.vram_ledger, label);
}
pub fn allocate(&self, bytes: usize) -> Result<DeviceBuffer<'_>> {
valid_size(bytes)?;
let total = self.allocated.get().checked_add(bytes).ok_or(Error::BudgetExceeded)?;
@@ -68,7 +73,7 @@ impl Context<'_> {
// A successful allocation whose pop fails stays charged. The poisoned
// context owns that allocation until destruction, so no unguarded free.
let handle = combine(allocation, guard.finish())?;
vram_ledger::note_alloc(handle.qwen_address(), bytes);
vram_ledger::note_alloc(&self.retained.vram_ledger, handle.qwen_address(), bytes);
Ok(DeviceBuffer { context: self, handle: Some(handle), bytes, _thread: PhantomData, borrowed: false })
}
/// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the
+40
View File
@@ -0,0 +1,40 @@
//! The serving context of a Context: the cell count its buffers are sized from and the RoPE constants of its rotating
//! kernels (fixed when the context is created), and the resident KV window its streamed QSA owners keep in VRAM
//! (`--kv-resident N`, the Original's `qsa_set_kv_resident`). Both belong to the Context, not to the process: every
//! owner sizes its pool from the value when it is created, so an owner created before the window is set keeps the
//! default window consistently.
use super::{Context, Error, Result};
use crate::serving_context::{KV_RESIDENT_DEFAULT_CELLS, ServingContext};
use leleka_context::geometry::QsaGeometry;
impl Context<'_> {
/// The serving context this context was created for.
pub fn serving(&self) -> &ServingContext {
&self.retained.serving
}
/// The geometry every context-linear size of this context is derived from.
pub fn serving_geometry(&self) -> QsaGeometry {
self.retained.serving.geometry
}
/// Fix the resident KV window of this context. The first call wins; a later call must request the same count.
pub fn configure_kv_resident(&self, cells: usize) -> Result<()> {
self.serving().resident_pages_for(cells)?;
match self.retained.kv_resident.get() {
Some(set) if set != cells => {
Err(Error::InvalidDriverValue("resident KV window already configured differently"))
}
_ => {
self.retained.kv_resident.set(Some(cells));
Ok(())
}
}
}
/// Resident pages (VRAM slots) a new streamed QSA owner of this context allocates.
pub(crate) fn kv_resident_pages(&self) -> Result<usize> {
self.serving().resident_pages_for(self.retained.kv_resident.get().unwrap_or(KV_RESIDENT_DEFAULT_CELLS))
}
}
+2 -2
View File
@@ -1,9 +1,9 @@
//! DeviceBuffer host/device copies (whole buffer and ranges, staged through a host Vec, synchronised) and its release
//! and Drop, plus the LELEKA_CHAIN 'mtp' selector chain_selects_mtp with its no-driver stubs.
use super::{DeviceBuffer, Error, Result, combine, compute_drain, vram_ledger};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
use super::original_verify;
use super::{DeviceBuffer, Error, Result, combine, compute_drain, vram_ledger};
impl DeviceBuffer<'_> {
pub fn len(&self) -> usize {
@@ -153,7 +153,7 @@ impl DeviceBuffer<'_> {
if self.borrowed {
return Ok(());
}
vram_ledger::note_free(handle.qwen_address());
vram_ledger::note_free(&self.context.retained.vram_ledger, handle.qwen_address());
if compute_drain::background() != 0 && !self.context.poisoned.get() {
// a chunk expert stream is in flight: do not synchronize the device now
return self.context.defer_free(handle, self.bytes);
+4 -4
View File
@@ -136,8 +136,8 @@ pub const PINS: [PtxPin; 6] = [
},
PtxPin {
source_sha256: [
119, 197, 14, 91, 175, 248, 66, 227, 31, 13, 113, 98, 74, 87, 6, 244, 110, 215, 74, 86, 205, 252, 94, 66,
17, 8, 109, 46, 240, 134, 113, 197,
68, 48, 78, 150, 125, 198, 142, 146, 35, 63, 107, 120, 194, 94, 109, 128, 71, 94, 164, 192, 233, 66, 98,
207, 146, 143, 116, 5, 205, 85, 55, 51,
],
ptx_sha256: [
26, 184, 184, 21, 110, 140, 130, 65, 49, 192, 12, 236, 218, 23, 127, 229, 125, 116, 178, 134, 160, 43, 126,
@@ -156,8 +156,8 @@ pub const PINS: [PtxPin; 6] = [
},
PtxPin {
source_sha256: [
212, 254, 34, 27, 17, 86, 157, 183, 50, 71, 100, 75, 183, 145, 24, 179, 77, 4, 11, 73, 193, 72, 151, 224,
186, 193, 88, 220, 212, 202, 53, 110,
137, 3, 129, 40, 102, 78, 164, 104, 142, 32, 222, 105, 235, 50, 245, 93, 209, 124, 58, 81, 187, 29, 103,
236, 119, 116, 203, 169, 126, 199, 6, 134,
],
ptx_sha256: [
25, 58, 221, 92, 180, 72, 245, 225, 147, 242, 15, 242, 72, 202, 68, 89, 171, 185, 98, 180, 114, 102, 60, 0,
+1 -1
View File
@@ -6,7 +6,7 @@
// an explicit ExperimentalOptIn (experimental.rs). With the flag off and no pending write the kernel is a no-op;
// with a pending write it applies the fused hyper-connection read's own arithmetic.
//
// LITERAL PORT of engine/strata/src/kernels/cuda/cvec.cu: `cvec_kernel`'s BODY and `sigmoidf_` are
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/cvec.cu: `cvec_kernel`'s BODY and `sigmoidf_` are
// byte-identical to the Original's (experimental_cvec.rs::literal_bodies_match_the_original). Edits:
// `__global__ cvec_kernel` became the `__device__ cvec_kernel_body` function called by the `extern "C" __global__`
// entry; the host tables (g_dev, cvec_upload, cvec_apply) are Rust. A null `bo`/`inj` is a 64-bit zero argument.
@@ -5,7 +5,7 @@
// model-quality gate (docs/keyless-runtime.md): this is an unqualified experiment, off by default, and the driver
// refuses the program without an explicit ExperimentalOptIn (experimental.rs).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/keyless.cu: the kernel BODY is byte-identical to the Original's
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/keyless.cu: the kernel BODY is byte-identical to the Original's
// (experimental_attn.rs::literal_bodies_match_the_original). Edits: `__global__ route_kernel` became the
// `__device__ route_kernel_body` function called by the `extern "C" __global__` entry; the host wrapper
// `keyless_route_query` (argument checks and launch geometry) is Rust.
+1 -1
View File
@@ -3,7 +3,7 @@
// 256-point Walsh-Hadamard transform they rely on. Off by default; the driver refuses to open this program
// without an explicit ExperimentalOptIn for a mode that needs it (experimental.rs).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/kv_q4.cu (Original, PR #21). Every kernel BODY below is
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/kv_q4.cu (Original, PR #21). Every kernel BODY below is
// byte-identical to the Original's (experimental_kv.rs::literal_bodies_match_the_original compares them).
// The only edits:
// 1. each `__global__` kernel became a `__device__ ..._body` function with the same parameters, called by
+2 -2
View File
@@ -8,7 +8,7 @@
// Both are lossy/unqualified and off by default; the driver refuses this program without an explicit
// ExperimentalOptIn (experimental.rs). The production INT8 path of the Rust runtime does not use this file.
//
// LITERAL PORT of engine/strata/src/kernels/cuda/kv_q8.cu. Kernel BODIES are byte-identical to the Original's
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/kv_q8.cu. Kernel BODIES are byte-identical to the Original's
// (experimental_kv.rs::literal_bodies_match_the_original). Edits: each `__global__` kernel became a
// `__device__ ..._body` function with the same parameters called by an `extern "C" __global__` entry with a
// flat pointer/integer ABI (KvHostPools rebuilt from pointers; a null pointer argument is a 64-bit zero);
@@ -22,7 +22,7 @@
// `cur_stride` (the Original's S26 multi-token append); the body is copied verbatim and the entry instantiates the
// single-token form (MULTI = false, strides 0), the old behaviour bit for bit, with its ABI unchanged. The MULTI
// branch is therefore not instantiated here. The Original's 8-wide gather (kv_gather_q8_wide_kernel) exists only
// under STRATA_EXPERIMENTAL_SM60 and is not part of this sm_120 program (tests/literal_port.rs lists it as excluded).
// under STRATA_EXPERIMENTAL_SM60 and is not part of this sm_120 program.
// Not compiled after the re-sync (no nvcc on that host): the sealed PTX is the 2026-10-15 build of the previous source
// and experimental::PENDING_RESEAL makes the program refuse to open until the server reseals it.
// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (the Original builds kv_q8.cu with
@@ -5,7 +5,7 @@
// bitwise equal to resident attention), but it is unqualified in this port and off by default; the driver
// refuses this program without an explicit ExperimentalOptIn (experimental.rs).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/kv_stream.cu (resolve_kernel, copy_kernel, reset_kernel,
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/kv_stream.cu (resolve_kernel, copy_kernel, reset_kernel,
// ring_kernel, block_scan, Runs, RT). Bodies are byte-identical to the Original's
// (experimental_stream.rs::literal_bodies_match_the_original). Edits: `__global__` kernels became
// `__device__ ..._body` functions with the same parameters called by `extern "C" __global__` entries with a flat
@@ -7,7 +7,7 @@
// ExperimentalOptIn (experimental.rs). The fp16 and INT8 modes of the Original kernel are NOT instantiated here
// (INT8 is qsa_native_decode.cu; fp16 is not part of the Rust runtime).
//
// LITERAL PORT of engine/strata/src/kernels/cuda/qsa_decode_attn.cu: warp_sum, warp_max, load8_*, load8<>,
// LITERAL PORT of Strata 41cf05a0, src/kernels/cuda/qsa_decode_attn.cu: warp_sum, warp_max, load8_*, load8<>,
// attn_chunk_kernel<> and attn_merge_kernel BODIES are byte-identical to the Original's
// (experimental_attn.rs::literal_bodies_match_the_original), as are the constants and mrope_pos. Edits: the
// `__global__` kernels became `__device__ ..._body` functions with the same parameters, called by
@@ -24,7 +24,7 @@
// LANE_CELL, QUERY_SWIZZLE, REDUCE12>` (with reduce12_gfx906 / reduce12_head_of_lane), copied verbatim; the entries
// instantiate it with the three flags off, which is the previous kernel's arithmetic. The Original's alternate
// schedules and batch variants (attn_chunk_kernel_pre75 and its helpers, attn_merge_v2_kernel, the INT8 v3 kernel,
// the slot / row kernels) are not part of this program: tests/literal_port.rs lists each as excluded with its reason.
// the slot / row kernels) are not part of this program.
// Not compiled after the re-sync (no nvcc on that host): the sealed PTX is the 2026-10-15 build of the previous
// source and experimental::PENDING_RESEAL makes the program refuse to open until the server reseals it.
// Sealed 2026-10-15 with nvcc 13.2.86 -ptx -O3 -arch=sm_120 -std=c++17, precise math (the Original builds
+1 -1
View File
@@ -121,7 +121,7 @@ fn routed_ptx(format: RoutedFormat) -> &'static [u8] {
// standalone installed-Driver proof is distinct from composition.
RoutedFormat::IQ3_XXS => concat!(include_str!("../iq3_xxs_q8_1.ptx"), "\0").as_bytes(),
// Root-delivered STRA-149 frozen routed artifact
// 94f798c00813c2fb860b4bf77be9225767d408955e3421330ac34a4ebd43978f.
// ebfcabd456b8cf16608c529b906849e4391096322a88e5a665ac87657a91dde6.
RoutedFormat::IQ3_S => concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes(),
// Root-delivered STRA-150 frozen routed artifact a31e653d.
RoutedFormat::IQ2_S => concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes(),
+2 -2
View File
@@ -1,7 +1,7 @@
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -27,11 +27,11 @@ fn synthetic_image(rng: &mut Rng) -> [Vec<u8>; 4] {
/// The real mapped host copy holding `image` and the device addresses of its four runs.
fn map_host(c: &Context<'_>, image: &[Vec<u8>; 4]) -> (MappedAllocation, [u64; 4]) {
let geometry = crate::serving_context::geometry();
let geometry = c.serving_geometry();
let offsets = geometry.stage_offsets().unwrap();
let mut mapped = {
let g = c.enter().unwrap();
let m = MappedAllocation::new();
let m = MappedAllocation::new(geometry);
g.finish().unwrap();
m.expect("pinned mapped host copy")
};
@@ -61,7 +61,7 @@ impl<'c> Pools<'c> {
let identity = upload(c, &i32s(&(0..N_BLOCKS as i32).collect::<Vec<_>>())).unwrap();
let stage = PAGE.iter().map(|n| c.allocate(n * N_BLOCKS).unwrap()).collect();
let resident = PAGE.iter().map(|n| c.allocate(n * slots).unwrap()).collect();
let table = c.allocate(crate::serving_context::geometry().page_table_bytes()).unwrap();
let table = c.allocate(c.serving_geometry().page_table_bytes()).unwrap();
Self { reference, identity, stage, resident, table }
}
@@ -205,7 +205,7 @@ impl<'c> Stream<'c> {
fn new(c: &'c Context<'c>) -> Self {
let mut w = c.native_batch_workspace().expect("workspace");
let mut rng = Rng(0x2545_f491_4f6c_dd1d);
let slots = crate::serving_context::geometry().resident_pages_for(20_480).unwrap();
let slots = c.serving_geometry().resident_pages_for(20_480).unwrap();
assert_eq!(slots, 5120);
let image = synthetic_image(&mut rng);
let (mapped, host) = map_host(c, &image);
@@ -257,7 +257,7 @@ impl<'c> Stream<'c> {
/// Every block the call named is resident and holds the host bytes; nothing overflowed.
fn check_resident(&mut self, call: usize, named: &BTreeSet<usize>) {
let bytes = crate::serving_context::geometry().page_table_bytes();
let bytes = self.pools.table.context.serving_geometry().page_table_bytes();
let map = self.pools.table.copy_to_owned(bytes).unwrap();
let map: Vec<i32> = map.chunks_exact(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect();
let slots = self.slots;
+1
View File
@@ -273,6 +273,7 @@ use q6_k_shape::q6_k_shape;
use q6_k_shape::vector_shape;
mod context;
mod context_gate_up_projection_admission;
mod context_serving;
mod context_matvec_k_quant_projections;
mod context_projection_kernel_slots;
mod context_routed_gate_up_projection;
@@ -59,8 +59,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
schedule: &OriginalMmqCopySchedule<'ctx>,
layer: usize,
) -> Result<usize> {
let admitted: &dyn RingArena = read;
let count = admitted.stage_slots()?;
let count = RingArena::stage_slots(read)?;
schedule.validate_context(context)?;
if !schedule_serves_ring(schedule.ring_slots(), count) {
let e = Error::InvalidProjectionShape;
@@ -3,7 +3,7 @@
// Literal Original prefill/moe_mmq.cu kernels that the Rust MMQ owners did not carry: copy1_kernel (the
// unaligned branch of gather_native), strata_q2_kernel (a Strata-pack Q2_0 expert blob -> GGUF Q2_0 blocks) and
// iota_kernel (the identity row map `ids_identity`, written by Prefill::run at the start of every prompt).
// Bodies are copied verbatim from engine/strata/src/prefill/moe_mmq.cu; only the export names change
// Bodies are copied verbatim from Strata 41cf05a0, src/prefill/moe_mmq.cu; only the export names change
// (leleka_original_mmq_*), the anonymous namespace is dropped. Original build flags for this file:
// --extended-lambda -use_fast_math (no arithmetic here, so precise/fast-math PTX is identical).
// Launch geometry (Original): 256 threads, ceil(n / 256) blocks, n = elements below.
+2 -2
View File
@@ -1,7 +1,7 @@
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -5,8 +5,8 @@
// Tail activation loads clamp to last genuine pointer; only live stores write.
// IQ3_S Q8_1 routed projection; derived from llama.cpp/ggml native Fmt21.
// Copyright (c) 2023-2026 The ggml authors. MIT License.
// Native source: engine/strata/src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: engine/strata/third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Native source: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu SHA256 07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537
// Grid source: Strata 41cf05a0, third_party/ggml/ggml-common.h SHA256 0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c
// Full MIT notice is retained in crates/quant-core/LICENSE-GGML.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -3,7 +3,7 @@
// i.e. `fused_gdn_conv_l2` + `fused_gdn_ab` + `fused_gdn_step_norm` in place of the decomposed
// conv / L2 / alpha-beta / gate / step / out-norm launches.
//
// Origin: engine/strata/src/kernels/cuda/fused_gdn.cu (Strata upstream commit recorded in docs/upstream.md):
// Origin: Strata 41cf05a0, src/kernels/cuda/fused_gdn.cu (Strata upstream commit recorded in third_party/strata/UPSTREAM.md):
// gdn_conv_l2_kernel, gdn_ab_kernel, gdn_step_norm_kernel.
// The bodies below are the original statements unchanged. The ONLY edits:
// * each original `__global__` kernel became a `__device__ __forceinline__` body of identical parameters and
@@ -19,7 +19,7 @@
// nvcc -ptx -O3 -arch=sm_120 offline_gdn_fused_t1_kernel.cu -o offline_gdn_fused_t1.ptx
// The PTX, its length and sha256 are produced and pinned by the toolchain owner (see gdn_fused_t1.rs).
//
// Strata is MIT-licensed upstream code of its authors; see engine/strata for the provenance record.
// Strata is MIT-licensed upstream code of its authors; see third_party/strata/UPSTREAM.md for the provenance record.
#include <cuda_runtime.h>
@@ -1,6 +1,6 @@
// STRA-169 candidate source: the Strata PREFILL GDN kernels, transcribed verbatim.
//
// Origin: engine/strata/src/prefill/kernels.cu (Strata upstream commit recorded in docs/upstream.md):
// Origin: Strata 41cf05a0, src/prefill/kernels.cu (Strata upstream commit recorded in third_party/strata/UPSTREAM.md):
// gdn_gates_kernel, gdn_conv_kernel, gdn_conv_tiled_kernel, gdn_conv_hist_kernel, gdn_l2_kernel,
// gdn_rec_cols_pipe_kernel, gdn_out_norm_kernel, and the BF16/FP16 image tail of gr_mix_kernel.
// This is NOT the pinned native/decode T1 arithmetic of offline_gdn_kernel.cu (that one stays untouched and keeps
@@ -22,7 +22,7 @@
// nvcc -ptx -O3 -arch=sm_120 offline_gdn_prefill_kernel.cu -o offline_gdn_prefill.ptx
// The PTX, its length and sha256 are produced and pinned by the toolchain owner (see gdn_native_batch.rs).
//
// Strata is MIT-licensed upstream code of its authors; see engine/strata for the provenance record.
// Strata is MIT-licensed upstream code of its authors; see third_party/strata/UPSTREAM.md for the provenance record.
#include <cuda_fp16.h>
#include <cuda_runtime.h>
@@ -1,6 +1,6 @@
// STRA-169 candidate source: the Strata PREFILL MoE router / shared-expert / combine dispatches, verbatim.
//
// Origin: engine/strata/src/prefill/kernels.cu (Strata upstream commit recorded in docs/upstream.md):
// Origin: Strata 41cf05a0, src/prefill/kernels.cu (Strata upstream commit recorded in third_party/strata/UPSTREAM.md):
// route_kernel<16> (the 512-expert instantiation chosen by route()), swiglu_pair_kernel, moe_combine_kernel,
// and the BF16/FP16 image tail of gr_mix_kernel (bf()/bf_lo()/hf()).
// The decode/T1 router asset (moe_route_top10.cu, one token per launch, native_router.cu arithmetic) stays untouched
@@ -16,7 +16,7 @@
// nvcc -ptx -O3 -arch=sm_120 offline_moe_prefill_kernel.cu -o offline_moe_prefill.ptx
// The PTX, its length and sha256 are produced and pinned by the toolchain owner (see moe_prefill_batch.rs).
//
// Strata is MIT-licensed upstream code of its authors; see engine/strata for the provenance record.
// Strata is MIT-licensed upstream code of its authors; see third_party/strata/UPSTREAM.md for the provenance record.
#include <cuda_fp16.h>
#include <cuda_runtime.h>
@@ -1,6 +1,6 @@
// STRA-169 candidate source: native GGUF blocks -> FP16 dequantization of the Strata prompt path.
//
// Origin: engine/strata/src/kernels/cuda/dequant_bf16.cu (group32<TYPE>, dequant_kernel, the H16 output of
// Origin: Strata 41cf05a0, src/kernels/cuda/dequant_bf16.cu (group32<TYPE>, dequant_kernel, the H16 output of
// dequant_f16), itself transcribed from ggml/src/ggml-quants.c at the pinned llama.cpp (MIT License,
// Copyright (c) 2023-2026 The ggml authors): dequantize_row_q8_0/q4_K/q5_K/q6_K/iq4_nl/iq4_xs.
// Only the GGUF types the GDN projections (attn_qkv, attn_gate, ssm_out) can carry are instantiated:
@@ -1,5 +1,5 @@
// Adapted from the pinned native operation:
// engine/strata/src/kernels/cuda/native_bf16.cu
// Strata 41cf05a0, src/kernels/cuda/native_bf16.cu
// SHA-256 70b44795528fb73d636be5914d60f0adaa849a48cc38f309d327a2976c3ed3da
// and exact BF16 bit expansion in bf16_bits.hpp
// SHA-256 813b51f17c5c264d642f4d77b3d6e5f35e7ea7310ba87b18b3a2a5bc9185198f.
@@ -16,9 +16,15 @@ use super::kernels::ArenaMap;
use super::moe::{self, MoeKnobs, OriginalVerifyExpertFormats};
use super::window_plan::PlanLayout;
use super::window_record::{ExpertTier, Rows};
use super::*;
use super::{
Arg, Command, Context, Error, MappedAllocation, MappedRouteOperands, OriginalVerifyBank, OriginalVerifyCpuRows,
OriginalVerifyCpuSink, OriginalVerifyGeometry, Physical, Result, RouteRowSpan, combine, command, handle, kernels,
};
use crate::{OriginalGpuStream, OriginalStreamKind};
mod probe_geometry;
pub use probe_geometry::expert_probe_geometry;
struct ProbeArena<'p, 'ctx>(&'p Physical<'ctx>);
impl ArenaMap for ProbeArena<'_, '_> {
fn span(&self, name: &str, offset: usize, bytes: usize) -> Result<u64> {
@@ -34,32 +40,6 @@ pub struct OriginalExpertTierProbe<'ctx> {
formats: OriginalVerifyExpertFormats,
}
/// The probe geometry: the model's MoE shape with a small context and vocabulary (no head runs here).
pub fn expert_probe_geometry(max_t: usize, max_expert_blob: usize) -> OriginalVerifyGeometry {
OriginalVerifyGeometry {
max_t,
n: 2560,
hc: 4,
lr: 320,
ff: 640,
experts: 512,
k: 10,
channels: 10240,
value_heads: 48,
key_heads: 16,
heads: 24,
kv_heads: 2,
head_dim: 256,
index_heads: 4,
index_dim: 128,
index_block: 4,
selection: 2051,
max_cells: 256,
vocabulary: 1024,
max_expert_blob,
}
}
impl<'ctx> Context<'ctx> {
pub fn original_expert_tier_probe(
&'ctx self,
@@ -0,0 +1,28 @@
//! The geometry of the expert tier probe: the shape the probe's verifier bank is sized for.
use crate::original_verify::OriginalVerifyGeometry;
/// The probe geometry: the model's MoE shape with a small context and vocabulary (no head runs here).
pub fn expert_probe_geometry(max_t: usize, max_expert_blob: usize) -> OriginalVerifyGeometry {
OriginalVerifyGeometry {
max_t,
n: 2560,
hc: 4,
lr: 320,
ff: 640,
experts: 512,
k: 10,
channels: 10240,
value_heads: 48,
key_heads: 16,
heads: 24,
kv_heads: 2,
head_dim: 256,
index_heads: 4,
index_dim: 128,
index_block: 4,
selection: 2051,
max_cells: 256,
vocabulary: 1024,
max_expert_blob,
}
}
@@ -33,7 +33,7 @@ pub(in super::super) fn all_window_assets() -> Vec<&'static AssetSpec> {
}
/// The kernel assets that are placeholders or fail their SHA-256 pin (none while every window PTX is the one
/// sealed with nvcc 13.2.86 on 2026-10-15): a window cannot be recorded while any is listed
/// (`scripts/build-original-verify-ptx.sh`, `crates/cuda-driver/seal-plans/cuda-seal-plan-additions-window.json`).
/// (`crates/cuda-driver/seal-plans/cuda-seal-plan-additions-window.json`).
pub fn unsealed_window_assets() -> Vec<&'static str> {
unsealed_keys(all_window_assets())
}
@@ -1,7 +1,7 @@
// src/original_verify_window_moe_experts.cu - the grouped native-expert gate/up and down kernels of the
// Verifier window (child of `original_verify`, producer family MoE / FFN).
//
// Original: engine/strata/src/kernels/cuda/iq_kernels.cu, `native_expert_grouped`:
// Original: Strata 41cf05a0, src/kernels/cuda/iq_kernels.cu, `native_expert_grouped`:
//
// launch_gu<T> -> native_gu_kernel<T> | native_gu_multi_kernel<T> (kSplit<T> selects the second)
// swiglu_entries_kernel, quantize_q8_1_kernel (sealed in mtp_original_full_head_iq.ptx)
@@ -18,8 +18,8 @@
// STRATA_D_FMTS). The split/non-split choice of `launch_gu` / `launch_down` is made at compile time per type,
// exactly as in the Original with STRATA_OLD_IQ_MMVQ unset (the default).
//
// Build: scripts/build-original-verify-ptx.sh flags (nvcc --ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false);
// engine/strata/CMakeLists.txt gives iq_kernels.cu no per-source options (it is not in the --use_fast_math list).
// Build: precise flags (nvcc --ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false);
// Strata 41cf05a0, CMakeLists.txt gives iq_kernels.cu no per-source options (it is not in the --use_fast_math list).
#include "mtp_original_full_head_iq.cu"
namespace strata::kernels {
@@ -1,16 +1,37 @@
//! The host-side lists a `Context` keeps for the verify-window modules and the deferred buffer frees.
//! What a `Context` keeps for itself: the verify-window modules, the deferred buffer frees and the resident KV window
//! its streamed QSA owners are sized from.
use super::{Rc, RefCell, ffi};
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
use super::original_verify;
use super::{Cell, Rc, RefCell, ffi};
use crate::vram_ledger::Ledger;
use leleka_cuda_model::serving_context::ServingContext;
/// Lists that live and die with the context: both start empty.
#[derive(Default)]
/// State that lives and dies with the context: its serving context, the lists (empty at the start) and the KV window
/// (unset at the start).
pub(crate) struct Retained {
/// The serving context this context was created for: the cell count every context-linear buffer is sized
/// from and the RoPE constants of the rotating kernels. Fixed for the life of the context.
pub(crate) serving: ServingContext,
/// Sealed verify-window modules loaded under this context, shared by every verifier bank created later
/// (the serve path assembles one per request) and unloaded with the context.
pub(crate) window_modules: RefCell<Vec<(&'static str, Rc<original_verify::abi::Module>, Vec<&'static str>)>>,
/// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole
/// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged.
pub(crate) deferred_frees: RefCell<Vec<(ffi::BufferHandle, usize)>>,
/// The resident KV window of this context's streamed QSA owners, in cells; `None` keeps the default window.
pub(crate) kv_resident: Cell<Option<usize>>,
/// The device allocations of this context by call site (`LELEKA_VRAM_LEDGER=1`; empty while it is off).
pub(crate) vram_ledger: RefCell<Ledger>,
}
impl Retained {
pub(crate) fn new(serving: ServingContext) -> Self {
Self {
serving,
window_modules: RefCell::default(),
deferred_frees: RefCell::default(),
kv_resident: Cell::new(None),
vram_ledger: RefCell::default(),
}
}
}
+12 -6
View File
@@ -1,5 +1,6 @@
//! Private fixed Original QSA entries. No stream/Blas ownership or public grid API.
use crate::{Error, Result, combine, ffi::BufferHandle};
use leleka_cuda_model::serving_context::ServingContext;
use std::ffi::CStr;
pub(crate) enum Arg {
Address(BufferHandle),
@@ -21,9 +22,9 @@ pub(crate) struct Arguments {
}
impl Arguments {
/// The arguments of `shape` followed, where its kernel takes them, by the serving context's RoPE constants.
pub(crate) fn for_launch(shape: Launch, mut values: Vec<Arg>) -> Result<Self> {
pub(crate) fn for_launch(serving: &ServingContext, shape: Launch, mut values: Vec<Arg>) -> Result<Self> {
shape.check_reach(serving)?;
if shape.carries_rope() {
let serving = crate::serving_context::serving_context();
values.extend(rope_tail(rope_abi()?, serving.rope_is_scaled(), serving.rope_args)?);
}
Self::new(values)
@@ -186,14 +187,19 @@ impl Launch {
fn carries_rope(self) -> bool {
matches!(self, Self::First | Self::Blocks(_) | Self::Rope(_) | Self::DecodeAppend | Self::DecodeRope(_))
}
/// Refuses a ScoreTC reach past the score row of the serving context (checked where the arguments are built, which
/// is where the serving context is known).
fn check_reach(self, serving: &ServingContext) -> Result<()> {
match self {
Self::Tc { reach, .. } if reach as usize > serving.geometry.max_blocks() => Err(Error::InvalidQwenShape),
_ => Ok(()),
}
}
/// Refuses the launches whose extents the Original fixes: the ScoreTC window and the decode norm/rope widths.
fn check_extents(self) -> Result<()> {
match self {
Self::Tc { t, reach } => {
if !(1..=256).contains(&t)
|| reach == 0
|| reach as usize > crate::serving_context::geometry().max_blocks()
{
if !(1..=256).contains(&t) || reach == 0 {
return Err(Error::InvalidQwenShape);
}
}
@@ -31,7 +31,7 @@ pub(super) fn with_gpu(body: impl FnOnce(&Context<'_>, usize, usize)) {
let context = device.create_context(6usize << 30).expect("context");
let workspace = context.native_batch_workspace().expect("workspace");
let stream = workspace.blas().expect("blas").stream();
let max_blocks = crate::serving_context::geometry().max_blocks();
let max_blocks = context.serving_geometry().max_blocks();
body(&context, stream, max_blocks);
}
@@ -1,9 +1,10 @@
//! Private fixed mapped-host allocation. Caller holds actual Context and drains before CPU access/free.
use crate::{Error, Result};
/// Original payload + four 256 B cursor alignment allowances, for the configured serving context
use leleka_context::geometry::QsaGeometry;
/// Original payload + four 256 B cursor alignment allowances, for the serving context of `geometry`
/// (`276_825_088` at the trained 262144 cells).
fn configured_bytes() -> Result<usize> {
crate::serving_context::geometry().mapped_host_bytes().map_err(|_| Error::InvalidSize)
fn configured_bytes(geometry: QsaGeometry) -> Result<usize> {
geometry.mapped_host_bytes().map_err(|_| Error::InvalidSize)
}
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod enabled {
@@ -55,12 +56,12 @@ mod enabled {
free: Free,
}
impl MappedAllocation {
pub(crate) fn new() -> Result<Self> {
pub(crate) fn new(geometry: QsaGeometry) -> Result<Self> {
let library = open_library()?;
let alloc = sym!(library, c"cuMemHostAlloc", Alloc);
let address = sym!(library, c"cuMemHostGetDevicePointer_v2", Address);
let free = sym!(library, c"cuMemFreeHost", Free);
let bytes = configured_bytes()?;
let bytes = configured_bytes(geometry)?;
let mut ptr = std::ptr::null_mut();
// SAFETY: valid out pointer; flags 3 = PORTABLE|DEVICEMAP; a context is current (the caller holds the
// Context). On success the allocation is `bytes` long, page-aligned, and owned by `MappedAllocation`
@@ -173,11 +174,11 @@ pub(crate) struct MappedAllocation;
target_pointer_width = "64"
)))]
impl MappedAllocation {
pub(crate) fn new() -> Result<Self> {
pub(crate) fn new(_: QsaGeometry) -> Result<Self> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn bytes(&self) -> usize {
configured_bytes().unwrap_or(0)
0
}
pub(crate) fn address(&self, _: usize, _: usize) -> Result<u64> {
Err(Error::UnsupportedPlatform)
@@ -37,9 +37,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> {
Ok(())
}
fn select_bounds_ok(&self, p: usize, n: usize) -> bool {
n != 0
&& n <= self.capacity
&& p.checked_add(n).is_some_and(|e| e <= crate::serving_context::geometry().cells())
n != 0 && n <= self.capacity && p.checked_add(n).is_some_and(|e| e <= self.context.serving_geometry().cells())
}
/// Budget check, exact-size allocation and alias admission of the five outputs; releases them on failure.
fn admit_outputs(
@@ -2,14 +2,14 @@
//! buffer sizes), the f32 little-endian encoder for uploads and the Context constructors.
use super::{Context, Error, QsaPromptIndexWorkspace, Result};
use leleka_context::geometry::QsaGeometry;
/// Score row stride (blocks plus tail and spare) of the configured serving context: `65538` at 262144 cells.
pub(super) fn max_blocks() -> usize {
crate::serving_context::geometry().max_blocks()
/// Score row stride (blocks plus tail and spare) of the serving context `g`: `65538` at 262144 cells.
pub(super) fn max_blocks(g: QsaGeometry) -> usize {
g.max_blocks()
}
// pooled,tail,dead,block_position,raw,K,V,Qfull,IndexQ,scores,status.
pub(super) fn sizes() -> [usize; 11] {
let g = crate::serving_context::geometry();
pub(super) fn sizes(g: QsaGeometry) -> [usize; 11] {
[
g.pooled_rows() * 128 * 4,
384 * 4,
@@ -7,6 +7,7 @@ use super::{
QsaPromptIndexWorkspace, RESERVE, Result, S, SCRATCH, SELECT, arena_span, combine, common, ffi, max_blocks,
native_block, sizes,
};
use leleka_context::geometry::QsaGeometry;
type Spans = Vec<(ffi::BufferHandle, usize)>;
@@ -30,11 +31,12 @@ pub(super) fn index_for<'ctx>(
context: &'ctx Context<'ctx>,
capacity: usize,
) -> ([usize; 11], QsaPromptIndexWorkspace<'ctx>) {
let mut sizes = sizes();
let geometry = context.serving_geometry();
let mut sizes = sizes(geometry);
for i in [4, 5, 6, 7, 8] {
sizes[i] = 4
}
sizes[9] = capacity.min(256) * max_blocks() * 4;
sizes[9] = capacity.min(256) * max_blocks(geometry) * 4;
let index = QsaPromptIndexWorkspace {
capacity,
sizes,
@@ -250,9 +252,9 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
}
/// The prior image must have the lengths of a prompt starting at `p` and be finite.
pub(super) fn check_prior(t: usize, p: usize, prior: [&[f32]; 3]) -> Result<()> {
pub(super) fn check_prior(geometry: QsaGeometry, t: usize, p: usize, prior: [&[f32]; 3]) -> Result<()> {
let [pooled, tail, dead] = prior;
if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells())
if p.checked_add(t).is_none_or(|end| end > geometry.cells())
|| pooled.len() != p / 4 * 128
|| tail.len() != 384
|| dead.len() != 128
@@ -40,7 +40,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
let QsaChunkPrior { first_position: p0, image } = prior;
let QsaIndexPrior { pooled, tail, dead } = image;
let (t, p) = (read.rows(), p0 as usize);
Self::check_prior(t, p, [pooled, tail, dead])?;
Self::check_prior(self.context.serving_geometry(), t, p, [pooled, tail, dead])?;
let (w, gamma) = self.admit(&read, &weights, ws)?;
self.project_prior(&read, ws, &weights.kinds, w)?;
let (out, [raw, qfull, iq]) = self.index_spans(&read, t)?;
@@ -7,9 +7,10 @@ use super::{
OriginalQsaPromptWeights, QsaNativePacking, QsaPromptIndexWorkspace, RESERVE, Result, SCRATCH, ffi, max_blocks,
sizes,
};
use leleka_context::geometry::QsaGeometry;
impl<'ctx> OriginalQsaPromptDevice<'ctx> {
pub fn device_bytes(capacity: usize) -> Result<usize> {
pub fn device_bytes(geometry: QsaGeometry, capacity: usize) -> Result<usize> {
if !(1..=8192).contains(&capacity) {
return Err(Error::InvalidQwenShape);
}
@@ -17,17 +18,19 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> {
// projection/normalized/IDs/attn/Out payloads are actual arena spans.
(SCRATCH
+ {
let z = sizes();
let z = sizes(geometry);
z[0] + z[1] + z[2] + z[3]
}
+ 5 * 4
+ 64)
.checked_add(capacity.min(256) * max_blocks() * 4)
.checked_add(capacity.min(256) * max_blocks(geometry) * 4)
.and_then(|x| x.checked_add(capacity * 16))
.ok_or(Error::BudgetExceeded)
}
pub(super) fn new(context: &'ctx Context<'ctx>, capacity: usize, packing: QsaNativePacking) -> Result<Self> {
let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?;
let required = Self::device_bytes(context.serving_geometry(), capacity)?
.checked_add(RESERVE)
.ok_or(Error::BudgetExceeded)?;
check_assets()?;
if context.is_poisoned() {
return Err(Error::ContextPoisoned);

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