Subtractive scratchpad · NVIDIA/hyperflare-inference #590

Raw Markdown for agents: https://autobot.eidonix.com/p/524f1a5f-bf67-4842-a38f-3559aaace70a.md

#1 [high] Should fix: WaitBackoff ramp + Windows fork + yield_core re-adds #519's pending work (helios/src/engram.rs:325-377)

File: helios/src/engram.rs:325-377 (new), plus the two call sites at :310-316 and :618/:627/:673/:686/:689.

Added: SPIN_ROUNDS, NAP_GROWTH, NAP_MAX, yield_core (two cfg variants), WaitBackoff { spins } with new/reset/step, plus 4 doc-comment blocks. ~53 added lines, replacing one std::hint::spin_loop().

  1. The exact same policy is already proposed by open PR #519 (helios/src/engram.rs, +86/-13, "park an Engram gather while it waits for device-published ids"). #519's author (lukealonso, the same author as this PR) reviewed it at 2026-11-28 18:40 and wrote that the fix must be "re-targeting ReaderAction::WaitReady, with the spin counter reset on leaving WaitReady". This PR is that rebase, so the backoff belongs in #519's diff; carrying it in a five-fix bundle means two PRs adding one wait policy. Either way the ramp is unnecessary: #519's own review records that 96% of a measured 28.8 ms wait runs at NAP_MAX and that SPIN_ROUNDS cannot catch pre-published ids because the flag is loaded (Acquire) before the loop body.

  2. The repo already has spin-then-yield wait helpers, twice: helios/src/execution/threaded.rs:34-59 (receive) and :65-88 (spin_wait_until, spin 32 rounds then yield_now past HANDOFF_POLL), and helios/src/server/runtime.rs:1180-1208 (spin_loop then idle_wait() = 100 us). This adds a third hand-rolled policy with unexplained 25 us/250 us constants (already flagged as a nit in #519's reviews).

Smaller version — no ramp, no growth arithmetic, no second cfg body beyond what Windows forces:

#[cfg(not(windows))]
const NAP_MAX: Duration = Duration::from_micros(250);

/// After a short spin, give the core up for at most one decode step.
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();
    }
}

keeping only a rounds: u32 counter at each call site (or reusing WaitBackoff with step reduced to if self.spins < SPIN_ROUNDS { spin } else { sleep(NAP_MAX) }). Saves ~30 of the 53 added lines.

  1. The Requests::read half (helios/src/engram.rs:310-316, +6) is unreachable in serving: after #566 (7745deea), ReaderAction::Gather — the only production caller of Requests::read — is dispatched only when job.requests.is_ready(cancelled) is already true (engram.rs:401-406, :648-654). So the production path is WaitReady only; the read-side backoff plus its four new tests exist for a path that no longer waits. Deleting the read half saves 6 lines and ~60 lines of tests (see separate note).

Nothing lost: the flag load ordering, cancellation check and 250 us ceiling are unchanged; only the seven intermediate rungs (25-225 us) go, and they are under Linux timer slack anyway.

#2 [high] Should fix: Transfers::new mailbox bounds checks are a third copy of validation decode already did (helios/src/engram.rs:848-874)

File: helios/src/engram.rs:848-857 (required for the request mailbox) and :866-874 (required for the prefetch mailbox). +20 lines.

What the new code does: recomputes max_tokens * heads + 1 (or max_rows + 2) slots * 8 and rejects when nbytes < required.

Why nothing needs it:

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. The accompanying reader-side comment in the PR description ("Transfers::new and Requests::read ... pointer subtraction address + nbytes - 8") is the justification, but address there comes from host_address, which rejects a zero-length range.

If a check is wanted at this boundary it is one line, not ten: if nbytes < 8 * (binding.shared.max_tokens * table.heads + 1) { ... } — and even that duplicates decode.

Nothing lost: a malformed core is still rejected, by decode, before Transfers::new runs (decode is called from runtime_core/model.rs:448 for each rank, manifests are built afterwards at :1023).

#4 [high] Should fix: chunked CachedReader::warm is unreachable once the new clamp is in place — keep the clamp, drop the loop and its test (reader.rs:1081-1140, 2174-2229)

