Skip to content

Latest commit

 

History

History
135 lines (100 loc) · 31.4 KB

rust-quality.md

File metadata and controls

135 lines (100 loc) · 31.4 KB

Rust code quality strategy — the standard for review and refactoring

This document is the rule table that reviewers and refactoring rounds cite. Each rule has a number (R1…). A review report is written as path:line — R-number — one line — size. The sources are the official Rust guidance (API Guidelines, Rustonomicon, Unsafe Code Guidelines, clippy lint levels) and the incidents that actually happened in this repo. AGENTS.md Conventions holds the domain contract (correctness, measurement, comments). This document holds the shape of the code. If the two conflict, AGENTS.md wins.

0. Baseline

Instrument: grep -c '^warning:' of the just lint (--features gpu) output. It counts once per target, so it is higher than an agent's unique count. Measure before and after with the same instrument. Ratchet down only.

Instrument 2026-09-22 night (before review, 685462d) 2026-09-22 dawn (after review round 1, 0ff785e) 2026-09-22 evening (48ee5c2) 2026-09-22 night (after the night wave, 2d1abc0)
just lint warnings 308 (260 without the gpu feature; 09-21 morning 144) 221 211 (after gatesc, c69642b 210) 175 (gatesd 210 → tools6 210 → mechlint 189 → gatesc2 175 → gpucast 175)
undocumented_unsafe_blocks 123 63 — q3k-gemv 49, q3k-cpu 9 (stage 0 spike, share of MUL-10/11), model 4, gpu 1 (flash.rs) 62 — q3k-gemv 49, q3k-cpu 9, model 4, gpu 0 58 — q3k-gemv 49, q3k-cpu 9, model 0 (mechlint documented the four in tests/alloc.rs), gpu 0. The remaining 58 are all in stage 0 crates
too_many_arguments warnings (without allow) 12 17 (8/7 ×12, 9/7 ×2, 11/7 ×3) — target of the R8 round; every allow carries a reason (before the §0 re-measure; r8args removed the allows on the launchers and gate_p5 helpers) 16 (8/7 ×11, 9/7 ×2, 10/7 ×1, 11/7 ×2) 15 (8/7 ×10, 9/7 ×2, 10/7 ×1, 11/7 ×2)
chunks_exact constant → as_chunks 17 23 (R17 pass 2 — hot paths come with an A/B) 23 11 (chunks_exact 9 + _mut 2). What remains is four hot paths and runtime chunk sizes, which the lint does not catch
as casts in crates/gpu 637 not re-measured (before the R5 round) not re-measured 263 host narrowing sites became launch_u32, constant pairs and try_from (gpucast). The instrument for 637 was not run again — by gpucast's instrument, of 719 integer as casts in crates/gpu/src, 300 are host and 263 of those narrow
Largest files model.rs 3901, flash.rs 2628 flash.rs 3241 (a4d and a4e kernels), model.rs 3963 flash.rs 3397, qdot/lib.rs 2466 (after fnsplit, gpu/model.rs 1252) flash.rs 3443, qdot/lib.rs 2466, gpu/model.rs 1253

Review round 1 (3 agy rounds) and 4 refactoring rounds (opus: qtools, gatesdedup, cpumech, gpusafety, one axis each) undid the 116 that grew in one day and then lowered the count by 87 more. Review not finished: flash.rs, model.rs, gate_p5, gate_e2e (the 4 files deferred until after a4e), the GpuError enum (R9), the *Args structs (R8).

