Opened by a workflow run, Dec 4, 2026 12:28 PM EST. decide malicious: all_clear (100%): No malicious content found
explore
Author: lukealonso (COLLABORATOR, charter-named priority contributor, 51 merged PRs in 180 days; de-facto sole owner of the AsyncTransfer / teardown / CopyEngineGate area); Discord lukealonso Motivation: On 4-GPU PCIe boxes, serving with the prefix cache's host offload enabled deadlocks: the Copy Engine gate only recognises graphs with explicit peer copies, so kernel-based peer-to-peer graphs slip past it and transfers collide with them, hanging the GPUs at 100 % with no error. This PR widens that detection, and also repairs three further latent defects in model teardown, asynchronous extent transfers, and startup error handling. Scale: +1973 / −221 lines in 16 files Proposal:
- Split
NativeResourcesintopeer_copy_graphsandpeer_access_graphs(peer copies, memsets, kernel args/globals/inline addresses, indirect peer-pointer tables found by a new 8-byte payload scan) and gate the wider set on single-host multi-rank hosts that lack all-pairs NVLink, while keeping the strict predicate forExecution.async_transfersvalidation. - Replace sequential reverse-rank teardown with a three-phase barrier: drain +
cuCtxSynchronizeeverywhere, then joinengram.clear()/offload.reset()while mailboxes are live, then destroy contexts in reverse order; leak everything if any rank fails to drain. - Fix
IoUringBackendSQE stranding (EINTRretry,flush_queued_sqes,pending_submissions()), never clobber completion slots after a hardware-signaledcuStreamWriteValue64_v2, and labelflare_async_transfer_*metrics with true global rank ids; extendAsyncTransfer.tlato 16 integers. - Make
Reply::StartedcarryResult<()>so a peer whosefinish_startupfails still answersDrain; add aRankWedgeWatchdogand one shared drain deadline. Touches: - helios/src/runtime_core/{mod,model}.rs (+650/−19, +204/−24) — gate predicate, payload scan, three-phase teardown
- helios/src/execution/threaded.rs (+552/−64) — watchdog, startup drain handshake
- helios/src/async_transfer/{worker,scheduler,io_backend}.rs + server/metrics.rs — SQE flush, fault sentinel, rank labels Related items:
- #722 helios: TP4 serving hangs under --prefix-cache-memory on SM120 PCIe (open): the P1 bug this fixes, from external reporter egtoken-ai on release 0.5.3
- #721 helios,flare-cli: harden AsyncTransfer startup, DMA and teardown lifetimes (merged): merged hours earlier by the same author; #727 rewrites its teardown, metrics label and guards — and fixes the wrong-rank-label bug #721 introduced
- #628 helios: gate offload Copy Engine batches during peer-copy graphs (merged): source of the narrow
peer_copy_graphspredicate that #722 measures as covering 32/177 graphs - #711 helios,...: add domain-agnostic AsyncTransfer primitive (merged): the runtime cluster 3 builds on
- #726 helios: overlap startup allocation... (open, same author): sibling touching
release_execution_resources/prepare_async_transfersLink: https://github.com/NVIDIA/hyperflare-inference/pull/727 Autobot comments: The "measured live TP4" evidence is not the #722 reproduction (13k tokens/4G budget/135 graphs vs 32k tokens/256G/177 graphs with a different scheduler policy), and no patched-binary run exists on the reporter's workload; detection correctness rests on a pure-policy unit test and one live run, since the author had no core combiningasync_transferswithoutNode::Copy(Memory::Peer). The watchdog's remedy isstd::process::abort()after ~150 s — a bounded crash, which the description calls "bounds wedged-rank hangs" without saying the process dies (and which sits against the charter's root-cause rule). Cluster 3 fixes #721, merged the same day, including a Prometheusrank-label semantics change that will silently shift existing dashboards; on a failed drain the teardown now deliberately leaks CUDA/host memory to process exit. Declared unrun: SM103/SM121, multi-host RoCE, Kani, and 6 frontend template tests that also fail inside the cited "1,920 passed" run. Two CI workflow edits in the diff are not in the 16-file list (likely base drift). No reviews, comments, labels or CI result yet; the #722 reporter has not engaged.
Value Proposition
Value Proposition — PR #727 (helios: gate PCIe peer-access graphs…)
Charter alignment. The motivating report, #722, is a reproducible priority:P1 deadlock in shipped flare 0.5.3 on 4× SM120 PCIe under --prefix-cache-memory — squarely inside "What gets merged" (reproducible bug) and inside the charter's target hardware (captured-graph serving on SM120/SM121). The gate is topology-derived (copy_gate_policy, NVML P2P_CAPS_INDEX_NVLINK) rather than a per-model branch, and it explicitly preserves NVLink SM-P2P, which respects "keep the runtime small and model-agnostic." Two tensions are real: RankWedgeWatchdog ends in std::process::abort() after TIMEOUT + 30 s (threaded.rs:1027), a mitigation above #722's root cause that sits awkwardly with "fix the root cause"; and the PR concedes SM103/SM121 hardware and multi-host RoCE were never run, against the charter's supported-matrix expectation.
Novelty & status. Neither obsolete nor superseded. #722 is still open and latent since #628; no competing PR claims it; siblings #723/#726 don't cover it. But this is a same-day self-follow-up: it re-fixes defects #721 introduced hours earlier (SQE flush, DMA fault sentinel, the .enumerate() rank label at pr/721 metrics.rs:1557) and replaces #721's two-phase teardown. Useful, but two passes over the same code in 24 h by the author of the code being fixed, with zero independent review, is genuine maintenance churn.
Value vs cost. Beneficiaries are concrete: PCIe multi-rank operators exposed on 0.5.3 today, where the runtime currently hangs past its own 120 s deadlines. Evidence is uneven, though. The #722 fix is backed by tests of a pure function over synthetic booleans plus one live run that is not the reproduction (13k tokens/20-way/4G/135 graphs vs 32k/c4/256G/177 graphs), with no patched-vs-unpatched comparison. Clusters 2–4 have no external report at all. Operator-visible changes — rank label semantics, deliberate resource retention until exit, a ~150 s abort — are absent from the description, and the load-time scan over every 8-byte word is unquantified.
Needed: split the #722 cluster from the three self-found clusters; a patched run on #722's workload; document the abort, the leak, and the metrics-label change; quantify scan cost. Per #229, spell this out rather than closing.
Verdict: Worth it with changes — land the #722 gate promptly (release exposure), with the above conditions.
Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.
Classify intake
Selected: triage:review, priority:P1, bug, performance
Threshold: 65%
Triage
- [✓]
triage:review: 99.7% -
triage:validation: 0.1% -
triage:design-review: 0.0% -
triage:investigate: 0.0% -
triage:verify-for-closure: 0.0% -
triage:integration: 0.0% -
none: 0.0% -
triage:partial: 0.0% -
triage:superseded: 0.0%
Priority
- [✓]
priority:P1: 87.2% -
priority:P2: 11.8% -
none: 1.0%
Type
- [✓]
bug: 98.4% - [✓]
performance: 65.1% -
community: 26.9% -
duplicate: 1.1% -
enhancement: 0.3% -
documentation: 0.0%
Area
-
area:api: 37.8% -
area:memory: 37.8% -
area:engram: 32.1% -
area:caching: 24.5% -
area:preparation: 16.5% -
area:selene: 9.5% -
area:kernels: 6.8% -
area:scheduling: 3.3% -
area:rocenante: 0.9% -
area:packaging: 0.8% -
area:orbit: 0.4%
Model
-
model:glm-5.3: 6.0% -
model:deepseek-v4: 2.3% -
model:deepseek-v4.1: 1.6% -
model:kimi-k3.1: 0.5% -
model:mimo-v2.6: 0.3% -
model:qwen3.8-flash-next: 0.3% -
model:muse-glimmer: 0.2% -
model:gemma4: 0.1% -
model:inkling-small: 0.1% -
model:qwen3.8-27b: 0.0% -
model:nemotron-3.5-bolt: 0.0%
Apply Labels (Intake)
Applied: +triage:review, +priority:P1, +bug, +performance
Subtraction and simplicity
Subtraction & Simplicity audit — PR #727 (head 224fb40)
Scope read at head: runtime_core/{mod,model,payload,serving}.rs, async_transfer/{io_backend,worker,scheduler}.rs, execution/threaded.rs, server/metrics.rs (full diffs + targeted reads). Caveat: the local main is stale, so worker.rs/io_backend.rs/scheduler.rs show as "new files" in the raw diff; I scoped against real head line numbers, not the diff offsets.
The PR is mostly the right shape for a concurrency fix — phases documented in prose, pure policy function, testable seams. But it carries four genuinely free deletions and four wrapper/duplication clusters that add no behaviour.
High value — delete outright
1. stop_rank_workers is a test-only wrapper around two let statements
helios/src/runtime_core/mod.rs:2035-2042:
fn stop_rank_workers(
stop_persistent_worker: impl FnOnce() -> Result<()>,
stop_async_transfers: impl FnOnce() -> Result<()>,
) -> bool {
let worker_ok = stop_persistent_worker().is_ok();
let transfers_ok = stop_async_transfers().is_ok();
worker_ok && transfers_ok
}
Its single production caller (mod.rs:2055-2058) is inside a &mut self method, so the two-closure signature buys nothing over inline code:
let worker_ok = self.stop_persistent_worker().is_ok();
let transfers_ok = self.stop_async_transfers().is_ok();
if !(worker_ok && transfers_ok) { ... }
Deleting it also deletes the 27-line unit test stop_rank_workers_evaluates_both_stops_without_short_circuiting (mod.rs:2541-2567), which only exercises the wrapper. The real invariant (non-short-circuit evaluation) is better asserted through drain_execution_context, where a failure actually matters.
2. RankWedgeWatchdog::stop_and_join is a byte-for-byte duplicate of its Drop
helios/src/execution/threaded.rs:738-753:
fn stop_and_join(mut self) {
self.state.stop();
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
impl Drop for RankWedgeWatchdog {
fn drop(&mut self) {
self.state.stop();
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
stop_and_join(self) sets thread = None, then self is dropped and Drop::drop runs the same body as a no-op. stop_and_join is pure redundancy: self.watchdog.take() (the existing call site at threaded.rs:1231-1233) already drops and joins. Delete the method and the 3 test calls (threaded.rs:4045, 4074, 4103 region) become drop(watchdog).
3. WatchdogCallGuard::enter's keep_busy argument is dead at both call sites
helios/src/execution/threaded.rs:611-619:
impl WatchdogCallGuard {
fn enter(state: &Arc<WatchdogState>, keep_busy: bool) -> Self {
Both callers immediately overwrite the field:
threaded.rs:1070WatchdogCallGuard::enter(&self.watchdog_state, !self.pending.is_empty()), thenthreaded.rs:1126wd_guard.keep_busy = true;threaded.rs:1141WatchdogCallGuard::enter(&self.watchdog_state, !self.pending.is_empty()), thenthreaded.rs:1149wd_guard.keep_busy = !self.pending.is_empty();— the identical expression, so the parameter is provably inert.
Drop the parameter (enter(state)); the Drop impl already defaults to clearing busy. Six lines and one borrow-checker-sensitive argument go away.
4. Four dead public accessors on AsyncTransferRuntime
helios/src/async_transfer/worker.rs:484-507 defines name(), rank(), state(), host_pool_bytes(), device_pool_bytes(). Grep across helios/src shows:
name()/rank()— zero call sites anywhere (metrics renderss.name/s.rankfrom the snapshot).device_pool_bytes()— zero call sites.host_pool_bytes()— onlyworker.rs:1760in a unit test (assert_eq!(rt.host_pool_bytes(), 0);).state()— tests only.
AsyncTransferSnapshot (worker.rs:108-127) already carries name, rank, device_pool_bytes, host_pool_bytes, state, so the accessors are pure duplication of the snapshot surface. Delete name/rank/device_pool_bytes, keep at most state if tests need it.
High value — collapse duplicated logic
5. The async_transfers ↔ peer-copy rejection exists twice, with the same message
Load time, helios/src/runtime_core/model.rs:181-197:
fn validate_async_transfer_peer_copy_compatibility(
has_peer_copy_nodes: bool,
cores: &[Core],
) -> Result<()> {
...
if has_peer_copy_nodes && has_async_transfers {
return Err(invalid(
"Execution.async_transfers cannot accompany graphs with Copy Engine peer-to-peer copy nodes; \
in-graph demand waits cannot serialize behind CopyEngineGate without deadlocking the Copy Engine",
));
And again, reachable only if the load-time check didn't exist, mod.rs:1750-1755:
if self.has_any_peer_copy_graphs() {
return Err(invalid(
"Execution.async_transfers cannot accompany graphs with Copy Engine peer-to-peer copy nodes; \
in-graph demand waits cannot serialize behind CopyEngineGate without deadlocking the Copy Engine",
));
}
Since #727 moved validation to load time (model.rs:921-925, before prepare_offload/prepare_async_transfers), the mod.rs copy is unreachable for any core that reaches it — a dead branch carrying a duplicated 2-line string literal (the same text appears a third time in helios/manifest.md:206 (not opened)). Delete mod.rs:1750-1755 and the whole error text lives in exactly one place.
6. Two Vec<bool> + a mode flag + four accessors where one Vec<bool> + two bools suffice
helios/src/runtime_core/mod.rs:115-134 stores peer_copy_graphs: Vec<bool>, peer_access_graphs: Vec<bool>, gate_peer_access: bool, plus peer_table_allocations/peer_modules. The accessor cluster mod.rs:1588-1614 is:
pub(super) fn has_any_peer_copy_graphs(&self) -> bool { self.peer_copy_graphs.iter().any(|&has_peer| has_peer) }
pub(super) fn has_any_peer_access_graphs(&self) -> bool { self.peer_access_graphs.iter().any(|&has_peer| has_peer) }
pub(super) fn set_gate_peer_access(&mut self, gate: bool) { self.gate_peer_access = gate; }
pub(super) fn graph_uses_copy_gate(&self, index: usize) -> bool {
if self.gate_peer_access {
self.peer_access_graphs.get(index).copied().unwrap_or(false)
} else {
self.peer_copy_graphs.get(index).copied().unwrap_or(false)
}
}
But peer_access_graphs[i] implies peer_copy_graphs[i] by construction — node_peer_usage (mod.rs:303-307) computes let access_peer = copy_peer || .... And peer_copy_graphs is only ever consumed as "any" (model.rs:924, mod.rs:1750). So the minimal state is:
peer_access_graphs: Vec<bool>,
has_peer_copy: bool, // set during prepare_graphs
gate_peer_access: bool,
graph_uses_copy_gate(i) = if gate_peer_access { access[i] } else { access[i] && is_copy[i] }
— which still needs per-graph strictness… if the strict answer must stay per-graph, keep one Vec<u8> of bitflags (COPY=1, ACCESS=2) and drop one Vec<bool> + one accessor. Either way set_gate_peer_access (a one-field setter broadcast from model.rs:936-939) is unnecessary: pass the boolean down as a parameter of prepare_graphs, or store it once on NativeModel (which already holds copy_gate) instead of replicating it into every NativeResources.
7. node_peer_usage's allocations parameter and is_direct_peer closure are derivable
helios/src/runtime_core/mod.rs:278-296:
fn node_peer_usage(
node: &Node,
function_modules: &HashMap<usize, &str>,
allocations: &HashMap<String, Storage>,
peer_refs: &HashSet<String>,
peer_ref_intervals: &[(u64, u64)],
peer_modules: &HashSet<String>,
) -> (bool, bool) {
let is_direct_peer = |reference: &Reference| {
allocations
.get(&reference.allocation)
.is_some_and(|storage| matches!(storage.memory, Memory::Peer))
};
collect_peer_referencing_allocations (mod.rs:232-236) already builds exactly this direct-peer set as the seed of peer_refs:
let mut peer_refs: HashSet<String> = allocations
.iter()
.filter(|(_, storage)| matches!(storage.memory, Memory::Peer))
.map(|(name, _)| name.clone())
.collect();
Returning that seed alongside the closure result gives is_direct_peer(x) ≡ direct_peers.contains(&x.allocation). Six parameters → five, one closure and one HashMap<String, Storage> dependency removed from the graph-walking hot loop (called once per node across 135 graphs/rank).
8. Identical interval-collection closure written twice
helios/src/runtime_core/mod.rs:160-174:
fn peer_address_intervals(allocations: &HashMap<String, Storage>) -> Vec<(u64, u64)> {
let intervals = allocations
.values()
.filter(|storage| matches!(storage.memory, Memory::Peer) && storage.nbytes > 0)
.filter_map(|storage| {
storage
.address
.checked_add(storage.nbytes as u64)
.map(|end| (storage.address, end))
})
.collect();
merge_sorted_intervals(intervals)
}
and mod.rs:258-269, which repeats the identical filter(nbytes > 0).filter_map(checked_add → (address, end)) chain over peer_refs. One helper fn intervals<'a>(it: impl Iterator<Item = &'a Storage>) -> Vec<(u64,u64)> serves both; peer_address_intervals becomes a one-line caller.
9. collect_peer_referencing_allocations runs the same work twice per rank
mod.rs:994-998 (end of prepare_kernels) and mod.rs:1117-1121 (start of prepare_graphs) both call it with byte-identical arguments — (core, &self.allocations, &self.peer_table_allocations) — each time re-running the transitive-relocation fixpoint (mod.rs:242-257) and the interval merge over every peer allocation. Compute once (after load_payload finishes writing peer_table_allocations, at mod.rs:934) and store the pair on self. On the SM120 TP4 core this is 1.92 GiB of peer views re-scanned per rank per phase.
Medium value — generic wrapper that isn't generic
10. teardown_model_ranks — one instantiation, five parameters, four closures
helios/src/runtime_core/model.rs:1275-1303:
fn teardown_model_ranks<R>(
ranks: &mut Vec<R>,
mut drain_rank: impl FnMut(&mut R) -> bool,
release_host_subsystems: impl FnOnce(),
mut destroy_rank: impl FnMut(&mut R) -> bool,
mut release_rank_context: impl FnMut(R),
) -> bool {
It is called exactly once, with R = NativeResources (model.rs:1309-1320), and the only reason for R + the four closures is to dodge the borrow checker so engram/offload can be captured — which is why Drop needs the awkward preamble at model.rs:1307-1308:
let engram = &mut self.engram;
let offload = &mut self.offload;
The three phase bodies are three plain loops (&mut ranks.iter_mut().rev() ×2, while let Some(rank) = ranks.pop()); as an inherent method fn teardown(&mut self) -> bool on NativeModel the closures, the R generic, the impl Fn* signatures and the borrow-dodge preamble all disappear, and the ordering — the actual content of the fix — stays visible as straight-line code between two comments. The dedicated 40-line teardown_model_ranks_enforces_three_phase_cross_rank_barrier test (model.rs tests, ~line 1700 region) then tests the real method instead of a reified event log of a mock.
11. payload.rs: two Chunk fields that encode data already present
helios/src/runtime_core/payload.rs:212-213 adds
alloc_index: usize,
alloc_offset: usize,
threaded through all three Chunk construction sites (payload.rs:278-279, 301-302, plus the test at 509-510) solely so the reader thread can call contains_interval_address(bytes, peer_intervals, Some(chunk.alloc_offset)) and flag peer_flagged[chunk.alloc_index] (payload.rs:378-387). But alloc_offset is just offset + start relative to allocation.address, and destination already equals allocation.address + offset + start — i.e. both fields are recoverable as destination - allocation.address and the owning allocation. A single peer alloc base/Option<usize> per chunk (or storing Option<(usize /*alloc*/, usize /*offset*/)> as one Option so the "scanned" state is unrepresentable when there is no peer interval) achieves the same with one added field. Related: peer_flagged: Vec<AtomicBool> (payload.rs:310-314) is a full-length atomic array for at most a handful of hits; the reader threads already share a Mutex (available), so a small Mutex<HashSet<usize>> (or Vec<AtomicBool> only when !peer_intervals.is_empty(), which is the common case today) is simpler to reason about.
12. queued_sqes bookkeeping repeated four times in one function
helios/src/async_transfer/io_backend.rs:243-281 (cancel_and_drain) repeats
self.queued_sqes = self.queued_sqes.saturating_sub(submitted);
at four sites around self.ring.submit() / submit_with_args. A private fn submit_now(&mut self) -> io::Result<usize> that submits and decrements once collapses the loop and removes the risk of a fifth site forgetting the decrement — the very class of bug this PR is fixing.
Already lean — no action
copy_gate_policy(model.rs:166-175) is the right decomposition: a pure 4-bool function with a table-driven test (model.rs:1653+). Keep.flush_queued_sqes(&mut usize, impl FnMut() -> io::Result<usize>)(io_backend.rs:186-201) is a deliberate, testable seam (its unit test covers EINTR,Ok(0), andEBUSY). Keep.finish_startup_handshake/cleanup_failed_startup(threaded.rs:1344-1413) are a genuine deduplication within the PR — they replace ~35 lines of inline abort-prone cleanup and share theReply::Started(Result<()>)channel. Keep.best_effort_drain_peers' shared deadline (threaded.rs:1292-1306) is a net subtraction (oneInstanthoisted out of the loop). Keep.render_async_transfer_snapshotstakes snapshots, not runtimes (metrics.rs:1540), which is why it is testable without CUDA. Keep.
Worth a second look (not verified enough to assert)
AsyncTransferSnapshot::stateandextent_count(worker.rs:112-115) are filled and carried but never rendered byrender_async_transfer_snapshots— if no JSON status endpoint consumes them they are fields with no reader.Scheduler::{mark_io_flushed, is_io_flushed, unflushed_io_count, hw_signaled_faulted_dma_count}exist to feed the TLA+ projection; if the conformance runner only needs one of them, the other accessors are verification-only surface on a production type.- Two CI-workflow edits appear in the raw diff but not in
pr_files— base drift, not this PR; excluded from this audit.
Net: the four free deletions (§1–§4, ≈80 lines + 27 lines of wrapper test) and the two duplication collapses (§5 duplicated rejection, §8 duplicated interval closure) are pure wins with no behavioural change; §6/§7/§10 remove the state/indirection that a reviewer has to hold in their head to check the #722 fix, which is the part of this PR most at risk of being mis-reviewed.
Gates and contracts
Contracts, Charter & Verification Gates Audit — PR #727
Verdict: No contract, vendored-file, or mandatory verification gate blockers.
Four hard gates checked against docs/design-review.md (incl. the Layer 1–3 testing hierarchy and Mandatory Enforcement section), AGENTS.md, docs/verification.md, docs/core-format-design.md, docs/scheduling-theory.md, docs/scheduling-runtime-design.md, and the head diff.
Gate 1 — Signed core-format / wire / captured-graph / public contract boundaries: PASS
- No new captured-graph operation family or graph kind.
docs/design-review.md:22-26requires prior owner approval for a new captured-graph operation family, and this PR adds none. TheCopyEngineGatechange is classification of existing graph content, not a new op contract:node_peer_usage()(helios/src/runtime_core/mod.rs:278) inspects existingNode::Copy, memsets, kernel arg/attribute relocations, and module globals;peer_copy_graphs/peer_access_graphs(mod.rs:119-122, pushed at:1478-1479) are internalVec<bool>fields onNativeResources, not metadata or wire fields.graph_uses_copy_gate()(mod.rs:1608-1614) is a selector over those internal flags; the only consumer-side change ishelios/src/runtime_core/serving.rs:59(peer_copy_graphs.push(self.graph_uses_copy_gate(index))). - No Protobuf/wire change. Gate 1's trigger is "new proto/core-format/captured-graph enums, wire kinds." None of the 16 changed files is a
.protoorformat.rs(not opened)/schema file;helios/src/runtime_core/protobuf.rs(not opened),core/schema.rs(not opened),core/protection.rs(not opened),core/export.rs(not opened), andcore/conversion.rs(not opened) are not inpr_files.Core,Allocation,Execution.async_transfers,ExternalExtentTable, andRangeBody.external_extentskeep their recorded shapes. Principle 13 (design-review.md:116-123) — load previously exported cores without re-export — is therefore not stressed: no new required field, no reserved-identifier removal, no ABI gate added. - The signature-verified payload path is reused, not weakened. The new
payload::loadscan (helios/src/runtime_core/payload.rs:246-260, scan at:377-386) reads only bytes the loader has already authenticated and is about to copy; it feeds the pre-existing relocation collector (mod.rs:227-269, call at:1036) rather than replacing descriptor-based validation.contains_interval_address/peer_address_intervals/merge_sorted_intervals(mod.rs:148-269) are additive helpers with unit coverage (mod.rs:2236peer_usage_tests,:2287,:2340-2344). - Normative docs are consistent with the code, not contradicted. The PR updates the docs it contradicts:
docs/prefix-cache-offload.md(diff at theCopyEngineGateparagraph) now states both trigger sets — explicitNode::Copy(Memory::Peer)and single-host PCIe multi-rank graphs whose kernels, memsets, globals, or indirect pointer tables reachMemory::Peer— replacing the old peer-copy-only framing. Verified on disk atdocs/prefix-cache-offload.md:994-1010.docs/runtime-core-design.mddiff adds the three-phase teardown, the load-timeasync_transfers+ peer-copy rejection, and theExecutionError::Drain/resource-retention semantics; on disk atdocs/runtime-core-design.md:~700-750.- Neither
docs/scheduling-theory.mdnordocs/scheduling-runtime-design.mdstates any invariant aboutCopyEngineGate, peer access, or teardown ordering (searched: zero matches forCopyEngineGate,async_transfers,peer_access). Nothing normative was contradicted without an update.
- No new CLI flag, config key, or environment-variable behavior switch (
AGENTS.md:452-477).ChannelConfig.rank/AsyncTransferSnapshot.rank(helios/src/async_transfer/worker.rs:92-111) carry data, not configuration. Noenv::varadded to production paths — the only occurrences in the touched area are the existing test opt-inFLARE_RUN_CUDA_TESTS(worker.rs:1353) and the conformance traceFLARE_ASYNC_TRANSFER_TRACE(lifecycle_tests.rs:454), both permitted byAGENTS.md:475-477. - No per-model branch or
supports_*flag (design-review.md:58-61). The gate is decided by a pure topology function,copy_gate_policy(local_ranks, all_nvlink, has_peer_copy_nodes, has_peer_access_graphs)(helios/src/runtime_core/model.rs:166-175), fed by a pairwise NVMLP2P_CAPS_INDEX_NVLINKquery (model.rs:132-162; the constant is the documentedNVML_P2P_CAPS_INDEX_NVLINK = 2athelios/src/nvml.rs:20-23). Nothing keys on model identity. - Public-contract note for operators (not a gate violation, but worth recording): the
ranklabel onflare_async_transfer_*changes meaning from the flat local-channel index to the true global rank id (helios/src/server/metrics.rs:1566-1567, testasync_transfer_metrics_label_true_rank_ids_not_flat_vector_indicesat:1596-1640).docs/api.md:403-415documents the series as "labeled bychannelandrank" but does not state thatrankis the global rank id. That is a documentation-precision gap on a metrics contract, not a wire/core-format violation and not a shipped-default behavior change (the previous label was a defect introduced hours earlier in #721). Raise as an editorial follow-up, not a blocker.
Gate 2 — Vendored upstream dependencies and cross-PR conflicts: PASS
- No vendored-upstream fork.
helios/native/roce_proxy.c(not opened) — the repository's vendored-artifact case — is not inpr_filesand is untouched by this PR. Nothing underhelios/native/changes. The only external dependency touched is NVML, and this repo loads it dynamically through its own wrapper (helios/src/nvml.rs, existingdevice_p2p_status/P2P_STATUS_OK), not a vendored copy. - No unmerged external recipe or PR dependency. No recipe, no
ignition/change, nolocal-inference-lab/hyperflare-recipespin. Theverification/helios-lifecycleTLA+ toolchain stays on the pinnedtla2tools v1.7.4already referenced by.github/workflows/helios-lifecycle.yml(not opened). - Cross-PR overlap is informational only. #721 (merged, same author) is the direct predecessor — this PR rewrites its teardown, metrics label, and flush path; that is a same-day self-follow-up and the diff applies cleanly on top of it. #726/#723 are sibling open PRs by the same author touching
release_execution_resources/prepare_async_transfers; if #726 lands first, the two should be serialized, but there is no textual conflict in this diff and no competing fix for #722 exists. Info / Nit only, no gate. - Note on scoping: the raw per-file diff carries base-drift from a stale local
main(it rendersasync_transfer/{worker,scheduler}.rsanddocs/TODO.txt,docs/api.md,docs/cli-design.md(not opened),docs/core-design.md(not opened),.github/workflows/*.ymlas changed).pr_files— the trustworthy scope — lists 16 files and none of those excepthelios/src/async_transfer/{io_backend,lifecycle_tests,scheduler,worker}.rs. I therefore did not attribute the workflow edits or thedocs/TODO.txt/docs/api.md/docs/cli-design.md(not opened) /docs/core-design.md(not opened) hunks to this PR. Even if they were this PR's, they are benign:helios-lifecycle.yml(not opened) addscargo test --lib --no-runandnative-serving.yml(not opened) adds a native RoCE transport test — additions to the mandatory gate suite, not removals.
Gate 3 — Mandatory verification evidence and failing tests: PASS
This change touches all three gate-requiring surfaces: scheduler/cache/worker lifecycle, GPU/VMM teardown paths, and cross-rank dispatch. Each applicable layer is satisfied and was reported in this round's evidence, with the formal artifacts present in the diff:
- Layer 3 formal lifecycle conformance (
design-review.md:209-230) — run, and the models were updated in-step.verification/helios-lifecycle/check.py --tlc-jar … --mutationsreported exit0: all 10 TLA+ models and all 9 Rust↔TLA+ conformance suites pass, including 431 observedAsyncTransfertransitions and 7,940DispatchRingtransitions. The supporting artifacts exist at head, not merely in the claim:AsyncTransfer.tlaextends to the 16-integer projection (hwSignaledFaultedat:30,FlushIoat:83,hwSignaledFaultedtransfer at:132-148, invariantsUnflushedIoBoundedAt:247-251andHwSignaledFaultedSafeAt:252-255, aggregate:279-280, projection:304);AsyncTransfer.cfg:22-23enables both.- Rust mutations for both new guards exist in
check.py:742-780(unflushed io completed ok before flush,hardware-signaled faulted dma clobbered completion slot) plus model mutations at:428-454. - The conformance harness drives production entry points, not hand-written replays:
lifecycle_tests.rs:73async_transfer_scheduler_matches_lifecycle_modelexercisesstart/enqueue/dispatch_io/mark_io_flushed/complete_io/dispatch_dma/mark_dma_faulted/begin_drain/finish_drain/fail_drain(README:368-378). - This satisfies "update the model, conformance fixture, or Kani harness to cover the added domain rather than leaving it unverified" (
design-review.md:241-246).
- Layer 1 crate/release tests — run at
--release --lockedon every affected crate:eos(12 passed),seleneandselene-managerwith--features test-support,flare,flare-cli(incl. release build and--features rocecheck),heliopausecheck,helios --features runtime-core,server --test '*', andhelios --libwithRUSTFLAGS="-D warnings"→ 0 warnings, 1,920 passed. Pythontests/cli206 passed. - New unit tests exist exactly where claimed (verified at head, not taken on faith):
mod.rs:2287/:2541(node_peer_usage_…,stop_rank_workers_evaluates_both_stops_without_short_circuiting),model.rs:1661-regioncopy_gate_policy_*plus:1670/:1709(teardown_model_ranks_*),io_backend.rs:413(not opened) (flush_queued_sqes_retries_eintr_handles_partial_submit_and_preserves_unsubmitted_count),scheduler.rs:1101(hardware_signaled_faulted_dma_suppresses_completion_slot_sentinel),threaded.rs:3498(finish_startup_peer_error_drains_mixed_peers_cleanly_without_abort) and threeRankWedgeWatchdogtests at:4019/:4054/:4083. - Cross-rank transport coordination test requirement (
design-review.md:189-194): satisfied by the mock-transport multi-peer tests exercisingclose_peers/best_effort_drain_peers/cleanup_failed_startup(threaded.rs:3322-3560), including the mixed peer-failure matrix that asserts noabort()and that every surviving peer reachesReply::Drained. - Kani (
design-review.md:221-225) — correctly not re-run, and disclosed. The PR statescargo-kaniis not onPATHand that completion/state-view validators were not modified. Confirmed: the Kani harnesses athelios/src/async_transfer/kani_proofs.rs,execution/transport.rs:219(not opened),model/*, andoutput/tagged/kani_proofs.rs(not opened) cover completion-vector validation, extent arithmetic, and command bounds — none of which this diff changes (Command/Replyinthreaded.rsare Rust-internal control-channel enums validated byDispatchRing/RankProtocolTLA+ and the observed-edge suite, not by a Kani harness).design-review.md:247-251blocks skipping applicable Kani proofs; none is applicable here. - Multi-GPU collective execution (
design-review.md:252-259): reported live —FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=2 cargo test … live_cuda_async_transfer_end_to_endpassed on SM120, and a 4-rank exported core served TP4 throughflare run(135 graphs/rank) with 20/20 requests and cleanSIGTERM(status=0). Not merely per-rank synthetic graphs. - No performance claim, so no A/B benchmark gate.
design-review.md:106-115/principle 12 requires an attributablemain-vs-branch served-workload A/B only for a performance claim. The PR states explicitly: "No throughput regression claim or speedup claim is made beyond deadlock/fault elimination." The live TP4 numbers are offered as deadlock/lifetime evidence, and the PR does not attribute any speedup to this change. Gate 3's benchmark prong is therefore not triggered. - FAILING tests on
224fb40— none that this PR introduces. The one failing set is disclosed and environmental: 6helios --libfrontend template tests fail becausetests/frontend/prepare_templates.py(not opened) gets HTTP 403 from the gated HF repometa-models/Muse-Spark-Open-816B-A42B-NVFP4. That is a checkpoint-licensing/network failure in an untouched path, present identically onmain, and it is disclosed in the description rather than hidden — satisfyingdesign-review.md:106-115("keep material failures … visible") andAGENTS.md:106-112("Never invent evidence"). It is not a gate violation. - CI status: not flagged. Per the calibration rules I will not flag "no observable CI run"; the description shows no CI failure and does not state that tests were never run — on the contrary, it enumerates the runs above.
- Declared unrun checks are appropriate and disclosed, not silently skipped: SM103/SM121 hardware, multi-host RoCE, and the unavailable core combining
Execution.async_transferswithoutNode::Copy(Memory::Peer). Of these, only the last bears on a mandatory gate, and the PR names it plainly ("No multi-GPU core combining … was available locally"), whichdesign-review.md:106-115andAGENTS.md:193-199require; it does not leave an applicable CPU check unrun (design-review.md:247-251).
Gate 4 — Material scope / claim contradictions: PASS
- No invented test or benchmark. Every named test, invariant, and file I spot-checked exists at head at the cited location (list above; plus
verification/helios-lifecycle/README.md:349-380describing the extendedAsyncTransferprojection). - No thousands of lines of unrelated standalone tooling. The 16 files are all in the change's own surface:
runtime_core(gate predicate, payload scan, three-phase teardown),execution/threaded.rs(watchdog + startup drain handshake),async_transfer(flush, fault sentinel, rank labels),server/metrics.rs, two design docs, and the matching lifecycle verification. Nothing is bolted on. - The four fix clusters are logically independent but not scope abuse. They are 4 deleted-defect classes on largely disjoint files, all four tied to the same serving path;
AGENTS.md:198-199asks a PR to have "one coherent outcome and describe its problem, resulting behavior, validation, and material limitations," and the description does exactly that for each cluster with before/after framing. - Two description gaps worth naming, neither a gate violation: (a)
RankWedgeWatchdog's terminal action isstd::process::abort()afterTIMEOUT + 30 s(helios/src/execution/threaded.rs:547-753, abort at:1027), which the description calls "bounds wedged-rank hangs" without saying the process dies — accurate but under-specified prose (design-review.md:147-162). Note this abort is strictly better than the status quo #722 documents, and the PR's actual root-cause fix is the gate widening; the watchdog is an additional bound. (b) Theranklabel semantics change noted under Gate 1. - The live-evidence workload differs from #722's reproduction (13k tokens/20-way/4G/135 graphs vs 32k/c4/256G/177 graphs). This weakens the strength of the evidence for the #722 claim; it does not make the claim absent from the diff, which is what Gate 4 targets. Belongs to the Value/Correctness lenses, not here.
Summary of what I would record, by severity
| Severity | Finding |
|---|---|
| Blocker | None. |
| Major | None. |
| Info / Nit | (1) RankWedgeWatchdog ends in std::process::abort() after ≈150 s; the description says "bounds wedged-rank hangs" without stating the process terminates — worth one clarifying sentence in the description. (2) docs/api.md:403-415 should state that the flare_async_transfer_* rank label is the global rank ID, since its meaning changed. (3) #726/#723 overlap on prepare_async_transfers/release_execution_resources; serialize if #726 lands first. |
| Note | The 6 frontend template tests failing on HTTP 403 from the gated meta-models/Muse-Spark-Open-816B-A42B-NVFP4 repo are disclosed in the "1,920 passed" run and are environmental; they do not block. Kani correctly not re-run (no applicable validator changed). |
No contract or verification gate blockers.
Code correctness
Deep Code Correctness, Invariants & Hot-Path Audit — PR #727 @ 224fb40
Partitioning applied: PR touches 16 files / ~2,100 changed lines across 3 distinct helios subsystems (async_transfer, runtime_core, execution) plus verification, so per the large-PR rule I partitioned into 3 disjoint slices and launched all three sub-agents concurrently in Turn 1. All three completed with the full 4-part protocol applied (callee/enum resolution, same-loop state-order tracing, adversarial small-N, hot-path big-O). I verified the callee citations and quotes below against the reports; findings are all read-verified at 224fb40 (no execution was possible — see limitations).
Verdict: 6 verified defects (2 Blocker-adjacent Major, 4 Major, plus Minors). The PR's headline fixes (three-phase teardown barrier, Reply::Started(Result), metrics rank label) are genuinely correct, but three of its own new mechanisms introduce worse regressions than the bugs they replace.
BLOCKER-1 / MAJOR — CloseStalled watchdog aborts a progressing teardown (regression over pre-PR behaviour)
Diff site: helios/src/execution/threaded.rs:679-687; threshold threaded.rs:1015-1020; constants threaded.rs:23-25.
Calves it must cover (opened): threaded.rs:1211-1225 (close() pending-drain loop + close_peers), threaded.rs:1256-1258 (per-peer receive(..., timeout)), threaded.rs:1278-1316 (best_effort_drain_peers), threaded.rs:594-598 (begin_close), threaded.rs:1157-1167 (frame deadline).
// threaded.rs:679-687
if closing {
let since = *close_since.get_or_insert(now);
let elapsed = now.saturating_duration_since(since);
if elapsed >= stall_timeout {
if let Some(fire) = on_wedge.take() {
fire(WedgeReason::CloseStalled { elapsed });
}
break;
}
} else {
close_since = None; // <-- reset ONLY on the non-closing branch
// threaded.rs:594-598 — begin_close is one-way, bumps activity exactly once
fn begin_close(&self) {
self.closing.0.store(true, Ordering::Release);
self.activity.0.fetch_add(1, Ordering::Release); // never read on this path again
self.wake();
}
Defect. The closing branch is a plain wall-clock timer from begin_close(). It never samples activity, and close_since is reset only in the else arm — but closing never returns to false. So the coordinator gets exactly 150 s (TIMEOUT 120 s + WATCHDOG_GRACE 30 s) of total teardown time, while its own callees legitimately permit ≈ 120 × (peers + 2) s. This is not the "zero idle CPU" criterion the PR description claims for this branch (it is only true for the busy path at threaded.rs:702-716, which does read activity).
Concrete counterexample (TP3, started == true, graceful SIGTERM). Coordinator drains two frames for 60 s (both well under the 120 s frame deadline); peer 0 takes 90 s inside drain_rank (threaded.rs:1318-1342, under its 120 s Peer::receive deadline); peer 1 takes 30 s. Total 180 s > 150 s → watchdog fires CloseStalled → std::process::abort() at threaded.rs:1027 while every stage was inside its sanctioned deadline. This is a hard abort on a legitimate-but-slow teardown and is strictly worse than the pre-PR behaviour (which simply waited).
Fix. Drive close_since off the heartbeat: sample activity on the closing branch, reset close_since whenever it changed, and record_progress() after each close() stage (after the pending-drain loop at 1216, and per peer inside close_peers at 1261). Also size the close-path timeout as TIMEOUT * (peers + 2) + WATCHDOG_GRACE, or make CloseStalled a bounded eprintln! rather than abort().
BLOCKER-2 / MAJOR — Unflushed-OK complete_io silently drops a real completion → permanent inflight_io leak and permanent FailedDrain
Diff site: helios/src/async_transfer/scheduler.rs:578-583. Callees (opened): scheduler.rs:231-243 (mark_io_flushed), :226-228 (unflushed_io_count), :259-273 (bg_*_inflight), :583/:746 (swap_remove), worker.rs:993-1001 (poll_completions → complete_io), worker.rs:1228-1233/:1242-1246 (flushed_now = unflushed_io_count() - pending_submissions()), worker.rs:814 (finish_drain requires inflight_io.is_empty()).
// scheduler.rs:578
pub fn complete_io(&mut self, op_id: OpId, ok: bool) -> Option<CompletionNotice> {
let pos = self.inflight_io.iter().position(|op| op.op_id == op_id)?;
if ok && !self.inflight_io[pos].flushed {
return None; // consumes nothing, but the backend already reaped it
}
let op = self.inflight_io.swap_remove(pos);
// scheduler.rs:231 — marks the first `count` entries in *Vec* order
pub fn mark_io_flushed(&mut self, count: usize) -> usize {
let mut marked = 0;
for op in &mut self.inflight_io {
if marked >= count { break; }
if !op.flushed { op.flushed = true; marked += 1; }
}
Defect. mark_io_flushed assumes Vec order == SQE submission order, but complete_io (:583) and complete_dma (:746) both use swap_remove, which moves the last element into the freed index — so Vec order permanently diverges from submission order after the very first completion. worker.rs:1228-1233 infers "accepted by the kernel" as unflushed_io_count() - pending_submissions() and feeds that count to mark_io_flushed, which then marks the wrong ops whenever the kernel accepts only a prefix of the staged SQEs — the exact partial-submit case this PR exists to fix. The return None then permanently strands the op because its IoCompletion was already drained from the backend.
Concrete counterexample (defaults MAX_TOTAL_IO = 32, BOUNCE_SLOTS = 16):
pop_next_io×3 →inflight_io = [A, B, C], all unflushed,queued_sqes = 3.mark_io_flushed(1)marks A;pending_submissions() == 2.- A's read fails →
complete_io(A, false)→swap_remove(0)→ C moves to index 0 →[C, B]. - Kernel accepts 1 of 2 pending →
flushed_now = 2 - 1 = 1→ marks C, not B. - B's completion harvested →
complete_io(B, true)→ok && !flushed→return None. B is never removed and no future iteration can complete it.
Observable state: B is stuck in inflight_io forever → can_release_memory() permanently false, finish_drain returns Err → ChannelState::FailedDrain → AsyncTransferRuntime::stop() (worker.rs:670-686) retains the pinned host pool, bounce pool, CUDA context and stream until process exit. Repeated across channels: a slow pinned-memory leak plus guaranteed drain failure on a healthy channel.
Fix (both needed): (a) store a monotonic seq on InflightIo at pop_next_io and have mark_io_flushed mark the count unflushed entries with the lowest seq, not the first in Vec order; (b) never discard an ok completion — complete it normally (setting flushed = true) instead of return None.
Test that encodes the bug as correct: helios/src/async_transfer/lifecycle_tests.rs:
if ok && !is_flushed {
assert!(
notice.is_none() && n.inflight_io_count() == before_count,
"unflushed IO must not complete with ok=true before kernel submission"
);
continue;
check.py's mutation ("unflushed io completed ok before flush", "if ok && !self.inflight_io[pos].flushed {", ...) only proves the early-return exists, not that the dropped completion is ever recovered. AsyncTransfer.tla's CompleteIo cannot represent this state at all (its wasUnflushed arm always decrements inDemIo + inBgIo), so the model is structurally blind to the leak.
MAJOR-3 — best_effort_drain_peers shared deadline starves later peers and leaves their threads detached
Diff site: helios/src/execution/threaded.rs:1292 (the let deadline line was moved out of the loop by this PR); caller threaded.rs:1223-1225; short-circuit at threaded.rs:1207-1210.
let deadline = Instant::now() + timeout; // threaded.rs:1292 — one budget for all peers
for peer in peers.iter_mut() {
if peer.thread.is_none() { continue; }
let mut exited = false;
while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
match receive(&peer.receiver, Some(remaining)) { ... }
}
if exited {
if let Some(thread) = peer.thread.take() { let _ = thread.join(); }
}
}
Defect. When the shared budget is exhausted, checked_duration_since returns None and the while body never executes — no receive, no exited = true, no thread.take(), no join(). The function returns (), and Drop for ThreadedExecutor → close() short-circuits at threaded.rs:1208, so there is no second attempt: the Peer is dropped with thread: Some(JoinHandle) — a detached thread, precisely what the comment at 1223-1224 says is prevented.
Concrete counterexample. started == false, 4 ranks, peer 0 answers immediately, peer 1 wedged in drain_rank for the full 120 s. At t=120 s the budget is gone; peers 2 and 3 are skipped without a single receive even if they would answer Drained in 1 ms, and their threads are never joined. The PR description advertises this change as an improvement; the previous per-peer deadline had neither starvation nor unjoined threads.
Fix. Always take()+join(), and use deadline.checked_duration_since(Instant::now()).unwrap_or(Duration::ZERO).min(MIN_PER_PEER) so no peer is ever skipped; or revert to the original per-peer deadline.
MAJOR-4 — CopyEngineGate can be silently None while the widened peer-access predicate is installed
Diff site: helios/src/runtime_core/model.rs:921-942; predicate mod.rs:1591-1614; consumer serving.rs:49-59; policy model.rs:166-175; lease user offload/copy_gate.rs:267-275.
let (gate_peer_access, enable_copy_gate) = copy_gate_policy(
model.ranks.len(), all_nvlink_p2p(&pci_bus_ids), has_peer_copy_nodes, has_peer_access_graphs);
if gate_peer_access { for rank in &mut model.ranks { rank.set_gate_peer_access(true); } }
model.copy_gate = enable_copy_gate.then(|| Arc::new(crate::offload::CopyEngineGate::new()));
Defect. copy_gate_policy computes enable_gate = has_peer_copy_nodes || (gate_peer_access && has_peer_access_graphs), but set_gate_peer_access(true) is applied to every rank whenever gate_peer_access is true. When gate_peer_access == true and enable_copy_gate == false — the case the PR's own unit test asserts (copy_gate_policy(4, false, false, false) == (true, false), model.rs:1659-1660) — every rank routes through the widened peer_access_graphs (mod.rs:1608, published as peer_copy_graphs in serving.rs:59) while model.copy_gate is None. PeerGraphLeases::new(None, peer_copy_graphs) then holds all-false entries, so no graph gates and offload batches never pause — the #722 deadlock shape, restored by a policy inconsistency.
Fix. Make the two decisions consistent: enable_gate = gate_peer_access (gate exists whenever the widened predicate is installed), or do not set_gate_peer_access(true) when no peer-access graph was found.
MAJOR-5 — all_nvlink_p2p queries only one direction per pair → asymmetric NVLink disables the gate
Diff site: helios/src/runtime_core/model.rs:135-162; callee nvml.rs:358-369; constant nvml.rs:21-23.
for i in 0..handles.len() {
for j in (i + 1)..handles.len() {
if nvml.device_p2p_status(handles[i], handles[j], crate::nvml::P2P_CAPS_INDEX_NVLINK)
!= Some(Ok(crate::nvml::P2P_STATUS_OK))
{ return false; }
}
}
nvmlDeviceGetP2PStatus(d1, d2, ...) is directional (can d1 access d2). The loop never queries (j, i), so a topology where status(i→j) == OK but status(j→i) != OK (asymmetric NVLink, partially bridged or mis-reporting board) makes all_nvlink_p2p return true → gate_peer_access = false → the widened classification is not installed and no gate is created, even though graphs touch Memory::Peer. Per the policy's own test, copy_gate_policy(4, true, false, true) == (false, false) (model.rs:1662). Note the None (missing NVML symbol) case is safe — it falls toward gating.
Fix. Query both directions and require both Some(Ok(P2P_STATUS_OK)).
Related classification gap (Major-5b, mod.rs:227-270, 291-296): collect_peer_referencing_allocations closes only over recorded relocations plus payload-scanned bytes. A rank_data-style table that is zero at load and written with a peer address by a kernel at runtime never enters peer_table_allocations, so graphs reading it are classified non-peer-access. Counterexample: single-host PCIe TP2 core + rank_data (Memory::Device, stored_bytes() == 0), graph A's kernel writes the peer VA into it, graphs B/C take rank_data as an argument → node_peer_usage returns (false,false) for all of them. That is exactly the "indirect peer-pointer tables such as rank_data" case the PR description claims to cover; it is only covered when the table is populated during load.
MAJOR-6 — flush_queued_sqes retries EINTR with no bound; stop() joins with no timeout → teardown can hang forever
Diff site: helios/src/async_transfer/io_backend.rs flush_queued_sqes (added by this PR); callers IoUringBackend::flush, cancel_and_drain, worker.rs:1241/:1249, and worker.rs:654-661 (stop() → handle.join()).
while *queued_sqes > 0 {
match submit() {
Ok(0) => break,
Ok(submitted) => { *queued_sqes = queued_sqes.saturating_sub(submitted); }
Err(err) if err.raw_os_error() == Some(libc::EINTR) => continue, // unbounded
Err(err) => return Err(err),
}
}
Defect. No attempt counter and no deadline, unlike every other wait in this module (cancel_and_drain, the shutdown stream-drain loop at worker.rs:1302-1314 all take an Instant deadline). A signal storm delivered to the worker thread (profiler SIGPROF, SIGURG, SIGCHLD with a process-wide handler) makes io_uring_submit return EINTR on every attempt → infinite spin. AsyncTransferRuntime::stop() computes drained from handle.join() with no timeout (DRAIN_TIMEOUT is only enforced inside the worker, after the main loop exits), so a stuck flush() wedges stop() permanently — which turns clean SIGTERM into a hang and stalls teardown_model_ranks phase 1, i.e. the cross-rank hazard this PR exists to remove.
Fix. Bound the retries (MAX_FLUSH_ATTEMPTS, then Err(io::ErrorKind::Interrupted); the worker already only stores last_error and cancel_and_drain ignores the result), and give stop() a bounded join (handle.is_finished() polled against DRAIN_TIMEOUT, else FailedDrain). The added test uses a finite VecDeque scripted closure, so it structurally cannot detect the unbounded case.
MINOR findings (verified, lower impact)
poll_completionscollapses four outcomes intook == false(io_backend.rs):expected.remove(&op_id); result >= 0 && result as u64 == want. Short read is correctly failed, but-EINTRand-ECANCELED(fromcancel_and_drain) are published as a stickyCOMPLETION_ERROR_BITsentinel into the caller's slot andupdate_host_completionisfetch_max, so it is unrecoverable — while the rest of the module treats both as retryable. Fix: three-valuedIoCompletion(Ok/Interrupted/Failed).op_id == 0collision is NOT a bug —next_op_idstarts at 1 andwrapping_add(1).max(1)skips 0 (resolved per protocol item 1).peer_exit_grace= 30 s < the recovery window (threaded.rs:1019, branch690-698):mark_peer_exitedis set by the first peer to finish draining; if rank 0 is inside a legitimate 40 scuGraphLaunch, the nextpeer_exited()check at 40 s > 30 s firesstd::process::abort()instead of the gracefulon_peer_exit()error. Should be ≥TIMEOUT.chunk_bytes = ((CHUNK / ranks) & !7).max(8)(payload.rs:257): not a multiple ofBLOCK = 4096wheneverranksdoesn't divide 4 MiB in 4096 units (e.g.ranks = 3→ 1398104).read_range(payload.rs:216-241) still produces aligned reads but now re-reads up to 2 × 4096 bytes per chunk (~460 chunks × ≤8 KiB extra I/O for 1.92 GiB).ranks > CHUNKyieldschunk_bytes = 8whileStaging::newallocates 4096-byte buffers → 512× read amplification.ranks = 0panics on division by zero. Fix:((CHUNK / ranks.max(1)) & !(BLOCK - 1)).max(BLOCK).- Load-path scan cost / duplicated work (
payload.rs:257,378-387;mod.rs:191-222,242-257,994-998,1117-1121,291-296):contains_interval_addressruns inside the direct-I/O read closure, so every byte of the 1.92 GiB peer view (2.58 × 10⁸ words, each apartition_pointbinary search) lengthens staging-slot occupancy and sits on thecuMemcpyHtoDAsynccritical path; andcollect_peer_referencing_allocations(HashSet of all peer-referencing names + sorted interval vec + fixed-point closure) is recomputed twice per rank (prepare_kernelsandprepare_graphs) although it is final after the first. Fix: scan after the read, cache(peer_refs, peer_ref_intervals)onNativeResources, and skip allocations withstored_bytes() == 0. - Teardown failure path double-leaks the
driverArc (model.rs:1275-1328vsmod.rs:2051-2079,2197-2205):drain_execution_contextdoesmem::forget(self.driver.clone()); self.context = null_mut();on the sync-failure path, andteardown_model_ranksthenmem::forgets the wholeVec<NativeResources>— soDrop for NativeResourcesnever runs and the explicit clone leak is redundant. Leak-only (no UAF); the retained ranks also have a permanently nullcontext, which is currently unreachable becauseself.ranksismem::taken first. bg_io_inflight/bg_dma_inflightare O(n) scans (scheduler.rs:259-273) called per dispatch attempt inside a loop bounded byfree_events (16) × inflight_dma (16)= ≤256 cheap scans. Bounded; not a real perf defect, reported for completeness only. No per-poll heap allocation exists on the completion path (io_completionsreused viaclear()/drain(..),pending_dma_eventsreused).
Explicitly verified as CORRECT (so the report does not raise false alarms)
- Three-phase teardown barrier (
model.rs:1275-1328,mod.rs:2035-2042):stop_rank_workersevaluates both stops without short-circuit;all_drained &= drainedaccumulates over all ranks before theif !all_drainedcheck, so a rank-2 failure still drains ranks 3,1,0 and nothing is freed while a peer holds it. Phase 2 runsengram.clear()+offload.reset()beforedestroy_execution_resources;Layer::drop(engram.rs:584-592) joins the background threads. Phase 3 pops in reverse rank order. The stated UAF is genuinely closed. Reply::Started(Result<()>)is updated at every construction (threaded.rs:1431,1435) and every destructure (1355,1356-1358,1359-1361,cleanup_failed_startup:1385) in the whole crate; the coordinator does propagateErr(1356-1358). The failed-finish_startuppeer stays alive, loops toreceive(commands, None)(1429-1441), andcleanup_failed_startup:1376-1379sendsCommand::Drainto every peer unconditionally → no deadlock, and thestd::process::abort()path is genuinely removed.Condvarwatchdog usage: every state a waiter reads is written under awake()that takeswake_lockfirst (579-582,584-588,594-598,600-603,759-763); both waits holdwake_lockbefore re-checking → no lost wakeup;wait_whilepredicate matches the pre-wait predicate.Instantarithmetic uses saturating/checked forms. Watchdog is joined viastop_and_join(738-743) from1231-1233, plusDrop(746-752) → noSIGTERMhang from the watchdog.WatchdogCallGuard::enteris oneswap+ at most onewake()on the false→true edge → allocation-free per step.server/metrics.rsrank label is genuinely the GLOBAL rank — no defect.ChannelConfig.rank/AsyncTransferSnapshot.rankarepub rank: usize(worker.rs:94,111),snapshot()copiesself.config.rank(worker.rs:714-718), set toglobal_rank = cluster_rank.unwrap_or(idx)(model.rs:1064-1069,mod.rs:1851-1853); single-host hascluster == Nonesoidxis global; multi-host selects exactly one local rank (model.rs:421-426).render_async_transfer_snapshots(metrics.rs:1566-1592) usess.rank; the old flat.enumerate()bug is fixed and the new test (metrics.rs:1599-1640) exercises 3 snapshots → ranks 0,0,3. Series cardinality unchanged at 10/channel; the oneStringalloc per channel is inrender()(per scrape), not per transfer.AsyncTransfer.tlaUnflushedIoBounded/HwSignaledFaultedSafefaithfully model the Rust predicates (unflushed_io_count,hw_signaled_faulted_dma_count=faulted && hardware_signaled, a genuine subset), the width-16 projection agrees withDecode/project(), andcheck.py:247-265mutations requireoriginal.count(needle) == 1and the expected assertion text in the failing output, so they are real assertions.
Limitations of this audit
- Sub-agents were read-only: no
cargo test,check.py, or TLC execution. Every finding above is from reading files at224fb40; no finding depends on runtime observation. In particular the PR's claim ofcheck.pyexit 0 / 431 transitions and 1,920 passing lib tests is unconfirmed by me. - Multi-host RoCE, SM103/SM121, and Kani (no
cargo-kani) were out of scope, matching the PR's own limitation list.ring.rs::validate_commandwas read only for its constants, so no claim is made about slot range checks. - I could not observe a live SM120 run, so Major-1's 150 s threshold and Major-5's asymmetric-NVML case are constructed from the code's own deadlines and the NVML API contract, not from hardware.
Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.
Final review
Recommendation: Changes Requested
The core fixes for #722's PCIe kernel-P2P CopyEngineGate detection, the three-phase cross-rank teardown barrier, the Reply::Started(Result<()>) startup drain handshake, and the global-rank Prometheus metrics label are sound and well-structured. However, verification at 224fb40 confirmed one Blocker in AsyncTransfer's new unflushed-IO tracking (where swap_remove desynchronizes inflight_io order from io_uring SQ FIFO order after a partial submit, causing complete_io to permanently drop a real kernel completion) and two Should Fix defects in ThreadedExecutor (RankWedgeWatchdog::CloseStalled aborting progressing/multi-stage teardowns and best_effort_drain_peers skipping already-drained peers after a wedged peer exhausts the shared deadline).
Merge Risk
Level: High
- A partial
io_uringsubmission followed by any earlier completion causesmark_io_flushedto flag the wrongInflightIo, which makescomplete_iosilently drop a live kernel CQE and permanently hang GPU demand waits and leak pinned pools intoFailedDrain. RankWedgeWatchdogcallsstd::process::abort()insideclose()after a fixed 150 s wall-clock timer without tracking teardown progress, which can abort legitimate slow or poisoned teardowns whose own stage timeouts exceed 150 s.best_effort_drain_peerscan drop unjoinedJoinHandles for healthy peers that already sentReply::Drainedwhen an earlier peer consumes the shared 120 s timeout.
Walkthrough
- PCIe peer-access
CopyEngineGate&AsyncTransferdecoupling (helios/src/runtime_core/{payload,mod,serving,model}.rs,docs/prefix-cache-offload.md): Splitspeer_copy_graphs(strictlyNode::Copy(Memory::Peer), still used by load-timevalidate_async_transfer_peer_copy_compatibility) frompeer_access_graphs(peer copies/memsets, kernel arg/attr relocations or inline peer addresses, payload-scanned pointer tables, and peer-referencing module globals), enablingCopyEngineGateon single-host multi-rank deployments without all-pairs NVLink via NVMLP2P_CAPS_INDEX_NVLINK. - Three-phase cross-rank teardown barrier (
helios/src/runtime_core/{mod,model}.rs,docs/runtime-core-design.md): Replaces short-circuiting per-rank teardown withteardown_model_ranks— (1) stop persistent + async-transfer workers without short-circuiting andcuCtxSynchronizeon all ranks, (2) joinengram.clear()andoffload.reset()whileMappedHost/CUDA contexts remain live then destroy per-rank execution resources, (3) release green contexts, VA reservations, and primary CUDA contexts in reverse rank order (retaining resources until exit if any rank fails drain). AsyncTransferflush/fault hardening, rank metrics, and TLA+ (helios/src/async_transfer/{io_backend,scheduler,worker,lifecycle_tests}.rs,helios/src/server/metrics.rs,verification/helios-lifecycle/{AsyncTransfer.tla,AsyncTransfer.cfg,README.md (not opened),check.py}): Addsflush_queued_sqesandpending_submissions()to retryEINTR/partial submissions, tracksflushedonInflightIoandhardware_signaledon faulted DMAs to prevent completion-slot sentinel clobbering, fixesflare_async_transfer_*ranklabels to report global rank IDs, and extends the TLA+ model/conformance/mutation suite to 16-integer projections.- Startup drain handshake and rank-wedge watchdog (
helios/src/execution/threaded.rs): CarriesResult<()>inReply::Startedso peers failingfinish_startupremain inrun_startup_phaseto answerCommand::Drain -> Reply::Drained, shares a single deadline inbest_effort_drain_peers, and addsRankWedgeWatchdogto monitor coordinator/peer/close stalls and abort on wedges.
Pre-merge Checks
- [PASS] Security / malicious screen: No suspicious network, exfiltration, unsafe boundary bypass, or instruction-injection patterns; payload scanning reads already-authenticated bytes.
- [PASS] Charter & value fit: Directly addresses reproducible P1 release bug #722 on target SM120 PCIe hardware using topology-derived gating with no per-model branches or wire/core-format changes.
- [WARN] Related / duplicate / conflict check: Same-day follow-up to #721; sibling open PRs #726/#723 touch
prepare_async_transfers/release_execution_resourcesand should be serialized if merged alongside #727. - [WARN] Tests & verification evidence: Unit tests, TLA+ conformance/mutations, and an SM120 TP4 live run are documented (and environmental 403 failures on gated HF templates plus unrun SM103/SM121/RoCE/Kani are disclosed), but the live run used a different core/workload than #722 and existing
AsyncTransfertests did not catch theswap_remove/partial-flush ordering bug below.
Blockers
mark_io_flushed+complete_ioswap_removedesynchronizesinflight_iofromio_uringSQ FIFO order and permanently drops real kernel completions (helios/src/async_transfer/scheduler.rs:231-243,578-583;helios/src/async_transfer/worker.rs:994-1001,1226-1248)- Verified behavior:
pop_next_io()pushes newInflightIoentries to the back ofself.inflight_io(scheduler.rs:566), andworker.rs:1228-1248computesflushed_now = scheduler.unflushed_io_count().saturating_sub(args.io_backend.pending_submissions())and passes it toscheduler.mark_io_flushed(flushed_now), which marks the firstcountunflushed entries inVecindex order (scheduler.rs:233-241). However,complete_io()removes finished entries viaself.inflight_io.swap_remove(pos)(scheduler.rs:583), swapping the last element intoposand scrambling submission order relative to the kernelio_uringSQ FIFO. - Concrete failure trace:
- Stage reads
A, B, C->inflight_io = [A(unflushed), B(unflushed), C(unflushed)],io_uringSQ FIFO =[A, B, C],queued_sqes = 3. - Partial flush submits 1 SQE (
A) (Ok(1)thenEBUSY/Ok(0)):queued_sqes = 2,flushed_now = 1->mark_io_flushed(1)marksA. Acompletes (normalok = trueorok = false) ->complete_io(A, _)executesswap_remove(0)->inflight_iobecomes[C(unflushed), B(unflushed)], while theio_uringSQ still holds[B, C].- Next partial flush submits 1 SQE (
B):queued_sqes = 1,flushed_now = 1->mark_io_flushed(1)marksC(inflight_io[0]) asflushed = truewhile leavingBasflushed = false. poll_completions()(io_backend.rs:198-201) reapsB's CQE (IoCompletion { op_id: B, ok: true }) and removesBfromIoUringBackend.expected;worker.rs:998callsscheduler.complete_io(B, true).scheduler.rs:580-582executesif ok && !self.inflight_io[pos].flushed { return None; }and silently discardsB's completion without removingBfrominflight_io.
- Stage reads
- Impact:
B's CQE is permanently lost. Any GPU demand wait onB's completion slot hangs forever, any bounce slot held byBleaks permanently, and shutdownfinish_drain()(scheduler.rs:814) permanently fails intoChannelState::FailedDrain, leaking pinned pools and CUDA handles until process exit. - Fix: Preserve submission order in
inflight_ioby replacingswap_remove(pos)withremove(pos)atscheduler.rs:583(max_total_iois 32, so ordered removal is O(32) and preserves exact SQ FIFO order), or track a monotonic dispatch sequence number onInflightIoand havemark_io_flushedmark thecountunflushed entries with the lowest dispatch sequence. Add a regression test exercising partial flush -> completion of first op -> second partial flush ->complete_io(B, true).
- Verified behavior:
Should Fix
-
RankWedgeWatchdogCloseStalledfiresstd::process::abort()during legitimate slow or multi-stage teardowns (helios/src/execution/threaded.rs:594-598,679-687,1015-1029,1211-1233)- Verified behavior:
begin_close()setsclosing = true(one-way) and incrementsactivity, but theclosingarm of the watchdog loop (679-687) never readsactivityand never resetsclose_since. It applies a single fixed 150 s wall-clock deadline (TIMEOUT + WATCHDOG_GRACE) across all stages ofThreadedExecutor::close(): drainingself.pendingviaself.poll()?(up toTIMEOUT = 120 sper frame),close_peers(..., TIMEOUT = 120 s), fallbackbest_effort_drain_peers(..., TIMEOUT = 120 s)wheneverpoll()orclose_peersfails, andself.local.close(). As a result, a poisoned teardown wherepoll()orclose_peershits its 120 s deadline only gets 30 s insidebest_effort_drain_peersbefore the watchdog callsstd::process::abort(), and a healthy slow teardown draining frames plus peers in >150 s while actively progressing also aborts. - Fix: Track
activityin theclosingbranch (resettingclose_since = Some(now)wheneveractivityadvances, matching thebusybranch at703-707), and callself.watchdog_state.record_progress()acrossclose()stage transitions (afterpendingdrains, as each peer joins inclose_peers/best_effort_drain_peers, and beforeself.local.close()).
- Verified behavior:
-
best_effort_drain_peersshared deadline skips later peers without checking already-queuedReply::Drained, leaving finished threads detached (helios/src/execution/threaded.rs:1278-1316)- Verified behavior: Hoisting
let deadline = Instant::now() + timeout;outside thefor peer in peers.iter_mut()loop (1292) means that if an earlier peer is wedged and consumes the 120 s budget,deadline.checked_duration_since(Instant::now())returnsNonefor all subsequent peers (1298). Thewhilebody never executes even once, so peers that already exited cleanly and queuedReply::Drainedinpeer.receiverare never polled,exitedstaysfalse, and theirJoinHandles are dropped withoutjoin(). - Fix: Even when
deadlinehas expired, run a non-blockingtry_recv()loop on every remaining peer so peers that already sentReply::Drained/Err(_)/Disconnectedare still joined (or poll remaining peers round-robin against the shared deadline so a wedged peer at index 0 cannot starve peers1..N-1). Do not join peers that have not confirmed exit.
- Verified behavior: Hoisting
Subtract / Simplify
- Delete
RankWedgeWatchdog::stop_and_join(helios/src/execution/threaded.rs:738-753): Byte-for-byte duplicate ofimpl Drop for RankWedgeWatchdog;self.watchdog.take()(1231-1233) already drops and joins the watchdog thread. - Delete unreachable duplicate
async_transferspeer-copy check inNativeResources::prepare_async_transfers(helios/src/runtime_core/mod.rs:1750-1755):NativeModel::loadnow enforcesvalidate_async_transfer_peer_copy_compatibilityright afterprepare_graphs(model.rs:925), andprepare_async_transfershas no other caller. - Deduplicate interval builder and double
collect_peer_referencing_allocationscall (helios/src/runtime_core/mod.rs:162-174,258-269,994-998,1117-1121): Share one helper to build merged(address, end)intervals fromStorageiterators, and compute(peer_refs, peer_ref_intervals)once instead of repeating the identical relocation fixpoint in bothprepare_kernelsandprepare_graphs.
Nits
all_nvlink_p2ppair symmetry (helios/src/runtime_core/model.rs:152-160): Querying both(handles[i], handles[j])and(handles[j], handles[i])is 2 lines and guards against directional/asymmetric NVML P2P reports.- Bound
EINTRretries inflush_queued_sqes(helios/src/async_transfer/io_backend.rs:146-161): CappingEINTRretries per call (e.g., 16 attempts) avoids theoretical livelock under heavy signal delivery sinceworker.rs:1240already retries flushing on the next iteration wheneverpending_submissions() > 0. - Unused
AsyncTransferRuntime::rank()accessor (helios/src/async_transfer/worker.rs:493-495): Added with zero callers (metrics readsAsyncTransferSnapshot::rank); can be removed unless needed externally. - Documentation clarity: Note explicitly in the PR description that
RankWedgeWatchdogterminates viastd::process::abort(), and clarify indocs/api.md(not opened) that theflare_async_transfer_*ranklabel is the global rank ID.
Dropped on verification
- Upstream claim that
CopyEngineGatecan be silentlyNonewhilegate_peer_access == true(model.rs:921-942): False positive.copy_gate_policyreturns(true, false)only whenhas_peer_copy_nodes == falseandhas_peer_access_graphs == false— meaning every entry inpeer_access_graphson every rank is alreadyfalse, so no graph ever requests a gate lease andcopy_gate == Noneis completely consistent. - Upstream Major escalation for
flush_queued_sqesEINTRretry /stop()handle.join(): Over-escalated.ring.submit()(io_uring_enterwithmin_complete=0) is non-blocking and retryingEINTRmatches existing repo patterns (payload.rs:230,io_backend.rs:251);stop()'shandle.join()is pre-existing and bounded internally byDRAIN_TIMEOUT = 5 s. Downgraded to a Nit. - Upstream Major-5b claim about runtime-populated
rank_datapointer tables: Speculative limitation of static analysis; in captured Helios/b12x coresrank_datais populated before capture and stored in the payload (covered by the payload scan). - Upstream Minor claim that
peer_exit_grace = 30 s<TIMEOUT: Intentional design for #722 —mark_peer_exitedonly fires on unrecoverable peer exit/timeout (already poisoning the executor), so 30 s grace to enterclose()before aborting a wedged rank 0 is deliberate. - Upstream Minor claim that
chunk_bytes = ((CHUNK / ranks) & !7).max(8)introduces non-4096 read amplification / div-by-zero: Not a regression — pre-PRCHUNK / ranksalready had identicalranks = 3non-4096 sizing andranks >= 1assumption;& !7simply avoids splitting 8-byte pointers across chunk boundaries. - Upstream Minor claim of "2.58 × 10⁸
partition_pointbinary searches" inpayload::load: False —address_in_intervals(mod.rs:177-180) short-circuits onvalue < floor || value >= ceilingbefore callingpartition_point, so almost all weight words perform only two integer comparisons overlapped with direct I/O. - Upstream Subtraction claim that
WatchdogCallGuard::enter'skeep_busyparameter is dead (threaded.rs:611-619,1070): False —ThreadedExecutor::submit()has multiple early return paths (1071,1075,1085,1088,1130,1133) before line1127; passing!self.pending.is_empty()toenter()is necessary so early returns (e.g.,can_submit == falsewhile frames are pending) do not clearbusytofalse. - Upstream Subtraction claims to delete
stop_rank_workers(mod.rs:2035) andteardown_model_ranks(model.rs:1275): Dropped — both are deliberate testable seams providing the sole CPU-runnable unit tests for the non-short-circuit worker stop and three-phase teardown barrier. - Process/scope complaints (splitting PR into 4 PRs, unrun SM103/SM121/RoCE, live workload differing from #722, CI status not observable): Disclosed limitations or non-blocking process preferences; noted concisely in Pre-merge Checks rather than escalated.
Classify triage
Selected: triage:review
Threshold: 65%
Triage
- [✓]
triage:review: 99.9% -
triage:design-review: 0.0% -
triage:validation: 0.0% -
none: 0.0% -
triage:investigate: 0.0% -
triage:partial: 0.0% -
triage:integration: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0% Decision to Test: no (98%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.
Apply labels
No label changes decide malicious: all_clear (100%): No malicious content found
explore
Author: lukealonso (COLLABORATOR; charter-named priority contributor, 51 merged PRs/180d, de-facto sole owner of AsyncTransfer/teardown/CopyEngineGate; Discord lukealonso)
Motivation: A P1 external bug report (#722) shows a 4-GPU PCIe SM120 server deadlocking under --prefix-cache-memory: most captured graphs were never gated against Copy Engine traffic and nothing bounds a wedged rank. The PR widens that gate and hardens the surrounding teardown, AsyncTransfer and startup-drain code — some of which it had just merged hours earlier as #721.
Scale: +2234 / −253 lines in 17 files
Proposal:
- Split
peer_copy_graphsfrom a newpeer_access_graphs(payload pointer-table scan, peer memsets, kernel arg/attr relocations, peer module globals) and gate the latter wheneverlocal_ranks > 1 && !all_nvlink(NVMLP2P_CAPS_INDEX_NVLINK, both directions). - Replace #721's two-phase teardown with a three-phase cross-rank barrier (drain+
cuCtxSynchronizeall ranks → joinengram.clear()/offload.reset()→ destroy contexts in reverse rank order), leaking resources on a failed drain. AsyncTransfer:flush_queued_sqes/pending_submissions()with bounded EINTR retry (16),hardware_signaledDMA fault tracking, and a true globalrankmetrics label (fixing the.enumerate()label #721 introduced); TLA+ model grown to 16 integers.Reply::Started(Result<()>)keeps a failed-startup peer alive to answerDrain, instead of aborting;RankWedgeWatchdogaborts the process afterTIMEOUT + 30 s(~150 s) of zero activity; close stages now report progress.- Fully rewritten description in before/after form; review-round blocker (unordered
swap_removeincomplete_iodesynchronising io_uring SQ FIFO) fixed with a regression test at headc9df77bd. Touches: helios/src/execution/threaded.rs(+728/−88): watchdog, startup drain handshake, teardown barrier; the abort-on-wedge path.helios/src/runtime_core/{mod,model,payload}.rs(+654/+214/+46): gate widening and load-time peer scan; three-phase teardown.helios/src/async_transfer/*+server/metrics.rs: SQ flush ordering, DMA fault sentinel, metrics label semantics change. Related items:- #721 (merged): same author, 11 shared files — #727 rewrites its teardown, flush path and rank label hours after merge.
- #722 (open): the P1 bug this claims to fix; reporter
egtoken-aihas still not commented. - #628 (merged): introduced the
CopyEngineGatepredicate #722 measures at 32/177 graphs; #727 narrows and reuses it. - #711 (merged): introduced the domain-agnostic
AsyncTransferprimitive and runtime-sized pools. - #726 / #723 (open, same author): sibling series; #726 touches
prepare_async_transfers/release_execution_resources, so serialise if merged together. Link: https://github.com/NVIDIA/hyperflare-inference/pull/727 Autobot comments: New since the intake report: flare-autobot posted Changes Requested at224fb40(1 blocker, 2 should-fix, 3 simplify, 4 nits, merge risk High); the author replied at 22:34 claiming all fixed inc9df77bd, but auto re-review runs 90 min after a push, so no review artifact yet verifies the new head — my fixes are code-verified only. Two earlier caveats are now void: the.github/workflow hunks were base drift (pr_filesshows 17 files, none under.github/), and the description now does state thestd::process::abort()remedy, so the charter root-cause tension is a disclosed choice rather than an omission. Still unbacked: the live TP4 run (135 graphs/rank, 4G cache, ~13k tokens, 20 concurrent) is not the #722 workload (177 graphs, 256G, 32k tokens,balanced); no patched-vs-unpatched comparison exists; detection correctness rests on the pure-policy testcopy_gate_policy_*(model.rs:1662-1677) plus that one run; full-crate and live evidence are still dated224fb403. New residual:GraphExecutor::close(execution/transport.rs:1354-1391) synchronises with no timeout after the last progress mark, so a driver-level hang there still ends instd::process::abort()at ~150 s. New behaviour: a persistent EINTR storm now surfaces aslast_error = IoFailureinstead of retrying forever, andall_nvlink_p2ptreats a one-way NVLink link as not-all-NVLink (fails safe toward gating).docs/api.md:403-405now says "the globalrankID" but never says the label used to be a per-process channel index, so dashboards keyed onrankshift silently. Also: theasync_transfers+Node::Copy(Memory::Peer)rejection moved to load time only in this push, andNativeResources::load_preparednever calls it — the policy is enforced only on theNativeModel::loadpath.
Classify intake
Selected: triage:review, priority:P1, bug, performance
Threshold: 65%
Triage
- [✓]
triage:review: 98.6% -
triage:validation: 0.9% -
triage:design-review: 0.5% -
triage:investigate: 0.0% -
none: 0.0% -
triage:integration: 0.0% -
triage:partial: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Priority
- [✓]
priority:P1: 98.6% -
priority:P2: 1.2% -
none: 0.1%
Type
- [✓]
bug: 98.0% - [✓]
performance: 89.3% -
community: 43.8% -
duplicate: 4.2% -
enhancement: 0.1% -
documentation: 0.0%
Area
-
area:memory: 53.1% -
area:api: 43.8% -
area:preparation: 32.1% -
area:caching: 24.5% -
area:kernels: 16.5% -
area:engram: 6.8% -
area:rocenante: 4.2% -
area:selene: 2.0% -
area:scheduling: 1.6% -
area:orbit: 0.3% -
area:packaging: 0.1%
Model
-
model:deepseek-v4.1: 6.0% -
model:glm-5.3: 2.3% -
model:nemotron-3.5-bolt: 1.6% -
model:muse-glimmer: 1.2% -
model:deepseek-v4: 1.0% -
model:qwen3.8-flash-next: 0.6% -
model:inkling-small: 0.4% -
model:kimi-k3.1: 0.2% -
model:mimo-v2.6: 0.2% -
model:gemma4: 0.0% -
model:qwen3.8-27b: 0.0%
Apply Labels (Intake)
No label changes
Gates and contracts
Contracts, Charter & Verification Gates Audit — PR #727 @ c9df77bd
Verdict: no hard contract or vendored-file gate violations; one genuine mandatory-verification gap (Gate 3, live multi-GPU execution of the reordered peer-drain path at the current head). Everything else in all four gates passes; I deliberately did not escalate process preferences (PR splitting, unrun SM103/SM121, workload-differs-from-#722, unobservable CI) into findings.
Scope verified at head: 17 files, none under .github/, no .proto/core-format/schema file, nothing under helios/native/ (pr_files). The earlier .github/ hunks were base drift, now confirmed absent.
Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries: PASS
- No new captured-graph operation family or graph kind.
docs/design-review.md:22-26requires owner approval for a new op contract "even if it reuses a graph kind or enum value". This PR adds none: it classifies existing graph content.node_peer_usage()(helios/src/runtime_core/mod.rs:278(not opened)) inspects existingNode::Copy, memsets, kernel arg/attribute relocations, module globals, and a payload word scan;peer_copy_graphs/peer_access_graphsare internalVec<bool>fields, and the only consumer-side change isgraph_uses_copy_gate(index)athelios/src/runtime_core/serving.rs:59, which fills the pre-existingpeer_copy_graphsvector ofGraphDescriptor. - No wire/core-format change.
Core,Allocation,Execution.async_transfers,ExternalExtentTable, andRangeBody.external_extentskeep their recorded shapes;docs/core-format-design.md(its onlyasync_transfersmention is the unchangedExternalExtentTablerow at:224) is not touched. Principle 13 (docs/design-review.md:116-123) is therefore not stressed: no new required field, no reserved identifier removed, no ABI gate. No previously supported core changes shape, and the load-time rejection the PR adds is documented rather than silently introduced. - Normative invariants are consistent, and contradicted prose was updated in this diff.
docs/scheduling-theory.md(not opened) anddocs/scheduling-runtime-design.md(not opened) contain zero mentions ofCopyEngineGate, peer access,peer_copy, orasync_transfers(regex search) — nothing normative is contradicted there.docs/core-design.md:595mentions "peer access" generically without a gate invariant. The two docs that did state the old, narrower behavior are updated in this PR's diff:docs/prefix-cache-offload.md— the gate paragraph now covers explicitNode::Copy(Memory::Peer)and single-host PCIe multi-rank graphs whose "kernels, memsets, module globals, or indirect pointer tables accessMemory::Peer", with "gated graphs bound their drain wait at 120 seconds". I verified that 120 s is the real bound (helios/src/offload/copy_gate.rs:27-28,PEER_GRAPH_GATE_TIMEOUT, "Aligned withThreadedExecutor's 120 s stall deadline"), so the doc matches code.docs/runtime-core-design.md:687-702— replaced the old single-rank teardown prose with the three-phase cross-rank barrier, the load-timeasync_transfers+ peer-copy rejection, and "all ranks retain their CUDA and host resources until process exit".docs/api.md:403-405— theflare_async_transfer_*series are now documented as "labeled bychanneland the globalrankID", matchinghelios/src/server/metrics.rs:1567(let rank = s.rank;).
- No new CLI flag, config key, or environment-variable behavior switch (
AGENTS.md:450-477). A repo-wideenv::var(scan finds only test opt-ins and existing terminal/dashboard detection; the touched area addsFLARE_ASYNC_TRANSFER_TRACE-style test variables only, whichAGENTS.md:475-477permits. - No per-model branch. The decision is a pure topology function,
copy_gate_policy(local_ranks, all_nvlink, has_peer_copy_nodes, has_peer_access_graphs)(helios/src/runtime_core/model.rs:176-185), fed by a pairwise NVMLP2P_CAPS_INDEX_NVLINKquery that now checks both directions (model.rs:152-170) and fails toward gating when NVML is absent. Nothing keys on model identity or asupports_*flag. - Operator-facing note (Info only, not a gate): the
ranklabel semantics change is documented as the new meaning but not as a change (dashboards keyed onrankshift silently); andRankWedgeWatchdog's terminal action,std::process::abort()at ~TIMEOUT + WATCHDOG_GRACE(helios/src/execution/threaded.rs:1017-1028), has no entry anywhere underdocs/. Grading rule applied: these are documentation precision gaps on an internal-alpha runtime, not wire/format contradictions on a shipped default → not flagged above Nit.
Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS
- No vendored-upstream fork.
helios/native/roce_proxy.c(not opened) (the repository's vendored-artifact case) and everything else underhelios/native/are untouched (pr_files). The RDMA path changes only in the sibling-decoding slice. - No unmerged external recipe or PR dependency. No
ignition/change, no recipe pin, nolocal-inference-lab/hyperflare-recipesreference. The verification toolchain stays on the pinnedtla2tools v1.7.4used by.github/workflows/helios-lifecycle.yml:34(not opened). - Cross-PR overlap is informational. #721 (merged, same author) is the direct predecessor this PR revises; #726/#723 touch
prepare_async_transfers/release_execution_resourcesand should be serialised if they land together. No textual conflict and no competing #722 fix. Info / Nit, per the calibration rule.
Gate 3 — Mandatory verification evidence & failing tests: one gap
What is satisfied (verified at head, not taken on faith). This PR touches async_transfer scheduler/lifecycle state and rank coordination, so check.py + mutations are mandatory (docs/design-review.md:209-240); the artifacts exist, not just the claim:
AsyncTransfer.tlagrew exactly as described:FlushIo(:83-87),UnflushedIoBoundedAt(:247-251),HwSignaledFaultedSafeAt(:252-255), aggregate:279-280, 16-slotProjection/Decode(:286,:304),StepincludesFlushIo(:186);AsyncTransfer.cfg:22-23enables both invariants.check.py:36widens theAsyncTransferprojection to 16 integers, and the new guards have both a model mutation (check.py:428-454:FlushIooverwrite → must violateUnflushedIoBounded;hwSignaledFaultedno-decrement → must violateHwSignaledFaultedSafe) and Rust mutations (check.py:771-780: "unflushed io completed ok before flush", "hardware-signaled faulted dma clobbered completion slot"). These are real assertions because the runner requires exactly one needle occurrence and the expected assertion text.- Conformance drives production entry points (
verification/helios-lifecycle/README.md:368-378listsstart/enqueue/cancel_epoch/dispatch_io/mark_io_flushed/complete_io/dispatch_dma/complete_dma/mark_dma_faulted/begin_drain/finish_drain/fail_drain), satisfying "not only hand-written replays". - Model/suite counts in the description check out: 9
CHECKS+RankDispatch= the "10 TLA+ models", and 9 Rust conformance suites (check.py:22-37). - Layer 3 Kani correctly not re-run. The harnesses cover completion-vector validation, state-view extent arithmetic, command bounds, pool geometry, and tagged-output parsing (
helios/src/async_transfer/kani_proofs.rs,execution/transport/kani_proofs.rs(not opened),model/{contract/,}kani_proofs.rs,output/tagged/kani_proofs.rs(not opened)). This diff changes none of those validators — it adds scheduling bookkeeping (flushed,hardware_signaled) andCommand/Replyenum variants that are Rust-internal control messages validated byDispatchRing/RankProtocol. Sodesign-review.md:247-251("does not excuse skipping runnable checks") is not triggered. CI does run Kani (.github/workflows/helios-lifecycle.yml:38-49(not opened),cargo kani --lib). - No performance gate. The PR states plainly: "No throughput speedup claim is made beyond deadlock/fault elimination." Numbers are offered as deadlock/lifetime evidence, so
design-review.md:106-115's A/B prong is not triggered. - No reported failing CI or failing test attributable to this PR. The only failing set is disclosed and environmental: 6
helios --libfrontend template tests blocked by HTTP 403 from the gatedmeta-models/Muse-Spark-Open-816B-A42B-NVFP4repo — an untouched path that fails identically onmain, disclosed rather than hidden, which is whatdesign-review.md:112-115requires. I did not flag "no observable CI run" (the Dossier reports lifecycle/kani/pytest green; the description reports the targeted and full runs).
The gap (Gate 3, live multi-GPU prong). docs/design-review.md:252-259 is explicit:
"Replacing or reordering cross-rank launch, commit, cancellation, or drain paths in
helios/src/execution/{threaded,parallel,roce}*requires ... live multi-GPU execution of real collective graphs (for example, serving a multi-GPU exported core throughflare run), not only independent per-rank synthetic graphs. Disclosing busy or unavailable GPUs does not waive this requirement for changes to TP execution paths."
best_effort_drain_peers — a peer drain path — was reordered in exactly this push, from per-peer sequential receive() with an individual deadline to a round-robin, non-blocking try_recv() sweep against one shared deadline (helios/src/execution/threaded.rs:1294-1358), with close_peers/best_effort_drain_peers gaining WatchdogState::record_progress() calls (threaded.rs:1281-1283, :1337-1339). The PR's own evidence places the multi-GPU live run before that change:
- multi-GPU evidence: "On
224fb403: Live SM120 PCIe TP4 serving ... 20/20 requests ...SIGTERMexited cleanly" (224fb403, not the head); - head evidence: "On
c9df77bd: ...live_cuda_async_transfer_end_to_end: passed (0.59s)" — that test is single-device (CUDA_VISIBLE_DEVICES=2), i.e. the independent-per-rank case the rule excludes.
So the reordered drain path has no live multi-GPU run at the head, and the rule says the disclosure of that gap does not waive it. The CPU side is covered (a mock-transport multi-peer test exists: best_effort_drain_peers_joins_healthy_peers_even_when_earlier_peer_is_wedged, threaded.rs:4175), which is why I am recording this as a gap to close by re-running the existing TP4 flare run sequence on c9df77bd — one command, not a design change — rather than as an architectural objection.
Gate 4 — Material scope / claim contradictions: PASS
- Every named artifact I spot-checked exists at head at the cited location:
copy_gate_policy_gates_pcie_kernel_peer_access_without_blocking_nvlink_or_single_rank(model.rs:1663), the twoteardown_model_ranks_*tests (model.rs:1680,:1719),hardware_signaled_faulted_dma_suppresses_completion_slot_sentinelandpartial_flush_preserves_sq_fifo_order_across_completions(scheduler.rs:1101,:1128),flush_queued_sqes_retries_eintr_handles_partial_submit_and_preserves_unsubmitted_count(io_backend.rs:420),finish_startup_peer_error_drains_mixed_peers_cleanly_without_abort(threaded.rs:3540), the threewatchdog_fires_*tests (threaded.rs:4057,:4092,:4121),async_transfer_metrics_label_true_rank_ids_not_flat_vector_indices(metrics.rs:1601). - All four review nits were in fact applied at this head: both-direction NVML (
model.rs:152-170), boundedEINTR(MAX_EINTR_RETRIES = 16,io_backend.rs:146-170, with the test asserting exactly 16 calls),rank()accessor removed (worker.rs:489-501now hasname/state/host_pool_bytes/device_pool_bytesonly), and theapi.mdwording. - No invented benchmark, no thousands of lines of unrelated tooling: the 17 files are all inside the change's own surface (runtime_core gate + payload scan + teardown,
execution/threaded.rs,async_transfer,server/metrics.rs, two design docs, and the matching lifecycle verification). The four defect clusters are disjoint but all on the same serving path, and the description gives each a before/after rationale — a coherent outcome underAGENTS.md:198-199. - The disclosed limitations are accurate as far as I can check: no core combining
Execution.async_transferswithoutNode::Copy(Memory::Peer)existed locally; SM103/SM121, multi-host RoCE, and local Kani were not run (CI runs Kani).
Findings by severity
| Severity | Finding |
|---|---|
| Blocker | None. |
| Major (gate) | Live multi-GPU execution is missing for the reordered peer-drain path at the head. best_effort_drain_peers was reordered (round-robin try_recv, one shared deadline) in c9df77bd (helios/src/execution/threaded.rs:1294-1358), and the only multi-GPU live run is dated 224fb403; the head's live test is single-device. docs/design-review.md:252-259 names drain paths explicitly and says disclosure does not waive live multi-GPU execution. Remedy: re-run the same SM120 PCIe TP4 flare run sequence (serve the exported 4-rank core, exercise SIGTERM teardown) on c9df77bd and report it. |
| Info / Nit | (1) std::process::abort() as the watchdog remedy (threaded.rs:1017-1028) has no docs/ entry, though it is now stated in the PR description; the charter's "don't just swallow/retry an unexplained error" tension is a disclosed design choice, not an omission. (2) docs/api.md:403-405 gives the new meaning of the rank label but not the migration fact that it was previously a flat per-process channel index. (3) #726/#723 overlap on prepare_async_transfers/release_execution_resources; serialise if #726 lands first. |
| Note | 6 frontend template tests failing on HTTP 403 from the gated HF repo are environmental and disclosed; Kani correctly not re-run because no validator it covers changed (CI covers it); the .github/ hunks seen in earlier rounds remain confirmed base drift, not this PR's. |
No contract or vendored-file gate blockers. One mandatory verification prong (Gate 3, live multi-GPU drain) needs a re-run at c9df77bd to clear.
Subtraction and simplicity
Subtraction & Simplicity audit — PR #727 (helios: PCIe peer-access gate, teardown, AsyncTransfer, startup drain), head c9df77bd
Verdict: the production code is mostly lean and the added comment/doc density is unusually good, but there are three genuine deletions (a 4th and 5th copy of an interval-merge fold, an unreachable fallback that is a second source of truth, and a hand-maintained 16-element format string) and five simplifications where an Option/bool selector, a closure-injection helper, or a duplicated accounting block could be collapsed. Test volume is where the fat is: helios/src/execution/threaded.rs +728 and helios/src/runtime_core/mod.rs +654 are ~70 % tests, and the new peer_usage_tests module repeats the same 6-argument call 7 times.
A. High-value deletions
A1. merge_sorted_intervals is the third copy of the same sort-and-fold in runtime_core
helios/src/runtime_core/mod.rs:151-163 (new):
fn merge_sorted_intervals(mut intervals: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
intervals.retain(|&(start, end)| start < end);
intervals.sort_unstable();
let mut merged: Vec<(u64, u64)> = Vec::new();
for (start, end) in intervals {
if let Some(last) = merged.last_mut().filter(|last| start <= last.1) {
last.1 = last.1.max(end);
} else {
merged.push((start, end));
}
}
merged
}
The identical loop already exists twice in the same crate:
helios/src/runtime_core/host.rs:62-70—ranges.sort_unstable(); let mut merged: Vec<(u64, u64)> = Vec::new(); for (start, end) in ranges { if let Some(last) = merged.last_mut().filter(|last| start <= last.1) { last.1 = last.1.max(end); } else { merged.push((start, end)); } }helios/src/runtime_core/archive.rs:300-313—fn merge_ranges(...), same fold over(offset, nbytes).
Recommendation: make this one helper pub(super)/pub(crate) and have host.rs::ranges and archive.rs::merge_ranges delegate to it (the latter only needs a map on the way in). Net −~25 lines and one fewer merge semantic to keep consistent.
A2. The peer_refs: Option<…> fallback is unreachable in-tree and re-derives the same set a second way
helios/src/runtime_core/mod.rs:127-130 adds
/// Transitive closure of `Memory::Peer` and peer-pointer-table allocations, computed in
/// `prepare_kernels` and consumed in `prepare_graphs`.
peer_refs: Option<(HashSet<String>, Vec<(u64, u64)>)>,
and helios/src/runtime_core/mod.rs:1119-1125:
let (peer_refs, peer_ref_intervals) = self.peer_refs.take().unwrap_or_else(|| {
collect_peer_referencing_allocations(
core,
&self.allocations,
&self.peer_table_allocations,
)
});
Every in-tree caller already runs prepare_kernels immediately before prepare_graphs: mod.rs:527-528 (load_prepared), model.rs:913/:929, event_tests.rs:116-118 (not opened), persistent_worker.rs:2845-2847 (not opened). So the unwrap_or_else closure is dead, and if it ever ran it would disagree with peer_modules (populated during prepare_kernels at mod.rs:1049-1051), i.e. it is a silent second source of truth for the very predicate the PR exists to get right. Recommendation: keep the field non-Option (or better, drop the field and compute it at the top of prepare_graphs from self.allocations + self.peer_table_allocations — the exact same inputs), i.e. delete ~7 lines and one invalid state.
A3. format_json_vec is a hand-maintained arity that this PR already had to edit by hand
helios/src/async_transfer/lifecycle_tests.rs:51-57:
fn format_json_vec(v: &Projection) -> String {
format!(
"[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]",
v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13],
v[14], v[15]
)
}
Rust's {:?} for [i64; 16] emits exactly [1, 2, 3, …], the same text this produces. Deleting the function and calling format!("{v:?}") removes 7 lines and the recurring "bump 14 → 16 → 18" edit that the projection growth forces on every model change (lifecycle_tests.rs:19-24).
B. Simplifications
B1. gate_peer_access: bool + two parallel bool vectors ⇒ one selected mask
helios/src/runtime_core/mod.rs:1605-1618:
pub(super) fn set_gate_peer_access(&mut self, gate: bool) {
self.gate_peer_access = gate;
}
/// True when prepared graph `index` must acquire `CopyEngineGate` during serving.
pub(super) fn graph_uses_copy_gate(&self, index: usize) -> bool {
if self.gate_peer_access {
self.peer_access_graphs.get(index).copied().unwrap_or(false)
} else {
self.peer_copy_graphs.get(index).copied().unwrap_or(false)
}
}
The policy decision is made once, in model.rs:940-950, and is immutable afterwards; serving.rs:59 (not opened) only ever calls graph_uses_copy_gate(index) (its sole caller). Carrying a bool plus two vectors plus a mutator to model "which of the two vectors is live" is an invalid state the type could prevent: after copy_gate_policy(...) returns, set a single copy_gate_graphs: Vec<bool> (the chosen one) and reduce the accessor to self.copy_gate_graphs.get(index).copied().unwrap_or(false). peer_copy_graphs still needs to survive for has_any_peer_copy_graphs / validate_async_transfer_peer_copy_compatibility, and has_any_peer_access_graphs can then fold into the same pass in model.rs:936-939. Net: −1 field, −1 pub(super) mutator, −1 branch.
B2. stop_rank_workers injects two closures to defeat a borrow that does not exist
helios/src/runtime_core/mod.rs:2033-2040:
fn stop_rank_workers(
stop_persistent_worker: impl FnOnce() -> Result<()>,
stop_async_transfers: impl FnOnce() -> Result<()>,
) -> bool {
let worker_ok = stop_persistent_worker().is_ok();
let transfers_ok = stop_async_transfers().is_ok();
worker_ok && transfers_ok
}
Both callees take &self — pub fn stop_persistent_worker(&self) -> Result<()> (mod.rs:1922) and pub fn stop_async_transfers(&self) -> Result<()> (mod.rs:1886) — so the call site at mod.rs:2053-2056 could be the two plain statements, no closures:
let worker_ok = self.stop_persistent_worker().is_ok();
let transfers_ok = self.stop_async_transfers().is_ok();
The helper's only justification is the unit test stop_rank_workers_evaluates_both_stops_without_short_circuiting (mod.rs:~2540), which therefore tests the helper, not drain_execution_context — the property under test is not actually exercised where it matters. Delete the helper and its closure plumbing (~15 lines); the no-short-circuit property is visible from two adjacent statements. Note stop_async_transfers (mod.rs:1886-1897) already carries the "run all, keep first error" idiom, so there is nothing new to abstract here either.
B3. queued_sqes accounting is duplicated raw in 4 places, re-opening the very invariant the PR fixes
helios/src/async_transfer/io_backend.rs:
:226-230if self.ring.submission().is_full() { if let Ok(submitted) = self.ring.submit() { self.queued_sqes = self.queued_sqes.saturating_sub(submitted); } }:234-236the same three lines after the cancel loop:262-264the same inside theErr(_)arm ofsubmit_with_args:252-255Ok(submitted) => { self.queued_sqes = self.queued_sqes.saturating_sub(submitted); }
All four can be let _ = self.flush(); — the helper already retries bounded EINTR (flush_queued_sqes, :148-170) and each site currently swallows the error anyway (if let Ok(...)). Routing them through flush() removes four hand-maintained copies of the counter invariant, which is precisely the class of bug (submitted_io reset / stranded SQEs) the PR is fixing.
B4. WatchdogCallGuard::enter(state, keep_busy) — the constructor argument is dead at both call sites
helios/src/execution/threaded.rs:608-627:
fn enter(state: &Arc<WatchdogState>, keep_busy: bool) -> Self {
state.mark_busy();
Self { state: Arc::clone(state), keep_busy }
}
Both callers overwrite the field immediately after using it as an initial value and then re-derive it: let mut wd_guard = WatchdogCallGuard::enter(&self.watchdog_state, !self.pending.is_empty()); (:1069) … wd_guard.keep_busy = true; (:1125) and wd_guard.keep_busy = !self.pending.is_empty(); (:1150). The parameter is therefore write-only state carried through a constructor. Drop it (enter(state) starting keep_busy: false) or, cleaner, keep keep_busy out of the guard entirely and let the guard always clear busy on drop, with the "stay busy across a gap" case expressed by an explicit state.mark_busy() at the two transition points — the two call sites become self-documenting instead of reverse-engineered.
B5. contains_interval_address duplicates its scan body for a one-bit difference
helios/src/runtime_core/mod.rs:201-232: the Some(alloc_offset) branch (chunks_exact(8) after a skip) and the None branch (windows(8)) contain the same value-extraction and address_in_intervals test twice. Both are one indexed loop with a different stride:
let skip = aligned_start.map_or(0, |o| (8 - (o % 8)) % 8);
let step = if aligned_start.is_some() { 8 } else { 1 };
for start in (skip..=bytes.len().saturating_sub(8)).step_by(step) { … }
That collapses ~18 lines to ~8 and removes the risk of the two modes drifting (only the None mode guards small kernel blobs, mod.rs:294, so a fix applied to one branch would silently miss the other). Same file, mod.rs:2062-2076 / :2086-2096 / :2160-2166: the context_get / context_set / std::mem::forget(self.driver.clone()); self.context = null_mut(); "retain until process exit" preamble is written out three times and could be one unsafe fn enter_context(&mut self) -> Option<Handle> + one fn retain_until_exit(&mut self) (≈−12 lines, and the leak-on-failure rule becomes stated once).
C. Nits worth 5 lines each
helios/src/server/metrics.rs:1530-1537:render_async_transfer_metricsexists only to mapchannelsto snapshots and delegate; its single caller (:999) could inlinerender_async_transfer_snapshots(&mut text, &channels.iter().map(|c| c.snapshot()).collect::<Vec<_>>()). The split buys testability (:1599-1630), so this is a justified wrapper — flagging only so it is a conscious choice.helios/src/async_transfer/scheduler.rs:217-223(hw_signaled_faulted_dma_count) and:245-250(is_io_flushed) arepubbut used only by tests (scheduler.rs:1076/1122/1124,lifecycle_tests.rs:47/111/277). They are legitimate TLA+ projection fields (lifecycle_tests.rs:46-47), but they do not need to be public API;#[cfg(test)]orpub(crate)avoids growing the crate surface with test observability.helios/src/execution/threaded.rs:375-377fn drain_requested(&self)has exactly one use — the watchdog's log string at:1022-1024. Fine to keep, but it is diagnostic-only surface.helios/src/runtime_core/model.rs:1074-1077:let cluster_rank = self.cluster.as_ref().map(|cluster| cluster.rank); … let global_rank = cluster_rank.unwrap_or(idx);—unwrap_or(idx)silently restores the flat-local-index semantics that the metrics fix is removing; ifclusteris everNoneon a multi-rank topology the metric goes back to being wrong with no diagnostic. Prefer an explicit rank source or an assertion instead of a silent fallback.helios/src/execution/threaded.rstest-onlyPeerExitGuardconstruction now requireswatchdog: Arc::new(WatchdogState::new())at five sites (:2142,:2209,:3350,:3427,:3492, plus the new startup test) purely to satisfy the field. APeerExitGuard::new(ring)that leaveswatchdog: Nonedeletes that boilerplate (the struct is internal).
D. Where the diff is already lean (no action)
helios/src/async_transfer/io_backend.rs:146-170flush_queued_sqes(&mut usize, impl FnMut) -> io::Result<usize>: the&mutcounter + injected submit closure is the minimum needed to unit-test boundedEINTRand partial submits; do not "simplify" it into a method.helios/src/async_transfer/worker.rs:1222-1250:if submitted_io || args.io_backend.pending_submissions() > 0plus theunflushed_io_count().saturating_sub(pending_submissions())derivation is repeated three times (:1224-1229,:1238-1244,:1287-1292) — afn sync_flushed(scheduler, backend)helper would remove ~9 duplicated lines, but the three sites have genuinely differentdid_work/last_errorside effects, so the duplication is shallow; borderline, list only if you want one more.helios/src/execution/threaded.rs:629-760watchdog: three explicitOption<Instant>since-fields (stall_since,peer_exit_since,close_since) and the three-branch body are the readable form of an inherently stateful monitor; therecord_progress()call sites are already the minimum needed for progress-awareness.helios/src/runtime_core/payload.rs:alloc_index/alloc_offsetonChunkplus theVec<AtomicBool>flag vector are the cheapest possible way to flag peer-pointer tables during the read (buffers are transient, so a post-load scan is not available); keep. The((CHUNK / ranks) & !7).max(8)chunk alignment is the right one-line fix.- No new CLI flags, config knobs, or feature gates were added anywhere in the 17 files; the one new public config field (
ChannelConfig.rank,worker.rs:94) is required data, not speculative generality.
E. Biggest remaining fat: the new tests
helios/src/runtime_core/mod.rs peer_usage_tests (~330 lines, mod.rs:~2230-2560) repeats the same 6-argument call seven times, e.g.
assert_eq!(
node_peer_usage(
&peer_copy,
&function_modules,
&allocations,
&peer_refs,
&peer_ref_intervals,
&peer_modules,
),
(true, true)
);
A single let usage = |node| node_peer_usage(node, &function_modules, &allocations, &peer_refs, &peer_ref_intervals, &peer_modules); reduces each of the seven blocks to assert_eq!(usage(&peer_copy), (true, true)); — roughly 130 lines deleted with zero loss of coverage, and the seven cases become scannable as a table. Same pattern in helios/src/execution/threaded.rs:3530-3620 (finish_startup_peer_error_drains_mixed_peers_cleanly_without_abort spawns an identical peer harness for each of 4 tuples) — that one is already structured as a loop over cases, so it is fine.
Totals if A1–A3 + B1–B5 + the test helper are taken: ≈ −250 lines, −1 struct field, −2 accessors/mutators, −1 duplicate merge semantic, −1 unreachable branch, −1 hand-maintained arity. None of these touch the four fixes' semantics.
Code correctness
Audit — PR #727 helios: gate PCIe peer-access graphs and fix teardown, AsyncTransfer, and startup drain races @ c9df77b
Partitioned into 3 disjoint slices (execution/threaded.rs; runtime_core/* + 2 docs; async_transfer/* + server/metrics.rs + verification/*), each audited with the full 4-part protocol, then I re-verified every headline finding myself against the head sources (quotes below are from read_file at c9df77b, not from the sub-reports).
Verdict: 2 Major correctness defects, 1 Major state-loss defect (TLA-modeled invariant is violated in the model's own premise but the real bug is the queued_sqes/flushed desync), 3 Minor. The teardown barrier, the widened peer-access gate, the RankWedgeWatchdog activity bookkeeping, the EINTR bound, and the metrics rank labels are all verified correct.
Finding 1 — Major: best_effort_drain_peers treats a peer's error reply as thread exit and then join()s it with no deadline, defeating the shared deadline and the whole point of the fix
Diff site helios/src/execution/threaded.rs:1317-1340 (verified verbatim):
let mut exited = false;
loop {
match peer.receiver.try_recv() {
Ok(Ok(Reply::Drained))
| Ok(Err(_))
| Err(mpsc::TryRecvError::Disconnected) => {
exited = true;
break;
}
Ok(Ok(_)) => {
made_progress = true;
continue;
}
Err(mpsc::TryRecvError::Empty) => break,
}
}
if exited {
if let Some(thread) = peer.thread.take() {
let _ = thread.join();
Callee resolution — Ok(Err(_)) does not imply the peer thread is exiting. On the peer side (threaded.rs:1543-1555) the rank sends its error and only then drains outstanding frames for up to TIMEOUT (120 s) inside executor.poll() (cuStreamQuery/cuStreamSynchronize — precisely where a wedged GPU blocks, i.e. the #722 failure mode):
let _ = replies.send(Err(error.clone()));
ring.mark_peer_exited();
let _ = drain_outstanding_frames(
executor, |exec| exec.outstanding(), |exec| exec.poll(),
&mut started, TIMEOUT,
|completion| { let _ = send(Reply::Complete(completion)); },
);
The thread only reaches its exit path afterwards. The single shared deadline is at threaded.rs:1309 (let deadline = Instant::now() + timeout;) and the join() at 1335 is outside it; after the join the for loop continues to the next peer, so remaining is only re-checked at 1348, i.e. after an unbounded join.
Concrete counterexample (SM120 PCIe TP4, ranks 1..3): every peer fails validate_submission on epoch e → each sends Err, then blocks up to 120 s in drain_outstanding_frames. Coordinator: close_peers times out (120 s) → best_effort_drain_peers(120s) reads Ok(Err(_)) from peer 1 at t0 and join()s it, blocking ~120 s; peer 2 and 3 are never even polled before the deadline expires at 1348, so they are left unconfirmed and the local.close()/watchdog path fires (CloseStalled → std::process::abort()). Worst case per close is 120 + N·120 s instead of one shared 120 s — the new watchdog then converts that into exactly the process abort the drain handshake was added to remove.
Fix: only Reply::Drained or TryRecvError::Disconnected may set exited; an Err reply must be recorded and treated as progress, never joined:
Ok(Ok(Reply::Drained)) | Err(mpsc::TryRecvError::Disconnected) => { exited = true; break; }
Ok(Err(e)) => { peer.reported_error = Some(e); made_progress = true; continue; }
and only join when Disconnected was observed (or hand handles to a detached joiner so the sweep stays within deadline).
Finding 2 — Major: flushed_now is inferred from two counters that do not count the same SQEs; cancel SQEs corrupt queued_sqes, so reads are marked flushed that the kernel never submitted (and vice versa)
Diff site helios/src/async_transfer/worker.rs:1222-1229 and 1236-1244 (verified verbatim):
if res.is_ok() {
submitted_io = true;
let flushed_now = scheduler
.unflushed_io_count()
.saturating_sub(args.io_backend.pending_submissions());
if flushed_now > 0 {
scheduler.mark_io_flushed(flushed_now);
}
if submitted_io || args.io_backend.pending_submissions() > 0 {
let flush_result = args.io_backend.flush();
let flushed_now = scheduler
.unflushed_io_count()
.saturating_sub(args.io_backend.pending_submissions());
Callee resolution: pending_submissions() is self.queued_sqes (io_backend.rs:195-197), which is incremented only in push_read_sqe (io_backend.rs:136) but is decremented by the total submission count on paths that also submit cancel SQEs (io_backend.rs:224-236 and :252-255):
for op_id in pending_ids {
let cancel = opcode::AsyncCancel::new(op_id).build().user_data(0);
if self.ring.submission().is_full() {
if let Ok(submitted) = self.ring.submit() {
self.queued_sqes = self.queued_sqes.saturating_sub(submitted);
}
}
let _ = unsafe { self.ring.submission().push(&cancel) };
}
if let Ok(submitted) = self.ring.submit() {
self.queued_sqes = self.queued_sqes.saturating_sub(submitted);
}
submit_with_args(1, &args) (io_backend.rs:252) submits everything staged, cancels included, and its return is subtracted from queued_sqes. So the identity "queued_sqes == number of staged SQEs belonging to unflushed ops" is false.
Concrete counterexample: 2 reads staged & unflushed, expected holds 4 ops → 4 cancel SQEs pushed, queued_sqes still 2; submit_with_args submits 6 and returns 6 → queued_sqes = 2.saturating_sub(6) = 0. The worker then computes flushed_now = 2 - 0 = 2 and calls mark_io_flushed(2) on reads with no guarantee of kernel submission. Mirror direction: any orphan SQE makes unflushed_io_count() - pending_submissions() equal the true count while a genuinely submitted read is never marked; its CQE is then silently dropped by the new complete_io guard (scheduler.rs:580-582, if ok && !self.inflight_io[pos].flushed { return None; }) at the harvest site worker.rs:993-997, inflight_io never empties, finish_drain (scheduler.rs:816) never reaches Stopped, and FailedDrain pins all host memory + CUDA handles until process exit. saturating_sub hides the accounting corruption in both directions.
Fix: count read SQEs explicitly — increment queued_read_sqes in push_read_sqe, return the number of read SQEs actually accepted from flush(), and drive mark_io_flushed from that delta; give cancel SQEs a distinct user_data so poll_completions's op_id == 0 filter (io_backend.rs:203-206) stays sound.
Finding 3 — Major: the cuEventQuery-fault path can never advance the mapped-host completion mirror; host waiters block to their own timeout on a transfer that completed
Diff site helios/src/async_transfer/worker.rs:1039-1044 (verified verbatim):
untracked_faulted_dmas.push(UntrackedFaultedDma {
op_id: done.op_id,
pending_notice: None,
hardware_signaled: done.hardware_signaled,
host_mirror_on_drain: None,
});
Callee resolution: the drain branch that is supposed to advance the mirror is worker.rs:1053-1059: if let Some((slot, val)) = item.host_mirror_on_drain { update_host_comp(slot, val); }. host_mirror_on_drain is hard-None on this path, and PendingEventDma (worker.rs:315-321) carries completion_action but the fault construction drops it — only the cuEventRecord-failure path populates host_mirror_on_drain (worker.rs:1180-1185).
Concrete counterexample: DMA with cuStreamWriteValue64_v2 already enqueued (hardware_signaled = true, worker.rs:1143-1149) whose cuEventQuery then returns a sticky error. mark_dma_faulted(.., true) correctly suppresses the error sentinel (scheduler.rs:724-728), complete_dma releases the bounce slot on clean drain — but update_host_comp is never called, so a host consumer polling that completion slot never observes the success cookie and spins to its own timeout (or mis-times the transfer) even though the DMA finished.
Fix: retain completion_action in PendingEventDma and compute host_mirror_on_drain at fault time with the same match used at worker.rs:1180-1185.
Finding 4 — Minor: all_nvlink_p2p collapses three fabric states into two, so "cannot tell" silently widens the gate to peer_access_graphs
helios/src/runtime_core/model.rs:135-172 (per source read): Nvml::load(), device_by_pci_bus_id and device_p2p_status failures all return false, which copy_gate_policy reads as "not all-pairs NVLink" → gate enabled on peer_access_graphs. Counterexample: 4× H100 NVSwitch host in a container without libnvidia-ml.so; copy_gate_policy(4,false,false,true) == (true,true) → every peer-access graph serializes behind prefix-cache offload batches and can fail with ExecutionError::Drain after PEER_GRAPH_GATE_TIMEOUT (120 s) for no reason. Fails safe (gates more), hence Minor. Fix: return a tri-state and, for Unknown, keep today's narrower peer_copy_graphs predicate plus a one-time load-time diagnostic. The predicate itself is correct: it queries (i,j) and (j,i) for P2P_CAPS_INDEX_NVLINK, so asymmetric NVLink correctly reads as "not all NVLink".
Finding 5 — Minor: cleanup_failed_startup join()s with no deadline and the watchdog is spawned only after a successful startup
helios/src/execution/threaded.rs:1437-1444: match thread.join() { Ok(shutdown) if shutdown.drained => {} ... } — peer.receive() is TIMEOUT-bounded but join() is not, and the RankWedgeWatchdog is created at 1012-1028, after startup succeeds. A peer stuck in GraphExecutor::close() (synchronize(), engram.drain(), unbounded) hangs ThreadedExecutor::new forever. Fix: spawn the watchdog before the startup closure, or poll JoinHandle::is_finished() against TIMEOUT.
Finding 6 — Minor: two hot-path costs and one dropped-CQE silence
worker.rs:1199-1233+1238-1243: every submit doesunflushed_io_count()(O(n) scan,scheduler.rs:226-228) andmark_io_flushed(O(n),scheduler.rs:231-243), twice per iteration;complete_ionow does an orderedVec::remove(O(n),scheduler.rs:585) instead ofswap_remove— fine atDEFAULT_MAX_TOTAL_IO = 32(worker.rs:46) but the bound is not enforced:TransferScheduler::newaccepts anymax_total_io(scheduler.rs:162-169). Keep anunflushedcounter instead of rescanning.complete_io'sNone(unflushed-okguard) is discarded at both harvest sites (worker.rs:993-997,:1294-1295): a dropped CQE yields no counter, nolast_error, and leaves the op pinned with zero diagnostics.threaded.rs:1326-1329:made_progress = true; continue;skips the loop's only sleep (1354-1356), so a peer streaming non-terminal replies busy-spins all peers.
Verified correct (explicitly checked, no defect)
- Three-phase teardown barrier (
model.rs:1277-1340): phases strictly drain-all →engram.clear()+offload.reset()(whileMappedHoststaging buffers and CUDA contexts are live;Layer::dropengram.rs:584-592joins the reader thread,Transfers::Dropoffload/transfer.rs:843-854joins every offload thread) → destroy-all → reverse-rank context release.teardown_model_ranksaccumulatesall_drained &= drainedover every rank before skipping phases 2–3, so N=4 with rank 2 failing drain frees nothing → the cross-rank UAF cannot recur.stop_rank_workers(mod.rs:2033-2040) genuinely removes the||short-circuit (both&self, idempotent stops). peer_access_graphsvspeer_copy_graphsseparation (mod.rs:297-327,1482-1483,1612-1618;serving.rs:54-59): both vectors pushed in the samecore.graphsiteration ⇒ aligned withself.executables;Node::Copy(Memory::Peer)sets both, local copy neither,Memset/Kernelset access only viapeer_refs,Empty/EventWaitneither.validate_async_transfer_peer_copy_compatibility(model.rs:191-207) keeps onlyhas_any_peer_copy_graphs⇒ NVLink/kernel-P2P cores are no longer falsely rejected — the intended decoupling.- Peer-referencing closure ordering:
collect_peer_referencing_allocationsruns afterload_payloadhas populatedpeer_table_allocationsand before the module-global scan (mod.rs:995-1043), stored inself.peer_refs(1091), consumed withtake()+ recompute fallback (1119-1125); monotone fixpoint (252-267).prepare_kernelsis called unconditionally per rank beforeprepare_graphs(model.rs:912-930, joined at1183-1214), so the gate can never see a half-filled vector. - Payload 8-byte scan boundaries (
mod.rs:201-232,payload.rs:257,378-387):chunks_exact(8)on analloc_offset-derivedskipcatches a pointer in the last 8-byte word; emptypeer_intervalsshort-circuits before any scan; search is O(words · log m) viapartition_point, not O(n·m). Only residual doubt:format.rsacceptsalignment == 1, under which an unaligned pointer table could be missed — unreachable for the exported cores examined, but worth hardening toalignment >= 8for payload-bound allocations. RankWedgeWatchdog: resets only whencurrent != last_activity(no off-by-one/never-reset);wake.wait_whilere-checks busy/closing/peer_exited/stopped under the lock with every notify-holder takingwake_lockfirst ⇒ no lost wakeup, zero idle CPU; the closing branch dominatespeer_exitedso a healthy teardown arms no 30 s grace; dropped insideclose()beforeself.shutdownis recorded.flush_queued_sqes(io_backend.rs:146-170): EINTR bounded to 16 consecutive retries,Ok(0)breaks without spinning, non-EINTR errors propagate withqueued_sqespreserved — unit-tested at:461-471.hardware_signaledsentinel suppression acrossInflightDma/PendingEventDma/UntrackedFaultedDma:mark_dma_faulted(hw=true)returnscompletion_slot: None(scheduler.rs:724-728) and every publish site passes!hardware_signaled/false, sosignal_completion_slotis unreachable for already-signaled DMAs;host_compstill advances monotonically.- Metrics rank labels (
metrics.rs:1535-1567):s.rankis the true global rank (ChannelConfig.rank = global_rank,runtime_core/mod.rs:1849-1852, fromcluster_rank.unwrap_or(idx)), channel names are unique per rank ⇒ no duplicate(channel, rank)series; the newVecof snapshots is one extra POD allocation per scrape on a path that already cloned aStringper channel. - TLA+/
.cfg/check.pywiring is real, not vacuous:FlushIois inStep(AsyncTransfer.tla:186) and kind 12 inActionMatches(:320) hence reachable fromNext;UnflushedIoBounded/HwSignaledFaultedSafeare defined (:247-255), wrapped intoObservedSafe(:267-268) and listed inAsyncTransfer.cfg:22-23; projection width 16 matcheslifecycle_tests.rs:24; both new TLA mutations and both new Rust mutations match the shipped text verbatim (count(needle) == 1enforced atcheck.py:273-274).
Limits: source-reading only — no execution of the live SM120 TP4 run, the TLA+ suite, or the crate tests was possible here; Findings 1–3 are established by code reading and need a partial-submit/EINTR + wedged-peer workload to reproduce live.
Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.
Re-review
Recommendation: Changes Requested
All Round 1 findings are cleanly resolved at c9df77b — complete_io now preserves io_uring SQ FIFO order via remove(pos) with a regression test, RankWedgeWatchdog::CloseStalled now tracks activity across close() stages, best_effort_drain_peers sweeps peers round-robin against a shared deadline, and all 3 simplifications and 4 nits were addressed. However, verification at c9df77b identified two concrete edge-case code defects — one in the rewritten best_effort_drain_peers loop (where Ok(Err(_)) triggers an unbounded thread.join() while a peer is still inside drain_outstanding_frames) and one in AsyncTransfer's cuEventQuery-fault path (which drops host_mirror_on_drain instead of propagating HostOnly completions on clean stream drain) — plus the mandatory live multi-GPU re-run for modified threaded.rs drain paths (docs/design-review.md:252-259). Fixing both small defects and re-running the existing SM120 PCIe TP4 flare run + SIGTERM check on the final commit will make this ready to merge.
Merge Risk
Level: Medium
- The Round 1 High-risk
swap_removeCQE-drop bug and fixed-wall-clockCloseStalledabort are fixed and covered by unit/conformance/mutation tests. - On a multi-peer validation failure with an in-flight frame,
best_effort_drain_peerscan still block unboundedly inthread.join()after readingOk(Err(_))from a peer still insidedrain_outstanding_frames, starving healthy peers and riskingCloseStalledprocess abort. - On a
cuEventQueryerror followed by cleancopy_streamdrain for a hardware-signaled DMA withdevice_completions_base != 0,host_comp[slot]is never updated becausehost_mirror_on_drainis hardcoded toNone.
Walkthrough
- Round 1 Blocker fixed (
helios/src/async_transfer/scheduler.rs:583-585,1128-1175): Replacedswap_remove(pos)with orderedremove(pos)incomplete_iosoinflight_iostays synchronized with kernelio_uringSQ FIFO order across partial submits; addedpartial_flush_preserves_sq_fifo_order_across_completions. - Round 1 Should-Fix items addressed (
helios/src/execution/threaded.rs:679-693,1216-1358,4152-4272):CloseStallednow resetsclose_sincewheneveractivityadvances acrossclose()/close_peers/best_effort_drain_peersprogress marks;best_effort_drain_peersnow polls all live peers round-robin via non-blockingtry_recv()against a single shared deadline (with one remainingOk(Err(_))join bug noted below). - Round 1 Simplifications & Nits applied (
helios/src/runtime_core/{mod,model}.rs,helios/src/async_transfer/{io_backend,worker}.rs,docs/api.md): DeletedRankWedgeWatchdog::stop_and_joinand the unreachable duplicateprepare_async_transferspeer-copy check; consolidated interval building (storage_intervals) and single-passpeer_refscaching; checked both(i, j)and(j, i)inall_nvlink_p2p; boundedflush_queued_sqesEINTRretries toMAX_EINTR_RETRIES = 16; removed unusedAsyncTransferRuntime::rank(); documented globalrankID labels indocs/api.md:403-405and explicitstd::process::abort()behavior in the PR description.
Pre-merge Checks
- [PASS] Security / malicious screen: Clean; no suspicious network/exfiltration/unsafe-boundary issues, and payload scanning reads already-authenticated bytes.
- [PASS] Charter & value fit: Directly resolves reproducible P1 bug #722 on SM120 PCIe with topology-derived gating, no per-model branches, and no wire/core-format or captured-graph op-contract changes.
- [WARN] Related / duplicate / conflict check: Same-day follow-up to #721; sibling open PRs #726/#723 touch
prepare_async_transfers/release_execution_resourcesand should be serialized if merged alongside #727. - [WARN] Tests & verification evidence: TLA+ conformance/mutations (
check.py (not opened) --mutations), targeted Rust suites (50/50,0warnings), and single-GPUlive_cuda_async_transfer_end_to_endwere re-run onc9df77bd, but the live SM120 PCIe TP4flare runcheck is dated224fb403(prior to thebest_effort_drain_peers/close_peerschanges inc9df77bd, whereasdocs/design-review.md:252-259requires live multi-GPU execution for modifiedthreaded.rsdrain paths).
Blockers
None.
Should Fix
-
best_effort_drain_peerstreatsOk(Err(_))as thread exit and calls unboundedthread.join()while a peer may still be insidedrain_outstanding_frames(helios/src/execution/threaded.rs:1319-1340,1540-1555,913-919)- Verified behavior: When a peer fails
validate_submission(threaded.rs:1540-1555), it sendsreplies.send(Err(error.clone()))at1543before callingdrain_outstanding_frames(..., TIMEOUT)at1545-1554(which can block up to120 sor wedge insideexecutor.poll()). Inbest_effort_drain_peers(1319-1336),Ok(Err(_))setsexited = trueand immediately callsthread.join()without a deadline — starving subsequent healthy peers from being polled/joined within the shared deadline and allowingCloseStalledto abort the process. By contrast, every real error-exit path (901,916) returns immediately and dropsreplies, producingErr(mpsc::TryRecvError::Disconnected), and clean drain sendsReply::Drainedonly afterexecutor.close()returns (1375-1382). - Fix: Only treat
Ok(Ok(Reply::Drained)) | Err(mpsc::TryRecvError::Disconnected)asexited = true. MoveOk(Err(_))into theOk(Ok(_)) | Ok(Err(_)) => { made_progress = true; continue; }arm so a peer that already exited after sendingErrimmediately hitsDisconnectedon the nexttry_recv()iteration and joins, while a peer still draining indrain_outstanding_framesdoes not block the round-robin sweep. Add a regression test where peer 0 sendsErr(...)while remaining blocked and peer 1 sendsReply::Drained.
- Verified behavior: When a peer fails
-
cuEventQuery-fault path hardcodeshost_mirror_on_drain: None, leavinghost_compstale after clean stream drain (helios/src/async_transfer/worker.rs:1031-1066,1143-1149,1164-1192)- Verified behavior: When
args.use_write_value64 && args.config.device_completions_base != 0, a hardware-signaled DMA storescompletion_action: EventCompletionAction::HostOnly(slot, dma.signal_value)inPendingEventDma(1143-1149,1164-1174). OncuEventRecordfailure (1180-1192),worker_mainextractshost_mirror_on_drainfromcompletion_actionsoupdate_host_comp(slot, val)advances the mapped-host mirror whencuStreamQuery(copy_stream) == 0(1057-1059). However, oncuEventQueryfailure (1039-1044),UntrackedFaultedDmais constructed withhost_mirror_on_drain: None, droppingdone.completion_actionso host-side readers pollinghost_comp[slot]never observe completion even aftercopy_streamdrains cleanly. - Fix: Compute
host_mirror_on_drainfromdone.completion_actionatworker.rs:1039-1044using the sameEventCompletionAction::HostOnly(slot, val) if done.hardware_signaled => Some((slot, val))match (or a small helper shared with1180-1185).
- Verified behavior: When
-
Re-run live SM120 PCIe TP4 serving +
SIGTERMverification on the final commit (docs/design-review.md:252-259)- Verified behavior:
docs/design-review.md:252-259requires live multi-GPU execution of real collective graphs (e.g., serving a multi-GPU exported core viaflare run) when replacing or reordering drain paths inhelios/src/execution/threaded.rs. The PR's live TP4 run is from224fb403, prior toc9df77bd's changes tobest_effort_drain_peersandclose_peers. - Fix: After applying fixes (1) and (2) above, re-run the existing SM120 PCIe TP4
flare run+SIGTERMcheck on the final head and record the commit hash and result in the PR description.
- Verified behavior:
Subtract / Simplify
- Reuse
merge_sorted_intervals(helios/src/runtime_core/mod.rs:151-163vshelios/src/runtime_core/host.rs:62-70): Both implement the identical sort-and-merge loop overVec<(u64, u64)>; makingmerge_sorted_intervalspub(super)letshost.rsdelegate to it. - Replace
format_json_vec(helios/src/async_transfer/lifecycle_tests.rs:51-57) withformat!("{v:?}"):[i64; 16]'sDebugrepresentation produces identical JSON array output without maintaining a 16-placeholder format string across future projection changes.
Nits
None.
Dropped on verification
- Upstream Code Correctness Finding 2 (
queued_sqes/cancel_and_drainSQE desync,io_backend.rs:224-264,worker.rs:1224-1292): False positive.cancel_and_drainruns only once at shutdown (worker.rs:1284-1286) after the main loop exits and no further read SQEs can be pushed. BecauseAsyncCancelSQEs are appended strictly behind any remaining read SQEs in the FIFOio_uringSQ ring ([Read_1..Read_k, Cancel_1..Cancel_m]), submittingsSQEs always consumesmin(k, s)read SQEs first, soqueued_sqes.saturating_sub(submitted)remains exact. - Upstream Subtraction B3 (replace all 4
ring.submit()calls incancel_and_drainwithself.flush()): Dangerous false positive.io_backend.rs:252is a timed CQE wait (submit_with_args), and lines227, 234, 262must submitAsyncCancelSQEs even whenqueued_sqes == 0; callingself.flush()(which loopswhile *queued_sqes > 0) would silently skip submitting cancellations. - Upstream Code Correctness Finding 5 (
cleanup_failed_startupunboundedjoin()without watchdog,threaded.rs:1416-1447): False positive.cleanup_failed_startupwaits forReply::DrainedviaPeer::receive(), which enforcesTIMEOUT(120 s,threaded.rs:788-791), anddrain_rankonly sendsReply::Drainedafterexecutor.close()returns (1375-1382); a wedged close times out inpeer.receive()beforethread.join()is called. - Upstream Code Correctness Finding 6 (
best_effort_drain_peersmade_progress = true; continue;busy-spin;unflushed_io_count()O(N) scan): False positive / non-defect. Each peer has at most 2 in-flight frames, so draining bufferedReply::Completemessages finishes immediately and falls through toEmptyand the 1 ms sleep;unflushed_io_count()scans at mostDEFAULT_MAX_TOTAL_IO = 32entries (worker.rs:46). - Upstream Code Correctness Finding 4 (
all_nvlink_p2preturningfalsewhen NVML is unavailable): Intentional fail-safe behavior — failing open on unknown P2P topology would risk reintroducing #722 in containers lackinglibnvidia-ml.so. - Upstream Dossier §B4 (
self.local.close()synchronizing without progress marks): Intended behavior — detecting a CUDA driver hang insideself.local.close()is the purpose ofWedgeReason::CloseStalled. - Upstream Dossier §C4 (
load_preparednot callingvalidate_async_transfer_peer_copy_compatibility): Non-issue —load_prepared(mod.rs:510-532) never callsprepare_async_transfers, whose sole caller isNativeModel::load(model.rs:1046), which enforces the check atmodel.rs:935. - Upstream Subtraction A2 (
peer_refs: Option<...>), B2 (stop_rank_workers), B4 (WatchdogCallGuard::enterkeep_busy), B5 (contains_interval_address): Dropped —peer_refsdirectly implements Round 1's caching suggestion;stop_rank_workersandWatchdogCallGuard::enter'skeep_busy(required for early returns insubmit()atthreaded.rs:1071-1088) were already verified and dropped in Round 1; replacingchunks_exact(8)with a strided loop degrades payload-scan optimization.
Classify triage
Selected: triage:review
Threshold: 65%
Triage
- [✓]
triage:review: 95.8% -
triage:validation: 3.7% -
triage:design-review: 0.3% -
none: 0.1% -
triage:investigate: 0.0% -
triage:partial: 0.0% -
triage:integration: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Apply labels
No label changes Decision to Test: no (97%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.