Skip to content

helios: gate PCIe peer-access graphs and fix teardown, AsyncTransfer, and startup drain races - #727

Merged
lukealonso merged 3 commits into
mainfrom
fix-helios-p0s
Dec 4, 2026
Merged

lukealonso merged 3 commits into
mainfrom
fix-helios-p0s

Conversation

@lukealonso

@lukealonso lukealonso commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #722

Why

Four concurrency and memory-lifetime defects affect multi-rank PCIe serving, model teardown, asynchronous extent transfers, and startup error handling in Helios:

  1. PCIe multi-rank CopyEngineGate deadlock (helios: TP4 serving hangs under --prefix-cache-memory on SM120 PCIe; CopyEngineGate leaves 145/177 DeepSeek-V4.1-Flash graphs ungated #722) and unguarded rank wedges: NativeResources::prepare_graphs flagged only graphs containing explicit Node::Copy nodes targeting Memory::Peer. On single-host PCIe multi-rank topologies, captured graphs using kernel-based peer-to-peer collectives (accessing Memory::Peer through kernel parameters, module globals, or indirect peer-pointer tables such as rank_data) alongside local Node::Copy nodes bypassed CopyEngineGate. Under --prefix-cache-memory, concurrent host offload Copy Engine transfers deadlocked those GPUs at 100% utilization. Because Execution.async_transfers compatibility validation reused the same peer_copy_graphs predicate, widening CopyEngineGate without separating Copy Engine peer-copy nodes from kernel peer accesses would falsely reject NVLink SM P2P or kernel-P2P cores. Separately, when a coordinator rank wedged inside a CUDA driver call, ThreadedExecutor had no independent watchdog past its 120 s step/drain deadlines.
  2. Cross-rank teardown use-after-free in NativeModel::drop: NativeModel::drop iterated ranks in reverse calling release_execution_resources(), which short-circuited stop_persistent_worker().is_err() || stop_async_transfers().is_err() and freed peer Memory::Device allocations and Memory::MappedHost mailboxes on rank N-1 while ranks 0..N-2 had not finished draining and before self.engram.clear() joined background Engram threads polling those MappedHost addresses.
  3. AsyncTransfer SQE stranding, completion-slot sentinel clobbering, and wrong Prometheus rank labels:
    • In async_transfer/worker.rs, submitted_io was reset every loop iteration while IoUringBackend::flush() retained unsubmitted entries in queued_sqes after EINTR or partial submission, allowing DEMAND reads to strand in the submission queue.
    • When cuEventRecord or cuEventQuery failed after cuStreamWriteValue64_v2 had already been queued on the Copy Engine stream, draining the stream later called publish_notice(notice, true), overwriting live or reused completion slots with COMPLETION_ERROR_BIT | error_code. Neither failure mode was modeled in AsyncTransfer.tla.
    • server/metrics.rs labeled flare_async_transfer_* Prometheus series with the flat vector index across all local channels instead of each channel's global rank ID.
  4. Process abort on peer FinishStartup failure: In execution/threaded.rs, a peer rank whose finish_startup failed exited run_startup_phase without servicing Command::Drain or sending Reply::Drained, causing cleanup_failed_startup to call std::process::abort().

What changed

  • PCIe peer-access CopyEngineGate detection and AsyncTransfer decoupling (helios/src/runtime_core/{payload,mod,host,serving,model}.rs, docs/prefix-cache-offload.md):
    • Before: NativeResources recorded only peer_copy_graphs (Node::Copy with a Memory::Peer endpoint) and reused that predicate for both CopyEngineGate and Execution.async_transfers validation (duplicated in NativeResources::prepare_async_transfers).
    • After: payload::load aligns parallel chunk boundaries to 8 bytes and scans 8-byte aligned payload words against Memory::Peer intervals (when any exist) to flag indirect peer-pointer-table allocations. NativeResources computes the transitive peer-referencing closure once in prepare_kernels (sharing merge_sorted_intervals with host.rs and storage_intervals, consuming it in prepare_graphs) and tracks peer_copy_graphs (strictly Node::Copy(Memory::Peer)) separately from peer_access_graphs (peer copies, peer memsets, kernel argument/attribute relocations or inline fixed addresses into peer or peer-pointer-table allocations, and peer-referencing module globals). NativeModel checks symmetric NVML P2P_CAPS_INDEX_NVLINK (all_nvlink_p2p) and enables CopyEngineGate over peer_access_graphs on single-host PCIe multi-rank deployments without all-pairs NVLink, while validate_async_transfer_peer_copy_compatibility continues rejecting only peer_copy_graphs.
  • Rank-wedge watchdog, round-robin best-effort peer drain, and FinishStartup drain handshake (helios/src/execution/threaded.rs):
    • Before: Peer FinishStartup failures exited the startup loop without answering Command::Drain (triggering std::process::abort()), best_effort_drain_peers polled peers sequentially with separate deadlines, and no watchdog monitored wedged coordinator calls.
    • After: Reply::Started carries Result<()>; peers that fail finish_startup send Reply::Started(Err(error)) and stay in run_startup_phase to service Command::Drain -> Reply::Drained. best_effort_drain_peers sweeps all live peers round-robin with non-blocking try_recv() against one shared deadline (including a final non-blocking sweep at expiry) and only joins on Ok(Ok(Reply::Drained)) or Err(TryRecvError::Disconnected), so healthy peers join even when an earlier peer is wedged or still inside drain_outstanding_frames after sending Err(...). RankWedgeWatchdog monitors busy, closing, and peer-exit stalls with zero idle CPU via Condvar::wait_while—resetting the stall timer whenever activity advances across multi-stage close() transitions and terminating the process via std::process::abort() if a rank remains wedged past TIMEOUT + 30 s grace (or 30 s grace after unrecoverable peer exit).
  • Three-phase cross-rank teardown barrier (helios/src/runtime_core/{mod,model}.rs, docs/runtime-core-design.md):
    • Before: NativeModel::drop freed each rank sequentially in reverse order with || short-circuiting between persistent-worker and async-transfer stops before self.engram.clear() and self.offload.reset().
    • After: stop_rank_workers evaluates both worker stops without short-circuiting. teardown_model_ranks executes a three-phase barrier: (1) drain workers and call cuCtxSynchronize on every rank before freeing any storage; (2) join self.engram.clear() and self.offload.reset() while Memory::MappedHost mailboxes and CUDA contexts remain live, then destroy streams, graphs, modules, and allocations across ranks; (3) destroy green contexts, VA reservations, and primary CUDA contexts in reverse rank order. If any rank fails drain, all ranks retain their CUDA and host resources until process exit.
  • AsyncTransfer SQE flush, hardware-signaled faulted DMA, true rank metrics, and AsyncTransfer.tla (helios/src/async_transfer/{io_backend,scheduler,worker,lifecycle_tests}.rs, helios/src/server/metrics.rs, docs/api.md, verification/helios-lifecycle/{AsyncTransfer.tla,AsyncTransfer.cfg,README.md,check.py}):
    • Before: IoUringBackend::flush() did not retry EINTR or expose pending SQEs, worker.rs flushed only when submitted_io was true in the current iteration, complete_io removed entries with swap_remove, post-cuStreamWriteValue64_v2 faulted DMAs published error sentinels on drain, and metrics.rs used flat .enumerate() indices as rank labels.
    • After: IoUringBackend::flush() retries EINTR (bounded to 16 consecutive retries per call so shutdown polling stays responsive) and drains partial submissions via flush_queued_sqes while exposing pending_submissions(), and worker.rs flushes whenever submitted_io || pending_submissions() > 0. InflightIo tracks flushed and complete_io uses ordered remove(pos) (max_total_io <= 32) so mark_io_flushed remains synchronized with kernel io_uring SQ FIFO order across partial submits. InflightDma, PendingEventDma, and UntrackedFaultedDma track hardware_signaled so post-WriteValue64 faults (from either cuEventRecord or cuEventQuery) never overwrite completion slots with error sentinels and monotonically advance host_comp via EventCompletionAction::host_mirror_on_drain on clean stream drain. ChannelConfig and AsyncTransferSnapshot carry true global rank IDs rendered in metrics.rs (documented in docs/api.md). AsyncTransfer.tla, lifecycle_tests.rs, and check.py extend the projection to 16 integers adding FlushIo (UnflushedIoBounded), hwSignaledFaulted (HwSignaledFaultedSafe), and corresponding TLA+ and Rust mutations.

Claimed benefit and result

  • Expected & verified correctness: Prevents single-host PCIe TP>=2 CopyEngineGate deadlocks for kernel-P2P graphs under --prefix-cache-memory, bounds wedged-rank hangs via RankWedgeWatchdog (std::process::abort() on unrecoverable wedges while allowing progressing multi-stage closes), joins healthy peers behind wedged or draining peers in best_effort_drain_peers, eliminates cross-rank MappedHost/Device teardown UAF in NativeModel::drop, prevents io_uring SQE stranding, FIFO CQE drops on partial flush, and post-WriteValue64 completion-slot clobbering or stale host_comp mirrors in AsyncTransfer, reports true global rank IDs in Prometheus flare_async_transfer_* metrics, and replaces FinishStartup peer-error aborts with clean drain errors.
  • Measured live SM120 PCIe TP4 result (verified on f7b83ae2): Serving an exported 4-rank DeepSeek-V4.1-Flash core (135 graphs/rank, 1.92 GiB peer views, Engram lookahead prefetch) under --prefix-cache-memory 4G --memory-limit 81G on 4 SM120 PCIe GPUs completed 20 concurrent ~13k-token requests in 0.45s–3.74s while offloading 1.09 GiB (37 host records, 0 failures) concurrently with TP4 prefill/snapshot/speculative graphs and exited cleanly on SIGTERM (status=0 in 3s). No throughput speedup claim is made beyond deadlock/fault elimination.

Supporting evidence and limitations

  • TLA+ models, Rust conformance, and mutation suite (re-run on f7b83ae2):
    • Command: python3 verification/helios-lifecycle/check.py --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar --java /usr/bin/java --target-dir flare-cli/target --mutations
    • Result: exit 0. All 10 TLA+ models, all 9 Rust-to-TLA+ conformance suites (431 observed AsyncTransfer transitions, 7,940 DispatchRing transitions), and all TLA+ and Rust mutations passed (including UnflushedIoBounded, HwSignaledFaultedSafe, unflushed io completed ok before flush, and hardware-signaled faulted dma clobbered completion slot).
  • Rust crate tests & builds (--locked --release):
    • On f7b83ae2: targeted helios --features runtime-core,server tests with RUSTFLAGS="-D warnings" (54/54 passed, 0 warnings, including best_effort_drain_peers_does_not_block_joining_peer_that_sent_err_before_exiting, host_mirror_on_drain_preserves_hardware_signaled_host_only_completions, partial_flush_preserves_sq_fifo_order_across_completions, bounded EINTR retry, progressing multi-stage close watchdog test, best_effort_drain_peers_joins_healthy_peers_even_when_earlier_peer_is_wedged, and runtime_core::host::*), flare-cli release build, and flare-cli --features roce check all passed.
    • Full crate pass on 224fb403: eos (12 passed), selene --features test-support, selene-manager --features test-support, flare, flare-cli, helios --test '*' with FLARE_TEST_TEMPLATE_DIR=/tmp/flare-test-templates, heliopause check, helios --lib (1,920 passed), Python tests/cli (206 passed), plus GitHub CI (lifecycle, kani, pytest all green on c9df77bd).
  • SM120 GPU verification (RTX PRO 6000 Blackwell Max-Q, re-run on f7b83ae2):
    • FLARE_RUN_CUDA_TESTS=1 CUDA_VISIBLE_DEVICES=10 cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server -- async_transfer::worker::cuda_tests::live_cuda_async_transfer_end_to_end: passed (1.24s).
    • Live SM120 PCIe TP4 serving (CUDA_VISIBLE_DEVICES=3,4,5,6) of deepseek-ai/DeepSeek-V4.1-Flash-1017 (gb202-tp4-202611281955, --prefix-cache-memory 4G --memory-limit 81G --embedding-table-cache-size 1G): 20/20 concurrent ~13k-token requests succeeded (0.45s–3.74s, flare_host_cache_stored_total=37, flare_host_cache_bytes_out_total=1171271680 / 1.09 GiB, flare_host_cache_store_failed_total=0, 62 prefill / 37 snapshot / 140 speculative / 13 init launches, 404 Engram gathers); SIGTERM exited cleanly (status=0, 3s).
  • Unrun checks and material limitations:
    • 6 helios --lib frontend template tests failed locally because tests/frontend/prepare_templates.py receives HTTP 403 on gated HuggingFace repository meta-models/Muse-Spark-Open-816B-A42B-NVFP4.
    • SM103/SM121 hardware, multi-host RoCE execution, and local Kani CLI (cargo-kani not on PATH; CI runs the Kani workflow) were not run locally.
    • No multi-GPU core combining Execution.async_transfers without Node::Copy(Memory::Peer) was available locally (the local DeepSeek-V4.1-Flash TP2 tiered-MoE core includes Node::Copy(Memory::Peer) and was rejected at load time as intended).

Discord: lukealonso

… and startup drain races

Why:
Four concurrency and lifetime defects affect multi-rank PCIe serving,
teardown, asynchronous extent transfers, and startup error handling in
Helios:
1. CopyEngineGate previously flagged only graphs with explicit
   Node::Copy(Memory::Peer) nodes. Single-host PCIe multi-rank cores whose
   graphs use kernel-based P2P collectives (referencing Memory::Peer via
   kernel parameters, module globals, or indirect pointer tables such as
   rank_data) alongside local Node::Copy nodes bypassed CopyEngineGate and
   deadlocked GPUs under --prefix-cache-memory. If a coordinator rank
   wedged inside CUDA, ThreadedExecutor had no watchdog past its 120 s
   deadlines.
2. NativeModel::drop freed ranks sequentially in reverse order through
   release_execution_resources, which short-circuited
   stop_persistent_worker().is_err() || stop_async_transfers().is_err() and
   released peer Device allocations and MappedHost mailboxes on rank N-1
   before ranks 0..N-2 drained and before self.engram.clear() joined
   background Engram threads polling those MappedHost addresses.
3. In AsyncTransfer, worker.rs reset submitted_io each iteration while
   IoUringBackend::flush could leave queued_sqes unsubmitted on EINTR or
   partial submit (stranding DEMAND reads); a cuEventRecord or cuEventQuery
   failure after cuStreamWriteValue64_v2 had already succeeded later called
   publish_notice(notice, true), clobbering live or reused completion slots
   with error sentinels (neither path was modeled in AsyncTransfer.tla);
   and server/metrics.rs labeled async-transfer Prometheus metrics with flat
   vector indices rather than true rank IDs.
4. In ThreadedExecutor::new, a peer failing Command::FinishStartup exited
   without servicing Command::Drain or sending Reply::Drained, causing
   startup cleanup to call std::process::abort().

What changed:
- PCIe peer-access gating and AsyncTransfer decoupling
  (helios/src/runtime_core/{payload,mod,serving,model}.rs,
  docs/prefix-cache-offload.md):
  - Before: NativeResources tracked only peer_copy_graphs
    (Node::Copy(Memory::Peer)) and reused that predicate for both
    CopyEngineGate and Execution.async_transfers validation.
  - After: payload::load scans 8-byte aligned payload words against
    Memory::Peer intervals to identify indirect peer-pointer tables;
    NativeResources tracks both peer_copy_graphs (strictly
    Node::Copy(Memory::Peer)) and peer_access_graphs (copies, memsets,
    kernel argument/attribute relocations or inline fixed addresses into
    peer/peer-table allocations, and peer-referencing module globals).
    NativeModel queries NVML P2P_CAPS_INDEX_NVLINK via all_nvlink_p2p and
    gates all peer_access_graphs under CopyEngineGate on single-host PCIe
    multi-rank deployments without all-pairs NVLink, while
    validate_async_transfer_peer_copy_compatibility continues checking only
    peer_copy_graphs.
- Rank-wedge watchdog and FinishStartup drain handshake
  (helios/src/execution/threaded.rs):
  - Before: peer FinishStartup errors exited the startup loop without
    answering Command::Drain (triggering abort during cleanup),
    best_effort_drain_peers gave each peer a separate deadline, and no
    watchdog monitored wedged coordinator calls.
  - After: Reply::Started carries Result<()>; failing peers reply
    Reply::Started(Err(error)) and remain in run_startup_phase to service
    Command::Drain -> Reply::Drained cleanly; best_effort_drain_peers uses
    one shared deadline; RankWedgeWatchdog monitors busy/closing/peer-exit
    stalls past TIMEOUT + 30 s grace with zero idle CPU via Condvar.
- Three-phase cross-rank teardown barrier
  (helios/src/runtime_core/{mod,model}.rs, docs/runtime-core-design.md):
  - Before: NativeModel::drop freed ranks in reverse order with ||
    short-circuiting before joining Engram/offload workers.
  - After: stop_rank_workers stops both persistent workers and async
    transfers without short-circuiting; teardown_model_ranks drains and
    synchronizes every rank first, joins self.engram.clear() and
    self.offload.reset() while MappedHost and CUDA contexts remain live,
    destroys graphs/modules/allocations across ranks, and releases green
    contexts, VA reservations, and CUDA contexts in reverse order (retaining
    all resources if any rank fails drain).
- AsyncTransfer SQE flush, hardware-signaled faulted DMA, 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,check.py}):
  - Before: IoUringBackend::flush did not retry EINTR or expose
    pending_submissions, worker.rs flushed only when submitted_io was set in
    the current iteration, post-WriteValue64 faulted DMAs published error
    sentinels on drain, and metrics labeled flat indices.
  - After: IoUringBackend::flush loops on EINTR and partial submits via
    flush_queued_sqes and exposes pending_submissions(); worker.rs flushes
    whenever submitted_io || pending_submissions() > 0; InflightDma,
    PendingEventDma, and UntrackedFaultedDma track hardware_signaled so
    post-WriteValue64 faults never overwrite completion slots with error
    sentinels and still monotonically advance host_comp on clean drain;
    ChannelConfig and AsyncTransferSnapshot carry true global rank IDs
    rendered in metrics.rs; AsyncTransfer.tla, lifecycle_tests.rs, and
    check.py model unflushedIo (FlushIo / UnflushedIoBounded) and
    hwSignaledFaulted (HwSignaledFaultedSafe) with matching TLA+ and Rust
    mutations.