1. unsafe — smallest scope, invariants in types

  • R1 One operation per unsafe block. Directly above it, one or two lines of // SAFETY: for that operation's invariant (which index is in range, and why). An unsafe {} that wraps a whole function is forbidden. (The 123 undocumented_unsafe_blocks hits were this violation.)
  • R2 If the same invariant repeats in three or more places, make it a type — a view with proven bounds (a shape like StaticTileMut32 and InBounds32 in cuda-device view.rs), or one safe wrapper function. Writing an invariant in a comment ten times gives ten chances to get it wrong.
  • R3 An unsafe fn must have a # Safety section in its doc comment (missing_safety_doc = deny, already a contract). Write only what the caller must uphold.
  • R4 Raw pointer arithmetic belongs only inside kernels. If host orchestration (model.rs, lib.rs) touches *const/*mut, that is the wrong layer — move it down into a method of the buffer type.

2. Types carry the contract

  • R5 Numbers with different units have different types. Element count and byte count, rows and keys and dimensions, words and f16 pairs — if one usize names them all, an 8x over-reservation compiles (ik #2501: alloc takes an element count and was passed a byte count). When such a value crosses a function boundary in host code, use a newtype (Elems(usize), Bytes(usize), Rows, Keys), or at least put the unit in the name (n_elems, bytes). as casts inside a kernel body are allowed (register arithmetic). Narrowing as in host code (u64 as u32, usize as i32) goes through try_from; if the failure is impossible, write the reason in expect("...").
  • R6 Shape constants are const and const generics. Relations are fixed at compile time with const { assert!(...) } (KEY_TILE == 32, smem stride ≡ 16 (mod 128), MMA_KEYS == MMA_WARPS * MMA_NTILE). A runtime assert! is only for values known only at runtime (the cache length).
  • R7 A function whose result must not be dropped gets #[must_use] (launch builders, band computation, segments_for). A method that changes state takes &mut self. Interior mutability (Cell/RefCell/OnceLock) is only for levers (reading an env var once) and caches, with the reason in one line.
  • R8 A function with more than 8 arguments takes a parameter struct (12 too_many_arguments hits). A kernel launcher takes one LaunchArgs-style struct plus a stream. Field names carry the unit (R5).

3. Errors — enums for libraries, anything for binaries

  • R9 The public functions of the library crates (gguf, model, gpu, qdot, threads) return that crate's error enum (LoadError, ModelError, GpuError…). Box<dyn Error> and String errors are only for binaries (gpu-gates/src/bin/*, q3k-*).
  • R10 unwrap() and expect() appear only in gates, tests and main. Library crates have 0. The one exception is a place "where the type cannot prove the failure is impossible", and it must take the form expect("why this cannot fail").
  • R11 Split error variants only as far as callers handle them differently. Each variant carries context a person can read (which tensor, which kernel). A variant that passes a driver error code up unchanged gets our own context added.

4. Functions, modules, duplication

  • R12 An orchestration function fits in two screens (AGENTS). A kernel body is not split (#[target_feature], #[kernel] — a measured 10–13 % loss). The constants and index arithmetic of a kernel may be moved out into const fn helpers (they inline and the SASS is the same — if you move them, show the sameness with ptx-scan).
  • R13 Default visibility is pub(crate). pub only for what another crate actually calls. A public item gets one doc sentence (what it takes and what it returns).
  • R14 The moment a second copy appears, extract a common core (a const generic, or an #[inline(always)] core plus a thin entry — kprobe's seg_pass::<TWICE> has that shape). A third copy is forbidden. The current flash_latent/_q8/_seg trio and a4c's head_groups with a4d's mma_groups violate this.
  • R15 One file, one subject. The 3901 lines of model.rs mix step orchestration, scratch ownership, probes and the seed cache — the axis for splitting is "who owns it" (buffer ownership = residency, launch order = step, instrumentation = probe).

5. clippy — levels and the ratchet

  • R16 Three lint levels: deny (only for lints with 0 hits — unsafe_op_in_unsafe_fn, missing_safety_doc), warn (the ones being driven down toward 0), and allow with a reason — always as #[allow(clippy::x, reason = "…")] per item; a crate-wide allow is forbidden. The total warning count is compared with the baseline in AGENTS.md Known state: if it goes up, that round is red.
  • R17 Close what can be closed mechanically in one round, together (chunks_exact constant → as_chunks, is_multiple_of, len() < 1, blank lines, doc indentation — 50 hits). That commit carries a bit-identical gate plus a same-lease A/B (R20).
  • R18 Run cargo fmt on the Mac, always before a commit. just deny (the dependency pins) is a merge gate.

6. Device code (cuda-oxide kernels)

  • R19 A kernel is #![no_std], with no allocation and no panic. For index checks, use an access with proven bounds (R2) or a get_unchecked that carries SAFETY, not debug_assert!. Shared-memory layout (stride, padding, alignment) is const plus const { assert! } (R6), and bank conflicts are counted at compile time with cuda-device swizzle::conflict_degree. Declare the block shape in #[launch_contract] (including dynamic smem — above 48 KB, declare it as dynamic_shared and the launch enables it by itself), and do not duplicate it with a runtime check in the launcher.
  • What the toolchain cannot do (#[unroll] failures, a missing intrinsic) gets one line in docs/upstream/nvlabs-ledger.md before any workaround (AGENTS). Say "it does not exist" only after looking in both the cuda-oxide tree and the host crates (cuda-core, cuda-bindings).

7. Conditions for refactoring

  • R20 A refactoring commit proves unchanged behavior with gates: identical tokens (gate-gpu-e2e 648 nodes, gate-gpu-p8), unchanged bands (gate-gpu-p5), unchanged PTX shape (ptx-scan: depot 0, same registers, same smem). It also proves unchanged speed with a same-lease A/B (±1 % ruler — bit-identical does not mean speed-identical, AGENTS). A refactoring commit missing either one is not merged.
  • R21 One round, one axis. Do not mix an unsafe comment round, a parameter struct round and a deduplication round — the diff stays readable, and if a regression appears it is attributed to one axis.
  • R22 Do not put a refactoring in the same commit as a behavior change (the code version of the incident that mixed the look core into a UI commit). If a kernel performance round wants to fix names on the way, that is a separate commit.

7′. Exceptions and added rules confirmed in review round 1 (2026-09-22, three agy rounds)

Only what the reviewers proposed and the lead checked against the source and accepted. What was rejected comes at the end, with the reason.

  • R1 addendum — A contiguous vector load in a kernel (a bundle of 4 or 8 words of get_unchecked) needs one SAFETY per bundle: one line that proves the chunk bound (base + 8 <= len). Collective access to a shared-memory array (SharedArray) uses the standard phrase — // SAFETY: block-shared, N == blockDim.x, written before the barrier that publishes it. "as above", "as in X" and "cuda-oxide shared array access" are not SAFETY (12 places).
  • R8 addendum — #[kernel] entries are exempt from the argument limit (the device ABI takes the arguments as they are). Host enqueue_* launchers are not exempt — each takes one *Args struct and spreads it into the kernel launch.
  • R12 addendum — A #[kernel] body gets the same exemption as a #[target_feature] body (the measured basis is in AGENTS). The main of a gate binary is a linear pipeline, so it is not held to 120 lines; it is only required to be split by logical stage (load / eager / graph / timing).
  • R9 exception — lib.rs of gpu-gates (the gate helper library) keeps Box<dyn Error>: all its consumers are gate binaries, and a failure means exit. GpuError = Box<dyn Error> in crates/gpu is not an exception — it is an R9 violation and a target for a round. → Closed on 2026-09-22 by gpuerr (960bde5, 9 variants, hand-written impl). thiserror is a workspace dependency (gguf, model, qdot), so using it is not a new dependency — choosing the hand-written impl was a judgment in that round's spec and is not a rule.
  • R10 exception — Recovering a poisoned lock (lock().unwrap_or_else(|e| e.into_inner())) is not an unwrap. A launch().unwrap() inside a bench loop is in a binary, so R10 does not apply.
  • R23 (new) — Compare and sort floats with total_cmp. partial_cmp().unwrap() panics on NaN, and NaN is a value for the gate to catch, not a reason to panic.
  • R24 (new) — let x = e.unwrap() else { … } is dead code (the unwrap panics first). Use ok_or_else(..)? or match. An ok: &mut bool accumulator argument in a check helper is the same kind — return a bool or a Result.
  • R25 (new) — Declare a graph handle before the buffers whose addresses it captured (fields drop in declaration order). Head, GpuModel and Stage already follow this order; a new struct uses the same order plus a one-line comment.
  • R26 (new) — A binary whose body hides behind a feature is linted with that feature on. just lint and just check use --features gpu. The runners (depth-gpu.sh, ncu-gpu.sh, nsys-gpu.sh) build the binary or print the build hash in the witness — measuring a binary that was not built is the shape of the stale binary incident (on the night of 2026-09-22 the ik_ref column printed an old value that way).
  • R27 (new) — #[doc(hidden)] pub that exists only so an integration test can call an internal function is forbidden. Use an inline unit test, or the output that a gate observes.
  • R28 (new, 2026-09-23) — A function that relies on a bound the caller keeps is an unsafe fn. A function whose body uses get_unchecked and writes "callers keep …" as its contract may stay a pub(crate) safe function inside the crate, but the moment it is opened outside the crate it becomes a pub unsafe fn with a /// # Safety section. The call site vouches for that bound with unsafe { } and a one-line // SAFETY:. The proof is an identical ptx-scan table (the move class). In the B4 wave, q3k_sb_decode (b4hc) and two lane bodies (b4moe) were opened as safe pub fn and then reverted. cores::q3k_row_dot, which was pub from the start, is the same kind.
  • R29 (new, 2026-09-23) — Device arithmetic whose sum order is a contract writes the contraction into the source. cuda-oxide fuses a*b + c into one FMA, like nvcc's --fmad=true (docs/upstream/nvlabs-ledger.md line 17). So a host rule that writes the same expression as * and + and a kernel round differently — in b4hc's first run, 319 of 320 places differed in bits. Write mul_add or fma where the ops should fuse, and mul_rn_f32 or add_rn_f32 where they should round separately. The proof is the fma column of ptx-scan. For a core whose doc says "plain multiplies" or "no fused multiply-add" but whose PTX is FMA, fix the doc to match the PTX (the weighted_sum and moe_combine bodies in elem.rs — b4moe report).

At an asynchronous device boundary, state the writer invariant rather than infer it from buffer length. The head-256 partial append requires distinct cache-valid positions; repeated out-of-range sentinels fault without appending. Its generic KV and selecting-attention wrappers carry that obligation too. An embedding producer can justify a caller's sequence-local positions; different slots may repeat the same numerical positions only because their launches use separate cache planes.

Rejected: ① Extracting a common core from the flash_row_scalar/flash_row_avx2 twins (the cpu review's priority 1) — this collides head-on with the ban on splitting a #[target_feature] body (AGENTS, measured 10–13 %). The twin is the intended shape, and the TWIN comment is the contract. What remains is to move the softmax scan arithmetic outside the twins into an #[inline(always)] core, showing identical SASS and A/B — a separate round, not now. ② The head.rs drop order defect — the graph already comes first (a false positive; accepted only as rule R25). ③ The reviewer's claim that "cuda-oxide cannot take struct arguments" is unconfirmed, so it was not used as a basis for the R8 addendum (the ABI reason is enough).

7″. Review round 2 (2026-09-22, agy — flash.rs, model.rs, gate_p5, gate_e2e, the four deferred until after the kernel rounds)

About 90 violations in 8,814 lines. Dispositions only for what was confirmed against the source.

  • Accepted → rounds ① R8 *Args — 12 launchers (flash.rs enqueue_flash_* 9 plus check_flash, model.rs enqueue_*_gemv_heads* 3) and 4 gate_p5 helpers. The reviewer's top 5 (starting with enqueue_flash_latent_split at 13 arguments) set the order. → Closed on 2026-09-22 by r8args (f9c7b9a, 17 sites, shared FlashGeom and FlashInputs; ptx-scan p5 and p8 identical in 52 rows, lint 221→219 — most targets were hidden behind allows; A6000 eager step p50 median b0f52a4 4.741 / main 4.772 / r8args 4.778 ms, rotated over 3 rounds, within-arm scatter ±1.5 %, so read as no difference — rows with a 3090 gate running during the witness are mixed in). The inner context structs of enqueue_chain/layer/attn/ffn_moe (the ChainCtx kind) are not the same axis (the dispatch path — comes with an A/B) → separate. ② R1 scope — 2 unsafe { if live { … } } sites in flash_latent_mma (905, 967), the 28 lines that wrap the warp reduction (1052–1081), and 8 // SAFETY: as in … sites (1272, 1340, 1408, 1476, 1634, 1724, 1744, 1746) — what is left from gpusafety, which excluded flash.rs. ③ R6 const assert — bank-avoidance invariants such as MMA_QSTRIDE*2 ≡ 16 (mod 128) and MMA_KSTRIDE, plus MMA_KEYS == MMA_QK_WARPS*MMA_NTILE, MMA_WIDTH % (2*MMA_K), LATENT % KEY_TILE — as const _: () = assert!, not prose. An identical ptx-scan is the proof. ④ R12: enqueue_attn at 510 lines, enqueue_ffn_moe at 257 lines, LayerScratch::new at 167 lines, and the R15 split of model.rs (step_kernels.rs plus model/{residency,dispatch,profile}.rs) — take the reviewer's 5-way split as the skeleton, but separate the round that only moves files from the round that splits functions (R21). Both carry all of R20 (e2e 648 nodes, p8, identical ptx-scan, A/B). ⑤ R10 model.rs:1795 residency.as_ref().unwrap() — confirmed; goes into the gpu comment round after gpuerr. ⑥ R24 6 ok: &mut bool sites in gate_p5 — already a rule in 7′, a target for a round. ⑦ R13 visibility, such as mla_width (a re-export only, 0 calls) — but the reviewer's claim that "20 MMA_* have 0 references outside flash.rs" is unconfirmed (gate_p5 uses flash constants): the compiler decides — a mechanical round that lowers them to pub(crate) and reverts only what breaks. ⑧ R5 casts — about 20 host narrowing casts such as q_rows as u32 — u32::try_from(..).expect(..) is right for grid arguments (the kind of the user-reported 8x incident). Group them into one axis as a mechanical round, with an identical ptx-scan.
  • Rejected ① gate_e2e.rs:538·544 "consecutive duplicate calls" of device_step_params() — a false positive: between them are a reset() and a different step(), and the two values are what is compared between the seeded and decoded states. ② flash.rs R12 flash_latent_mma at 354 lines and latent_range at 345 lines — #[kernel] exemption (7′). ③ R5 "newtypes for m, latent, segs" — pushing newtypes to the kernel ABI boundary means unwrapping them in #[kernel] arguments, with no gain; the field names of the host-side *Args structs carry that unit (absorbed into ①).
  • e2e divergence pin — Outside the review but in the same file: a round (e2epin) opened on the same day as this review to move the diverged ≤ 3 pin on the first difference of free generation (33 samples) to the teacher-forced position distribution (1056 positions, count of ik margin ≥ 0.5 disagreements). It is a gate rewrite, so the completion conditions are PIN, FAIL-first and scalar calibration.

8. Review procedure

  1. A reviewer (an investigation round) reads one crate at a time and reports violations as path:line — R-number — one line — size (XS/S/M/L). The reviewer does not assign severity — the rule number is the classification. The reviewer does not fix code.
  2. The lead disposes of each item as one of three: this round / tracker / rejected with a reason (that reason rises into a rule exception in this document or becomes an allow(reason)).
  3. A refactoring round (implementation) takes one axis (R21), a file whitelist, and the gates and A/B of R20 as its completion conditions.
  4. When a round ends, re-measure the §0 table and update this document. If the table moves in the rising direction, that round is the cause.

9. Google's Rust style guide (published 2026-10-21)

The guide is https://google.github.io/styleguide/rustguide.html. Rules tagged [chrome] or [Fuchsia] are out of scope. Where the guide and this file or AGENTS.md disagree, the clause named below stays. Performance-first and §6 win over a style preference. The rules below are this project's reading of the guide; a lint is adopted as deny only at 0 spans in the workspace. The 0-span lints are deny in [workspace.lints.clippy]. Seven lints still have spans in crates/metal, crates/hf, crates/model-hf, crates/serve, crates/jinja, crates/tokenizer, and crates/embed. Those seven are not in the table: a workspace warn would raise the ^warning: count, and deny would fail just lint. Each becomes deny when its spans reach 0. ubatch_rule.rs stays beside the bins: the qwen3 seat's place, the decide seat, and the Qwen3.8 seat each include it, and #[allow(clippy::duplicate_mod)] is on those three modules. The function reads one model's lever, so it is not a lib item.

The §0 ratchet is the one number in tools/lint-ratchet.txt (the ^warning: lines of just lint, one per target). mac-check.sh reads exactly one bare number. A workspace warn for a lint that still has spans would raise that number, so the seven lints above stay out of the table. Each # 적중 N only goes down. A deny is a lint with 0 spans in the whole workspace.

  • R30 A glob import is one of three forms: use super::* in a child module, use std::arch::x86_64::* inside a #[target_feature] body (AGENTS: that body is not split into helpers), or a pub use …::* re-export. An enum-variant glob (use TapKind::*, Rule::*) stays in the function that matches that enum. clippy::wildcard_imports is 132 spans (118 use super::*, 13 use std::arch::x86_64::*, 1 use names::* in crates/model/src/arch/gemma_encoder.rs). clippy::enum_glob_use is 8 spans, all variant globs. Neither lint is adopted: each forbids a form this rule keeps. The check is a grep for use …::* outside those forms. A false positive is the same text inside a string, or a pub use broken across lines.
  • R31 One use path per statement, which is rustfmt imports_granularity = "Module". There is no rustfmt.toml. rustfmt 1.10.0-stable defaults are max_width = 100 (the guide's width), imports_granularity = "Preserve", hex_literal_case = "Preserve", format_macro_matchers = false. The width already matches. The hex and macro settings stay: the guide allows a codebase to skip them. The granularity change is a fmt round (R18), not part of this diff.
  • R32 A host signature borrows the data: &str, &[T], &Path, &T, rather than &String, &Vec<T>, &PathBuf, &Box<T>. Kernels and #[target_feature] bodies are exempt (R4, the R8 addendum, R19). ptr_arg and borrowed_box are deny, 0 spans.
  • R33 A bool parameter whose meaning is not obvious at the call is an enum. Sibling of R8, which counts arguments. fn_params_excessive_bools is deny, 0 spans.
  • R34 assert!, assert_eq!, and assert_ne! carry a message that says why the invariant holds. A restatement of the condition is not that message. missing_assert_message is warn, 688 spans (630 under src/, heaviest in crates/gpu/src/flash_gqa.rs). A kernel still does not panic (R19); a debug_assert there that the lint flags takes #[allow(clippy::missing_assert_message, reason = "…")] on that item (R16).
  • R35 R13's one sentence on a public item is the lint missing_docs (warn, 5731 spans, 5724 under src/). The guide's leave-out for a trivial comment does not apply: R13 already requires the sentence, and a pure restatement of the name is an allow with a reason on that item. A public function that can panic has a # Panics section (missing_panics_doc, warn, 187 spans, all under src/). missing_safety_doc stays the R3 deny. A // TODO that carries a bug number stays forbidden (AGENTS.md comments, tools/check-comments.sh).
  • R36 R7, plus the lint. must_use_candidate is warn, 820 spans (813 under src/; name tables such as crates/model/src/arch/deepseek41/names.rs are the dense files). A function whose type is already #[must_use] does not get a second attribute (double_must_use, deny, 0). A method that returns Self and builds a value is #[must_use] (return_self_not_must_use, deny, 0). CallAcc::scaled in crates/model/src/profile.rs carries the attribute. A type that exists to be consumed (a builder, an error newtype that is not Result) gets #[must_use] on the type. That half is review: no lint in this toolchain names a missing type attribute.
  • R37 A check-then-unwrap is if let, let/else, or ?. Extends R24. unnecessary_unwrap is deny, 0. get_unwrap is deny, 0 (crates/gguf/tests/oracle.rs indexes the map). manual_let_else is deny, 0. needless_for_each is deny, 0. A long combinator that mutates outer state, or a chain written in a for header, is review. A short any / all / map stays. unwrap_used is not a workspace lint. On this clippy it flags .unwrap() and .unwrap_err() and does not flag expect, so R10's expect("why this cannot fail") stays legal. It is 5427 spans (3688 under src/, 267 under bin/, 1472 under tests/; an inline mod tests counts as src/). Tests, gates, and main may unwrap (R10), and R16 forbids a crate-wide allow, so a workspace warn has no legal suppression short of an allow on every site.
  • R38 A manual impl that the derive expresses is a derive, and a method that is a standard trait implements the trait. Deny, 0 spans: should_implement_trait, new_without_default, wrong_self_convention (as_ / to_ / into_ take the receiver the name claims), len_without_is_empty, derivable_impls (on this clippy: a manual Default identical to the derive, not every trait), new_ret_no_self, clone_on_copy, iter_overeager_cloned. cloned_instead_of_copied is deny, 0 (crates/gpu/src/arch/deepseek2/taps.rs uses copied). default_trait_access is deny, 0. Write Type::default(), including in a struct update. The guide's example spells Default::default(); Type::default() still updates the struct. implicit_clone is deny, 0 (to_vec where clone is the same call). An options struct with public fields implements Default. A From that is a primary constructor has an inherent from_foo / try_new beside it. Both of those are review. Getter names (foo, foo_mut, set_foo, take_foo, with_foo, replace_foo) are review. try_new for a fallible constructor is review.
  • R39 redundant_clone is deny, 0 (a clone of an owned value that is then dropped). A clone that is used is review, which is the rest of "prefer a borrow". string_add is deny, 0. Outside a kernel or a step its fix is one format! expression. A kernel or a step does not allocate (R19, AGENTS performance first), so there the form is push_str (a one-character literal is push) into a buffer it already owns. string_add_assign (the form x = x + y) is deny, 0. rc_buffer is deny, 0: probe_nvread's rig holds Arc<[SplitTable]> and Arc<[Arc<DirectFile>]>. Arc itself stays. A grep of crates/ is 922 Arc< and 29 Rc<: shared ownership across the pool and a session is the case the guide allows when unique ownership would be the harder structure.
  • R40 An in-tree public enum or struct stays exhaustive. A grep finds 0 #[non_exhaustive] under crates/. A new variant breaks the match (AGENTS.md: undefined input is a named error, never a defined output). exhaustive_enums (487) and exhaustive_structs (1120) are not adopted. wildcard_enum_match_arm is warn, 648 spans, and match_wildcard_for_single_variants is deny, 0: a _ that could name a variant we have. A foreign #[non_exhaustive] enum lists the variants it handles and ends with _.
  • R41 Three host rules, each a grep, each with a false positive named. A poisoned mutex in the worker pool recovers with unwrap_or_else(|e| e.into_inner()) (R10's exception; a grep of that pattern is 76). The guide's ban on reaching into a poisoned mutex does not apply to that recovery. catch_unwind stays in the pool, where a worker panic is reported on the caller, and in tests that must observe a panic (85 lines under crates/). A new catch_unwind outside those is a review item. The grep's false positive is a cfg(test) module inside src/ and the pool's own lines. Nothing runs before main. Levers are parsed by bloomery_levers::at_main inside main (AGENTS runtime levers). A grep of ctor::, #[ctor], inventory::submit, and linkme:: under crates/ is 0. The false positive is the word in a comment. No #![feature] in crates/ (grep 0). RUSTC_BOOTSTRAP stays: the cuda-oxide pin's cuda-device, cuda-host, and cuda-macros need those gates (AGENTS toolchain pins). The false positive is the attribute quoted in a string. labs/hip-native is outside the workspace and is not this grep.
  • R42 A domain name that the code already uses as a word stays a word: KV, GGUF, PTX, FFN, SM, and the rest of that set. R15's "one file, one subject" stays; a leaf file is not required to be the type's snake name (model.rs, flash.rs). A non-leaf lib.rs may hold the crate's implementation. An extension trait, if one is added, ends in Ext. A grep of trait …Ext under crates/ is 0.

Guide clauses that stay as they are, with the clause that wins:

  • Unsafe in its own crate, and a file-level justification in place of a SAFETY line: R1 (one operation, one SAFETY on that operation) and AGENTS "common code first". undocumented_unsafe_blocks is already deny.
  • Qualify every free function, and import traits inside the function: a kernel and a #[target_feature] body use the short name (R12, AGENTS). Module-level use is the file's dependency list. Review.
  • Return an iterator, or take impl IntoIterator, on a step or a launch: the step writes Tensor2::scratch and does no load-time allocation (AGENTS), and a generic launch monomorphizes (performance first, §6). A host helper that only walks a sequence may return an iterator. Review.
  • impl Into<T> on a hot or device-facing signature: code size (performance first). The guide's own note that application code almost never takes Into is the bin side, and it matches R9's split. Review.
  • Make error types Copy: R11, the variant carries a context a person can read, which is often a String. Floats compare with total_cmp (R23), so they do not gain Eq.
  • #[non_exhaustive] on our public enums and structs: R40.
  • format! as the default concatenation, inside a kernel or a step: R39 (push_str / write! into an owned buffer).
  • A closure accessor around the pool's mutex: the condvar wait in crates/threads/src/lib.rs holds the guard across the wait. Review for a mutex that only scopes a closure.
  • A test framework other than #[test]: the gates are hw_-prefixed #[ignore] tests run by the just gate-* recipes (AGENTS).
  • The guide's [chrome] and [Fuchsia] rules (small crates, flat rust_library layout, chromium::import!, no async, no std threads, fuchsia_sync::Mutex) are not rules here.