Conventions scratchpad · NVIDIA/hyperflare-inference #590

Raw Markdown for agents: https://autobot.eidonix.com/p/779a1073-0ec1-4c09-871b-8a1f5d1e7e1f.md

#1 [high] Should fix: Windows reader keeps the unfixed <= DEPTH lane dispatch (duplicate of the fixed Unix block)

The PR changes the Unix dispatch in DiskReader::gather (helios/src/engram/reader.rs:787-800) from self.reads.len() <= DEPTH to a per-lane lane_depth = DEPTH / self.lanes.len() with active_lanes = reads.len().div_ceil(lane_depth).min(len).

helios/src/engram/reader/windows.rs is the structural twin of that block and was NOT changed:

So on Windows, with --embedding-table-workers 4|8, 17..=128 reads still collapse onto lane 0 — the same queue-depth collapse the PR ships a test for on Unix (unix_disk_reader_fans_out_when_reads_exceed_single_lane_depth_below_total_depth, reader.rs:2200+). Two copies of one dispatch decision, now divergent, and nothing makes them agree.

Rule: AGENTS.md:497-500 "When a potential correctness, memory, or performance deficiency appears in one model, inspect the shared components and equivalent paths in every supported recipe before scoping the fix"; charter "Code Review Standards": "Check interactions across every supported model, cache scheme, parallel layout, multi-host setup, and hardware target named in the docs". docs/windows.md qualifies Windows Engram (cited in #519's review).

Fix: apply the same lane_depth / active_lanes computation in windows::Readers::gather, or factor the lane fan-out (active-lane count + chunking + scoped joins) into one function both backends call, since the two bodies are otherwise identical. If Windows is deliberately out of scope, say so in the description and open the follow-up.

#2 [high] Should fix: publish_lookahead allocates two GPU tensors per call, unlike publish and unlike the Engram precedent

New PreparedPLELookup.publish_lookahead (ignition/components/ngram_delivery.py:157-164):

g = self.geometry
ids = torch.empty_like(self.ids)
requests = torch.empty(self.ids.shape[0], dtype=torch.int32, device=self.ids.device)
_advisory_requests(...)

Both tensors are allocated on every call (token-shaped: self.ids is table.hashes[:tokens]), and both are write-only scratch the caller never sees (the op's mutates_args is ("ids","requests","mailbox")).

The closest precedent is the sibling method in the same class, publish (:148-155), which reuses the buffer prepared in __init__ (self.requests, :122) and only falls back to an allocation for the functional() case where it was dropped (:151-152). The Engram twin, PreparedEngram.publish_lookahead (ignition/components/engram.py:280-283), likewise reuses the prepared buffers (self.hashes, self.requests, and _hash_window(..., dest=self.hashes) at engram.py:241-271). This PR's new method is the only preparation-time hashing path that allocates its own scratch.

Why it matters: AGENTS.md:417-419 "Do not introduce an eager serving fallback, runtime compilation, graph recapture, or GPU allocation in steady-state execution", and AGENTS.md:177 "Reject architectural violations … steady-state GPU allocation". The docstring (:158) says the path hashes "an upcoming prompt window", i.e. it runs per lookahead publish, not once at export. The PR description claims "zero additional persistent GPU VRAM", which is true only if the buffers are not persistent and nothing depends on their identity — but the per-call allocation is exactly the steady-state allocation the rule forbids.

Fix: hoist ids/requests next to self.ids/self.requests in __init__ (and keep the functional()-style fallback that publish already uses), or pass self.requests through when it is not None, matching publish.

#9 [high] Research summary

Reviewed all four changed files through the conventions-and-duplication lens, against AGENTS.md, docs/design-review.md (not opened)'s rules as cited by AGENTS.md, and the charter. Eight notes recorded in the scratchpad; two are real findings worth acting on, the rest are nits and positives.

Should fix — the Windows reader keeps the defect this PR fixes. The Unix DiskReader::gather dispatch now uses per-lane lane_depth = DEPTH / lanes.len() with an active-lane fan-out (reader.rs:787-800). Its structural twin, helios/src/engram/reader/windows.rs:56,91,94, was not changed and still routes every batch with reads.len() <= DEPTH to lanes[0], so the 4x–8x queue-depth collapse survives on Windows with --embedding-table-workers 4|8. The two bodies are otherwise identical, so the fix should be applied to both or the lane fan-out factored out. AGENTS.md:497-500 and the charter's "check every parallel layout and hardware target" both apply, and docs/windows.md (not opened) qualifies Windows Engram.

Should fix — publish_lookahead allocates two GPU tensors per call. ignition/components/ngram_delivery.py:157-164 calls torch.empty_like and torch.empty on every invocation, while its sibling publish (:148-155) reuses the buffers prepared in __init__ and the Engram precedent (PreparedEngram.publish_lookahead, engram.py:280-283 with _hash_window(..., dest=...)) reuses prepared scratch too. AGENTS.md:417-419 and :177 prohibit steady-state GPU allocation. The buffers should be hoisted beside self.ids/self.requests, as publish already does.

Nits. WaitBackoff (engram.rs:325-377) lands as a third hand-rolled spin-then-park policy with no cross-reference to threaded::spin_wait_until/receive or persistent_worker's drain poll, and its NAP_MAX doc asserts an unenforced invariant. _advisory_requests collides conceptually with the adjacent publish_advisory_requests and duplicates _requests apart from two constexpr flags. CachedReader::warm now repeats gather's body almost verbatim, and Transfers::new's new capacity checks restate validate_mailbox's arithmetic in a second layer without naming it. open_readonly_view's .ok() silently drops the reopen failure — the one place the fix discards an error.

Positives. The GraphKind filter change correctly adopts the exact expression already used at runtime_core/model.rs:480 and removes two hard-coded five-kind lists, so the PR reduces duplication there. The hand-rolled /proc/self/fd reopen is not a duplicate of eos::direct_reopen (that adds O_DIRECT, which cannot back an mmap), and map_fd has no existing counterpart. The prefetch_rows_loaded counter survives its move with the metric name intact, and the new tests follow the file's existing temp-file/Plane/Stats conventions with a reused helper rather than a new harness. Nothing blocking in this lens.

#10 [high] Report index: rule citations per finding, compat check, and review coverage

Consolidated citation index for the report writer, so each finding can cite a rule without re-reading the docs. All line numbers verified in this session.

Charter (read_charter), "Code Review Standards": "Supported matrix & compatibility: Check interactions across every supported model, cache scheme, parallel layout, multi-host setup, and hardware target named in the docs." → supports the Windows-twin finding (entry 1). Charter, "Standards & Contributions" / "What gets merged": PRs must address a maintainer request, a reproducible bug, a measured issue. The PR does (it fixes #481 and #519's rebase), so this is satisfied — do not cite it against the PR.

AGENTS.md:

No design doc states a wait/backoff policy today (docs/runtime-core-design.md is the natural home; entry 3 relies on this). Metric names stay valid: docs/cli-design.md:816 and helios/README.md:671 both name flare_engram_prefetch_rows_loaded_total / flare_engram_prefetch_errors_total, matching the counters the PR preserves (entry 7).

Coverage statement for the report: every changed file read in full at the PR head — helios/src/engram.rs (1283 lines), helios/src/engram/reader.rs (relevant regions plus the whole diff and its tests), helios/src/runtime_core/engram.rs (all 792), ignition/components/ngram_delivery.py (176, whole file). Callers followed for behaviour changes: Requests::read (only production caller is the Gather arm, engram.rs:654), next_reader_action (:388-415), Reader::warm (:1293-1304), Transfers::new/enqueue (:816-894, :923-990), Shared::with_readers (:566-715), runtime_core/model.rs:478-500,830-900, windows.rs (whole), ignition/components/engram.py:200-283. Eight scratchpad notes: 2 should-fix (entries 1, 2), 4 nits (3, 4, 6, 7), 2 positives/coverage notes (5, 8). Nothing blocking.

#3 [medium] Nit: WaitBackoff is a third hand-rolled spin-then-park policy with no cross-reference to the other two

helios/src/engram.rs:325-377 adds a third hand-rolled spin-then-park policy in helios:

  1. WaitBackoff (new, :354-377): 4096 spin_loop() rounds, then thread::sleep(25us * n).min(250us); Windows spins.
  2. server/runtime.rs:1176-1182: if !executor.park() { spin_loop() } thread::yield_now().
  3. execution/threaded.rs:65-88 spin_wait_until: 32 fast spins, then spin until HANDOFF_POLL (500us, threaded.rs:24), then yield_now; receive (:34-59) is the same shape.
  4. runtime_core/persistent_worker.rs:26-29,507-512: WORKER_DRAIN_SPIN_POLLS = 64 then WORKER_DRAIN_POLL_INTERVAL = 1ms.

Note the PR did not introduce the first version of this: #519 (open, PR by peperunas) added SPIN_ROUNDS/NAP_GROWTH/NAP_MAX/yield_core at helios/src/engram.rs with exactly these constants, and this PR adopts that code (and, per the PR body, fixes #519's rebase defect). So the duplication is inherited, not invented here — but this PR is where it lands on main, and it lands as a third policy with no stated relation to the other three.

Observed, verifiable deltas from precedent: the neighbours park with yield_now() (no timer) or a wall-clock-bounded poll; this one uses thread::sleep, so the wait is subject to Linux timer slack on the 25-75us rungs (the ramp only reaches NAP_MAX after ~10 rounds), while spin_wait_until documents its reason for each rung (threaded.rs:66, :82-86). WaitBackoff::step also has no elapsed-time bound at all, so a caller that keeps getting WaitReady sleeps forever with no diagnostic and no metric.

Where the reviewer should point: NAP_MAX's doc (:330-331) asserts "under one decode step" — an invariant nothing enforces and nothing measures (see #519's review round: flare_replay_readiness_wait_nanoseconds_total is the counter that would show the cost). Docs: docs/runtime-core-design.md is the place a shared wait policy would be stated; no design doc names a wait policy today.

Recommendation (nit/should-fix depending on owner appetite): either reuse threaded::spin_wait_until-style bounded poll, or state in one place (a doc comment on WaitBackoff) why Enram's reader uses sleep rather than the two existing mechanisms, and reference the other two so a future reader is not left reconciling four policies.

#5 [medium] Note (positive): the GraphKind filter change correctly adopts the existing model.rs:480 precedent

Two distinct points, both verified in the code.

(a) The GraphKind::try_from(...).is_ok_and(crate::engram::consumes) filter is the right de-duplication — and it is now the shared pattern. Before: helios/src/runtime_core/engram.rs:221-231 and :327-331 each hard-coded matches!(g.kind.as_str(), "prefill" | "terminal_prefill" | "decode" | "speculative" | "mixed"). After: both sites use the same two-line expression (:224, :333), and crate::engram::consumes (helios/src/engram.rs:1011-1021) has a third caller in runtime_core/model.rs:480-481 which already used this exact expression before the PR. So the PR brings runtime_core/engram.rs into line with the existing precedent at model.rs:480 — that is correct and should be recorded as a positive, not a finding.

Note for the other reviewers: the try_from half is not dead. Unknown kinds are rejected earlier when the manifest is decoded (GraphKind::try_from(...).unwrap() at runtime_core/protobuf.rs:886, :909, selection.rs:216), so the is_ok_and cannot fail here in practice; it exists only because consumes takes a typed GraphKind. A tiny alternative would be consumes over &str to drop the redundant parse, but that would move away from model.rs:480's precedent, so keeping it is right.

(b) One remaining hard-coded kind list in the same file, which the PR left alone. Not a finding against this PR (it is pre-existing and outside the diff), recorded only so the reviewers do not re-flag it as newly missed: helios/src/runtime_core/selection.rs:318 still has matches!(g.kind.as_str(), "init" | "restore" | "snapshot" | "resume"). That is a different set (lifecycle kinds, not Engram consumers), so it is correct that it was not folded into consumes.

#6 [medium] Note: reader.rs /proc/self/fd reopen has no reusable precedent; one silent fallback (ok()) drops the cause

Three helpers were introduced inside ResidentMapping::new (helios/src/engram/reader.rs:106-177) for the pre-6.7 EPERM fix. Checked each against the closest existing mechanism:

Would have been a duplicate, and is not: the PR description says the read-only reopen uses O_RDONLY | O_CLOEXEC. The shipped code (open_readonly_view, reader.rs:108-111) is File::open(format!("/proc/self/fd/{fd}")) — std's File::open sets O_CLOEXEC by default and read-only, so the flags named in the description are what the code actually does; the description just does not match the source text. Not a defect, but worth telling the author: a reviewer reading only the description will look for OpenOptions::custom_flags.

Precedent that exists and was not reused: eos/src/unix.rs:60-65 already exposes direct_reopen(file) — literally direct_file(&format!("/proc/self/fd/{fd}"), false). It is not reusable here: it adds O_DIRECT, and an O_DIRECT descriptor cannot back a mmap. So the PR correctly hand-rolls the reopen. Recorded so the next reviewer does not ask for it. Related pre-existing duplicates of the /proc/self/fd reopen idiom (eos/src/unix.rs:62, heliopause/src/export/archive.rs:350, heliopause/src/export/io.rs:777, helios/src/runtime_core/archive.rs:566,666, helios/src/core/container.rs:730) are all direct-I/O or path-only uses; none is an mmap-capable plain reopen.

Silent fallback: reader.rs:139-143 let readonly_view = if !writable { Self::open_readonly_view(file).ok() } else { None }; — the .ok() discards the reason the reopen failed and falls back to the writable fd, i.e. straight back into the pre-6.7 EPERM. AGENTS.md:185 forbids "suppress errors" and "silently substitute execution paths". The kernel-version hint on the EPERM path (:151-159) partly compensates by naming /proc/self/fd, but it cannot say why the reopen failed (e.g. procfs not mounted, fd closed, permission). This is the one place in the fix where an error is dropped. Severity: nit — procfs is effectively always present on a Linux box that mounts the NVMe core, and the fallback is the pre-PR behaviour, so nothing regresses; but .map_err(|e| format!("reopen resident embedding table read-only: {e}")) carried into the hint string would cost one line and keep the cause.

map_fd helper (:113-129) vs crate::os::map_host (eos/src/unix.rs:85-103): different jobs (MAP_SHARED on an fd vs MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE anonymous plus MADV_HUGEPAGE), so no duplication. eos has no shared mmap-a-file helper, so this helper has no precedent to reuse. Fine as written. Also cfg(target_os = "linux") is used rather than the file's own #[cfg(unix)] convention (reader.rs:19, 100, 179, 186, 395) — correct, because /proc/self/fd is Linux-only and the fallback keeps macOS building, but it does introduce a second cfg vocabulary in a file that used only unix/windows. Nit at most.

#7 [medium] Nit: CachedReader::warm now copies gather's body; Transfers::new restates validate_mailbox's capacity math

Two duplicated bodies inside one PR, both checkable from the code:

1. warm was un-chunked; gather was already chunk-free but bounded. After the change (helios/src/engram/reader.rs:1081-1140) CachedReader::warm is a chunk loop whose body is a near-verbatim copy of CachedReader::gather (:1001-1079):

The only real differences are insert_advisory vs insert, "copy into output" vs nothing, and the new prefetch_rows_loaded bump. That is a lot of repeated index arithmetic (count * weights + index * scales appears in both) for two functions that must stay in agreement about the workspace layout. Not newly wrong — warm already duplicated gather before this PR — but the PR deepens the copy by ~40 lines instead of factoring the shared "miss → disk gather → split into w/s" tail into one helper taking a closure for the insert. Given AGENTS.md:192-193 ("Refactoring must directly support the requested behavior or remove a demonstrated source of defects or cost"), it is defensible either way; flagging as a nit because the duplicated miss_output indexing is where a future width change would desynchronize.

2. Transfers::new mailbox capacity checks (:843-882) restate validate_mailbox (runtime_core/engram.rs:272-301). The PR adds required-bytes checks at load time for the request mailbox (:848-857) and prefetch mailbox (:866-874) that mirror, in a second place and with different arithmetic, runtime_core/engram.rs:287 mailbox.shape[0].checked_mul(8) != Some(mailbox.nbytes) and :303-311/:313-322 min_request_len = max_staged_rows + 1 / max_prefetch_len = max_staged_rows + 2.

The two disagree in scope on purpose (runtime_core validates the declared shape against the max staged rows across all cores; engram.rs validates the mapped buffer's byte length against max_tokens * heads computed from the shared index), and Transfers::new is the layer that actually has the address, so having a check there is right and closes a real gap (address + nbytes - 8 on an undersized mailbox). Recording it as a nit only: if the two ever drift, the symptom is a startup error whose message points at the wrong layer ("smaller than staged capacity" vs "invalid mapped n-gram request mailbox"). A one-line comment in Transfers::new naming the runtime_core check as its twin would remove the cost.

Checked and found consistent: prefetch_queue_bytes (engram.rs:212-224) budgets cap * 8 per table; max_prefetch_len is max_staged_rows + 2 and cap = len - 2, while warm now chunks by max_rows so the queue no longer needs to hold a whole warmed step — the description's "silently dropping tail rows" defect is genuinely fixed for the queue too, not just the disk read. prefetch_rows_loaded moved from Reader::warm (reader.rs:1295-1303, removed) into CachedReader::warm (:1133-1136) per chunk, so the counter still counts rows and the metric name in docs/cli-design.md:816 and helios/README.md:671 stays accurate.

#4 [low] Nit: _advisory_requests duplicates _requests and sits beside the already-named publish_advisory_requests

Two separate things share the name and neither references the other:

  1. ignition/components/ngram_delivery.py:47 — @torch.library.custom_op("flare::publish_advisory_embedding_requests") / fn publish_advisory_requests, which publishes already-hashed ids to an advisory mailbox. Called from engram.py:283 (PreparedEngram.publish_lookahead).
  2. ignition/components/ngram_delivery.py:78 — NEW @torch.library.custom_op("flare::ple_advisory_requests") / fn _advisory_requests (leading underscore, unlike its siblings publish_requests :37 and publish_advisory_requests :48), which hashes and then publishes.

Naming: the existing precedent for "hash + publish" is flare::ple_requests/_requests (:59-75) — private, underscore, PLE-specific; the new op correctly mirrors that. The existing precedent for "publish to an advisory mailbox" is the public publish_advisory_requests. The new name _advisory_requests is neither: dropping "publish" and "embedding" makes it read like the advisory sibling of _requests, which it is, but it collides conceptually with publish_advisory_requests two definitions above, and the two ops differ only in whether hashing happens first.

Duplication inside the new op: _advisory_requests (:84-89) is _requests (:65-69) with the two lines _copy_requests[...](ids, mailbox, mailbox, n, 256, False) → (ids, live_rows, mailbox, n, 256, True) _publish[...](mailbox, mailbox, sequence, ..., False) → (mailbox, live_rows, sequence, ..., True) swapped for their HAS_LIMIT/HAS_COUNT=True variants. The kernel bodies already take the flag as tl.constexpr (_copy_requests :18-25, _publish :29-33), so one custom op with a live_rows: Optional[Tensor] (or a bool constexpr argument) would cover both without a duplicated op + duplicated fake registration + duplicated wrapper.

Severity: nit. Not a defect; booking it because the lens asks whether existing helpers were reused. Whether it matters depends on whether anything other than publish_lookahead will ever call the PLE advisory op — if it is one call site, the two-op split is cheap and the names are the real cost.

#8 [low] Note: remaining checks came back clean (test conventions, helpers, doc style)

Verified in the code, recorded so the summary is honest about coverage rather than implying no checks were made.

Nothing blocking found in my lens beyond the Windows twin (entry 1). The PR for the most part reduces duplication (the GraphKind filter) and adds an abstraction that has an exact precedent (publish_lookahead on PreparedEngram) — its defect is which buffers it allocates, not that it invents a new interface.