STRA-338 S13: diagnostics settings, and the ratchets follow modules declared inside test-only files

Diagnostics topic of Settings: the bring-up trace, the driver-error trace (the nine driver_error functions
share crate::driver_errors_traced), the PLE, prefill-residual, seed and prefix traces, the serve profile
and the prefill profile sync. A set-ness switch is on for any value, as before; the serve profile and the
spec traces stay off for 0 and the empty string. The OnceLock readers are gone.

measure.py: a module declared inside a file that is itself compiled only for tests (for example
fivecase_frames.rs under native_down_candidate_only.rs, through #[path]) is test-only too. Unit test added.
Accounting only; env-read of leleka-runtime is now 1 (ProcessEnv::get_os, the one place that calls std::env),
instant-now 45 to 42, path-include 102 to 101, process-global 69 to 61.
This commit is contained in:
Pavlo Ratushnyi
2026-11-05 22:41:12 +01:00
parent dd584a09d6
commit c347d46b80
22 changed files with 180 additions and 37 deletions
+4 -4
View File
@@ -165,7 +165,7 @@
"env-read:leleka-npu-service": 1,
"env-read:leleka-npu-worker": 1,
"env-read:leleka-obs": 2,
"env-read:leleka-runtime": 24,
"env-read:leleka-runtime": 1,
"env-read:leleka-tokenizer": 2,
"env-read:strata-control": 19,
"env-read:strata-desktop-core": 15,
@@ -182,13 +182,13 @@
"instant-now:leleka-model-format": 10,
"instant-now:leleka-native-cpu-expert": 30,
"instant-now:leleka-npu-service": 5,
"instant-now:leleka-runtime": 45,
"instant-now:leleka-runtime": 42,
"instant-now:strata-control": 35,
"instant-now:strata-desktop-core": 15,
"path-include:leleka-cuda-driver": 115,
"path-include:leleka-model-format": 12,
"path-include:leleka-native-cpu-expert": 2,
"path-include:leleka-runtime": 102,
"path-include:leleka-runtime": 101,
"path-include:strata-desktop-core": 2,
"process-global:leleka-cuda-driver": 110,
"process-global:leleka-gateway-text": 5,
@@ -198,7 +198,7 @@
"process-global:leleka-model-format": 8,
"process-global:leleka-native-cpu-expert": 32,
"process-global:leleka-obs": 7,
"process-global:leleka-runtime": 69,
"process-global:leleka-runtime": 61,
"process-global:leleka-tokenizer": 4,
"process-global:strata-control": 14
}
+5 -2
View File
@@ -4,8 +4,11 @@
/// Bring-up tracing: `LELEKA_BRINGUP_TRACE` set (any value) enables the `DBG`/`PROBE` diagnostics on stderr.
/// Off by default so production serving prints nothing extra.
pub(crate) fn bringup_trace_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("LELEKA_BRINGUP_TRACE").is_some())
settings::process().diagnostics.bringup_trace
}
/// A driver error is printed when `LELEKA_BRINGUP_TRACE` or `LELEKA_TRACE_DRIVER_ERRORS` is set.
pub(crate) fn driver_errors_traced() -> bool {
settings::process().diagnostics.traces_driver_errors()
}
macro_rules! bringup_trace {
($($arg:tt)*) => {
@@ -45,7 +45,8 @@ pub(in crate::qwen_forward) fn run_original_prompt(plan:crate::backend::original
DriveError::Runner(e)=>e,
})
}
pub(super) fn driver_error(error:leleka_cuda_driver::Error)->Error{if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
pub(super) fn driver_error(error:leleka_cuda_driver::Error)->Error{
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
match error{
leleka_cuda_driver::Error::NonFiniteMmqOutput(_)=>Error::NonFinite,
leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation=>Error::InputAllocation,
@@ -176,7 +176,7 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
crate::bringup_trace!("DBG[{:.0}s] final_row ok",crate::qwen_forward::original_serve_stack::dbg_el());
// Bring-up gate (LELEKA_TRACE_PREFILL_R=1): FNV-1a of the bits of every row of the chunk's final residual R
// (all four streams), for bit-exact A/B comparison of prefill variants. Slow (one drain per row); off by default.
if std::env::var_os("LELEKA_TRACE_PREFILL_R").is_some(){
if crate::settings::process().diagnostics.trace_prefill_r{
let first=txn.start_position();let count=txn.len();
let hash=rows.with_final_residual(binding,dense,&txn,&final_row,|residual|{
let mut hash=0xcbf29ce484222325u64;let mut rows_hash=Vec::with_capacity(count);
@@ -3,7 +3,8 @@
#[allow(unused_imports)]
use super::*;
pub(in super::super) fn driver_error(error: DriverError) -> Error {if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
pub(in super::super) fn driver_error(error: DriverError) -> Error {
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
match error {
DriverError::UnsupportedQwenOperation
| DriverError::UnsupportedProjection
@@ -25,7 +25,8 @@ pub(super) fn download_f32(buffer: &DeviceBuffer<'_>, count: usize) -> Result<Bo
validate_values(&values, count)?;
Ok(values.into_boxed_slice())
}
pub(super) fn driver_error(error: DriverError) -> Error {if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
pub(super) fn driver_error(error: DriverError) -> Error {
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
#[cfg(test)]
eprintln!("PUBLIC CUDA raw adapter=gr error={error:?}");
match error {
@@ -205,8 +205,7 @@ impl InputStage {
}
/// `LELEKA_TRACE_PLE`, read once (it sat on the per-token path of every window).
pub(super) fn trace_ple() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("LELEKA_TRACE_PLE").is_some())
crate::settings::process().diagnostics.trace_ple
}
pub(super) fn validate_ids(
constants: &crate::model_binding::qwen4exp_input::InputConstants,
@@ -59,7 +59,8 @@ pub(super) fn binding_error(error: InputBindingError) -> Error {
_ => Error::InvalidDimension,
}
}
pub(super) fn driver_error(error: DriverError) -> Error {if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
pub(super) fn driver_error(error: DriverError) -> Error {
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
match error {
DriverError::UnsupportedQwenOperation
| DriverError::UnsupportedProjection
@@ -4,7 +4,8 @@
use super::*;
pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error {if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error {
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
match shared_driver_error(error) {
Error::Unsupported(_) => Error::Unsupported(Stage::Gr),
other => other,
@@ -215,7 +215,8 @@ impl<'ctx> OriginalMtpFullOwner<'ctx>{
}
impl Drop for OriginalMtpFullOwner<'_>{fn drop(&mut self){let _=self.close_inner();}}
fn driver_error(error:leleka_cuda_driver::Error)->Error{if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
fn driver_error(error:leleka_cuda_driver::Error)->Error{
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
match error{
leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch,
leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize
@@ -226,7 +226,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{
}
}
fn driver_error(error:leleka_cuda_driver::Error)->Error{if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
fn driver_error(error:leleka_cuda_driver::Error)->Error{
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
match error{
leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch,
leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize
@@ -8,8 +8,7 @@ use std::time::Instant;
/// `LELEKA_SERVE_PROFILE` set to anything but `0`, read once.
pub(crate) fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_SERVE_PROFILE").is_ok_and(|v| !v.is_empty() && v != "0"))
crate::settings::process().diagnostics.serve_profile
}
thread_local! {
@@ -74,7 +74,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
if max_rows > 0 {
let rows = original_serve_seed::summarize(counts, &[]).rows;
if rows > max_rows as u64 {
if std::env::var_os("LELEKA_SEED_TRACE").is_some() {
if crate::settings::process().diagnostics.seed_trace {
eprintln!("DBG seed: skipped, the prompt routed {rows} rows (cap {max_rows})");
}
return Ok(());
@@ -87,14 +87,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
report.plan_ms = planned.as_secs_f64() * 1e3;
report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3;
self.residency.add_usage(counts, usage);
if std::env::var_os("LELEKA_SEED_TRACE").is_some() {
if crate::settings::process().diagnostics.seed_trace {
eprintln!(
"DBG seed: prompt rows {} routed -> {} swaps (gain {:.0}, most in one layer {}), plan {:.2} ms, queue {:.2} ms",
report.rows, report.planned, report.gain, report.max_layer_swaps, report.plan_ms, report.queue_ms
);
}
self.seed_report = Some(report);
if std::env::var_os("LELEKA_SEED_TRACE").is_some() {
if crate::settings::process().diagnostics.seed_trace {
self.seed_counts = Some(counts.to_vec());
}
Ok(())
@@ -90,12 +90,12 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let _span = profile::span("prefix.after_chunk");
match prefix.after_chunk(self, prompt, end) {
Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => {
if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() {
if crate::settings::process().diagnostics.prefix_trace {
operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20));
}
}
Ok(other) => {
if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) {
if crate::settings::process().diagnostics.prefix_trace && !matches!(other, ChunkOutcome::Nothing) {
operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default()));
}
}
@@ -187,7 +187,8 @@ pub(super) fn binding_error(error: OutputBindingError) -> Error {
}
}
pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error {if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {error:?}");}
pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error {
if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");}
use leleka_cuda_driver::Error as DriverError;
match error {
@@ -115,8 +115,7 @@ pub(crate) fn enabled() -> bool {
crate::bringup_trace_enabled()
}
fn sync_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| enabled() && std::env::var_os("LELEKA_PREFILL_PROFILE_SYNC").is_some())
enabled() && crate::settings::process().diagnostics.prefill_profile_sync
}
/// Something the span can drain at its end in the synchronized attribution mode.
@@ -93,7 +93,8 @@ pub(in super::super) fn binding_error(e: InputBindingError) -> Error {
_ => Error::InvalidDimension,
}
}
pub(in super::super) fn driver_error(e: DriverError) -> Error {if crate::bringup_trace_enabled()||std::env::var_os("LELEKA_TRACE_DRIVER_ERRORS").is_some(){eprintln!("driver error: {e:?}");}
pub(in super::super) fn driver_error(e: DriverError) -> Error {
if crate::driver_errors_traced(){eprintln!("driver error: {e:?}");}
#[cfg(test)]
eprintln!("PUBLIC CUDA raw adapter=qsa error={e:?}");
match e {
+6
View File
@@ -6,6 +6,7 @@
//! read the captured namespace through [`Settings::env`] where they always did. Every field keeps the default, the
//! spelling and the fallback of the call site it replaced; the tests of each topic pin them with a `MapEnv`.
mod decode;
mod diagnostics;
mod kv;
mod memory;
mod parse;
@@ -17,6 +18,8 @@ mod capture_tests;
#[cfg(test)]
mod decode_tests;
#[cfg(test)]
mod diagnostics_tests;
#[cfg(test)]
mod kv_tests;
#[cfg(test)]
mod memory_tests;
@@ -26,6 +29,7 @@ mod serve_tests;
#[cfg(test)]
pub(crate) use decode::DRAFT_AFTER_COMMIT_ON;
pub(crate) use decode::DecodeSettings;
pub(crate) use diagnostics::DiagnosticsSettings;
pub(crate) use kv::KvSettings;
#[cfg(test)]
pub(crate) use kv::{FOOTPRINT_LEGACY_ON, PROMPT_EMBED_ALIAS_ON};
@@ -46,6 +50,7 @@ pub(crate) struct Settings {
pub(crate) decode: DecodeSettings,
pub(crate) memory: MemorySettings,
pub(crate) kv: KvSettings,
pub(crate) diagnostics: DiagnosticsSettings,
}
impl Settings {
@@ -57,6 +62,7 @@ impl Settings {
decode: DecodeSettings::from_source(&env),
memory: MemorySettings::from_source(&env),
kv: KvSettings::from_source(&env),
diagnostics: DiagnosticsSettings::from_source(&env),
env,
}
}
@@ -0,0 +1,45 @@
//! Settings of the bring-up and operator diagnostics. They only decide what is printed or profiled on stderr; none
//! of them changes what the engine computes.
use super::parse::set_and_not_zero;
use super::source::EnvSource;
/// What the operator asked to see.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct DiagnosticsSettings {
/// `LELEKA_BRINGUP_TRACE` is set (to anything): the `DBG`/`PROBE` lines on stderr.
pub(crate) bringup_trace: bool,
/// `LELEKA_TRACE_DRIVER_ERRORS` is set (to anything).
pub(crate) trace_driver_errors: bool,
/// `LELEKA_TRACE_PLE` is set (to anything).
pub(crate) trace_ple: bool,
/// `LELEKA_TRACE_PREFILL_R` is set (to anything): the hash of every prefill chunk's final residual.
pub(crate) trace_prefill_r: bool,
/// `LELEKA_SEED_TRACE` is set (to anything).
pub(crate) seed_trace: bool,
/// `LELEKA_PREFIX_TRACE` is set (to anything).
pub(crate) prefix_trace: bool,
/// `LELEKA_SERVE_PROFILE`: set, non-empty and not `0`.
pub(crate) serve_profile: bool,
/// `LELEKA_PREFILL_PROFILE_SYNC` is set (to anything); it only matters while the bring-up trace is on.
pub(crate) prefill_profile_sync: bool,
}
impl DiagnosticsSettings {
pub(super) fn from_source(env: &impl EnvSource) -> Self {
Self {
bringup_trace: env.is_set("LELEKA_BRINGUP_TRACE"),
trace_driver_errors: env.is_set("LELEKA_TRACE_DRIVER_ERRORS"),
trace_ple: env.is_set("LELEKA_TRACE_PLE"),
trace_prefill_r: env.is_set("LELEKA_TRACE_PREFILL_R"),
seed_trace: env.is_set("LELEKA_SEED_TRACE"),
prefix_trace: env.is_set("LELEKA_PREFIX_TRACE"),
serve_profile: set_and_not_zero(env, "LELEKA_SERVE_PROFILE"),
prefill_profile_sync: env.is_set("LELEKA_PREFILL_PROFILE_SYNC"),
}
}
/// A driver error is printed when either the bring-up trace or the driver-error trace is on.
pub(crate) fn traces_driver_errors(&self) -> bool {
self.bringup_trace || self.trace_driver_errors
}
}
@@ -0,0 +1,59 @@
//! Golden cases of the diagnostics topic: each row is what the call site this field replaced returned for that value.
use super::*;
fn diag(pairs: &[(&str, &str)]) -> DiagnosticsSettings {
DiagnosticsSettings::from_source(&MapEnv::of(pairs))
}
/// A switch that is on when the variable is set to anything, the empty string and `0` included.
fn set_ness(key: &str, field: fn(&DiagnosticsSettings) -> bool) {
assert!(!field(&diag(&[])), "{key} unset");
for value in ["1", "0", "", "off"] {
assert!(field(&diag(&[(key, value)])), "{key}={value:?}");
}
}
#[test]
fn the_trace_switches_are_on_when_set_to_anything() {
set_ness("LELEKA_BRINGUP_TRACE", |d| d.bringup_trace);
set_ness("LELEKA_TRACE_DRIVER_ERRORS", |d| d.trace_driver_errors);
set_ness("LELEKA_TRACE_PLE", |d| d.trace_ple);
set_ness("LELEKA_TRACE_PREFILL_R", |d| d.trace_prefill_r);
set_ness("LELEKA_SEED_TRACE", |d| d.seed_trace);
set_ness("LELEKA_PREFIX_TRACE", |d| d.prefix_trace);
set_ness("LELEKA_PREFILL_PROFILE_SYNC", |d| d.prefill_profile_sync);
}
#[test]
fn a_raw_os_value_counts_as_set() {
let raw = std::ffi::OsString::from("x");
let settings =
DiagnosticsSettings::from_source(&MapEnv::new().with_os("LELEKA_TRACE_PLE", raw));
assert!(settings.trace_ple);
}
#[test]
fn the_serve_profile_is_set_non_empty_and_not_zero() {
assert!(!diag(&[]).serve_profile);
for (value, want) in [
("1", true),
("on", true),
("00", true),
("0", false),
("", false),
] {
assert_eq!(
diag(&[("LELEKA_SERVE_PROFILE", value)]).serve_profile,
want,
"{value:?}"
);
}
}
#[test]
fn driver_errors_print_under_either_trace() {
assert!(!diag(&[]).traces_driver_errors());
assert!(diag(&[("LELEKA_BRINGUP_TRACE", "")]).traces_driver_errors());
assert!(diag(&[("LELEKA_TRACE_DRIVER_ERRORS", "")]).traces_driver_errors());
assert!(!diag(&[("LELEKA_TRACE_PLE", "1")]).traces_driver_errors());
}
+22 -10
View File
@@ -96,18 +96,29 @@ _PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]')
def test_only_modules(src):
"""Files compiled only for tests: a `mod x;` declared under a `#[cfg(...test...)]` attribute (with or without a
`#[path]`). `_under_test_module` extends this to the files below such a module."""
`#[path]`), and every module those files declare in turn. `_under_test_module` extends this to the files below
such a module."""
declared = {path.resolve(): _declarations(_text(path)) for path in rust_files(src)}
found = set()
for path in rust_files(src):
for name, explicit in _test_declarations(_text(path)):
target = _module_file(path, name, explicit)
if target is not None:
queue = []
for path, decls in declared.items():
for name, explicit, tested in decls:
target = _module_file(path, name, explicit) if tested else None
if target is not None and target not in found:
found.add(target)
queue.append(target)
while queue:
owner = queue.pop()
for name, explicit, _ in declared.get(owner, []):
target = _module_file(owner, name, explicit)
if target is not None and target not in found:
found.add(target)
queue.append(target)
return found
def _test_declarations(text):
"""[(module name, #[path] value or None)] of the `mod x;` lines whose attribute block is a test cfg."""
def _declarations(text):
"""[(module name, #[path] value or None, declared under a test cfg)] of the `mod x;` lines of a file."""
out = []
attrs = []
for line in text.splitlines():
@@ -116,9 +127,10 @@ def _test_declarations(text):
attrs.append(stripped)
continue
decl = _MOD_LINE.match(stripped)
if decl and _is_test_cfg(" ".join(attrs)):
explicit = _PATH_ATTR.search(" ".join(attrs))
out.append((decl.group(1), explicit.group(1) if explicit else None))
if decl:
block = " ".join(attrs)
explicit = _PATH_ATTR.search(block)
out.append((decl.group(1), explicit.group(1) if explicit else None, _is_test_cfg(block)))
attrs = []
return out
+12
View File
@@ -145,6 +145,18 @@ class Measurement(unittest.TestCase):
self.assertEqual([r for r in rows if "env::var" in r], [
'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");'])
def test_a_module_declared_inside_a_test_only_file_is_not_production_either(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "proofs" / "top").mkdir(parents=True)
(src / "lib.rs").write_text('let a = env::var("A");\n#[cfg(test)]\n#[path = "proofs/top.rs"]\nmod top;\n')
(src / "proofs" / "top.rs").write_text('#[path = "nested.rs"]\nmod nested;\nmod sibling;\nlet b = env::var("B");\n')
(src / "proofs" / "nested.rs").write_text('let c = env::var("C");\n')
(src / "proofs" / "top" / "sibling.rs").write_text('let d = env::var("D");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_counts_are_per_crate_and_skip_test_files(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"