Claimed result:
Eliminates single-host PCIe TP>=2 CopyEngineGate deadlocks for kernel-P2P
graphs under --prefix-cache-memory, bounds wedged-rank hangs via the
watchdog, prevents cross-rank MappedHost/Device UAF during NativeModel::drop,
prevents io_uring SQE stranding and post-WriteValue64 completion-slot
clobbering in AsyncTransfer, reports accurate rank labels in Prometheus
metrics, and replaces FinishStartup peer-error process aborts with clean
drain errors.

Validation:
- Formal & mutation checks (python3 verification/helios-lifecycle/check.py
  --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar
  --java /usr/bin/java --target-dir flare-cli/target --mutations):
  exited 0; all 10 TLA+ models, all 9 Rust conformance suites (431 observed
  AsyncTransfer transitions, 7,940 DispatchRing transitions), and all TLA+
  and Rust mutations (including UnflushedIoBounded, HwSignaledFaultedSafe,
  unflushed io completed ok before flush, and hardware-signaled faulted dma
  clobbered completion slot) passed.
- Rust crate tests & builds (release, --locked):
  - eos (12 passed), selene, selene-manager, flare, flare-cli, helios
    integration tests with FLARE_TEST_TEMPLATE_DIR=/tmp/flare-test-templates,
    flare-cli release build, flare-cli --features roce check, and heliopause
    check all passed.
  - helios --lib with RUSTFLAGS="-D warnings": 0 warnings, 1,920 passed
    (including all new peer_usage_tests, copy_gate_policy,
    teardown_model_ranks, stop_rank_workers, flush_queued_sqes,
    hardware_signaled_faulted_dma, async_transfer_metrics_label_true_rank_ids,
    finish_startup_peer_error_drains_mixed_peers_cleanly_without_abort, and
    3 RankWedgeWatchdog tests). 6 frontend template tests failed because
    meta-models/Muse-Spark-Open-816B-A42B-NVFP4 returns HTTP 403 without
    gated HuggingFace access.
  - Python tests/cli: 206 passed.
