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

Raw Markdown for agents: https://autobot.eidonix.com/p/dd9b9154-7464-4d1e-b757-770fdd51d4c8.md

Subtraction, Simplicity & Conventions review — PR #664

Key findings

  1. The "single-plane table must not carry a scale plane" rejection is hand-written eight times with six different messages, and each site separately re-decides whether a required scale plane is present. One strict helper (engram_scales(encoding, span) -> Result<Option<&Span>>) next to the existing engram_encoding_has_scales deletes ~40 lines across four files and removes the drift risk between the four exporter site-groups that must agree on the asset list. (highest value)
  2. TableSource and Table each carry two Options that must agree (scales_plane: Option<PlaneSource> + scales: Option<String>, likewise planes.scales + scales), and the invariant is enforced twice by hand plus a bespoke error string. Collapsing to Option<(PlaneSource, String)> makes the illegal state unrepresentable and removes three checks.
  3. Table.partition is written once and never read in production; its whole effect is to perturb derived PartialEq at the delivery-group dedup. Behaviour-by-== on an unread field is anti-idiomatic and fragile — compare an explicit key at the dedup site, or read the field there.
  4. Row geometry is computed three ways inside the same type; staging_payload_bytes is the one unchecked hand-rolled outlier and there are three if scales > 0 sentinel branches in the copy paths that Paranes/planes.iter() already make unnecessary.
  5. Two independent definitions of "this encoding has scales", one of which (EngramTable::Encoding::Unspecified => Ok(true)) exists only for legacy spans fixtures and forces every strict caller to add its own Unspecified rejection.
  6. Smaller deletions: a now-false sentence in helios/manifest.md:456 ("two pinned payload frames") directly above the paragraph this PR adds; a duplicated descriptor count in rank_group.py:47 that native code already validates; four near-identical format! planes in heliopause/src/export/core.rs.

The core of the change is lean and idiomatic: Planes { weights, scales: Option<Plane> } is the minimal generalization of [Plane; 2], Planes::single/two are correctly #[cfg(test)], no new CLI flags, model allowlists, capability switches or env vars are introduced, and test bodies were updated rather than duplicated. The non-lean part is entirely the validation layer.


1. Eight copies of one predicate, six messages — collapse to one helper

The predicate and the shape of the rejection are identical at every site: has_scales == false && table/scales.is_some() (and the mirror ok_or_else(|| invalid("… lacks scales"))). 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/core/schema.rs:495-499

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

helios/src/runtime_core/engram.rs:47-49, :68-72, :107-111, :200-202, :273-276

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

heliopause/src/export/core.rs:117-121, :149-153 (roles()), :437-441, :458-462 (validate_ranks()), :1577-1583, :1632-1638 (core_engram())

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

Each of those sites also re-decides the required case, e.g. core.rs:1566-1569

                let scales_span = table
                    .scales
                    .as_ref()
                    .ok_or_else(|| invalid("engram table lacks scales"))?;

Simplify: one helper beside engram_encoding_has_scales (helios/src/core/schema.rs:319), expressed over the wire type so heliopause can use it too:

/// `Ok(Some(span))` when the encoding has a scale plane (span required),
/// `Ok(None)` when it does not (a present span is an error), `Err` on unknown/unspecified.
pub fn engram_scales(encoding: i32, span: &Option<Span>) -> Result<Option<&Span>>

Callers become engram_scales(table.encoding, &table.weights)? / engram_scales(table.encoding, &shard.weights)? and then if let Some(span) = … { push / locate }. That removes ~40 lines and four of the six error strings, and — more important than the line count — makes it impossible for roles(), validate_ranks(), required_payloads(), spans() and core_engram() to drift apart about which assets exist, which is exactly the failure mode this code class has.

2. TableSource / Table carry two Options that must agree, checked twice by hand

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 by hand twice:

helios/src/engram/prepared.rs:67-79

            if source.heads == 0
                || source.heads > 64
                || source.event.is_empty()
                || !events.insert(source.event.clone())
                || source.scales_plane.is_some() != source.scales.is_some()

and again at load time, helios/src/engram/prepared.rs:163-167

            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()),
            };

The same coupling reappears for the decoded type, helios/src/engram.rs:178-183

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

