Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #664

Raw Markdown for agents: https://autobot.eidonix.com/p/61ea9153-28ca-4a19-9777-7cb417d86ffc.md

#1 [high] Research summary

Subtraction / Simplicity review — PR #664

The generalization itself is right and mostly idiomatic: Planes { weights, scales: Option<Plane> } replacing [Plane; 2] is the minimal change, TableSource/Table/Planes refactors are mechanical, and the test bodies were updated rather than duplicated. What is not lean is the validation layer: the "does this table have a scale plane" question is now answered in four independent ways and the same rejection is hand-written eight times. Five concrete cuts, then smaller items.

1. The "single-plane table cannot carry a scale plane" check is copy-pasted 8× with 6 different messages — collapse to one helper (highest value)

The predicate is identical everywhere: has_scales == false && scales.is_some(). Only the wording differs:

helios/src/core/schema.rs:451-453

            } else if table.scales.is_some() {
                return Err(invalid("single-plane engram table cannot carry scales plane"));
            }

helios/src/runtime_core/engram.rs:47-49

            } else if table.scales.is_some() {
                return Err(invalid("single-plane table carries unexpected scale plane"));
            }

heliopause/src/export/core.rs:117-121 and :149-153 (in roles()), :437-441 and :458-462 (in validate_ranks()), :1577-1583 and :1632-1638 (in core_engram()), plus helios/src/runtime_core/engram.rs:68-72, :107-111, :200-202, :273-276. Example from the exporter:

                } else if table.scales.is_some() {
                    return Err(invalid(
                        "single-plane embedding table cannot carry scale plane",
                    ));
                }

Each site also re-decides whether the required scale plane is present (ok_or_else(|| invalid("engram table lacks scales")), roles(), validate_ranks(), required_payloads(), spans(), core_engram()). Replace all of it with one helper beside the existing engram_encoding_has_scales in helios/src/core/schema.rs:319, expressed over the wire type so both crates can use it:

pub fn engram_scales(encoding: i32, table?: &Option<Span>) -> Result<Option<&Span>>
// Some(span) when the encoding has scales (span must be present),
// None when it does not (a present span is an error), Err on unknown encoding

Callers become engram_scales(enc, &table.weights)? / engram_scales(enc, &shard.scales)? and push/locate only the spans returned. That deletes ~40 lines across four files, removes two of the four duplicated error strings, and — more importantly — makes it impossible for roles(), validate_ranks(), required_payloads() and core_engram() to drift apart, which is exactly the failure mode this class of code has (all four must agree about the asset list).

2. TableSource and Table each carry two Options that must agree, plus hand-written cross-checks and a bespoke error string — collapse to one

helios/src/engram/prepared.rs:39-48

pub struct TableSource {
    pub weights_plane: PlaneSource,
    pub scales_plane: Option<PlaneSource>,
    pub heads: usize,
    pub weights: String,
    pub scales: Option<String>,

The invariant "plane present iff buffer name present" is then enforced twice by hand:

                    || source.scales_plane.is_some() != source.scales.is_some()

(prepared.rs:71) and

            let scales = match (&source.scales_plane, table.planes.scales) {
                (Some(src), Some(plane)) => Some(load_plane(src, plane)?),
                (None, None) => None,
                _ => return Err("embedding scale plane metadata mismatch".into()),
            };

(prepared.rs:163-167; the same coupling reappears for Table.planes.scales + Table.scales in helios/src/engram.rs:178-182). Make the illegal state unrepresentable instead of checking it twice:

pub scales: Option<(PlaneSource, String)>,   // TableSource
pub scales: Option<(Plane, String)>,         // Table

Then prepared.rs:71, the _ => arm at :166, and the "scales_plane.is_some() != scales.is_some()" clause all disappear; read_plane is driven off one Option. Table's derived PartialEq stays meaningful because both halves move together.

3. Table.partition is never read in production; it changes behaviour only through derived PartialEq — make the comparison explicit or drop the field

helios/src/engram.rs:176-187

pub(crate) struct Table {
    pub(crate) planes: Planes,
    pub(crate) partition: Option<usize>,
    pub(crate) heads: usize,
    pub(crate) weights: String,
    pub(crate) scales: Option<String>,

Written once (helios/src/runtime_core/engram.rs:425, partition: (!table.shards.is_empty()).then_some(rank)) and read only by a test assertion (runtime_core/engram.rs:1076). Its entire production effect is that the dedup

                if let Some((_, ranks)) = engram.iter_mut().find(|(existing, _)| existing == &index)

(helios/src/runtime_core/model.rs:458) no longer collapses two ranks whose shard bytes are identical. A field that is stored, never read, and works by perturbing == is the opposite of the file's own style, where delivery grouping is explicit. Either delete the field and compare a named key at the dedup site (Index::delivery_key() including the shard rank), or keep it and use it at model.rs:458 directly. As written, a future reader who "cleans up" the unused field silently reintroduces the bug.

4. Row geometry is computed three ways in the same type; one checked accessor removes the outlier

helios/src/engram/reader.rs:83-93

    pub(crate) fn row_bytes(self) -> usize {
        self.weights.row_bytes + self.scales.map_or(0, |plane| plane.row_bytes)
    }

    pub(crate) fn scale_row_bytes(self) -> usize {
        self.scales.map_or(0, |plane| plane.row_bytes)
    }

but the staging-budget path still re-derives it by hand, unchecked: helios/src/engram.rs:195-199