- SM120 GPU verification (RTX PRO 6000 Blackwell Max-Q):
  - live_cuda_async_transfer_end_to_end (CUDA_VISIBLE_DEVICES=2): passed.
  - Live SM120 PCIe TP4 serving of DeepSeek-V4.1-Flash (135 graphs/rank,
    1.92 GiB peer views, Engram lookahead prefetch, --prefix-cache-memory 4G,
    --memory-limit 81G) on GPUs 2,3,4,14: 20 concurrent 13k-token requests
    completed (0.59-3.86 s) with 1.09 GiB active Copy Engine host offload
    (37 stored records, 0 store failures, 67 prefill / 38 snapshot / 161
    speculative launches, 456 Engram gathers) and exited cleanly on SIGTERM
    (status 0 in 3 s).
- Limitations / unrun checks: SM103/SM121 hardware, multi-host RoCE runs,
  Kani CLI (cargo-kani not on PATH; completion/state-view validators were
  not modified), and the 6 gated Muse-Spark template tests were not run.
  No multi-GPU core combining Execution.async_transfers without
  Node::Copy(Memory::Peer) was available locally (the local DeepSeek TP2
  tiered-MoE core contains Node::Copy(Memory::Peer) and was correctly
  rejected at load time).

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 727.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. priority:P1 High attention: unresolved correctness, serving failure, or model-data deletion risk. triage:review Proposed change needs code review; this does not imply merge readiness. labels Dec 4, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

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).

  • Blockers: 1 · Should fix: 2 · Subtract/Simplify: 3 · Nits: 4