File: helios/src/engram/reader.rs:1081-1140 (CachedReader::warm).

The PR turns a straight-line body into for chunk in ids.chunks(self.max_rows) { ...body... }, +~20 lines net (the diff shows +43/-33). The chunking half of the change cannot trigger:

So after the clamp, every warm call already has ids.len() <= warm_batch <= max_rows, and ids.chunks(self.max_rows) yields exactly one chunk. The loop, total_loaded accumulator and the implicit "one chunk" reasoning are dead generality; Reader::warm even lost its prefetch_rows_loaded update to a per-chunk increment inside CachedReader::warm, so the counter now lives in a place that only needs it because of the loop.

Smaller version: keep the clamp at engram.rs:607-609 (that is the actual fix for tail-row loss) and leave CachedReader::warm as it was on main, including Ok(count) and the prefetch_rows_loaded fetch_add in Reader::warm (reader.rs:1295-1298 removed by this PR). Saves ~20 code lines in reader.rs plus ~86 lines of the advisory_warm_chunks_ids_exceeding_workspace_max_rows test (reader.rs:2174-2229) that only exercises a call shape the clamp makes impossible.

If the author prefers defence in depth, the loop needs no test that constructs an unreachable input; the existing warm_rows_avoid_disk_and_failed_misses_never_enter_the_cache covers warm.

#7 [high] Should fix: flare::ple_advisory_requests duplicates _requests + an existing publish op; ~18 lines of new custom op for one caller (ngram_delivery.py:78-95)

File: ignition/components/ngram_delivery.py:78-95, 157-164.

Added: a second registered op flare::ple_advisory_requests (_advisory_requests + fake, ~18 lines) and PreparedPLELookup.publish_lookahead (~8 lines), whose body re-derives ids/requests buffers and calls the op.

What already exists: flare::publish_advisory_embedding_requests (publish_advisory_requests, ngram_delivery.py:47-56) takes (ids, live_rows, mailbox, sequence) and is what PreparedEngramRequests.publish_lookahead (ignition/components/engram.py:280-283) already uses. The new op is only needed because the PLE path has to hash first. The hashing half is a copy of _requests (:59-69): the same require_prepared + hash_state.run_tensors(...) + _copy_requests(..., HAS_LIMIT=True) + _publish(..., HAS_COUNT=True).

Smaller version — keep one op and give the existing one the shape both callers need, i.e. two calls in publish_lookahead and no new custom op at all:

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)

That is the exact body of _advisory_requests minus its registration, with publish_advisory_requests (already imported/defined in the same module) doing the copy and publish. It removes the whole custom op + fake (~18 lines) and leaves ~9 lines of Python. Two advantages beyond size: the torch custom-op registry gains no op (it is a global, permanent namespace, and this one exists only to shorten one caller), and there is one publish implementation instead of two.

If a captured-graph custom op really is required at that call site (the other publishes are custom ops because they run inside capture), then the new op should at least share its body with _requests: both are hash_state.run_tensors + _copy_requests + _publish, differing only in HAS_LIMIT/HAS_COUNT and the source buffers. One op with live_rows: torch.Tensor | None and the existing HAS_LIMIT=live_rows is not None constexpr removes the duplication and one fake function (~10 lines).

Evidence bar: no caller of PreparedPLELookup.publish_lookahead exists in this repository (grep: only ignitions/components/ngram_delivery.py:157). The only consumer is the companion recipe PR in local-inference-lab/hyperflare-recipes, which the description asks to merge after this one. Per AGENTS.md:165-169 ("Hypothetical future consumers ... do not establish a need for a change") and :188-193 ("Do not add ... speculative compatibility ... without a concrete requirement"), the Python half is unverified here; the reviewer must at minimum see the recipe-side call.

#8 [high] Should fix: new io_uring fan-out test duplicates the existing multi-worker test; ~70 lines can fold into it

