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

This commit is contained in:
Pavlo Ratushnyi
2026-11-24 08:53:08 +01:00
27 changed files with 695 additions and 464 deletions
+69 -14
View File
@@ -49,10 +49,9 @@
"patterns": ["^impl_.*\\.rs$", "_fn\\.rs$", "_[0-9]+(_[0-9]+)*\\.rs$"], "patterns": ["^impl_.*\\.rs$", "_fn\\.rs$", "_[0-9]+(_[0-9]+)*\\.rs$"],
"allow": ["^(quantize_)?q[0-9]_[0-9k]\\.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": [ "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": "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": "kept: operator environment switch. The OnceLock is the cell of each `static EnvSwitch` that is declared where the switch is read; the variable cannot change after process start, so the first-read value equals a fresh read, and the crate sits below the engine Settings owner, so a settings value cannot be handed down to it (dependency direction)"},
{"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-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-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"}, {"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"},
@@ -123,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/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.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/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": "kept: ambient environment. The huge-page mode (LELEKA_HUGEPAGES) is immutable after start so the cache equals a fresh read; model-format is below the engine Settings owner (dependency direction), so no settings value reaches the mapping helpers"}, {"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/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": "not a process global: a per-instance lazily opened set of file handles (a OnceLock field of the archive); the gate pattern matches the type name"}, {"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-model-format", "file": "src/kar/verified_kar_ple_artifact.rs", "ratchet": "process-global", "reason": "not a process global: constructs the per-instance lazy handle cell of kar.rs; the gate pattern matches the type name"},
{"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-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-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"}, {"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"},
@@ -171,11 +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/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/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/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": "not a process global: `std::cell::OnceCell` is an instance field of the binding (lazy PLE reader); the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/model_binding/weight_binding/model_binding.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises the instance field `ple_reader` of one ModelBinding; 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-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-engine-qwen35-cuda", "file": "src/qwen_forward/session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell` is an instance field of the session; the gate pattern matches the type name"},
{"crate": "leleka-engine-qwen35-cuda", "file": "src/qwen_forward/session/qwen_session.rs", "ratchet": "process-global", "reason": "not a process global: `std::cell::OnceCell::new()` initialises an instance field of one session; the gate pattern matches the type name"},
{"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/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/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"}, {"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"},
@@ -216,20 +210,81 @@
{"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.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/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": "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/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"}, {"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_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/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/asset_admission.rs", "ratchet": "process-global", "reason": "kept: per-operation pure memo of the PTX proof of an embedded sealed image, 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-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-cuda-driver", "file": "src/marker_files.rs", "ratchet": "process-global", "reason": "kept: the marker files of the A/B controls are operator-named paths read once with the time of the first look, so a hot path stats the disk at most every 250 ms; one type serves three controls"},
{"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/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-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": [ "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": "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": "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": "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": "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": "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"} {"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"}
+2 -6
View File
@@ -38,14 +38,10 @@ mod tests;
mod state; mod state;
pub use state::{AppState, EngineLink, HttpPolicy, ModelView, Services}; pub use state::{AppState, EngineLink, HttpPolicy, ModelView, Services};
mod routes; mod routes;
#[allow(unused_imports)]
pub use routes::*; pub use routes::*;
mod admin_routes; mod admin_routes;
#[allow(unused_imports)] use admin_routes::*;
pub use admin_routes::*;
mod readiness; mod readiness;
#[allow(unused_imports)] use readiness::*;
pub use readiness::*;
mod metrics_document; mod metrics_document;
#[allow(unused_imports)]
pub use metrics_document::*; pub use metrics_document::*;
-2
View File
@@ -98,8 +98,6 @@ mod tests;
mod analyze; mod analyze;
mod previous; mod previous;
mod sample; mod sample;
#[allow(unused_imports)]
pub use analyze::*; pub use analyze::*;
mod sample_records; mod sample_records;
#[allow(unused_imports)]
pub use sample_records::*; pub use sample_records::*;
+3 -8
View File
@@ -103,17 +103,12 @@ mod tests;
mod archive_entry_points; mod archive_entry_points;
mod archive_file; mod archive_file;
mod archive_plan; mod archive_plan;
#[allow(unused_imports)]
pub use archive_entry_points::*; pub use archive_entry_points::*;
mod archive_write_steps; mod archive_write_steps;
#[allow(unused_imports)] use archive_write_steps::*;
pub use archive_write_steps::*;
mod nested_layout; mod nested_layout;
#[allow(unused_imports)]
pub use nested_layout::*; pub use nested_layout::*;
mod section_payload; mod section_payload;
#[allow(unused_imports)] use section_payload::*;
pub use section_payload::*;
mod directory_record; mod directory_record;
#[allow(unused_imports)] use directory_record::*;
pub use directory_record::*;
+4 -10
View File
@@ -146,17 +146,14 @@ pub struct Hub {
mod tests; mod tests;
mod mcp_settings_errors; mod mcp_settings_errors;
#[allow(unused_imports)] use mcp_settings_errors::*;
pub use mcp_settings_errors::*;
mod stdio_transport; mod stdio_transport;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use stdio_transport::*; pub use stdio_transport::*;
mod stdio_message_routing; mod stdio_message_routing;
#[allow(unused_imports)] use stdio_message_routing::*;
pub use stdio_message_routing::*;
mod http_transport; mod http_transport;
#[allow(unused_imports)] use http_transport::*;
pub use http_transport::*;
mod transport; mod transport;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use transport::*; pub use transport::*;
@@ -164,11 +161,8 @@ mod server;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use server::*; pub use server::*;
mod tool_result_text; mod tool_result_text;
#[allow(unused_imports)]
pub use tool_result_text::*; pub use tool_result_text::*;
mod hub; mod hub;
#[allow(unused_imports)] use hub::*;
pub use hub::*;
mod parse_config; mod parse_config;
#[allow(unused_imports)]
pub use parse_config::*; pub use parse_config::*;
+1 -4
View File
@@ -30,11 +30,8 @@ struct Events(mpsc::Receiver<Event>);
mod tests; mod tests;
mod count_tokens; mod count_tokens;
#[allow(unused_imports)]
pub use count_tokens::*; pub use count_tokens::*;
mod error_type; mod error_type;
#[allow(unused_imports)]
pub use error_type::*; pub use error_type::*;
mod messages_stream; mod messages_stream;
#[allow(unused_imports)] use messages_stream::*;
pub use messages_stream::*;
+1 -3
View File
@@ -44,8 +44,6 @@ pub struct ModelFile {
mod tests; mod tests;
mod manifest_fetch; mod manifest_fetch;
#[allow(unused_imports)]
pub use manifest_fetch::*; pub use manifest_fetch::*;
mod file_download; mod file_download;
#[allow(unused_imports)] pub(crate) use file_download::*;
pub use file_download::*;
+5 -12
View File
@@ -70,23 +70,16 @@ pub struct Options {
mod tests; mod tests;
mod pack_rules; mod pack_rules;
#[allow(unused_imports)] use pack_rules::*;
pub use pack_rules::*;
mod expert_layout; mod expert_layout;
#[allow(unused_imports)] use expert_layout::*;
pub use expert_layout::*;
mod convert_tensor; mod convert_tensor;
#[allow(unused_imports)] use convert_tensor::*;
pub use convert_tensor::*;
mod dense_files; mod dense_files;
#[allow(unused_imports)] use dense_files::*;
pub use dense_files::*;
mod pack_publication; mod pack_publication;
#[allow(unused_imports)]
pub use pack_publication::*; pub use pack_publication::*;
mod pack_outputs; mod pack_outputs;
#[allow(unused_imports)]
pub use pack_outputs::*; pub use pack_outputs::*;
mod same_bytes; mod same_bytes;
#[allow(unused_imports)] use same_bytes::*;
pub use same_bytes::*;
+4 -11
View File
@@ -79,26 +79,19 @@ struct StagingDir(PathBuf);
mod tests; mod tests;
mod preview_entry_points; mod preview_entry_points;
#[allow(unused_imports)]
pub use preview_entry_points::*; pub use preview_entry_points::*;
mod prepare_sharded; mod prepare_sharded;
#[allow(unused_imports)]
pub use prepare_sharded::*; pub use prepare_sharded::*;
mod streamed_sharded_prepare; mod streamed_sharded_prepare;
#[allow(unused_imports)] use streamed_sharded_prepare::*;
pub use streamed_sharded_prepare::*;
mod spool_raw_f32; mod spool_raw_f32;
#[allow(unused_imports)] use spool_raw_f32::*;
pub use spool_raw_f32::*;
mod prepare_single_file; mod prepare_single_file;
#[allow(unused_imports)] use prepare_single_file::*;
pub use prepare_single_file::*;
mod tensor_encoding; mod tensor_encoding;
#[allow(unused_imports)]
pub use tensor_encoding::*; pub use tensor_encoding::*;
mod derived_verification; mod derived_verification;
#[allow(unused_imports)] use derived_verification::*;
pub use derived_verification::*;
mod preview_tensor_io; mod preview_tensor_io;
use preview_tensor_io::*; use preview_tensor_io::*;
mod sharded_encode; mod sharded_encode;
-1
View File
@@ -41,5 +41,4 @@ mod tests;
mod series; mod series;
use series::SERIES; use series::SERIES;
mod render; mod render;
#[allow(unused_imports)]
pub use render::*; pub use render::*;
-2
View File
@@ -168,10 +168,8 @@ impl Default for RequestMetrics {
mod tests; mod tests;
mod request_context; mod request_context;
#[allow(unused_imports)]
pub use request_context::*; pub use request_context::*;
mod observation; mod observation;
#[allow(unused_imports)]
pub use observation::*; pub use observation::*;
mod metrics_text; mod metrics_text;
#[allow(unused_imports)] #[allow(unused_imports)]
+1 -3
View File
@@ -93,11 +93,9 @@ struct Tap {
mod tests; mod tests;
mod captured_text; mod captured_text;
#[allow(unused_imports)] use captured_text::*;
pub use captured_text::*;
mod record; mod record;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use record::*; pub use record::*;
mod capture; mod capture;
#[allow(unused_imports)]
pub use capture::*; pub use capture::*;
+1 -3
View File
@@ -28,8 +28,6 @@ mod unix;
mod tests; mod tests;
mod command_line; mod command_line;
#[allow(unused_imports)] use command_line::*;
pub use command_line::*;
mod control; mod control;
#[allow(unused_imports)]
pub use control::*; pub use control::*;
+2 -5
View File
@@ -188,13 +188,10 @@ mod storage {
mod tests; mod tests;
mod switch_profiles; mod switch_profiles;
#[allow(unused_imports)] use switch_profiles::*;
pub use switch_profiles::*;
mod run; mod run;
#[allow(unused_imports)]
pub use run::*; pub use run::*;
mod reconcile; mod reconcile;
#[cfg(unix)] #[cfg(unix)]
mod transaction; mod transaction;
#[allow(unused_imports)] use reconcile::*;
pub use reconcile::*;
-22
View File
@@ -21,50 +21,28 @@ pub use recent_ids::{DEFAULT_RECENT_IDS, RecentIds};
mod tests; mod tests;
mod backend_contract; mod backend_contract;
#[allow(unused_imports)]
pub use backend_contract::BACKEND_API_VERSION; pub use backend_contract::BACKEND_API_VERSION;
#[allow(unused_imports)]
pub use backend_contract::Backend; pub use backend_contract::Backend;
#[allow(unused_imports)]
pub use backend_contract::BackendCapabilities; pub use backend_contract::BackendCapabilities;
#[allow(unused_imports)]
pub use backend_contract::BackendError; pub use backend_contract::BackendError;
#[allow(unused_imports)]
pub use backend_contract::BackendIdentity; pub use backend_contract::BackendIdentity;
#[allow(unused_imports)]
pub use backend_contract::ContractError; pub use backend_contract::ContractError;
#[allow(unused_imports)]
pub use backend_contract::ErrorCode; pub use backend_contract::ErrorCode;
#[allow(unused_imports)]
pub use backend_contract::FinishReason; pub use backend_contract::FinishReason;
#[allow(unused_imports)]
pub use backend_contract::GenerationEvent; pub use backend_contract::GenerationEvent;
#[allow(unused_imports)]
pub use backend_contract::GenerationRequest; pub use backend_contract::GenerationRequest;
#[allow(unused_imports)]
pub use backend_contract::GenerationSink; pub use backend_contract::GenerationSink;
#[allow(unused_imports)]
pub use backend_contract::GenerationTerminal; pub use backend_contract::GenerationTerminal;
#[allow(unused_imports)]
pub use backend_contract::LoadedModel; pub use backend_contract::LoadedModel;
#[allow(unused_imports)]
pub use backend_contract::MAX_OUTPUT_TOKENS; pub use backend_contract::MAX_OUTPUT_TOKENS;
#[allow(unused_imports)]
pub use backend_contract::ModelDescriptor; pub use backend_contract::ModelDescriptor;
#[allow(unused_imports)]
pub use backend_contract::RuntimeConfig; pub use backend_contract::RuntimeConfig;
#[allow(unused_imports)]
pub use backend_contract::SamplingOptions; pub use backend_contract::SamplingOptions;
#[allow(unused_imports)]
pub use backend_contract::SupportedModelTuple; pub use backend_contract::SupportedModelTuple;
#[allow(unused_imports)]
pub use backend_contract::Usage; pub use backend_contract::Usage;
mod generation_stream; mod generation_stream;
#[allow(unused_imports)]
use generation_stream::EventSender; use generation_stream::EventSender;
#[allow(unused_imports)]
pub use generation_stream::GenerationStream; pub use generation_stream::GenerationStream;
#[allow(unused_imports)]
pub use generation_stream::StreamError; pub use generation_stream::StreamError;
mod contract_rules; mod contract_rules;
+2 -6
View File
@@ -103,12 +103,8 @@ pub struct ScriptedEngine {
mod tests; mod tests;
mod scripted_handle; mod scripted_handle;
#[allow(unused_imports)] use scripted_handle::*;
pub use scripted_handle::*;
mod backend_port; mod backend_port;
#[allow(unused_imports)]
pub use backend_port::*;
mod play; mod play;
#[allow(unused_imports)] use play::*;
pub use play::*;
mod shared_ops; mod shared_ops;
@@ -59,8 +59,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
schedule: &OriginalMmqCopySchedule<'ctx>, schedule: &OriginalMmqCopySchedule<'ctx>,
layer: usize, layer: usize,
) -> Result<usize> { ) -> Result<usize> {
let admitted: &dyn RingArena = read; let count = RingArena::stage_slots(read)?;
let count = admitted.stage_slots()?;
schedule.validate_context(context)?; schedule.validate_context(context)?;
if !schedule_serves_ring(schedule.ring_slots(), count) { if !schedule_serves_ring(schedule.ring_slots(), count) {
let e = Error::InvalidProjectionShape; let e = Error::InvalidProjectionShape;
@@ -16,9 +16,15 @@ use super::kernels::ArenaMap;
use super::moe::{self, MoeKnobs, OriginalVerifyExpertFormats}; use super::moe::{self, MoeKnobs, OriginalVerifyExpertFormats};
use super::window_plan::PlanLayout; use super::window_plan::PlanLayout;
use super::window_record::{ExpertTier, Rows}; 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}; use crate::{OriginalGpuStream, OriginalStreamKind};
mod probe_geometry;
pub use probe_geometry::expert_probe_geometry;
struct ProbeArena<'p, 'ctx>(&'p Physical<'ctx>); struct ProbeArena<'p, 'ctx>(&'p Physical<'ctx>);
impl ArenaMap for ProbeArena<'_, '_> { impl ArenaMap for ProbeArena<'_, '_> {
fn span(&self, name: &str, offset: usize, bytes: usize) -> Result<u64> { fn span(&self, name: &str, offset: usize, bytes: usize) -> Result<u64> {
@@ -34,32 +40,6 @@ pub struct OriginalExpertTierProbe<'ctx> {
formats: OriginalVerifyExpertFormats, 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> { impl<'ctx> Context<'ctx> {
pub fn original_expert_tier_probe( pub fn original_expert_tier_probe(
&'ctx self, &'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,
}
}
-1
View File
@@ -47,7 +47,6 @@ pub async fn main_native(mut args: Vec<String>) -> i32 {
// `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it). // `--hidden` (the logon task): hide the console window (the console itself stays, children stop through it).
if let Some(index) = args.iter().position(|a| a == "--hidden") { if let Some(index) = args.iter().position(|a| a == "--hidden") {
args.remove(index); args.remove(index);
crate::supervisor::HIDDEN.store(true, std::sync::atomic::Ordering::Relaxed);
#[cfg(windows)] #[cfg(windows)]
crate::winsys::hide_console(); crate::winsys::hide_console();
} }
-3
View File
@@ -34,9 +34,6 @@ use tokio::{
const LOG_ROTATE_BYTES: u64 = 64 << 20; const LOG_ROTATE_BYTES: u64 = 64 << 20;
/// Set by `--hidden` (the Windows logon task): the children get no console window.
pub static HIDDEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Options { pub struct Options {
pub config: PathBuf, pub config: PathBuf,
@@ -79,8 +79,6 @@ pub struct Run {
mod tests; mod tests;
mod budget; mod budget;
#[allow(unused_imports)]
pub use budget::*; pub use budget::*;
mod generation_loop; mod generation_loop;
#[allow(unused_imports)]
pub use generation_loop::*; pub use generation_loop::*;
+4 -10
View File
@@ -123,20 +123,14 @@ struct QuoteBalance<'a> {
mod tests; mod tests;
mod notes; mod notes;
#[allow(unused_imports)] use notes::*;
pub use notes::*;
mod incremental; mod incremental;
#[allow(unused_imports)]
pub use incremental::*; pub use incremental::*;
mod parse_text; mod parse_text;
#[allow(unused_imports)]
pub use parse_text::*; pub use parse_text::*;
mod parse_call; mod parse_call;
#[allow(unused_imports)] use parse_call::*;
pub use parse_call::*;
mod parameter_value; mod parameter_value;
#[allow(unused_imports)] use parameter_value::*;
pub use parameter_value::*;
mod find_parameter_end; mod find_parameter_end;
#[allow(unused_imports)] use find_parameter_end::*;
pub use find_parameter_end::*;
+1 -3
View File
@@ -280,8 +280,6 @@ copy!(
mod tests; mod tests;
mod trace_state; mod trace_state;
#[allow(unused_imports)]
pub use trace_state::*; pub use trace_state::*;
mod launch_interposers; mod launch_interposers;
#[allow(unused_imports)] pub(crate) use launch_interposers::*;
pub use launch_interposers::*;
+54 -60
View File
@@ -4,6 +4,8 @@ import pathlib
import re import re
import subprocess import subprocess
from .rustsource import cell_alternation, cell_holders, production_lines, requires_test, type_definitions
TEST_DIRS = ("tests",) TEST_DIRS = ("tests",)
@@ -64,72 +66,68 @@ def is_test_file(path, src):
return path.name == "tests.rs" or path.name.endswith("_tests.rs") or any(d in parts[:-1] for d in TEST_DIRS) return path.name == "tests.rs" or path.name.endswith("_tests.rs") or any(d in parts[:-1] for d in TEST_DIRS)
def production_lines(text):
"""Lines before the first `#[cfg(test)]` module (column 0, followed by `mod`); comment lines are dropped.
An inline module under another test cfg (`#[cfg(all(test, ...))]` then `mod x {`) is skipped up to its closing
`}` at column 0; the code after it still counts."""
lines = text.splitlines()
kept = []
index = 0
while index < len(lines):
line = lines[index]
following = lines[index + 1] if index + 1 < len(lines) else ""
if line.startswith("#[cfg(test)]") and following.startswith("mod "):
break
skipped_to = _test_module_declaration_end(lines, index)
if skipped_to is None and _opens_test_block(line, following):
skipped_to = _after_block(lines, index + 1)
if skipped_to is not None:
index = skipped_to
continue
if not line.lstrip().startswith("//"):
kept.append(line)
index += 1
return kept
def _opens_test_block(line, following):
"""A test cfg line whose next line opens an inline `mod x {` block."""
opens_block = following.startswith("mod ") and following.rstrip().endswith("{")
return _is_test_cfg(line) and line.startswith("#[cfg(") and opens_block
def _test_module_declaration_end(lines, index):
"""Index after a `mod x;` declaration that a test cfg line starts and further attributes (`#[path = ...]`) follow;
the declaration is test code, the production code after it still counts. None when `index` starts no such one."""
following = lines[index + 1] if index + 1 < len(lines) else ""
if not (_is_test_cfg(lines[index]) and lines[index].startswith("#[cfg(") and following.startswith("#[")):
return None
cursor = index + 1
while cursor < len(lines) and lines[cursor].startswith("#["):
cursor += 1
declaration = lines[cursor] if cursor < len(lines) else ""
names_a_module = declaration.startswith(("mod ", "pub mod ", "pub(crate) mod "))
return cursor + 1 if names_a_module and declaration.rstrip().endswith(";") else None
def _after_block(lines, start):
"""Index of the line after the column-0 `}` that closes the block opened at `start`."""
for index in range(start + 1, len(lines)):
if lines[index].startswith("}"):
return index + 1
return len(lines)
def count_patterns(packages, patterns, exceptions=(), excused=None): def count_patterns(packages, patterns, exceptions=(), excused=None):
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only """{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only
(test files and modules declared under a test cfg are skipped). A file named by an entry of `exceptions` (test files and modules declared under a test cfg are skipped). A file named by an entry of `exceptions`
({"crate", "file", "ratchet", "reason"}; `file` is relative to the crate directory) is not counted for that ({"crate", "file", "ratchet", "reason"}; `file` is relative to the crate directory) is not counted for that
ratchet; the hits it excused are added to `excused` ({(crate, file, ratchet): n}) when it is given.""" ratchet; the hits it excused are added to `excused` ({(crate, file, ratchet): n}) when it is given."""
compiled = [(p["id"], re.compile(p["regex"]), bool(p.get("ignore_imports"))) for p in patterns] compiled = _compile_patterns(patterns, packages)
counts = {} counts = {}
for pkg in packages: for pkg in packages:
skip = {(e["file"], e["ratchet"]) for e in exceptions if e["crate"] == pkg["name"]} skip = {(e["file"], e["ratchet"]) for e in exceptions if e["crate"] == pkg["name"]}
for pid, n in _package_counts(pkg["dir"] / "src", compiled, skip, pkg["name"], excused).items(): for pid, n in _package_counts(pkg["dir"] / "src", compiled[pkg["name"]], skip, pkg["name"], excused).items():
counts[f"{pid}:{pkg['name']}"] = n counts[f"{pid}:{pkg['name']}"] = n
return counts return counts
CELL_TYPES = "{cell_types}"
def _compile_patterns(patterns, packages):
"""{crate: [(id, compiled regex, ignore_imports)]}. `{cell_types}` in a regex stands for the interior-mutable types
a crate can name: the standard cells and every type that holds one, so `static X: Holder` is found like
`static X: Mutex<_>` while an instance field of the same type is not."""
needs_cells = any(CELL_TYPES in pattern["regex"] for pattern in patterns)
own = {pkg["name"]: _package_type_definitions(pkg) for pkg in packages} if needs_cells else {}
by_name = {pkg["name"]: pkg for pkg in packages}
compiled = {}
for pkg in packages:
alternation = cell_alternation(cell_holders(_visible_definitions(pkg, by_name, own))) if needs_cells else ""
compiled[pkg["name"]] = [
(p["id"], re.compile(p["regex"].replace(CELL_TYPES, alternation)), bool(p.get("ignore_imports")))
for p in patterns]
return compiled
def _package_type_definitions(pkg):
"""{type name: definition text} of the production code of one package."""
src = pkg["dir"] / "src"
definitions = {}
if src.is_dir():
test_files = test_only_modules(src)
for path in rust_files(src):
if not is_test_file(path, src) and not _under_test_module(path, test_files):
for name, body in type_definitions(_text(path)).items():
definitions[name] = definitions.get(name, "") + body
return definitions
def _visible_definitions(pkg, by_name, own):
"""The type definitions a crate can name: its own, which shadow those of the workspace crates it depends on,
directly or not."""
reached, pending = set(), list(pkg["normal"])
while pending:
name = pending.pop()
if name in by_name and name not in reached:
reached.add(name)
pending.extend(by_name[name]["normal"])
visible = {}
for name in sorted(reached):
visible.update(own[name])
visible.update(own[pkg["name"]])
return visible
_MOD_LINE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;") _MOD_LINE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;")
_PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]') _PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]')
@@ -173,7 +171,7 @@ def _declarations(text):
if decl: if decl:
block = " ".join(attrs) block = " ".join(attrs)
explicit = _PATH_ATTR.search(block) explicit = _PATH_ATTR.search(block)
out.append((decl.group(1), explicit.group(1) if explicit else None, _is_test_cfg(block))) out.append((decl.group(1), explicit.group(1) if explicit else None, requires_test(block)))
attrs = [] attrs = []
return out return out
@@ -182,10 +180,6 @@ def _unbalanced(text):
return text.count("[") > text.count("]") or text.count("(") > text.count(")") return text.count("[") > text.count("]") or text.count("(") > text.count(")")
def _is_test_cfg(block):
return "cfg(" in block and re.search(r"\btest\b", block) is not None and "not(test" not in block
def _module_file(declaring, name, explicit): def _module_file(declaring, name, explicit):
here = declaring.parent here = declaring.parent
if explicit: if explicit:
@@ -216,7 +210,7 @@ def _file_hits(path, compiled):
"""{pattern id: hits} of the production code of one file.""" """{pattern id: hits} of the production code of one file."""
text = _text(path) text = _text(path)
rows = production_lines(text) rows = production_lines(text)
rows_without_imports = production_lines(_USE_STATEMENT.sub("", text)) rows_without_imports = _USE_STATEMENT.sub("", "\n".join(rows)).splitlines()
hits = {pid: sum(len(rx.findall(row)) for row in (rows_without_imports if ignore_imports else rows)) hits = {pid: sum(len(rx.findall(row)) for row in (rows_without_imports if ignore_imports else rows))
for pid, rx, ignore_imports in compiled} for pid, rx, ignore_imports in compiled}
return {pid: n for pid, n in hits.items() if n} return {pid: n for pid, n in hits.items() if n}
+143
View File
@@ -0,0 +1,143 @@
"""Reading Rust source text for the gate: which lines are production code and which items exist only for tests."""
import re
_CFG_ATTRIBUTE = re.compile(r"#!?\[\s*cfg\s*\(")
_TOKEN = re.compile(r'[A-Za-z_][A-Za-z0-9_]*|"[^"]*"|[(),=]')
def requires_test(block):
"""True when an attribute (or a run of attributes) has a `#[cfg(...)]` that holds only under `cfg(test)`: `test`
itself or an `all(...)` with `test` among its terms. `any(test, feature = "x")` and `not(test)` hold in
production builds too, so they are not test-only."""
for found in _CFG_ATTRIBUTE.finditer(block):
tokens = _TOKEN.findall(block[found.end():])
flags, _ = _arguments(tokens, 0)
if flags and flags[0]:
return True
return False
def _predicate(tokens, pos):
"""(holds only under test, next position) for the cfg predicate that starts at tokens[pos]."""
name = tokens[pos]
pos += 1
following = tokens[pos] if pos < len(tokens) else ""
if following == "(":
flags, pos = _arguments(tokens, pos + 1)
if name == "all":
return any(flags), pos
return (name == "any" and bool(flags) and all(flags)), pos
if following == "=":
return False, pos + 2
return name == "test", pos
def _arguments(tokens, pos):
"""([test-only flag per argument], position after the closing parenthesis)."""
flags = []
while pos < len(tokens) and tokens[pos] != ")":
flag, pos = _predicate(tokens, pos)
flags.append(flag)
if pos < len(tokens) and tokens[pos] == ",":
pos += 1
return flags, pos + 1
def _unbalanced(text):
return text.count("[") > text.count("]") or text.count("(") > text.count(")")
def _attributes(lines, index):
"""(attribute text, index after the attribute lines) for the run of `#[...]` attributes that starts at `index`;
comment lines inside the run are passed over. ("", index) when `index` starts no attribute."""
parts = []
cursor = index
while cursor < len(lines):
stripped = lines[cursor].strip()
if stripped.startswith("#[") or stripped.startswith("#![") or (parts and _unbalanced(" ".join(parts))):
parts.append(stripped)
elif not (parts and stripped.startswith("//")):
break
cursor += 1
return " ".join(parts), (cursor if parts else index)
def _indent(line):
return len(line) - len(line.lstrip())
def _block_end(lines, opening, indent):
"""Index after the closing `}` at `indent` of the block that ends line `opening`; just after `opening` when no such
line exists (the body then stays visible to the counters instead of being hidden)."""
for index in range(opening + 1, len(lines)):
if _indent(lines[index]) == indent and lines[index].lstrip().startswith("}"):
return index + 1
return opening + 1
def item_end(lines, head, indent):
"""Index after the item whose first line is `head`: a `...;` item, a one-line `{}` item or a `{ ... }` block closed
at `indent`."""
for index in range(head, len(lines)):
text = lines[index].rstrip()
if text.endswith(";") or text.endswith("}"):
return index + 1
if text.endswith("{"):
return _block_end(lines, index, indent)
return head + 1
def production_lines(text):
"""The lines of a file that are not test code, comment lines dropped. An item under a test-only `#[cfg(...)]` (an
inline `mod x { ... }`, a `mod x;` declaration, a `fn`, a `use`) is skipped as a whole and the code after it counts
again; a file that starts with `#![cfg(test)]` has none."""
lines = text.splitlines()
kept = []
index = 0
while index < len(lines):
attributes, after = _attributes(lines, index)
if attributes and requires_test(attributes):
if lines[index].lstrip().startswith("#!["):
return []
index = item_end(lines, after, _indent(lines[index]))
continue
if not lines[index].lstrip().startswith("//"):
kept.append(lines[index])
index += 1
return kept
# the standard and common interior-mutable types: a `static` of one of them is process state
CELL_PRIMITIVES = (r"Atomic[A-Z]\w*", "Mutex", "RwLock", "Once", "OnceLock", "OnceCell", "LazyLock", "LazyCell", "Lazy",
"Cell", "RefCell", "UnsafeCell", "SyncUnsafeCell")
_TYPE_ITEM = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum|union|type)\s+(\w+)")
def type_definitions(text):
"""{type name: the text of its definition} for the struct, enum, union and type alias items of production code."""
rows = production_lines(text)
found = {}
for index, row in enumerate(rows):
declared = _TYPE_ITEM.match(row)
if declared:
body = "\n".join(rows[index:item_end(rows, index, _indent(row))])
found[declared.group(1)] = found.get(declared.group(1), "") + body
return found
def cell_holders(definitions):
"""Names of the types that hold interior-mutable state: one whose definition names a cell primitive or another
holder. `static X: Holder` is a process global just like `static X: Mutex<_>`; an instance field of the same type is
not. `definitions` is {type name: definition text}."""
holders = set()
while True:
word = re.compile(cell_alternation(holders))
added = {name for name, body in definitions.items() if name not in holders and word.search(body)}
if not added:
return holders
holders |= added
def cell_alternation(holders):
"""The regex group that `{cell_types}` in an architecture.json pattern stands for: a cell primitive or a holder."""
return r"\b(?:" + "|".join(list(CELL_PRIMITIVES) + sorted(map(re.escape, holders))) + r")\b"
+362 -244
View File
@@ -1,244 +1,362 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Negative and positive proofs for the architecture gate: each rule must fail on a synthetic violation. """Negative and positive proofs for the architecture gate: each rule must fail on a synthetic violation.
Usage: python3 scripts/check_architecture_test.py (no cargo, no network) Usage: python3 scripts/check_architecture_test.py (no cargo, no network)
""" """
import pathlib import json
import sys import pathlib
import tempfile import sys
import unittest import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from archcheck import baseline as bl # noqa: E402
from archcheck import measure, rules # noqa: E402 from archcheck import baseline as bl # noqa: E402
from archcheck import measure, rules # noqa: E402
CONFIG = {
"max_lines": 400, CONFIG = {
"adapter_layer": "L3", "max_lines": 400,
"pure_layers": ["L0", "L1"], "adapter_layer": "L3",
"forbidden_in_pure": ["tokio"], "pure_layers": ["L0", "L1"],
"layers": {"L0": ["api"], "L1": ["lib"], "L2": ["core"], "L3": ["adapter-a", "adapter-b"], "L4": ["host"]}, "forbidden_in_pure": ["tokio"],
"adapter_edges": [["adapter-b", "adapter-a"]], "layers": {"L0": ["api"], "L1": ["lib"], "L2": ["core"], "L3": ["adapter-a", "adapter-b"], "L4": ["host"]},
} "adapter_edges": [["adapter-b", "adapter-a"]],
EMPTY = {"violations": [], "oversize": {}, "source": {}} }
EMPTY = {"violations": [], "oversize": {}, "source": {}}
def pkg(name, normal=(), external=()):
return {"name": name, "dir": pathlib.Path(name), "normal": list(normal), "external": list(external)} def pkg(name, normal=(), external=()):
return {"name": name, "dir": pathlib.Path(name), "normal": list(normal), "external": list(external)}
def packages(**overrides):
base = { def packages(**overrides):
"api": pkg("api"), "lib": pkg("lib", ["api"]), "core": pkg("core", ["lib"]), base = {
"adapter-a": pkg("adapter-a", ["core"]), "adapter-b": pkg("adapter-b", ["core", "adapter-a"]), "api": pkg("api"), "lib": pkg("lib", ["api"]), "core": pkg("core", ["lib"]),
"host": pkg("host", ["adapter-a", "adapter-b", "core"]), "adapter-a": pkg("adapter-a", ["core"]), "adapter-b": pkg("adapter-b", ["core", "adapter-a"]),
} "host": pkg("host", ["adapter-a", "adapter-b", "core"]),
base.update(overrides) }
return list(base.values()) base.update(overrides)
return list(base.values())
def run(pkgs, baseline=None, sizes=None, counts=None):
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, rules.Measured(sizes or {}, counts or {})) def run(pkgs, baseline=None, sizes=None, counts=None):
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, rules.Measured(sizes or {}, counts or {}))
def base(violations=(), oversize=None, source=None):
return {"violations": list(violations), "oversize": oversize or {}, "source": source or {}} def base(violations=(), oversize=None, source=None):
return {"violations": list(violations), "oversize": oversize or {}, "source": source or {}}
class GraphRules(unittest.TestCase):
def test_clean_graph_passes(self): class GraphRules(unittest.TestCase):
found = run(packages()) def test_clean_graph_passes(self):
self.assertEqual((found.errors, found.debt, found.stale), ([], [], [])) found = run(packages())
self.assertEqual((found.errors, found.debt, found.stale), ([], [], []))
def test_upward_edge_fails(self):
found = run(packages(core=pkg("core", ["host"]))) def test_upward_edge_fails(self):
self.assertIn("layer-up core -> host", found.violations) found = run(packages(core=pkg("core", ["host"])))
self.assertEqual(len(found.errors), 1) self.assertIn("layer-up core -> host", found.violations)
self.assertEqual(len(found.errors), 1)
def test_core_may_not_depend_on_an_adapter(self):
found = run(packages(core=pkg("core", ["adapter-a"]))) def test_core_may_not_depend_on_an_adapter(self):
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in found.errors)) found = run(packages(core=pkg("core", ["adapter-a"])))
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in found.errors))
def test_sideways_adapter_edge_fails_unless_listed(self):
found = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])})) def test_sideways_adapter_edge_fails_unless_listed(self):
self.assertIn("adapter-sideways adapter-a -> adapter-b", found.violations) found = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])}))
self.assertEqual(run(packages()).errors, []) self.assertIn("adapter-sideways adapter-a -> adapter-b", found.violations)
self.assertEqual(run(packages()).errors, [])
def test_unassigned_package_fails(self):
found = run(packages(extra=pkg("extra"))) def test_unassigned_package_fails(self):
self.assertTrue(any("extra has no layer" in e for e in found.errors)) found = run(packages(extra=pkg("extra")))
self.assertTrue(any("extra has no layer" in e for e in found.errors))
def test_pure_crate_with_forbidden_dependency_fails_but_an_adapter_may_use_it(self):
found = run(packages(lib=pkg("lib", ["api"], ["tokio"]))) def test_pure_crate_with_forbidden_dependency_fails_but_an_adapter_may_use_it(self):
self.assertIn("forbidden-dep lib tokio", found.violations) found = run(packages(lib=pkg("lib", ["api"], ["tokio"])))
self.assertEqual(run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])})).errors, []) self.assertIn("forbidden-dep lib tokio", found.violations)
self.assertEqual(run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])})).errors, [])
def test_baselined_violation_is_debt_and_a_fixed_one_is_stale(self):
known = base(violations=["layer-up core -> host"]) def test_baselined_violation_is_debt_and_a_fixed_one_is_stale(self):
found = run(packages(core=pkg("core", ["host"])), known) known = base(violations=["layer-up core -> host"])
self.assertEqual((found.errors, found.debt), ([], ["layer-up core -> host"])) found = run(packages(core=pkg("core", ["host"])), known)
self.assertEqual(len(run(packages(), known).stale), 1) self.assertEqual((found.errors, found.debt), ([], ["layer-up core -> host"]))
self.assertEqual(len(run(packages(), known).stale), 1)
class SizeAndRatchetRules(unittest.TestCase):
def test_new_large_file_fails_and_a_file_at_the_limit_passes(self): class SizeAndRatchetRules(unittest.TestCase):
self.assertEqual(len(run(packages(), sizes={"big.rs": 401}).errors), 1) def test_new_large_file_fails_and_a_file_at_the_limit_passes(self):
self.assertEqual(run(packages(), sizes={"ok.rs": 400}).errors, []) self.assertEqual(len(run(packages(), sizes={"big.rs": 401}).errors), 1)
self.assertEqual(run(packages(), sizes={"ok.rs": 400}).errors, [])
def test_baselined_large_file_may_not_grow_and_shrinking_is_stale(self):
known = base(oversize={"big.rs": 900}) def test_baselined_large_file_may_not_grow_and_shrinking_is_stale(self):
self.assertEqual(run(packages(), known, {"big.rs": 900}).errors, []) known = base(oversize={"big.rs": 900})
self.assertEqual(len(run(packages(), known, {"big.rs": 901}).errors), 1) self.assertEqual(run(packages(), known, {"big.rs": 900}).errors, [])
self.assertEqual(len(run(packages(), known, {"big.rs": 700}).stale), 1) self.assertEqual(len(run(packages(), known, {"big.rs": 901}).errors), 1)
self.assertEqual(len(run(packages(), known, {"big.rs": 700}).stale), 1)
def test_ratchet_may_only_fall(self):
known = base(source={"env-read:host": 10}) def test_ratchet_may_only_fall(self):
self.assertEqual(run(packages(), known, counts={"env-read:host": 10}).errors, []) known = base(source={"env-read:host": 10})
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 11}).errors), 1) self.assertEqual(run(packages(), known, counts={"env-read:host": 10}).errors, [])
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 9}).stale), 1) self.assertEqual(len(run(packages(), known, counts={"env-read:host": 11}).errors), 1)
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 9}).stale), 1)
def test_new_ratchet_key_starts_at_zero(self):
self.assertEqual(len(run(packages(), counts={"env-read:host": 1}).errors), 1) def test_new_ratchet_key_starts_at_zero(self):
self.assertEqual(len(run(packages(), counts={"env-read:host": 1}).errors), 1)
class BaselineRewrite(unittest.TestCase):
def test_refuses_increase_and_accepts_decrease(self): class BaselineRewrite(unittest.TestCase):
old = base(oversize={"a.rs": 500}, source={"env-read:host": 3}) def test_refuses_increase_and_accepts_decrease(self):
higher = base(["layer-up a -> b"], {"a.rs": 501}, {"env-read:host": 4}) old = base(oversize={"a.rs": 500}, source={"env-read:host": 3})
self.assertEqual(len(bl.raised(old, higher)), 3) higher = base(["layer-up a -> b"], {"a.rs": 501}, {"env-read:host": 4})
self.assertEqual(bl.raised(old, base(oversize={"a.rs": 450}, source={"env-read:host": 2})), []) self.assertEqual(len(bl.raised(old, higher)), 3)
self.assertEqual(bl.raised(old, base(oversize={"a.rs": 450}, source={"env-read:host": 2})), [])
def test_code_that_moved_between_crates_keeps_its_total(self):
old = base(source={"env-read:host": 3}) def test_code_that_moved_between_crates_keeps_its_total(self):
self.assertEqual(bl.raised(old, base(source={"env-read:other": 3})), []) old = base(source={"env-read:host": 3})
self.assertEqual(bl.raised(old, base(source={"env-read:other": 3})), [])
def test_a_moved_file_is_accepted_but_a_new_large_one_is_not(self):
old = base(oversize={"src/a.rs": 500}) def test_a_moved_file_is_accepted_but_a_new_large_one_is_not(self):
self.assertEqual(bl.raised(old, base(oversize={"src/sub/a.rs": 500})), []) old = base(oversize={"src/a.rs": 500})
self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1) self.assertEqual(bl.raised(old, base(oversize={"src/sub/a.rs": 500})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1) self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1)
self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1)
def test_a_split_may_add_only_its_module_declaration(self):
old = base(oversize={"src/big.rs": 1000}) def test_a_split_may_add_only_its_module_declaration(self):
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 503, "src/big/tests.rs": 500})), []) old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 503, "src/big/tests.rs": 500})), [])
def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self):
old = base(oversize={"src/big.rs": 1000}) def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self):
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), []) old = base(oversize={"src/big.rs": 1000})
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1) self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1)
class MechanicalNames(unittest.TestCase):
"""A file named by a mechanical split (impl_*, *_fn, numbered) may not be new; the baselined ones only go.""" class MechanicalNames(unittest.TestCase):
"""A file named by a mechanical split (impl_*, *_fn, numbered) may not be new; the baselined ones only go."""
DOT = chr(92) + ".rs$"
SPEC = {"patterns": ["^impl_.*" + DOT, "_fn" + DOT, "_[0-9]+(_[0-9]+)*" + DOT], "allow": ["^q[0-9]_[0-9]" + DOT]} DOT = chr(92) + ".rs$"
SPEC = {"patterns": ["^impl_.*" + DOT, "_fn" + DOT, "_[0-9]+(_[0-9]+)*" + DOT], "allow": ["^q[0-9]_[0-9]" + DOT]}
def test_a_new_mechanical_name_is_an_error_and_a_baselined_one_is_debt(self):
known = dict(EMPTY, mechanical_names=["src/impl_old.rs"]) def test_a_new_mechanical_name_is_an_error_and_a_baselined_one_is_debt(self):
found = run(packages(), known).errors known = dict(EMPTY, mechanical_names=["src/impl_old.rs"])
self.assertEqual(found, []) found = run(packages(), known).errors
errors, _ = rules.mechanical_findings(["src/impl_old.rs", "src/impl_new.rs"], known) self.assertEqual(found, [])
self.assertEqual(len(errors), 1) errors, _ = rules.mechanical_findings(["src/impl_old.rs", "src/impl_new.rs"], known)
self.assertIn("src/impl_new.rs", errors[0]) self.assertEqual(len(errors), 1)
self.assertIn("src/impl_new.rs", errors[0])
def test_a_file_that_was_renamed_makes_its_baseline_entry_stale(self):
known = dict(EMPTY, mechanical_names=["src/impl_old.rs"]) def test_a_file_that_was_renamed_makes_its_baseline_entry_stale(self):
self.assertEqual(rules.mechanical_findings([], known)[0], []) known = dict(EMPTY, mechanical_names=["src/impl_old.rs"])
self.assertEqual(len(rules.mechanical_findings([], known)[1]), 1) self.assertEqual(rules.mechanical_findings([], known)[0], [])
self.assertEqual(len(rules.mechanical_findings([], known)[1]), 1)
def test_the_rewrite_may_not_add_a_mechanical_name(self):
old = dict(base(), mechanical_names=["a/impl_x.rs"]) def test_the_rewrite_may_not_add_a_mechanical_name(self):
self.assertEqual(bl.raised(old, dict(base(), mechanical_names=[])), []) old = dict(base(), mechanical_names=["a/impl_x.rs"])
self.assertEqual(len(bl.raised(old, dict(base(), mechanical_names=["a/impl_x.rs", "a/b_fn.rs"]))), 1) self.assertEqual(bl.raised(old, dict(base(), mechanical_names=[])), [])
self.assertEqual(len(bl.raised(old, dict(base(), mechanical_names=["a/impl_x.rs", "a/b_fn.rs"]))), 1)
def test_the_measurement_matches_the_patterns_and_honours_the_allow_list(self):
with tempfile.TemporaryDirectory() as tmp: def test_the_measurement_matches_the_patterns_and_honours_the_allow_list(self):
src = pathlib.Path(tmp) / "src" with tempfile.TemporaryDirectory() as tmp:
src.mkdir() src = pathlib.Path(tmp) / "src"
for name in ("impl_a.rs", "b_fn.rs", "c_2.rs", "d_2_3.rs", "q4_0.rs", "plain.rs", "tests.rs"): src.mkdir()
(src / name).write_text("") for name in ("impl_a.rs", "b_fn.rs", "c_2.rs", "d_2_3.rs", "q4_0.rs", "plain.rs", "tests.rs"):
package = dict(pkg("p"), dir=pathlib.Path(tmp)) (src / name).write_text("")
found = measure.mechanical_names(pathlib.Path(tmp), [package], self.SPEC) package = dict(pkg("p"), dir=pathlib.Path(tmp))
self.assertEqual(found, ["src/b_fn.rs", "src/c_2.rs", "src/d_2_3.rs", "src/impl_a.rs"]) found = measure.mechanical_names(pathlib.Path(tmp), [package], self.SPEC)
self.assertEqual(found, ["src/b_fn.rs", "src/c_2.rs", "src/d_2_3.rs", "src/impl_a.rs"])
class Measurement(unittest.TestCase):
def test_counter_stops_at_a_test_module_and_skips_comments(self): class Measurement(unittest.TestCase):
text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n' def test_an_inline_test_module_is_skipped_and_comments_are_dropped_but_the_code_after_it_counts(self):
self.assertEqual(measure.production_lines(text), ['let a = std::env::var("A");']) text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n'
self.assertEqual(measure.production_lines(text), ['let a = std::env::var("A");', 'let c = env::var("C");'])
def test_a_single_cfg_test_function_does_not_hide_the_code_after_it(self):
text = '#[cfg(test)]\nfn only_tests() {}\nlet a = env::var("A");\n' def test_a_cfg_test_function_is_skipped_as_a_whole_and_the_code_after_it_counts(self):
self.assertEqual(len(measure.production_lines(text)), 3) text = '#[cfg(test)]\nfn only_tests() {\n env::var("T");\n}\nlet a = env::var("A");\n'
self.assertEqual(measure.production_lines(text), ['let a = env::var("A");'])
def test_an_inline_module_under_another_test_cfg_is_skipped_but_the_code_after_it_counts(self):
text = ('let a = env::var("A");\n#[cfg(all(test, unix))]\nmod proof {\n let b = env::var("B");\n}\n' def test_code_after_a_cfg_test_module_declaration_and_after_an_inline_test_module_counts(self):
'#[cfg(not(test))]\nmod live {\n let c = env::var("C");\n}\nlet d = env::var("D");\n') text = ('let a = env::var("A");\n#[cfg(test)]\nmod tests;\nlet b = env::var("B");\n'
rows = measure.production_lines(text) '#[cfg(test)]\nmod inline {\n let t = env::var("T");\n}\nlet c = env::var("C");\n')
self.assertEqual([r for r in rows if "env::var" in r], [ kept = [row for row in measure.production_lines(text) if "env::var" in row]
'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");']) self.assertEqual(kept, ['let a = env::var("A");', 'let b = env::var("B");', 'let c = env::var("C");'])
def test_a_module_declared_inside_a_test_only_file_is_not_production_either(self): def test_an_indented_test_item_is_skipped_up_to_its_own_closing_brace(self):
with tempfile.TemporaryDirectory() as tmp: text = ('impl X {\n #[cfg(test)]\n fn probe() {\n env::var("T");\n }\n'
src = pathlib.Path(tmp) / "src" ' fn real() {\n env::var("R");\n }\n}\n')
(src / "proofs" / "top").mkdir(parents=True) kept = [row for row in measure.production_lines(text) if "env::var" in row]
(src / "lib.rs").write_text('let a = env::var("A");\n#[cfg(test)]\n#[path = "proofs/top.rs"]\nmod top;\n') self.assertEqual(kept, [' env::var("R");'])
top = '#[path = "nested.rs"]\nmod nested;\nmod sibling;\nlet b = env::var("B");\n'
(src / "proofs" / "top.rs").write_text(top) def test_a_test_only_cfg_needs_test_in_every_build_that_compiles_the_item(self):
(src / "proofs" / "nested.rs").write_text('let c = env::var("C");\n') self.assertTrue(measure.requires_test("#[cfg(test)]"))
(src / "proofs" / "top" / "sibling.rs").write_text('let d = env::var("D");\n') self.assertTrue(measure.requires_test('#[cfg(all(test, target_os = "linux"))]'))
package = dict(pkg("p"), dir=pathlib.Path(tmp)) self.assertTrue(measure.requires_test("#[cfg(all(\n unix,\n test\n))]"))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}]) self.assertFalse(measure.requires_test('#[cfg(any(test, feature = "testing"))]'))
self.assertEqual(counts, {"e:p": 1}) self.assertFalse(measure.requires_test("#[cfg(not(test))]"))
self.assertFalse(measure.requires_test("#[cfg(all(unix, not(test)))]"))
def test_counts_are_per_crate_and_skip_test_files(self): self.assertFalse(measure.requires_test("#[cfg_attr(test, derive(Debug))]"))
with tempfile.TemporaryDirectory() as tmp: self.assertFalse(measure.requires_test('#[cfg(feature = "test")]'))
src = pathlib.Path(tmp) / "src"
src.mkdir() def test_an_item_that_is_also_compiled_in_production_stays_visible(self):
(src / "lib.rs").write_text('let a = env::var("A");\n') text = '#[cfg(any(test, feature = "probe"))]\nfn probe() {\n env::var("P");\n}\n'
(src / "tests.rs").write_text('let b = env::var("B");\n') self.assertEqual(len(measure.production_lines(text)), 4)
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}]) def test_a_file_under_an_inner_cfg_test_attribute_has_no_production_lines(self):
self.assertEqual(counts, {"e:p": 1}) self.assertEqual(measure.production_lines('#![cfg(test)]\nlet a = env::var("A");\n'), [])
def test_modules_declared_under_a_test_cfg_are_not_production(self): def test_a_test_only_import_does_not_hide_the_item_after_it_from_an_import_blind_pattern(self):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src" src = pathlib.Path(tmp) / "src"
(src / "a" / "proofs").mkdir(parents=True) src.mkdir()
(src / "lib.rs").write_text('mod a;\nmod b;\nlet a = env::var("A");\n') (src / "lib.rs").write_text("#[cfg(test)]\nuse std::sync::OnceLock;\nstatic A: OnceLock<u8> = x;\n")
(src / "b.rs").write_text('let b = env::var("B");\n') package = dict(pkg("p"), dir=pathlib.Path(tmp))
(src / "a.rs").write_text( pattern = {"id": "g", "regex": r"\bOnceLock\b", "ignore_imports": True}
'let c = env::var("C");\n#[cfg(not(test))]\nmod live;\n' self.assertEqual(measure.count_patterns([package], [pattern]), {"g:p": 1})
'#[cfg(all(\n test,\n target_os = "linux"\n))]\n#[path = "a/proofs/x.rs"]\nmod proof;\n'
'#[cfg(test)]\nmod helper;\n') def test_an_inline_module_under_another_test_cfg_is_skipped_but_the_code_after_it_counts(self):
(src / "a" / "proofs" / "x.rs").write_text('let d = env::var("D");\n') text = ('let a = env::var("A");\n#[cfg(all(test, unix))]\nmod proof {\n let b = env::var("B");\n}\n'
(src / "a" / "helper.rs").write_text('let e = env::var("E");\n') '#[cfg(not(test))]\nmod live {\n let c = env::var("C");\n}\nlet d = env::var("D");\n')
(src / "a" / "live.rs").write_text('let f = env::var("F");\n') rows = measure.production_lines(text)
package = dict(pkg("p"), dir=pathlib.Path(tmp)) self.assertEqual([r for r in rows if "env::var" in r], [
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}]) 'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");'])
self.assertEqual(counts, {"e:p": 4})
def test_a_module_declared_inside_a_test_only_file_is_not_production_either(self):
def test_a_listed_exception_is_not_counted_and_an_unused_one_is_an_error(self): with tempfile.TemporaryDirectory() as tmp:
with tempfile.TemporaryDirectory() as tmp: src = pathlib.Path(tmp) / "src"
src = pathlib.Path(tmp) / "src" (src / "proofs" / "top").mkdir(parents=True)
src.mkdir() (src / "lib.rs").write_text('let a = env::var("A");\n#[cfg(test)]\n#[path = "proofs/top.rs"]\nmod top;\n')
(src / "lib.rs").write_text('let a = env::var("A");\nmod clock;\n') top = '#[path = "nested.rs"]\nmod nested;\nmod sibling;\nlet b = env::var("B");\n'
(src / "clock.rs").write_text('let b = env::var("B");\n') (src / "proofs" / "top.rs").write_text(top)
package = dict(pkg("p"), dir=pathlib.Path(tmp)) (src / "proofs" / "nested.rs").write_text('let c = env::var("C");\n')
patterns = [{"id": "e", "regex": r"env::var\("}] (src / "proofs" / "top" / "sibling.rs").write_text('let d = env::var("D");\n')
listed = {"crate": "p", "file": "src/clock.rs", "ratchet": "e", "reason": "the clock adapter"} package = dict(pkg("p"), dir=pathlib.Path(tmp))
excused = {} counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
counts = measure.count_patterns([package], patterns, [listed], excused) self.assertEqual(counts, {"e:p": 1})
self.assertEqual((counts, excused), ({"e:p": 1}, {("p", "src/clock.rs", "e"): 1}))
self.assertEqual(rules.exception_findings([listed], excused, {"e"}), []) def test_counts_are_per_crate_and_skip_test_files(self):
unused = dict(listed, file="src/lib.rs", ratchet="x") with tempfile.TemporaryDirectory() as tmp:
self.assertEqual(len(rules.exception_findings([unused, dict(listed, reason="")], excused, {"e"})), 2) src = pathlib.Path(tmp) / "src"
src.mkdir()
def test_a_test_module_declaration_with_a_path_attribute_is_not_production(self): (src / "lib.rs").write_text('let a = env::var("A");\n')
text = "\n".join(["#[cfg(test)]", '#[path = "../tests/x.rs"]', "mod tests;", "let a = 1;"]) + "\n" (src / "tests.rs").write_text('let b = env::var("B");\n')
self.assertEqual(measure.production_lines(text), ["let a = 1;"]) package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
if __name__ == "__main__": self.assertEqual(counts, {"e:p": 1})
unittest.main()
def test_modules_declared_under_a_test_cfg_are_not_production(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "a" / "proofs").mkdir(parents=True)
(src / "lib.rs").write_text('mod a;\nmod b;\nlet a = env::var("A");\n')
(src / "b.rs").write_text('let b = env::var("B");\n')
(src / "a.rs").write_text(
'let c = env::var("C");\n#[cfg(not(test))]\nmod live;\n'
'#[cfg(all(\n test,\n target_os = "linux"\n))]\n#[path = "a/proofs/x.rs"]\nmod proof;\n'
'#[cfg(test)]\nmod helper;\n')
(src / "a" / "proofs" / "x.rs").write_text('let d = env::var("D");\n')
(src / "a" / "helper.rs").write_text('let e = env::var("E");\n')
(src / "a" / "live.rs").write_text('let f = env::var("F");\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": 4})
def test_a_listed_exception_is_not_counted_and_an_unused_one_is_an_error(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text('let a = env::var("A");\nmod clock;\n')
(src / "clock.rs").write_text('let b = env::var("B");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
patterns = [{"id": "e", "regex": r"env::var\("}]
listed = {"crate": "p", "file": "src/clock.rs", "ratchet": "e", "reason": "the clock adapter"}
excused = {}
counts = measure.count_patterns([package], patterns, [listed], excused)
self.assertEqual((counts, excused), ({"e:p": 1}, {("p", "src/clock.rs", "e"): 1}))
self.assertEqual(rules.exception_findings([listed], excused, {"e"}), [])
unused = dict(listed, file="src/lib.rs", ratchet="x")
self.assertEqual(len(rules.exception_findings([unused, dict(listed, reason="")], excused, {"e"})), 2)
def test_a_test_module_declaration_with_a_path_attribute_is_not_production(self):
text = "\n".join(["#[cfg(test)]", '#[path = "../tests/x.rs"]', "mod tests;", "let a = 1;"]) + "\n"
self.assertEqual(measure.production_lines(text), ["let a = 1;"])
class ProcessGlobals(unittest.TestCase):
"""The `process-global` pattern of architecture.json: a static cell is a process global, not an instance field."""
@staticmethod
def pattern():
config = json.loads((pathlib.Path(__file__).resolve().parent.parent / "architecture.json").read_text("utf-8"))
return next(p for p in config["source_patterns"] if p["id"] == "process-global")
@classmethod
def count(cls, source):
pattern = cls.pattern()
with tempfile.TemporaryDirectory() as tmp:
(pathlib.Path(tmp) / "src").mkdir()
(pathlib.Path(tmp) / "src" / "lib.rs").write_text(source)
return measure.count_patterns([dict(pkg("p"), dir=pathlib.Path(tmp))], [pattern]).get("process-global:p", 0)
def test_statics_of_every_cell_type_count_also_inside_thread_local(self):
source = "\n".join([
"static A: AtomicU32 = AtomicU32::new(0);",
"static B: std::sync::Mutex<Vec<u8>> = Mutex::new(Vec::new());",
"pub(crate) static C: [AtomicUsize; 4] = [const { AtomicUsize::new(0) }; 4];",
"static D: std::sync::OnceLock<u8> = std::sync::OnceLock::new();",
"thread_local! {",
" static E: RefCell<Option<u8>> = const { RefCell::new(None) };",
" static F: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };",
"}",
"static mut G: u8 = 0;",
])
self.assertEqual(self.count(source), 7)
def test_immutable_statics_lifetimes_instance_fields_and_imports_do_not_count(self):
source = "\n".join([
"use std::sync::{OnceLock, atomic::AtomicU32};",
'static A: &[u8] = b"x";',
"static B: [Entry; 2] = [Entry(1), Entry(2)];",
"static C: [&'static str; 2] = [\"a\", \"b\"];",
"fn name(x: &'static str) -> &'static str { x }",
"struct Archive { handles: OnceLock<Vec<u8>>, hits: AtomicU32 }",
"fn build() -> Archive { Archive { handles: OnceLock::new(), hits: AtomicU32::new(0) } }",
])
self.assertEqual(self.count(source), 0)
def test_a_static_of_a_type_that_holds_a_cell_counts_through_any_number_of_wrappers(self):
source = "\n".join([
"pub struct EnvSwitch { cell: OnceLock<bool>, name: &'static str }",
"pub struct Setting<T> { switch: EnvSwitch, parse: fn(&str) -> T }",
"pub struct Plain { n: u32 }",
"static A: EnvSwitch = EnvSwitch::new(\"A\");",
"static B: Setting<usize> = Setting::new();",
"static C: Plain = Plain { n: 1 };",
])
self.assertEqual(self.count(source), 2)
def test_the_wrapper_type_is_found_in_another_file_of_the_crate_but_not_in_test_code(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text("mod cell;\nstatic A: Lazy2 = Lazy2::new();\nstatic B: Fake = Fake::new();\n")
fake_in_tests = "#[cfg(test)]\nstruct Fake { v: Cell<u8> }\n"
(src / "cell.rs").write_text("pub struct Lazy2 { v: Mutex<u8> }\n" + fake_in_tests)
counts = measure.count_patterns([dict(pkg("p"), dir=pathlib.Path(tmp))], [self.pattern()])
self.assertEqual(counts, {"process-global:p": 1})
def test_a_holder_counts_only_in_the_crates_that_can_name_it_and_a_local_type_shadows_a_dependency_one(self):
sources = {
"low": "pub struct Gate { v: Mutex<u8> }\npub struct Entry { v: Cell<u8> }\n",
"app": "static A: Gate = Gate::new();\nstruct Entry { n: u8 }\nstatic E: [Entry; 1] = [Entry { n: 1 }];\n",
"other": "static B: Gate = Gate::new();\n",
}
pattern = self.pattern()
with tempfile.TemporaryDirectory() as tmp:
packages = []
for name, text in sources.items():
(pathlib.Path(tmp) / name / "src").mkdir(parents=True)
(pathlib.Path(tmp) / name / "src" / "lib.rs").write_text(text)
packages.append(dict(pkg(name, ["low"] if name == "app" else []), dir=pathlib.Path(tmp) / name))
self.assertEqual(measure.count_patterns(packages, [pattern]), {"process-global:app": 1})
if __name__ == "__main__":
unittest.main()