Walkthrough
  • PCIe peer-access CopyEngineGate & AsyncTransfer decoupling (helios/src/runtime_core/{payload,mod,serving,model}.rs, docs/prefix-cache-offload.md): Splits peer_copy_graphs (strictly Node::Copy(Memory::Peer), still used by load-time validate_async_transfer_peer_copy_compatibility) from peer_access_graphs (peer copies/memsets, kernel arg/attr relocations or inline peer addresses, payload-scanned pointer tables, and peer-referencing module globals), enabling CopyEngineGate on single-host multi-rank deployments without all-pairs NVLink via NVML P2P_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 with teardown_model_ranks — (1) stop persistent + async-transfer workers without short-circuiting and cuCtxSynchronize on all ranks, (2) join engram.clear() and offload.reset() while MappedHost/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).
  • AsyncTransfer flush/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,check.py}): Adds flush_queued_sqes and pending_submissions() to retry EINTR/partial submissions, tracks flushed on InflightIo and hardware_signaled on faulted DMAs to prevent completion-slot sentinel clobbering, fixes flare_async_transfer_* rank labels 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): Carries Result<()> in Reply::Started so peers failing finish_startup remain in run_startup_phase to answer Command::Drain -> Reply::Drained, shares a single deadline in best_effort_drain_peers, and adds RankWedgeWatchdog to monitor coordinator/peer/close stalls and abort on wedges.