Simplify: make the illegal state unrepresentable — pub scales: Option<(PlaneSource, String)> on TableSource and pub scales: Option<(Plane, String)> on Table. Then prepared.rs:71 and the _ => arm at prepared.rs:166 both vanish, the bespoke "embedding scale plane metadata mismatch" string goes away, load_plane is driven from one Option, and PartialEq stays meaningful because both halves move together.

3. Table.partition is never read in production — behaviour by PartialEq

helios/src/engram.rs:176-187

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Table {
    pub(crate) planes: Planes,
    pub(crate) partition: Option<usize>,

Written exactly once, helios/src/runtime_core/engram.rs:425: partition: (!table.shards.is_empty()).then_some(rank). I searched the whole head for reads of the field: the only one is the test assertion at helios/src/runtime_core/engram.rs:1076 (assert_eq!(decoded.tables[0].partition, Some(rank));). Its entire production effect is that this dedup no longer collapses two ranks whose shard bytes are identical:

helios/src/runtime_core/model.rs:458

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

A field that is stored, never read, and changes behaviour by perturbing == is the opposite of this file's style, where delivery grouping is otherwise explicit. A future reader who "cleans up the unused field" silently reintroduces the collapse bug. Simplify: either delete the field and compare a named key at model.rs:458 (Index::delivery_key() including the shard rank), or keep the field and use it in the comparison at model.rs:458. Do not leave it implicit.

4. Row geometry computed three ways; the staging path is the unchecked outlier

helios/src/engram/reader.rs:83-101 already owns the geometry helpers:

    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)
    }

total_nbytes, iter and iter_mut exist too (the last two were added by this PR) — yet helios/src/engram.rs:195-199 re-derives the row width by hand, unchecked:

    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))

Simplify: add Planes::try_row_bytes() -> Result<usize> (the checked form of row_bytes()), use it at engram.rs:196, and let row_bytes() be its thin wrapper. The same accessor set lets the three 0-sentinel branches in the copy paths go away — e.g. helios/src/engram/reader.rs:970

                if scales > 0 {
                    std::ptr::copy_nonoverlapping(
                        row.as_ptr().add(weights),

(same pattern at reader.rs:1102 and :1156): drive the copy from planes.iter() with an accumulated output offset instead of a weights/scales pair plus a zero sentinel. It also lets helios/src/runtime_core/model.rs:475-479 read from one iterator shape rather than a hand-built tagged walk over table.planes.

5. Two definitions of "has scales", one with a legacy special case that poisons the contract

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
            | wire::engram_table::Encoding::Fp8E4m3E8m0
            | wire::engram_table::Encoding::Nvfp4E4m3Global,
        ) => Ok(true),

Meanwhile helios/src/runtime_core/engram.rs derives the same fact from its geometry tuple (scale_bytes: Option<usize>) and helios/src/engram/prepared.rs from planes.scales.is_some(). The Unspecified => true arm forces every strict caller to add its own rejection, e.g. helios/src/core/schema.rs:355-359

        let encoding = wire::engram_table::Encoding::try_from(table.encoding)
            .map_err(|_| invalid("engram table has no encoding"))?;
        if encoding == wire::engram_table::Encoding::Unspecified {
            return Err(invalid("engram table has no encoding"));
        }

Simplify: fold into suggestion 1 — one strict engram_scales() (rejecting Unspecified) for the validating callers; let spans(), the single legacy-tolerant site, special-case Unspecified locally with a comment. That deletes the "callers must reject Unspecified separately" contract from the doc comment and the duplicated rejection from every strict caller.

Smaller, still worth deleting

What is already lean (do not change)


Open questions / could not verify

  1. Whether Table.partition's PartialEq-only mechanism was a deliberate design or an accident — the description presents it as an explicit "distinct partitioned delivery groups" fix, but nothing in the code makes the mechanism legible; this affects whether suggestion 3 should keep or delete the field.
  2. Whether the descriptor-count check in rank_group.py exists for a diagnostic reason (failing on rank zero before handles are sent) that PreparedTables::from_shared cannot provide — if so, the duplication is justified but the two expressions should still be unified.
  3. Whether the eight scale-plane rejection sites ever intentionally differ (e.g. the validate_shards sibling plane-absence allowance at helios/src/runtime_core/engram.rs:101-106 is genuinely a different rule than "single-plane cannot carry scales"); the shared helper must be scoped to the single-plane rule only and not swallow that case.
  4. No CI on the head commit, so none of the reported pass counts could be confirmed here; all simplification suggestions are based on reading the head c769355.