Subtraction, Simplicity & Conventions review — PR #664
Key findings
- 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 existingengram_encoding_has_scalesdeletes ~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) TableSourceandTableeach carry twoOptions that must agree (scales_plane: Option<PlaneSource>+scales: Option<String>, likewiseplanes.scales+scales), and the invariant is enforced twice by hand plus a bespoke error string. Collapsing toOption<(PlaneSource, String)>makes the illegal state unrepresentable and removes three checks.Table.partitionis written once and never read in production; its whole effect is to perturb derivedPartialEqat 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.- Row geometry is computed three ways inside the same type;
staging_payload_bytesis the one unchecked hand-rolled outlier and there are threeif scales > 0sentinel branches in the copy paths thatParanes/planes.iter()already make unnecessary. - Two independent definitions of "this encoding has scales", one of which (
EngramTable::Encoding::Unspecified => Ok(true)) exists only for legacyspansfixtures and forces every strict caller to add its ownUnspecifiedrejection. - 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 inrank_group.py:47that native code already validates; four near-identicalformat!planes inheliopause/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
helios/manifest.md:455-456now contradicts the paragraph this PR adds directly below it.
"two" is wrong for the tables this PR introduces; say "one or two pinned payload frames". One-word fix, but it is the sentence an implementer reads first.Native manifests with Engram tables carry a shared host reader and rank-local readiness events. Each table has two pinned payload frames and ready flags. Single-plane `BF16` tables store raw `embedding_width * 2`-byte rows without a scale planeignition/preparation/rank_group.py:47duplicates a count native code already validates (helios/src/engram/prepared.rs:181-187computesexpected_descriptors = 1 + usize::from(table.planes.scales.is_some())per table and raises"shared embedding descriptor count differs from its catalog"— the same message verbatim). The Python line is a second source of truth for a number the native side re-derives from the same catalog; dropping it also removes thecountargument from the("embedding_tables", catalog, count)handshake. If kept for early diagnosis, it should at least be the identical expression on both sides.heliopause/src/export/core.rs:1559-1584and:1604-1637are four near-identicalformat!pairs that differ only in plane suffix:
thenstaging_name: format!("engram-{index}-w.payload"), relative: format!("weights/engram-{index}-weights.safetensors"),-s/-scalestwins, then the shard twins at:1611-1627with-shard-{position}inserted. Oneplane_job(index, position, suffix, span)closure over("w", "weights")/("s", "scales")removes all four literals and keeps the naming scheme in one place.
What is already lean (do not change)
Planes { weights: Plane, scales: Option<Plane> }(helios/src/engram/reader.rs:60-64) is the minimal generalization;Planes::single/twoare correctly#[cfg(test)](reader.rs:67-81).- No new CLI flags, config knobs, model allowlists, capability flags or env switches; enum values are appended without touching existing tags (
helios/proto/core.proto(not opened)). - Test bodies were updated in place rather than duplicated (
helios/src/execution/threaded.rs,helios/src/engram/reader/windows.rs(not opened) are mechanical fixture updates). heliopause/src/export/binding.rs:648-658(null tolerance forweights/scales) is a behaviour relaxation, not a simplicity issue — it belongs to the Correctness lens, not this one.
Open questions / could not verify
- Whether
Table.partition'sPartialEq-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. - Whether the descriptor-count check in
rank_group.pyexists for a diagnostic reason (failing on rank zero before handles are sent) thatPreparedTables::from_sharedcannot provide — if so, the duplication is justified but the two expressions should still be unified. - Whether the eight scale-plane rejection sites ever intentionally differ (e.g. the
validate_shardssibling plane-absence allowance athelios/src/runtime_core/engram.rs:101-106is 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. - 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.