Merge Risk: High · up to 224fb40
  • A partial io_uring submission followed by any earlier completion causes mark_io_flushed to flag the wrong InflightIo, which makes complete_io silently drop a live kernel CQE and permanently hang GPU demand waits and leak pinned pools into FailedDrain.
  • RankWedgeWatchdog calls std::process::abort() inside close() 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_peers can drop unjoined JoinHandles for healthy peers that already sent Reply::Drained when an earlier peer consumes the shared 120 s timeout.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

…, and round-robin peer drain

Why:
Three concurrency defects and several redundant checks remained after the
initial Helios P0 patch:
1. TransferScheduler::complete_io removed completed reads from inflight_io
   with swap_remove(pos), which swaps the tail entry into pos and breaks
   FIFO submission order relative to the kernel io_uring SQ ring. After a
   partial flush of A followed by A completing, inflight_io reordered to
   [C, B] while the SQ held [B, C], causing the next mark_io_flushed(1) to
   mark C instead of B and complete_io(B, true) to permanently drop B's CQE.
2. RankWedgeWatchdog's closing branch applied one fixed 150 s wall-clock
   timer without checking activity progress, so a multi-stage or poisoned
   close() (draining pending frames, closing peers, running
   best_effort_drain_peers, and closing rank zero) could trigger
   std::process::abort() while still actively making stage progress.