Files: helios/src/engram/reader.rs:784-800 and 2221-2295.

  1. The DiskReader::gather lane fan-out fix (reader.rs:787-800) is small and correct-looking: it replaces self.reads.len() <= DEPTH with a per-lane depth and computes active_lanes. Only simplification available: active_lanes and chunk are two div_ceil calls where chunk = lane_depth.min(reads.len()) yields the same partition — reads.chunks(lane_depth) with self.lanes[..reads.len().div_ceil(lane_depth).min(len)]. Net save ~1 line; not worth flagging beyond a nit. Keep.

  2. Its new test unix_disk_reader_fans_out_when_reads_exceed_single_lane_depth_below_total_depth (reader.rs:2221-2295, ~75 lines) overlaps heavily with the existing parallel_unix_disk_workers_preserve_rows_and_propagate_truncation (:1932-2021, ~90 lines): both build a two-plane temp file with 256/8-byte rows, a stride of 300 rows to defeat coalescing, an expected buffer assembled the same way, loop over workers in [1,2,4,8] vs [2,4,8], gather and assert_eq!(actual, expected, "worker count {workers} corrupted rows"). The new test adds only the used_lanes assertion (reads each lane's slot_read). That assertion can be added to the existing test as three lines instead of a second 75-line fixture: in the existing loop, after gather, assert the count of lanes with a nonzero slot_read equals ids.len().div_ceil(DEPTH / workers).min(workers). Saves ~70 lines with strictly more coverage (the existing test also covers truncation and slot reuse).

  3. sealed_resident_readonly_mapping_drops_write_capability_via_proc_reopen (:2296-2329) duplicates setup with resident_sealing_waits_for_unmapped_pages_held_by_io/resident_sealing_rejects_a_retained_writable_mapping (both use unsealed_resident_file()/seal_resident), which is fine at ~34 lines; keep.

  4. advisory_warm_chunks_ids_exceeding_workspace_max_rows (:2174-2229) — see the separate note; it tests an unreachable call shape (~86 lines).

Total test subtraction available in this file: ~70 (merge fan-out test) + ~86 (chunked-warm test) of the PR's +265.

#9 [high] Summary: +588/−112 across 4 files; ~330 added lines removable, ~35-line defensible core

Counted from the diff (pr_diff): 4 files, +588/−112 (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 change bundles five independent fixes, three of which already have their own home or no consumer, and AGENTS.md:198-199 requires "Keep each PR focused on one coherent outcome and describe its problem, resulting behavior, validation, and material limitations." Charter "How We Work" → "Solve the right problem in the right place ... Look for the smallest footprint in shared code."

What can leave this PR without losing anything:

Part Lines Where it belongs / why it can go
Wait backoff (engram.rs:325-377 + call sites + 5 tests) ~+150 Open PR #519 changes this exact wait (same author reviewed it 2026-11-28 18:40 asking for precisely this rebase onto ReaderAction::WaitReady). Land it there; this PR is not the place for a second copy.
CachedReader::warm chunk loop (reader.rs:1081-1140) + its test (2174-2229) ~+20 / ~+86 Unreachable once engram.rs:607-609 clamps warm_batch to max_tokens*heads == max_rows. Keep the clamp, drop the loop and test.
Transfers::new required blocks (engram.rs:848-857, 866-874) ~+20 decode (runtime_core/engram.rs:303-316) and execution_manifest (runtime_core/serving.rs:33-38) already enforce them.
/proc/self/fd fallback + EPERM string fork (reader.rs:138-159) ~+15 Silent fallback re-creates #481's failure; the fork is prose. Keep the reopen through ?.
flare::ple_advisory_requests + fake + publish_lookahead (ngram_delivery.py:78-95, 157-164) ~+29 No consumer in this repo; companion recipe PR not here. Fold onto publish_advisory_requests or defer until the recipe lands.
New io_uring fan-out test (reader.rs:2221-2295) ~+75 Fold used_lanes assertion into parallel_unix_disk_workers_preserve_rows_and_propagate_truncation (:1932-2021).
checked_add(1)/(2) overflow arms (runtime_core/engram.rs:303-305, 314-316) ~+6 Unreachable after checked_mul on tokens * heads.

Genuinely needed in this PR and already minimal: the lane fan-out in DiskReader::gather (reader.rs:787-800, ~+8), the warm_batch clamp (engram.rs:607-609, +3), the /proc/self/fd reopen (reader.rs:108-111 + 138-147, ~+10), the checked_mul in validate_mailbox/validate_buffer and the GraphKind/consumes replacement (runtime_core/engram.rs, ~+15 net but −12 of duplicated kind lists). Those four are ~35 lines and are the whole defensible core of the change.

Estimated total removable: ~330 of the +588 added lines (about 55%), leaving a ~150-line diff (−112) that fixes #481, the QD collapse, the warm truncation and the mailbox overflow — each with one focused test.

Ranked findings (largest first): 1) split out the wait backoff to #519 (~150); 2) chunked warm + its test unreachable (~106); 3) io_uring test duplication (~70); 4) Transfers::new checks duplicate decode (~20); 5) PLE advisory custom op duplicates existing publish (~18); 6) /proc fallback + message fork (~15); 7) unreachable overflow arms (~6).

#10 [high] Research summary

Reviewed PR #590 (+588/−112, 4 files) strictly for subtraction. Seven confirmed removals, ~330 of the 588 added lines (~55%), leaving a ~150-line diff whose defensible core is ~35 lines: the /proc/self/fd reopen fix for #481, the io_uring lane fan-out, the warm_batch clamp, and the checked_mul mailbox validation with the shared GraphKind/consumes filter.

Ranked by lines saved: (1) the WaitBackoff ramp, Windows yield_core fork and four tests (~150 lines) re-add the exact work of open PR #519 — whose author, also this PR's author, reviewed it on 2026-11-28 asking for exactly this rebase onto ReaderAction::WaitReady; the read-side half is unreachable in serving after #566, and the repo already has two spin-then-yield helpers (execution/threaded.rs:34-88, server/runtime.rs:1180-1208 (not opened)). (2) The chunked CachedReader::warm loop plus its 86-line test are unreachable once the new warm_batch clamp caps ids at max_rows; keep the clamp, drop the loop. (3) The new io_uring fan-out test duplicates the existing multi-worker test's 90-line fixture; fold in its one new assertion. (4) The required bounds blocks in Transfers::new re-check what decode, execution_manifest and host_address already enforce. (5) flare::ple_advisory_requests re-implements hashing, capture and publish that exist as three lines in the same file, and has no consumer in this repository. (6) The /proc/self/fd .ok() fallback silently re-creates #481's failure and the EPERM message fork is prose. (7) Two checked_add arms guard an overflow that cannot happen.

All findings are in the scratchpad with file:line citations, the smaller replacement code, and why nothing is lost.

#3 [medium] Should fix: ~100 lines of tests exercise only the unreachable Requests::read backoff and restate step/reset (helios/src/engram.rs:1079-1167)

File: helios/src/engram.rs:1079-1167 region (tests). Added by this PR: device_request helper, AFTER_SPIN, and four tests — device_request_wait_returns_ids_already_published, device_request_wait_returns_ids_published_after_the_spin, device_request_wait_observes_cancellation_before_publication, device_request_wait_observes_cancellation_after_the_spin — replacing the one existing device_request_wait_observes_publication_and_cancellation. Plus wait_ready_backoff_naps_until_publication_or_cancellation_and_resets (~45 lines).

Subtraction:

Total ~100 test lines of the PR's +187 in this file. Nothing lost: publication and cancellation of a device request are still covered by one test, and the warm/gather correctness paths tested elsewhere in reader.rs are untouched by the wait.

#5 [medium] Should fix: /proc/self/fd reopen has a silent fallback and an EPERM message fork with no caller (reader.rs:106-177)

File: helios/src/engram/reader.rs:106-177 (ResidentMapping).

Added: open_readonly_view (linux), map_fd split out of new, a readonly_view local, a map_fd selector with a #[cfg(not(target_os = "linux"))] duplicate, and an EPERM-specific error message (+~25 lines net).

Unneeded parts:

Smaller version — one code path, no cfg duplicate, no fallback, no message fork:

fn new(file: &File, nbytes: usize, writable: bool) -> Result<Self> {
    // A read-only description carries no VM_MAYWRITE, which pre-6.7 kernels require
    // to map a write-sealed memfd shared; 6.7+ accepts it too.
    #[cfg(target_os = "linux")]
    let descriptor = if writable { None } else {
        Some(File::open(format!("/proc/self/fd/{}", file.as_raw_fd()))?)
    };
    #[cfg(target_os = "linux")]
    let fd = descriptor.as_ref().map_or(file.as_raw_fd(), |f| f.as_raw_fd());
    #[cfg(not(target_os = "linux"))]
    let fd = file.as_raw_fd();
    let protection = libc::PROT_READ | if writable { libc::PROT_WRITE } else { 0 };
    let address = unsafe { libc::mmap(std::ptr::null_mut(), nbytes, protection, libc::MAP_SHARED, fd, 0) };
    if address == libc::MAP_FAILED {
        return Err(format!("map resident embedding table: {}", std::io::Error::last_os_error()).into());
    }
    ...
}

i.e. keep the reopen (it is the #481 fix), drop map_fd as a separate fallible wrapper, drop the .ok() fallback and the EPERM string fork. Saves ~15-20 lines.

Note: File::open(...).ok() also swallows the error into the silent path; using ? is both shorter and louder.

Also, the new test sealed_resident_readonly_mapping_drops_write_capability_via_proc_reopen (reader.rs:2296-2329, ~34 lines) is worth keeping only if it also asserts the mapping succeeds — which it does (ResidentMapping::new(&file, BLOCK, false)). Keep it; but it duplicates F_GETFL == O_RDONLY (already asserted) plus mprotect EACCES, which is the positive control for #481. No subtraction there beyond trimming the open_readonly_view sub-assert if that helper is inlined.

#11 [medium] Review scope and limits: what was verified in code vs. not verified

Verified by reading the code at the PR head (4ea9ba0) and main:

Not verified / not claimed:

#6 [low] Nit: two checked_add(1/2) overflow arms in runtime_core/engram.rs guard an impossible overflow; three copies of the kind-filter closure

Files: helios/src/runtime_core/engram.rs:221-227, 242-244, 245-259, 262-271, 272-301, 302-329, 330-347.

The overflow-hardening changes are the right size (checked_mul/checked_add in validate_buffer replaces an unwrap_or(0) that could wrap; GraphKind::try_from(..).is_ok_and(consumes) replaces two hand-copied five-kind lists — that is a genuine subtraction of ~12 lines and a real divergence fix). Two leftovers:

  1. max_staged_rows was moved to :242-244 but is used only at :270 (validate_buffer(buffer, dtype, max_staged_rows, columns)) and via min_request_len/max_prefetch_len. Fine. However let min_request_len = ...checked_add(1) (:303-305) and let max_prefetch_len = ...checked_add(2) (:314-316) each add a 3-line ok_or_else closure for an overflow that tokens (≤ packed_token_capacity, a u32 from proto) times core_heads (a shape[1], itself bounded by the table's heads) cannot reach — max_staged_rows is already checked_mul; adding 1 or 2 to it cannot overflow u64. Delete the two ok_or_else arms and use max_staged_rows + 1 / max_staged_rows + 2 directly: −6 lines, no behaviour change, one fewer error string each.

  2. validate_buffer's new expected_nbytes (:246-248) rebuilds the whole value with two checked_* calls every invocation (3 per rank per table). It replaces shape[0].checked_mul(columns * dtype_bytes).unwrap_or(0). Same length, marginally clearer — no subtraction available; note it only because the PR description counts it as a change.

  3. The two GraphKind::try_from(g.kind.as_str()).is_ok_and(crate::engram::consumes) closures (:224, :333) are identical to the one already in helios/src/runtime_core/model.rs:480-481. Three copies of the same parse-and-filter. A one-word helper — fn consumer(kind: &str) -> bool — next to consumes in helios/src/engram.rs:1011 would let all three read .filter(|g| consumer(&g.kind)). Saves ~2 lines each and removes the risk that one site is updated without the others. Optional (net −4 lines); the important part is that this PR removes the two divergent lists.