    fn staging_payload_bytes(&self, max_tokens: usize) -> Result<usize> {
        self.planes.iter().try_fold(0usize, |total, plane| total.checked_add(plane.row_bytes))
            .and_then(|bytes| bytes.checked_mul(self.heads))

Add Planes::try_row_bytes() -> Result<usize> (the checked version of row_bytes) and use it at engram.rs:196; row_bytes() then becomes its unwrap-free wrapper. That also lets runtime_core/model.rs:472-479 (std::iter::once((false, table.planes.weights)).chain(...)) read from one iterator shape instead of a hand-built tagged iterator, and lets the three if scales > 0 guards in reader.rs (:970, :1102, :1156) be replaced by driving the copy from planes.iter() with the offset accumulated, rather than by a 0 sentinel plus a branch.

5. Two independent definitions of "this encoding has scales", one of them with a legacy special case

helios/src/core/schema.rs:316-329

/// Whether an `EngramTable` encoding carries a separate scale plane.
/// `Unspecified` stays two-plane for legacy `spans` fixtures; `validate_engram`
/// and `runtime_core::engram::decode` reject `Unspecified` separately.
pub fn engram_encoding_has_scales(encoding: i32) -> Result<bool> {
    match wire::engram_table::Encoding::try_from(encoding) {
        Ok(
            wire::engram_table::Encoding::Unspecified

Meanwhile helios/src/runtime_core/engram.rs derives the same fact from the geometry tuple (scale_bytes: Option<usize>, let has_scales = scale_bytes.is_some();), and prepared.rs from table.planes.scales.is_some(). The Unspecified => true arm exists only so spans() keeps working on legacy fixtures, and it forces every strict caller to add its own Unspecified rejection (schema.rs:355-359). Fold this into suggestion 1: one engram_scales(...) -> Result<Option<&Span>> (strict on Unspecified) for the validating callers, and let spans() — the one legacy-tolerant site — special-case Unspecified locally with a comment. That removes the "callers must reject Unspecified separately" contract from the helper's doc comment and from five call sites.

Smaller, still worth deleting

Nothing else in the diff looked like speculative generality: no new flags, no model allowlists, no env switches, Planes::single/two are correctly #[cfg(test)], and the added tests exercise the general contract rather than a model.

#2 [high] PR #664 subtraction/simplicity review — findings with citations

Verdict: the Planes{weights, scales:Option} refactor is minimal and idiomatic; test bodies updated not duplicated. The non-lean part is the validation layer: "does this table have a scale plane" is answered 4 ways and the same rejection is hand-written 8× with 6 different messages.

  1. DUPLICATED SCALE-PLANE REJECTION (8 sites, 6 messages) — collapse into one helper. Predicate identical everywhere: has_scales==false && scales.is_some(); only wording differs.
  1. TableSource/Table each carry TWO Options that must agree + hand-written cross-checks. helios/src/engram/prepared.rs:39-48: pub weights_plane: PlaneSource, pub scales_plane: Option<PlaneSource>, pub heads, pub weights: String, pub scales: Option<String>, Invariant enforced twice: prepared.rs:71 || source.scales_plane.is_some() != source.scales.is_some() and prepared.rs:163-167 match with _ => return Err("embedding scale plane metadata mismatch".into()). Same coupling for Table at helios/src/engram.rs:178-182. Proposal: pub scales: Option<(PlaneSource, String)> (TableSource) / Option<(Plane, String)> (Table). Removes prepared.rs:71, the _ => arm at :166, and the bespoke error string; read_plane driven off one Option; PartialEq still sound.

  2. Table.partition never read in production; works only via derived PartialEq. helios/src/engram.rs:176-187 pub(crate) partition: Option<usize>, written once at helios/src/runtime_core/engram.rs:425 partition: (!table.shards.is_empty()).then_some(rank); only reader is a test assertion (runtime_core/engram.rs:1076). Effect comes entirely from engram.iter_mut().find(|(existing, _)| existing == &index) at helios/src/runtime_core/model.rs:458 no longer collapsing byte-identical shard groups. Stored, never read, behaviour-by-== is anti-idiomatic here. Either delete and compare an explicit delivery key (Index::delivery_key() including shard rank) at model.rs:458, or read it there.

  3. Row geometry computed 3 ways in the same type; the staging path is the unchecked outlier. helios/src/engram/reader.rs:83-93 row_bytes()/scale_row_bytes()/total_nbytes(); but helios/src/engram.rs:195-199 self.planes.iter().try_fold(0usize, |total, plane| total.checked_add(plane.row_bytes)).and_then(|bytes| bytes.checked_mul(self.heads)) still re-derives it by hand. Proposal: add Planes::try_row_bytes() -> Result<usize> and use at engram.rs:196; also lets runtime_core/model.rs:472-479 drop its hand-built tagged iterator std::iter::once((false, table.planes.weights)).chain(table.planes.scales.map(|plane| (true, plane))), and lets the three sentinel branches in reader.rs (:970, :1102, :1156 all if scales > 0 {) come from planes.iter() with accumulated offset instead of a 0 sentinel.

  4. Two definitions of "this encoding has scales", one with a legacy special case. helios/src/core/schema.rs:316-329 engram_encoding_has_scales with Unspecified => Ok(true) + doc "Unspecified stays two-plane for legacy spans fixtures; validate_engram and runtime_core::engram::decode reject Unspecified separately"; meanwhile runtime_core/engram.rs derives it from scale_bytes: Option<usize> (let has_scales = scale_bytes.is_some();) and prepared.rs from planes.scales.is_some(). The Unspecified==true arm forces every strict caller to add its own rejection (schema.rs:355-359). Fold into (1): one strict engram_scales() for validators; let spans() (the one legacy-tolerant site) special-case Unspecified locally with a comment.

SMALLER:

LEAN/OK (do not flag): Planes::single/two correctly #[cfg(test)]; no new flags/allowlists/env switches; heliopause/src/export/binding.rs:653-657 null tolerance is a behaviour relaxation (Correctness lens, not this one); tests exercise the general contract, not a model.