3. best_effort_drain_peers iterated peers sequentially against one shared
   deadline; if an earlier peer was wedged and exhausted the deadline, later
   peers that had already sent Reply::Drained were skipped without a
   non-blocking try_recv() sweep, leaving finished threads detached.

What changed:
- AsyncTransfer SQ FIFO preservation and bounded EINTR retries
  (helios/src/async_transfer/{scheduler,io_backend,worker}.rs):
  - Before: complete_io used swap_remove(pos), flush_queued_sqes retried
    EINTR unboundedly, and AsyncTransferRuntime exposed an unused rank()
    getter.
  - After: complete_io uses remove(pos) (max_total_io <= 32) to preserve
    exact SQ FIFO order with regression test
    partial_flush_preserves_sq_fifo_order_across_completions;
    flush_queued_sqes caps consecutive EINTR retries at 16 per call while
    preserving queued_sqes for the next worker iteration; removed unused
    AsyncTransferRuntime::rank().
- Progress-aware watchdog close monitoring and round-robin best-effort drain
  (helios/src/execution/threaded.rs):
  - Before: closing ignored activity counters, stop_and_join duplicated
    Drop, and best_effort_drain_peers polled peers sequentially.
  - After: closing resets close_since whenever activity advances and close()
    records progress across pending drain, peer joins in close_peers and
    best_effort_drain_peers, and local close; removed stop_and_join in favor
    of drop(self.watchdog.take()); rewrote best_effort_drain_peers to sweep
    live peers round-robin with non-blocking try_recv() against the shared
    deadline (including a final non-blocking pass at deadline expiry) and
    added regression tests for progressing close() and healthy peers behind
    a wedged peer.
- Peer-interval and NVML P2P cleanup (helios/src/runtime_core/{mod,model}.rs,
  docs/api.md):
  - Before: interval merging and collect_peer_referencing_allocations were
    duplicated across prepare_kernels and prepare_graphs,
    prepare_async_transfers repeated the already-enforced peer-copy check,
    and all_nvlink_p2p queried only one direction per GPU pair.
  - After: factored storage_intervals(), computed peer_refs once in
    prepare_kernels and consumed it in prepare_graphs, removed the
    unreachable duplicate peer-copy check in prepare_async_transfers,
    checked both (i, j) and (j, i) NVLink P2P directions in all_nvlink_p2p,
    and clarified in docs/api.md that flare_async_transfer_* rank labels
    carry global rank IDs.

