Subtraction review — PR #590 helios,ignition: fix Engram reader bugs and add PLE lookahead publish
Key findings
The change is +588/−112 across 4 files, but its defensible core is about 35 lines: the /proc/self/fd read-only reopen for #481, the io_uring lane fan-out, the warm_batch clamp, and the checked_mul mailbox validation with the shared GraphKind/consumes filter. Everything else — roughly 330 of the 588 added lines (~55%) — can leave this PR without losing a behaviour the project needs, either because the code is unreachable once the clamp lands, because another component already enforces the same bound, or because an open PR (#519) already owns the exact change.
| # | Subtraction | Lines | Severity |
|---|---|---|---|
| 1 | WaitBackoff ramp + Windows fork + its four tests (re-adds #519) |
~150 | Should fix |
| 2 | Chunked CachedReader::warm + its 86-line test (unreachable after the clamp) |
~106 | Should fix |
| 3 | New io_uring fan-out test duplicates the existing multi-worker test |
~70 | Should fix |
| 4 | Transfers::new required blocks re-check what decode/manifest/host_address enforce |
~20 | Should fix |
| 5 | flare::ple_advisory_requests + fake duplicates _requests + existing publish op |
~18–29 | Should fix |
| 6 | /proc/self/fd .ok() fallback + EPERM message fork |
~15–20 | Should fix |
| 7 | Two checked_add(1/2) overflow arms over an impossible overflow |
~6 | Nit |
Line counts are from pr_diff: helios/src/engram.rs +187/−19, helios/src/engram/reader.rs +265/−67, helios/src/runtime_core/engram.rs +107/−26, ignition/components/ngram_delivery.py +29/−0.
The project's own rules support a split: AGENTS.md:198-199 ("Keep each PR focused on one coherent outcome") and AGENTS.md:165-169 (a change needs a demonstrated defect, not a future consumer); the charter's "How We Work" asks for the smallest footprint in shared code, and AGENTS.md:188-193 rejects "fallback layers … without a concrete requirement".
1. Should fix — the WaitBackoff ramp, its Windows fork and its four tests re-add open PR #519 (~150 lines)
helios/src/engram.rs:325-377 (new constants SPIN_ROUNDS = 1<<12, NAP_GROWTH = 25us, NAP_MAX = 250us; yield_core in two cfg bodies; WaitBackoff { spins } with new/reset/step), call sites :310-316, :618, :627, :673, :686, :689, plus tests :1079-1167.
- The identical policy is the subject of open PR #519 (
fix(helios): park an Engram gather while it waits for device-published ids, +86/−13). This PR's author reviewed #519 today and asked for exactly this rebase: "re-targetingReaderAction::WaitReady, with the spin counter reset on leavingWaitReady". Two PRs adding one wait policy is the duplicate; the backoff belongs in #519's diff. - The repo already has spin-then-yield waits twice:
helios/src/execution/threaded.rs:34-59(receive) and:65-88(spin_wait_until, spin 32 rounds thenyield_nowpastHANDOFF_POLL), andhelios/src/server/runtime.rs:1180-1208(not opened) (spin_loopthenidle_wait()at 100 us). This is a third hand-rolled ramp with unexplained 25/250 us constants. - The
Requests::readhalf (:310-316) is unreachable in serving:Requests::readis only reached fromReaderAction::Gather(:654), andnext_reader_actionreturnsGatheronly whenjob.requests.is_ready(cancelled)is already true (:401-406). After #566 (7745deea) no production path waits insideread.
Smaller version — no ramp, no growth arithmetic, one cfg for what Windows forces (~8 lines instead of ~53):
#[cfg(not(windows))]
const NAP_MAX: Duration = Duration::from_micros(250);
fn yield_core(spent: bool) {
if !spent { std::hint::spin_loop(); }
else {
#[cfg(not(windows))] thread::sleep(NAP_MAX);
#[cfg(windows)] std::hint::spin_loop();
}
}
Nothing lost: the Acquire flag load, the cancellation check and the 250 us ceiling are unchanged; only the seven intermediate rungs (25–225 us) go, and those are under Linux timer slack anyway. Keep one Requests::read test (device_request_wait_observes_publication_and_cancellation, as on main) — the four new ones (:1094-1140, plus the device_request helper and AFTER_SPIN = 5ms at :1079-1092) exist only to cover the deleted read-side backoff; wait_ready_backoff_naps_until_publication_or_cancellation_and_resets (:1142-1170+, ~45 lines) drives next_reader_action + WaitBackoff directly to assert wait.spins > SPIN_ROUNDS and that reset assigns 0 — a restatement of step/reset, and, as #519's review notes, it "does not establish that the thread parks".
2. Should fix — chunked CachedReader::warm is unreachable once the clamped warm_batch lands (~106 lines, ~20 code + ~86 test)
helios/src/engram/reader.rs:1081-1140 (net +~20, diff +43/−33) and its test advisory_warm_chunks_ids_exceeding_workspace_max_rows at :2174-2229 (~86 lines, constructs 24 ids against max_rows = 8).
After the clamp this PR also adds, no call can exceed one chunk:
warm's only caller isReader::warm←helios/src/engram.rs:677, which passes&pending_warm[warm_cursor..end]withend = (warm_cursor + warm_batch).min(pending_warm.len())andwarm_batch = WARM_BATCH_ROWS.min(max_tokens * table.heads).max(1)(:607-609,:674).- The reader's
max_rowsis the samemax_tokens * table.heads(runtime_core/model.rs:539-541→Reader::from_files(.., rows, ..)). pending_warmis filled byAdvisoryMailbox::snapshot, which clamps toself.max_rows(engram.rs:264), andprefetch_max_rowsis validated against staged rows (runtime_core/engram.rs:313-328).
So ids.chunks(self.max_rows) always yields exactly one chunk; the loop, the total_loaded accumulator and the per-chunk prefetch_rows_loaded increment inside CachedReader (which replaced the single fetch_add that used to sit in Reader::warm) are generality for a shape the clamp makes impossible. Smaller version: keep the clamp (it is the tail-row fix) and leave CachedReader::warm as on main. If defence in depth is wanted, it needs no test that builds an unreachable input; warm_rows_avoid_disk_and_failed_misses_never_enter_the_cache (:1619) already covers warm.
3. Should fix — the new io_uring fan-out test duplicates the existing multi-worker test (~70 lines)
helios/src/engram/reader.rs:2219-2292 (unix_disk_reader_fans_out_when_reads_exceed_single_lane_depth_below_total_depth, ~75 lines) vs the existing parallel_unix_disk_workers_preserve_rows_and_propagate_truncation at :1934-2021 (~90 lines). Both build a two-plane temp file (256 B + 8 B rows, ~300-row stride to defeat 64 KiB coalescing), assemble expected the same way, loop workers, call from_files/gather and assert_eq!(actual, expected, "worker count {workers} corrupted rows"). The only new assertion is used_lanes at :2276-2289. Fold three lines into the existing test — inside its workers loop, assert!(lanes with a nonzero slot_read == ids.len().div_ceil(DEPTH / workers).min(workers)) — and delete the second fixture. Strictly more coverage (the existing test also covers negative ids and truncation), ~70 lines less.
Note the fix itself (reader.rs:787-800, ~8 lines) is worth keeping and already minimal; at most chunk = lane_depth.min(reads.len()) replaces the second div_ceil (≤1 line).
4. Should fix — Transfers::new mailbox bounds checks are a third copy of validation (~20 lines)
helios/src/engram.rs:848-857 and :866-874 recompute max_tokens * heads + 1 (or max_rows + 2) slots × 8 and reject nbytes < required. Already enforced before Transfers::new runs:
runtime_core/engram.rs:303-311requiresshape[0] >= max_staged_rows + 1withmax_staged_rows = tokens * core_heads, andruntime_core/model.rs:857-863passes the sametokensasShared::new(.., tokens, ..)→max_tokens. That is exactly the quantity recomputed here.runtime_core/engram.rs:287enforcesshape[0] * 8 == nbytes(checked) and:289-296enforcesoffset + nbytesinside theMappedHostallocation.runtime_core/serving.rs:33-38(execution_manifest, the only producer of themanifestpassed atruntime_core/model.rs:1023) rejectsoffset + nbytes > allocation.nbytes.Stream::host_address(helios/src/cuda.rs:895-940) rejects empty and non-contiguous ranges, soaddress + nbytes - 8/- 16cannot underflow once it returns.
Smaller version: delete both required blocks and keep Ok::<_, Error>((address, address + nbytes - 8)) and the AdvisoryMailbox { count: address + nbytes - 16, flag: address + nbytes - 8, .. } as before. If a boundary check is truly wanted, it is one line, not ten — and it still duplicates decode (runtime_core/model.rs:448).
5. Should fix — flare::ple_advisory_requests duplicates _requests and the existing publish op (~18 lines, up to 29)
ignition/components/ngram_delivery.py:78-95 (_advisory_requests + _advisory_requests_fake) and PreparedPLELookup.publish_lookahead at :157-164. The new op is require_prepared + hash_state.run_tensors + _copy_requests(..., True) + _publish(..., True) — the body of _requests (:59-69) with the publish half of publish_advisory_requests (:47-56), which is what PreparedEngramRequests.publish_lookahead already calls (ignition/components/engram.py:280-283). Smaller version — call the two existing pieces from publish_lookahead and register nothing new:
def publish_lookahead(self, token_ids, query_start, history, num_seqs, num_tokens, live_rows, mailbox):
"""Hash an upcoming prompt window during graph capture and publish to an advisory mailbox."""
g, ids = self.geometry, torch.empty_like(self.ids)
requests = torch.empty(self.ids.shape[0], dtype=torch.int32, device=self.ids.device)
state = require_prepared(plan_from_handle(self.plan.handle), "sequence.ple_embedding", ids.device)
state.hash_state.run_tensors(token_ids, query_start, history, num_seqs, num_tokens,
g.multipliers, g.prime_sizes, g.table_offsets, ids, requests, token_count=ids.shape[0])
publish_advisory_requests(ids, live_rows, mailbox, self.sequence)
If capture requires a single custom op there, merge it into _requests with a live_rows: torch.Tensor | None and the existing HAS_LIMIT = live_rows is not None constexpr — one op and one fake instead of two (~10 lines). The torch op registry is a permanent global namespace, and this addition shortens exactly one caller. Caveat: the only consumer is the companion recipe PR in local-inference-lab/hyperflare-recipes (per the merge-order note); there is no in-repo caller (grep: only ngram_delivery.py:157), and AGENTS.md:165-169 says hypothetical consumers do not establish a need — the reviewer should at least see the recipe-side call before this half ships here.
6. Should fix — the /proc/self/fd .ok() fallback and the EPERM message fork (~15–20 lines)
helios/src/engram/reader.rs:106-177. Keep the reopen (:108-111, :138-147) — it is the #481 fix. Drop:
- the
.ok()fallback at:139-143: if the reopen fails, mapping through theO_RDWRfd behaves exactly as before the fix, i.e. it reproduces #481'sEPERMsilently on precisely the kernels that need the fix.AGENTS.md:188-193rejects fallback layers without a concrete requirement;.ok()also swallows the error that would explain a failure. - the
EPERMmessage fork at:151-159: an error string that narrates a kernel version is prose, not behaviour, and the PR's own limitations say pre-6.7 was not exercised. Oneformat!("map resident embedding table: {error}")covers both arms.
Smaller version: inline map_fd (which exists only to be called once), use File::open(...)? under #[cfg(target_os = "linux")], keep one error string — ~15–20 lines fewer, and the failure is louder instead of silent. Keep sealed_resident_readonly_mapping_drops_write_capability_via_proc_reopen (:2294-2329, ~34 lines): it is the positive control for #481.
7. Nit — two checked_add overflow arms over an impossible overflow (~6 lines)
helios/src/runtime_core/engram.rs:303-305 and :314-316 each wrap max_staged_rows.checked_add(1) / checked_add(2) in a three-line ok_or_else with its own error string. max_staged_rows is tokens * core_heads already checked_mul-ed at :242-244 from a bounded packed_tokens and a buffer width; adding 1 or 2 cannot overflow u64. Use max_staged_rows + 1 / + 2 directly.
The rest of this file's hardening is a genuine subtraction and should stay: checked_mul at :287 replaces an unchecked shape[0] * 8, and GraphKind::try_from(g.kind.as_str()).is_ok_and(crate::engram::consumes) at :224/:333 replaces two hand-copied five-kind lists that omitted scored_prefill. Optional further trimming: those two closures are now a third copy of runtime_core/model.rs:480-481; a one-word helper next to consumes (helios/src/engram.rs:1011) would let all three read .filter(|g| consumer(&g.kind)) and keep them from diverging again (net ~−4 lines).
What is already minimal and should stay
io_uring lane fan-out (reader.rs:787-800), the warm_batch clamp (engram.rs:607-609), the /proc/self/fd reopen itself (reader.rs:108-111, :138-147), and runtime_core/engram.rs's checked_mul/allocation-bounds validation with the shared kind filter. Together ~35 lines net, and each has one focused test (sealed_resident_readonly_mapping_*, warm_rows_*, parallel_unix_disk_workers_*, plus the mailbox validation tests). Keep the PR's graph-kind and mailbox tests as they are.
Open questions and what could not be verified
- No build or test run was performed here; the PR's reported counts (48 helios
engramtests, 228+7+1 flare,pytestpass) are taken as reported. - Pre-6.7
EPERMwas not exercised; finding 6 is about code shape (a silent fallback re-creating the bug, and an error string), not about whether the fallback is taken in practice. - The only caller of
PreparedPLELookup.publish_lookaheadlives inlocal-inference-lab/hyperflare-recipes, which I could not open; finding 5 flags it as unverified rather than asserting it is unused in practice. - Windows behaviour of
yield_core's spin-only variant was not judged at runtime; finding 1 rests on duplication and line count. - Whether #519 will land the backoff itself is a maintainer decision; if it does, finding 1 is a straight duplication and the dispatch should be closed rather than trimmed.