Claimed result:
Prevents silent CQE loss on partial io_uring submissions, prevents false
RankWedgeWatchdog aborts during progressing multi-stage close(), ensures
already-drained peers join cleanly behind a wedged peer without blocking
past the shared deadline, and removes duplicated runtime-core setup logic.

Validation:
- RUSTFLAGS="-D warnings" targeted helios unit tests (50/50 passed, 0
  warnings), including partial_flush_preserves_sq_fifo_order_across_completions,
  bounded EINTR retry, progressing multi-stage close watchdog test, and
  best_effort_drain_peers_joins_healthy_peers_even_when_earlier_peer_is_wedged.
- SM120 GPU (CUDA_VISIBLE_DEVICES=2): live_cuda_async_transfer_end_to_end
  passed (0.59 s).
- Formal & mutation checks (python3 verification/helios-lifecycle/check.py
  --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar
  --java /usr/bin/java --target-dir flare-cli/target --mutations): exit 0
  (all 10 TLA+ models, all 9 conformance suites, and all TLA+ and Rust
  mutations passed).
- flare-cli release build and --features roce check passed.
- Limitations: SM103/SM121 hardware, RoCE live runs, and Kani CLI were not
  re-run locally (CI runs Kani on push).

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@lukealonso

Copy link
Copy Markdown
Collaborator Author

@flare-autobot Pushed c9df77bd addressing all review findings (ordered remove(pos) in complete_io, progress-aware CloseStalled watchdog with stage record_progress(), round-robin best_effort_drain_peers, plus all 3 simplifications and 4 nits) with regression tests and updated PR description.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

All Round 1 findings are resolved at c9df77b, but verification surfaced two small edge-case defects in the rewritten drain and event-fault paths, plus a required live multi-GPU re-run for the modified threaded.rs drain paths (docs/design-review.md:252-259). Fix both defects and re-run the SM120 PCIe TP4 flare run + SIGTERM check on the final commit to make this ready to merge.

  • Blockers: 0 · Should fix: 3 · Subtract/Simplify: 2 · Nits: 0
Walkthrough
  • Round 1 Blocker fixed (helios/src/async_transfer/scheduler.rs:583-585, 1128-1175): Replaced swap_remove(pos) with ordered remove(pos) in complete_io so inflight_io stays synchronized with kernel io_uring SQ FIFO order across partial submits; added partial_flush_preserves_sq_fifo_order_across_completions.
  • Round 1 Should-Fix items addressed (helios/src/execution/threaded.rs:679-693, 1216-1358, 4152-4272): CloseStalled now resets close_since whenever activity advances across close()/close_peers/best_effort_drain_peers progress marks; best_effort_drain_peers now polls all live peers round-robin via non-blocking try_recv() against a single shared deadline (with one remaining Ok(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): Deleted RankWedgeWatchdog::stop_and_join and the unreachable duplicate prepare_async_transfers peer-copy check; consolidated interval building (storage_intervals) and single-pass peer_refs caching; checked both (i, j) and (j, i) in all_nvlink_p2p; bounded flush_queued_sqes EINTR retries to MAX_EINTR_RETRIES = 16; removed unused AsyncTransferRuntime::rank(); documented global rank ID labels in docs/api.md:403-405 and explicit std::process::abort() behavior in the PR description.
Merge Risk: Medium · up to c9df77b
  • The Round 1 High-risk swap_remove CQE-drop bug and fixed-wall-clock CloseStalled abort are fixed and covered by unit/conformance/mutation tests.
  • On a multi-peer validation failure with an in-flight frame, best_effort_drain_peers can still block unboundedly in thread.join() after reading Ok(Err(_)) from a peer still inside drain_outstanding_frames, starving healthy peers and risking CloseStalled process abort.
  • On a cuEventQuery error followed by clean copy_stream drain for a hardware-signaled DMA with device_completions_base != 0, host_comp[slot] is never updated because host_mirror_on_drain is hardcoded to None.
Pre-merge checks: ✅ 3 passed · ⚠️ 2 warnings

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

…eserve cuEventQuery host mirrors

Why:
Two edge-case defects remained in poisoned multi-rank drain and
asynchronous extent-transfer fault handling:
1. In execution/threaded.rs, a peer failing validate_submission sends
   replies.send(Err(error.clone())) before entering drain_outstanding_frames
   (which can block up to TIMEOUT = 120 s or wedge inside executor.poll()).
   best_effort_drain_peers treated Ok(Err(_)) as thread exit and called
   unbounded thread.join(), starving healthy peers behind it and risking
   CloseStalled watchdog aborts. Every actual peer exit drops replies
   (Disconnected) or sends Reply::Drained after executor.close() returns.
2. In async_transfer/worker.rs, the cuEventQuery failure branch constructed
   UntrackedFaultedDma with host_mirror_on_drain: None, discarding
   PendingEventDma.completion_action for hardware-signaled HostOnly
   completions (device_completions_base != 0) so host_comp[slot] never
   advanced even after copy_stream drained cleanly.

What changed:
- Round-robin peer drain exit detection (helios/src/execution/threaded.rs):
  - Before: best_effort_drain_peers set exited = true on Ok(Err(_)) and
    joined immediately.
  - After: only Ok(Ok(Reply::Drained)) and Err(TryRecvError::Disconnected)
    set exited = true; Ok(Err(_)) drains alongside other non-terminal
    replies so exiting peers hit Disconnected on the next try_recv() while
    peers still draining in drain_outstanding_frames never block healthy
    peers. Added regression test
    best_effort_drain_peers_does_not_block_joining_peer_that_sent_err_before_exiting.
- Shared EventCompletionAction host-mirror extraction
  (helios/src/async_transfer/worker.rs):
  - Before: cuEventRecord failure extracted HostOnly(slot, val) while
    cuEventQuery failure hardcoded host_mirror_on_drain: None.
  - After: added EventCompletionAction::host_mirror_on_drain(bool) shared
    by both cuEventRecord and cuEventQuery fault paths, with unit test
    host_mirror_on_drain_preserves_hardware_signaled_host_only_completions.
- Deduplication (helios/src/runtime_core/{mod,host}.rs,
  helios/src/async_transfer/lifecycle_tests.rs):
  - Exposed merge_sorted_intervals as pub(super) and reused it in
    host::host_vmm_ranges; simplified format_json_vec to format!("{v:?}").

Claimed result:
Prevents unbounded thread.join() blocking in best_effort_drain_peers when a
peer sends Err(...) before finishing drain_outstanding_frames, ensures
host_comp advances monotonically after clean copy_stream drain on
cuEventQuery faults for hardware-signaled DMAs, and removes duplicated
interval-merging and projection-formatting code.

Validation:
- RUSTFLAGS="-D warnings" targeted helios unit tests: 54/54 passed, 0
  warnings (including the two new regression tests and runtime_core::host::
  tests).
- SM120 GPU (CUDA_VISIBLE_DEVICES=10): live_cuda_async_transfer_end_to_end
  passed (1.24 s).
- Formal & mutation checks (python3 verification/helios-lifecycle/check.py
  --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar
  --java /usr/bin/java --target-dir flare-cli/target --mutations): exit 0
  (all 10 TLA+ models, all 9 conformance suites, and all TLA+ and Rust
  mutations passed).
- flare-cli release build and --features roce check passed.
- Live SM120 PCIe TP4 serving (CUDA_VISIBLE_DEVICES=3,4,5,6) of
  DeepSeek-V4.1-Flash (gb202-tp4-202611281955, --prefix-cache-memory 4G
  --memory-limit 81G --embedding-table-cache-size 1G): 20/20 concurrent
  ~13k-token requests succeeded (0.45-3.74 s, 1.09 GiB active Copy Engine
  host offload across 37 records, 0 failures, 62 prefill / 37 snapshot /
  140 speculative launches, 404 Engram gathers); SIGTERM exited cleanly
  (status=0 in 3 s).
- Limitations: SM103/SM121 hardware, multi-host RoCE runs, and local Kani
  CLI (CI runs Kani on push) were not executed locally.

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Luke Alonso <lalonso@gmail.com>
@lukealonso

Copy link
Copy Markdown
Collaborator Author

@flare-autobot Pushed f7b83ae2 addressing all Round 2 findings: best_effort_drain_peers now joins only on Reply::Drained or Disconnected (never blocking in thread.join() on Ok(Err(_)) while a peer drains in drain_outstanding_frames), cuEventQuery faults preserve host_mirror_on_drain via EventCompletionAction::host_mirror_on_drain, merge_sorted_intervals is shared with host.rs, format_json_vec uses format!("{v:?}"), and all unit, TLA+/mutation, CUDA, and live SM120 PCIe TP4 + SIGTERM checks were re-run on f7b83ae2.

@lukealonso
lukealonso merged commit 9ae01a6 into main Dec 4, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. priority:P1 High attention: unresolved correctness, serving failure, or model-data deletion risk. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

helios: TP4 serving hangs under --prefix-cache-memory on SM120 PCIe; CopyEngineGate leaves 145/177 DeepSeek-V4.1-Flash graphs ungated

2 participants