From 224fb4030df51c83e60d6947cb16a3a14535530f Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Fri, 4 Dec 2026 09:19:14 -0800 Subject: [PATCH 1/3] helios: gate PCIe peer-access graphs and fix teardown, AsyncTransfer, 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 --- docs/prefix-cache-offload.md | 17 +- docs/runtime-core-design.md | 20 +- helios/src/async_transfer/io_backend.rs | 93 ++- helios/src/async_transfer/lifecycle_tests.rs | 119 +++- helios/src/async_transfer/scheduler.rs | 105 ++- helios/src/async_transfer/worker.rs | 90 ++- helios/src/execution/threaded.rs | 616 ++++++++++++++-- helios/src/runtime_core/mod.rs | 669 +++++++++++++++++- helios/src/runtime_core/model.rs | 228 +++++- helios/src/runtime_core/payload.rs | 54 +- helios/src/runtime_core/serving.rs | 2 +- helios/src/server/metrics.rs | 54 +- .../helios-lifecycle/AsyncTransfer.cfg | 2 + .../helios-lifecycle/AsyncTransfer.tla | 60 +- verification/helios-lifecycle/README.md | 23 +- verification/helios-lifecycle/check.py | 42 +- 16 files changed, 1973 insertions(+), 221 deletions(-) diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index d74834305..ecee2c4f7 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -994,13 +994,16 @@ Offload limits interference through bounded work and explicit ownership: stream uses the default priority, which CUDA defines as the least priority as well, so stream priority does not separate offload work from model work. When a loaded model contains CUDA graphs with in-graph peer-to-peer Copy Engine - nodes (`Node::Copy` referencing `Memory::Peer`), Helios coordinates offload - batches against those graphs through a per-model `CopyEngineGate`: new offload - batches pause between 16 MiB windows while a peer-copy graph executes, waiting - peer-copy graphs bound their drain wait at 120 seconds, and continuous pipelined - peer-copy execution yields bounded fairness turns to waiting offload workers. - Models without peer-copy graphs omit the gate and keep one synchronization per - transfer window. Creating the model and copy streams at a greater priority + nodes (`Node::Copy` referencing `Memory::Peer`), or runs on a single-host PCIe + multi-rank topology (without all-pairs NVLink peer links) with graphs whose + kernels, memsets, module globals, or indirect pointer tables access + `Memory::Peer`, Helios coordinates offload batches against those graphs through + a per-model `CopyEngineGate`: new offload batches pause between 16 MiB windows + while a gated graph executes, waiting gated graphs bound their drain wait at + 120 seconds, and continuous pipelined execution yields bounded fairness turns + to waiting offload workers. Models without gated graphs omit the gate and keep + one synchronization per transfer window. Creating the model and copy streams at + a greater priority requires the section 4 measurements to show a benefit. Measure delays to input uploads, completion downloads, and Engram row copies on shared copy engines through per-token latency. Batch size and stream priority alone do diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index a79e26df5..742ca9df2 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -687,13 +687,19 @@ serving dashboard without synchronizing GPU streams. Shutdown drains compute and copy streams first, writes `1u32` (release) to the mapped-host `stop_flag` reference, and polls `cuStreamQuery` on the worker stream against a bounded drain timeout with context save/restore (returning `ExecutionError::Drain` and -retaining GPU resources on timeout). Resource teardown stops any still-running -worker, synchronizes the primary context, drains active telemetry counter -readers before unmapping allocations, and only after context synchronization -succeeds destroys worker and compute streams, executables, modules, mappings, -all created green contexts (worker, compute, and optional codec, clearing rather -than restoring the caller's current context if it referred to any destroyed -green context), virtual-address reservations, and the primary context. +retaining GPU resources on timeout). Multi-rank model teardown executes a +three-phase cross-rank barrier: first, every rank stops both persistent workers +and async-transfer workers without short-circuiting and synchronizes its CUDA +context before any rank frees shared memory; second, while `Memory::MappedHost` +mailboxes and CUDA contexts remain live, Engram background workers and prefix +offload workers join, after which every rank destroys its streams, executables, +modules, and allocations (draining active telemetry counter readers before +unmapping); third, every rank destroys all created green contexts (worker, +compute, and optional codec, clearing rather than restoring the caller's current +context if it referred to any destroyed green context), virtual-address +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. Before CUDA initialization or serving worker threads, Flare restricts `CUDA_VISIBLE_DEVICES` to `--gpus`, resolving indices within an inherited mask. diff --git a/helios/src/async_transfer/io_backend.rs b/helios/src/async_transfer/io_backend.rs index ba8a8d0eb..21ed2d119 100644 --- a/helios/src/async_transfer/io_backend.rs +++ b/helios/src/async_transfer/io_backend.rs @@ -42,6 +42,11 @@ pub trait IoBackend: Send { /// Flush any locally staged submission entries to the kernel without blocking. fn flush(&mut self) -> io::Result<()>; + /// Number of staged submission entries not yet accepted by the kernel. + fn pending_submissions(&self) -> usize { + 0 + } + /// Harvest all currently completed I/O operations without blocking. fn poll_completions(&mut self, out: &mut Vec) -> io::Result<()>; @@ -138,6 +143,23 @@ pub mod linux_uring { } } + pub(super) fn flush_queued_sqes( + queued_sqes: &mut usize, + mut submit: impl FnMut() -> io::Result, + ) -> io::Result<()> { + 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, + Err(err) => return Err(err), + } + } + Ok(()) + } + impl IoBackend for IoUringBackend { unsafe fn submit_read( &mut self, @@ -157,12 +179,12 @@ pub mod linux_uring { } fn flush(&mut self) -> io::Result<()> { - if self.queued_sqes == 0 { - return Ok(()); - } - let submitted = self.ring.submit()?; - self.queued_sqes = self.queued_sqes.saturating_sub(submitted); - Ok(()) + let ring = &mut self.ring; + flush_queued_sqes(&mut self.queued_sqes, || ring.submit()) + } + + fn pending_submissions(&self) -> usize { + self.queued_sqes } fn poll_completions(&mut self, out: &mut Vec) -> io::Result<()> { @@ -193,12 +215,16 @@ pub mod linux_uring { for op_id in pending_ids { let cancel = opcode::AsyncCancel::new(op_id).build().user_data(0); if self.ring.submission().is_full() { - let _ = self.ring.submit(); + if let Ok(submitted) = self.ring.submit() { + self.queued_sqes = self.queued_sqes.saturating_sub(submitted); + } } // SAFETY: AsyncCancel references no caller buffer. let _ = unsafe { self.ring.submission().push(&cancel) }; } - let _ = self.ring.submit(); + if let Ok(submitted) = self.ring.submit() { + self.queued_sqes = self.queued_sqes.saturating_sub(submitted); + } } let deadline = Instant::now() + timeout; while !self.expected.is_empty() { @@ -215,14 +241,18 @@ pub mod linux_uring { let ts = types::Timespec::from(remaining); let args = types::SubmitArgs::new().timespec(&ts); match self.ring.submitter().submit_with_args(1, &args) { - Ok(_) => {} + Ok(submitted) => { + self.queued_sqes = self.queued_sqes.saturating_sub(submitted); + } Err(err) if err.raw_os_error() == Some(libc::ETIME) => { let _ = self.poll_completions(out); return self.expected.is_empty(); } Err(err) if err.raw_os_error() == Some(libc::EINTR) => continue, Err(_) => { - let _ = self.ring.submit(); + if let Ok(submitted) = self.ring.submit() { + self.queued_sqes = self.queued_sqes.saturating_sub(submitted); + } let _ = self.poll_completions(out); if self.expected.is_empty() { break; @@ -342,7 +372,9 @@ mod tests { .submit_read(7, 0, 0, buf.as_mut_ptr(), 64) .expect("submit pipe read"); } + assert_eq!(pipe_backend.pending_submissions(), 1); pipe_backend.flush().expect("flush pipe read"); + assert_eq!(pipe_backend.pending_submissions(), 0); let mut out: Vec = Vec::new(); let start = Instant::now(); // Cancelable pipe read must drain promptly and return true. @@ -376,4 +408,45 @@ mod tests { assert_eq!(stuck.in_flight(), 1); drop(w2); } + + #[test] + fn flush_queued_sqes_retries_eintr_handles_partial_submit_and_preserves_unsubmitted_count() { + use super::linux_uring::flush_queued_sqes; + use std::collections::VecDeque; + + // EINTR retries and partial submissions drain all queued SQEs cleanly. + let mut queued = 3usize; + let mut responses = VecDeque::from([ + Err(std::io::Error::from_raw_os_error(libc::EINTR)), + Ok(1), + Err(std::io::Error::from_raw_os_error(libc::EINTR)), + Ok(2), + ]); + flush_queued_sqes(&mut queued, || responses.pop_front().unwrap()).expect("flush succeeds"); + assert_eq!(queued, 0); + assert!(responses.is_empty()); + + // Returning Ok(0) stops the inner loop without spinning while retaining queued > 0 + // so the worker retries flushing on the next iteration. + let mut queued = 2usize; + let mut calls = 0usize; + flush_queued_sqes(&mut queued, || { + calls += 1; + Ok(0) + }) + .expect("Ok(0) returns cleanly"); + assert_eq!(calls, 1); + assert_eq!(queued, 2); + + // Non-EINTR errors propagate immediately while keeping unsubmitted SQEs accounted for. + let mut queued = 2usize; + let mut responses = VecDeque::from([ + Ok(1), + Err(std::io::Error::from_raw_os_error(libc::EBUSY)), + ]); + let err = flush_queued_sqes(&mut queued, || responses.pop_front().unwrap()) + .expect_err("EBUSY propagates"); + assert_eq!(err.raw_os_error(), Some(libc::EBUSY)); + assert_eq!(queued, 1); + } } diff --git a/helios/src/async_transfer/lifecycle_tests.rs b/helios/src/async_transfer/lifecycle_tests.rs index 3e3401920..f5b821168 100644 --- a/helios/src/async_transfer/lifecycle_tests.rs +++ b/helios/src/async_transfer/lifecycle_tests.rs @@ -16,11 +16,12 @@ use super::{ scheduler::TransferScheduler, }; -/// Compact 14-integer projection shared with `AsyncTransfer.tla`. +/// Compact 16-integer projection shared with `AsyncTransfer.tla`. /// /// `[phase, active_epoch, q_io, q_dma, in_dem_io, in_bg_io, in_dem_dma, in_bg_dma, -/// b_in_io, b_q_dma, b_in_dma, free_bounce, can_release, faulted_dma]` -type Projection = [i64; 14]; +/// b_in_io, b_q_dma, b_in_dma, free_bounce, can_release, faulted_dma, unflushed_io, +/// hw_signaled_faulted]` +type Projection = [i64; 16]; fn project(sched: &TransferScheduler) -> Projection { let in_bg_io = sched.bg_io_inflight(); @@ -42,13 +43,16 @@ fn project(sched: &TransferScheduler) -> Projection { sched.free_bounce_count() as i64, i64::from(sched.can_release_memory()), sched.faulted_dma_count() as i64, + sched.unflushed_io_count() as i64, + sched.hw_signaled_faulted_dma_count() as i64, ] } 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[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] ) } @@ -103,10 +107,18 @@ fn async_transfer_scheduler_matches_lifecycle_model() { sched.faulted_dma_count() <= sched.inflight_dma_count(), "faulted DMA count exceeded inflight DMA count" ); - if sched.faulted_dma_count() > 0 { + assert!( + sched.hw_signaled_faulted_dma_count() <= sched.faulted_dma_count(), + "hw-signaled faulted DMA count exceeded faulted DMA count" + ); + assert!( + sched.unflushed_io_count() <= sched.inflight_io_count(), + "unflushed IO count exceeded inflight IO count" + ); + if sched.faulted_dma_count() > 0 || sched.unflushed_io_count() > 0 { assert!( !sched.can_release_memory(), - "faulted DMA must retain inflight and bounce ownership" + "faulted DMA and unflushed IO must retain inflight and bounce ownership" ); } assert_eq!( @@ -248,11 +260,32 @@ fn async_transfer_scheduler_matches_lifecycle_model() { } } - // 6. Complete any in-flight IO (both ok=true and ok=false) + // 12. Flush staged IO SQEs (partial and full flush). + if matches!(sched.state(), ChannelState::Running | ChannelState::Draining) + && sched.unflushed_io_count() > 0 + { + for count in 1..=sched.unflushed_io_count() { + let mut n = sched.clone(); + let marked = n.mark_io_flushed(count); + assert_eq!(marked, count); + push_next(12, n, io_ids.clone(), dma_ids.clone()); + } + } + + // 6. Complete any in-flight IO (both ok=true for flushed ops and ok=false for any op). for (idx, &op_id) in io_ids.iter().enumerate() { + let is_flushed = sched.is_io_flushed(op_id); for ok in [true, false] { let mut n = sched.clone(); + let before_count = n.inflight_io_count(); let notice = n.complete_io(op_id, ok); + 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; + } if !ok { let notice = notice.expect("failed IO must emit an error completion notice"); assert_eq!(notice.error, ErrorCode::IoFailure); @@ -296,39 +329,53 @@ fn async_transfer_scheduler_matches_lifecycle_model() { } } - // 11. Mark an in-flight DMA faulted after partial CUDA submission failure. + // 11. Mark an in-flight DMA faulted after partial CUDA submission failure, + // both before and after `cuStreamWriteValue64_v2` hardware signaling. if matches!(sched.state(), ChannelState::Running | ChannelState::Draining) { for &op_id in &dma_ids { if sched.is_dma_faulted(op_id) { continue; } - let mut n = sched.clone(); - let notice = n - .mark_dma_faulted(op_id) - .expect("unfaulted in-flight DMA must transition to faulted"); - assert_eq!(notice.error, ErrorCode::CudaFailure); - assert_eq!( - notice.signal_value, - completion_error_sentinel(ErrorCode::CudaFailure), - "failed transfer must signal error sentinel, not success value" - ); - assert_eq!( - n.inflight_dma_count(), - sched.inflight_dma_count(), - "faulted DMA must retain inflight and bounce ownership" - ); - assert_eq!( - n.free_bounce_count(), - sched.free_bounce_count(), - "faulted DMA must retain inflight and bounce ownership" - ); - assert_eq!( - n.bounce_in_dma(), - sched.bounce_in_dma(), - "faulted DMA must retain inflight and bounce ownership" - ); - assert!(!n.can_release_memory()); - push_next(11, n, io_ids.clone(), dma_ids.clone()); + for hardware_signaled in [false, true] { + let mut n = sched.clone(); + let notice = n + .mark_dma_faulted(op_id, hardware_signaled) + .expect("unfaulted in-flight DMA must transition to faulted"); + assert_eq!(notice.error, ErrorCode::CudaFailure); + if hardware_signaled { + assert!( + notice.completion_slot.is_none(), + "hardware-signaled faulted DMA must not overwrite live/reused completion slot" + ); + } else { + assert!( + notice.completion_slot.is_some(), + "un-signaled faulted DMA must report its completion slot for error sentinel" + ); + assert_eq!( + notice.signal_value, + completion_error_sentinel(ErrorCode::CudaFailure), + "failed transfer must signal error sentinel, not success value" + ); + } + assert_eq!( + n.inflight_dma_count(), + sched.inflight_dma_count(), + "faulted DMA must retain inflight and bounce ownership" + ); + assert_eq!( + n.free_bounce_count(), + sched.free_bounce_count(), + "faulted DMA must retain inflight and bounce ownership" + ); + assert_eq!( + n.bounce_in_dma(), + sched.bounce_in_dma(), + "faulted DMA must retain inflight and bounce ownership" + ); + assert!(!n.can_release_memory()); + push_next(11, n, io_ids.clone(), dma_ids.clone()); + } } } diff --git a/helios/src/async_transfer/scheduler.rs b/helios/src/async_transfer/scheduler.rs index 141fb855f..a0543d5fb 100644 --- a/helios/src/async_transfer/scheduler.rs +++ b/helios/src/async_transfer/scheduler.rs @@ -97,6 +97,8 @@ pub struct InflightIo { pub epoch: u64, pub completion_slot: Option, pub signal_value: u64, + /// True once the backend has flushed this read's submission entry to the kernel. + pub flushed: bool, } /// An active H2D DMA operation submitted to the Copy Engine stream. @@ -115,6 +117,10 @@ pub struct InflightDma { /// True once a post-enqueue CUDA failure (`cuEventRecord`/`cuEventQuery`) has been recorded /// while hardware drain of `copy_stream` has not yet been confirmed. pub faulted: bool, + /// True when `cuStreamWriteValue64_v2` was already enqueued on `copy_stream` with the + /// caller's success cookie before the post-enqueue fault occurred, so writing an error + /// sentinel later could clobber a completed or reused completion slot. + pub hardware_signaled: bool, } /// Completion notification emitted by the scheduler when an operation finishes. @@ -208,6 +214,41 @@ impl TransferScheduler { self.inflight_dma.iter().filter(|op| op.faulted).count() } + #[inline] + pub fn hw_signaled_faulted_dma_count(&self) -> usize { + self.inflight_dma + .iter() + .filter(|op| op.faulted && op.hardware_signaled) + .count() + } + + #[inline] + pub fn unflushed_io_count(&self) -> usize { + self.inflight_io.iter().filter(|op| !op.flushed).count() + } + + /// Mark up to `count` oldest unflushed in-flight IO entries as submitted to the kernel. + 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; + } + } + marked + } + + #[inline] + pub fn is_io_flushed(&self, op_id: OpId) -> bool { + self.inflight_io + .iter() + .any(|op| op.op_id == op_id && op.flushed) + } + #[inline] pub fn is_dma_faulted(&self, op_id: OpId) -> bool { self.inflight_dma @@ -497,6 +538,7 @@ impl TransferScheduler { epoch, completion_slot, signal_value, + flushed: false, }, QueuedOp::DiskToDevIo { op_id, @@ -517,6 +559,7 @@ impl TransferScheduler { epoch, completion_slot, signal_value, + flushed: false, }, QueuedOp::HostToDev { .. } => unreachable!(), }; @@ -534,6 +577,9 @@ impl TransferScheduler { /// is skipped and any bounce slot is returned so drain always terminates. pub fn complete_io(&mut self, op_id: OpId, ok: bool) -> Option { let pos = self.inflight_io.iter().position(|op| op.op_id == op_id)?; + if ok && !self.inflight_io[pos].flushed { + return None; + } let op = self.inflight_io.swap_remove(pos); if let Some(device_offset) = op.device_offset { @@ -642,6 +688,7 @@ impl TransferScheduler { signal_value, from_disk, faulted: false, + hardware_signaled: false, }; self.inflight_dma.push(inflight); return Some(inflight); @@ -653,9 +700,16 @@ impl TransferScheduler { /// Record a post-enqueue CUDA failure on an in-flight Copy Engine DMA while retaining its /// in-flight reservation and any owned bounce slot until hardware drain is confirmed. /// - /// Returns a fault [`CompletionNotice`] carrying `completion_error_sentinel(CudaFailure)` the - /// first time `op_id` is marked faulted, or `None` if `op_id` is unknown or already faulted. - pub fn mark_dma_faulted(&mut self, op_id: OpId) -> Option { + /// When `hardware_signaled` is `true`, `cuStreamWriteValue64_v2` was already enqueued on + /// `copy_stream` with the caller's success cookie before the fault, so the returned notice + /// suppresses `completion_slot` (`None`) to prevent overwriting a completed or reused + /// completion slot with an error sentinel while still reporting `ErrorCode::CudaFailure`. + /// Returns `None` if `op_id` is unknown or already faulted. + pub fn mark_dma_faulted( + &mut self, + op_id: OpId, + hardware_signaled: bool, + ) -> Option { if !matches!(self.state, ChannelState::Running | ChannelState::Draining) { return None; } @@ -664,7 +718,12 @@ impl TransferScheduler { return None; } op.faulted = true; - let completion_slot = op.completion_slot; + op.hardware_signaled = hardware_signaled; + let completion_slot = if hardware_signaled { + None + } else { + op.completion_slot + }; self.completed_cmds = self.completed_cmds.saturating_add(1); Some(CompletionNotice { op_id, @@ -881,6 +940,12 @@ mod tests { let io = sched.pop_next_io().unwrap(); assert_eq!(io.bounce_slot, Some(0)); assert_eq!(sched.free_bounce_count(), 0); + assert_eq!(sched.unflushed_io_count(), 1); + // An unflushed SQE cannot succeed in hardware until flushed. + assert!(sched.complete_io(io.op_id, true).is_none()); + assert_eq!(sched.inflight_io_count(), 1); + assert_eq!(sched.mark_io_flushed(1), 1); + assert_eq!(sched.unflushed_io_count(), 0); // Completing IO queues stage-2 DMA keeping bounce_slot=0. assert!(sched.complete_io(io.op_id, true).is_none()); let dma = sched.pop_next_dma().unwrap(); @@ -990,25 +1055,28 @@ mod tests { signal_value: 404, }); let io = sched.pop_next_io().unwrap(); + assert_eq!(sched.mark_io_flushed(1), 1); assert!(sched.complete_io(io.op_id, true).is_none()); let dma = sched.pop_next_dma().unwrap(); assert_eq!(dma.bounce_slot, Some(0)); assert_eq!(sched.free_bounce_count(), 0); // Partial submission failure retains bounce slot and inflight DMA count. - let notice = sched.mark_dma_faulted(dma.op_id).unwrap(); + let notice = sched.mark_dma_faulted(dma.op_id, false).unwrap(); assert_eq!(notice.error, ErrorCode::CudaFailure); + assert_eq!(notice.completion_slot, Some(0)); assert_eq!( notice.signal_value, completion_error_sentinel(ErrorCode::CudaFailure) ); assert_eq!(sched.inflight_dma_count(), 1); assert_eq!(sched.faulted_dma_count(), 1); + assert_eq!(sched.hw_signaled_faulted_dma_count(), 0); assert_eq!(sched.free_bounce_count(), 0); assert_eq!(sched.bounce_in_dma(), 1); assert!(!sched.can_release_memory()); // Marking a second time is a no-op. - assert!(sched.mark_dma_faulted(dma.op_id).is_none()); + assert!(sched.mark_dma_faulted(dma.op_id, false).is_none()); assert_eq!(sched.completed_cmds, 1); // Drain without completing hardware DMA fails into FailedDrain and retains memory. @@ -1028,4 +1096,29 @@ mod tests { sched.finish_drain(true).unwrap(); assert!(sched.can_release_memory()); } + + #[test] + fn hardware_signaled_faulted_dma_suppresses_completion_slot_sentinel() { + let mut sched = TransferScheduler::new(2, 1, 2, 1, 1); + sched.start().unwrap(); + sched.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Demand, + host_offset: 0, + device_offset: 0, + nbytes: 4096, + epoch: 1, + completion_slot: Some(5), + signal_value: 777, + }); + let dma = sched.pop_next_dma().unwrap(); + let notice = sched.mark_dma_faulted(dma.op_id, true).unwrap(); + assert_eq!(notice.error, ErrorCode::CudaFailure); + assert_eq!( + notice.completion_slot, None, + "hardware-signaled faulted DMA must not overwrite live/reused completion slot" + ); + assert_eq!(sched.hw_signaled_faulted_dma_count(), 1); + assert!(sched.complete_dma(dma.op_id, true).is_none()); + assert_eq!(sched.hw_signaled_faulted_dma_count(), 0); + } } diff --git a/helios/src/async_transfer/worker.rs b/helios/src/async_transfer/worker.rs index ed3ed8cd2..a5e188f8b 100644 --- a/helios/src/async_transfer/worker.rs +++ b/helios/src/async_transfer/worker.rs @@ -91,6 +91,7 @@ pub(crate) fn bounce_pool_geometry(max_extent_bytes: u64, alignment: u32) -> (us #[derive(Clone, Debug)] pub struct ChannelConfig { pub name: String, + pub rank: usize, pub device_pool_base: u64, pub device_pool_bytes: u64, pub host_pool_bytes: u64, @@ -107,6 +108,7 @@ pub struct ChannelConfig { #[derive(Clone, Debug, PartialEq, Eq)] pub struct AsyncTransferSnapshot { pub name: String, + pub rank: usize, pub state: ChannelState, pub device_pool_bytes: u64, pub host_pool_bytes: u64, @@ -314,12 +316,15 @@ struct PendingEventDma { op_id: OpId, event: Handle, failed: bool, + hardware_signaled: bool, completion_action: EventCompletionAction, } struct UntrackedFaultedDma { op_id: OpId, pending_notice: Option, + hardware_signaled: bool, + host_mirror_on_drain: Option<(u32, u64)>, } enum WorkerExit { @@ -485,6 +490,10 @@ impl AsyncTransferRuntime { &self.config.name } + pub fn rank(&self) -> usize { + self.config.rank + } + pub fn state(&self) -> ChannelState { ChannelState::from_u32(self.atomic_state.load(Ordering::Acquire)) } @@ -706,6 +715,7 @@ impl AsyncTransferRuntime { let counters = self.control.read_counters(); AsyncTransferSnapshot { name: self.config.name.clone(), + rank: self.config.rank, state: self.state(), device_pool_bytes: self.config.device_pool_bytes, host_pool_bytes: self.config.host_pool_bytes, @@ -1026,12 +1036,15 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { // Sticky CUDA error on `cuEventQuery`: retain event and bounce slot inside // `scheduler.inflight_dma` until `copy_stream` confirms drain (or `FailedDrain`). leaked_events.push(done.event); - if let Some(notice) = scheduler.mark_dma_faulted(done.op_id) { - publish_notice(notice, true); + if let Some(notice) = scheduler.mark_dma_faulted(done.op_id, done.hardware_signaled) + { + publish_notice(notice, !done.hardware_signaled); } untracked_faulted_dmas.push(UntrackedFaultedDma { op_id: done.op_id, pending_notice: None, + hardware_signaled: done.hardware_signaled, + host_mirror_on_drain: None, }); } } @@ -1040,22 +1053,32 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { if stream_status == 0 { did_work = true; for mut item in untracked_faulted_dmas.drain(..) { - let _ = scheduler.complete_dma(item.op_id, false); - if let Some(notice) = item.pending_notice.take() { + let _ = scheduler.complete_dma(item.op_id, item.hardware_signaled); + if item.hardware_signaled { + // Hardware already executed `cuStreamWriteValue64_v2` with the success + // cookie on `copy_stream` before drain; advance the host mirror if + // applicable and record `last_error` without overwriting the slot. + if let Some((slot, val)) = item.host_mirror_on_drain { + update_host_comp(slot, val); + } + if let Some(notice) = item.pending_notice.take() { + publish_notice(notice, false); + } + } else if let Some(notice) = item.pending_notice.take() { publish_notice(notice, true); } } } else if stream_status != CUDA_ERROR_NOT_READY { - // Stream entered a sticky CUDA error: signal any unsent fault notices while - // keeping `untracked_faulted_dmas` pinned in `scheduler.inflight_dma` so bounce - // slots and host memory are never reclaimed prematurely. + // Stream entered a sticky CUDA error: signal any unsent fault notices for + // non-hardware-signaled ops while keeping `untracked_faulted_dmas` pinned in + // `scheduler.inflight_dma` so bounce slots and host memory are never reclaimed. header .last_error .store(ErrorCode::CudaFailure as u32, Ordering::Release); for item in &mut untracked_faulted_dmas { if let Some(notice) = item.pending_notice.take() { did_work = true; - publish_notice(notice, true); + publish_notice(notice, !item.hardware_signaled); } } } @@ -1099,6 +1122,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { let mut completion_action = EventCompletionAction::None; let mut signal_status = 0; + let mut hardware_signaled = false; if let Some(slot) = dma.completion_slot { if args.use_write_value64 { let writes_device_word = args.config.device_completions_base != 0; @@ -1120,9 +1144,12 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { CU_STREAM_WRITE_VALUE_DEFAULT, ) }; - if signal_status == 0 && writes_device_word { - completion_action = - EventCompletionAction::HostOnly(slot, dma.signal_value); + if signal_status == 0 { + hardware_signaled = true; + if writes_device_word { + completion_action = + EventCompletionAction::HostOnly(slot, dma.signal_value); + } } } else { completion_action = @@ -1142,6 +1169,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { op_id: dma.op_id, event: ev, failed: signal_status != 0, + hardware_signaled, completion_action: if signal_status == 0 { completion_action } else { @@ -1153,10 +1181,18 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { // Retain `dma` and its bounce slot in `scheduler.inflight_dma` until `copy_stream` // confirms drain (or permanently into `FailedDrain`). free_events.push(ev); - let pending_notice = scheduler.mark_dma_faulted(dma.op_id); + let host_mirror_on_drain = match completion_action { + EventCompletionAction::HostOnly(slot, val) if hardware_signaled => { + Some((slot, val)) + } + _ => None, + }; + let pending_notice = scheduler.mark_dma_faulted(dma.op_id, hardware_signaled); untracked_faulted_dmas.push(UntrackedFaultedDma { op_id: dma.op_id, pending_notice, + hardware_signaled, + host_mirror_on_drain, }); break; } @@ -1189,12 +1225,28 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { }; 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); + } } else if let Some(notice) = scheduler.complete_io(io_op.op_id, false) { publish_notice(notice, true); } } - if submitted_io { - if args.io_backend.flush().is_err() { + // Flush unconditionally whenever new reads were staged or earlier SQEs remain queued + // after an EINTR/partial submit so DEMAND loads can never strand in the SQ ring. + 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()); + if flushed_now > 0 { + scheduler.mark_io_flushed(flushed_now); + did_work = true; + } + if flush_result.is_err() { header .last_error .store(ErrorCode::IoFailure as u32, Ordering::Release); @@ -1236,6 +1288,12 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { let io_drained = args .io_backend .cancel_and_drain(DRAIN_TIMEOUT, &mut io_completions); + let flushed_now = scheduler + .unflushed_io_count() + .saturating_sub(args.io_backend.pending_submissions()); + if flushed_now > 0 { + scheduler.mark_io_flushed(flushed_now); + } let _ = args.io_backend.poll_completions(&mut io_completions); for c in io_completions.drain(..) { let _ = scheduler.complete_io(c.op_id, c.ok); @@ -1260,7 +1318,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { free_events.push(done.event); } for item in untracked_faulted_dmas.drain(..) { - let _ = scheduler.complete_dma(item.op_id, false); + let _ = scheduler.complete_dma(item.op_id, item.hardware_signaled); } for ev in free_events.drain(..).chain(leaked_events.drain(..)) { unsafe { @@ -1470,6 +1528,7 @@ mod cuda_tests { { let cfg = ChannelConfig { name: "cuda-3tier".into(), + rank: 0, device_pool_base: dev_pool, device_pool_bytes: dev_pool_bytes as u64, host_pool_bytes: 2 << 20, @@ -1676,6 +1735,7 @@ mod cuda_tests { }); let cfg = ChannelConfig { name: "cuda-ram0-bounce".into(), + rank: 0, device_pool_base: dev_pool, device_pool_bytes: dev_pool_bytes as u64, host_pool_bytes: 0, diff --git a/helios/src/execution/threaded.rs b/helios/src/execution/threaded.rs index fb7bbe365..120949bb1 100644 --- a/helios/src/execution/threaded.rs +++ b/helios/src/execution/threaded.rs @@ -21,6 +21,8 @@ use std::{ }; const TIMEOUT: Duration = Duration::from_secs(120); +const WATCHDOG_GRACE: Duration = Duration::from_secs(30); +const WATCHDOG_POLL: Duration = Duration::from_secs(1); const HANDOFF_POLL: Duration = Duration::from_micros(500); const STACK_UPLOAD_CAPACITY: usize = 64; const MAX_RANKS: usize = 16; @@ -370,6 +372,10 @@ impl DispatchRing { self.peer_exited.0.load(Ordering::SeqCst) } + fn drain_requested(&self) -> bool { + self.drain.0.load(Ordering::SeqCst) + } + fn has_step(&self, next_epoch: u64) -> bool { self.prepare_epoch.0.load(Ordering::Acquire) >= next_epoch } @@ -538,10 +544,222 @@ fn drain_outstanding_frames( Ok(()) } -struct PeerExitGuard(Arc); +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum WedgeReason { + /// A peer rank exited while the coordinator remained outside teardown past `peer_exit_grace`. + PeerExitedWithoutRecovery { elapsed: Duration }, + /// Coordinator remained busy or held in-flight frames with no forward progress past `stall_timeout`. + CoordinatorStalled { elapsed: Duration }, + /// Coordinator entered teardown (`close()`) and failed to return within `stall_timeout`. + CloseStalled { elapsed: Duration }, +} + +/// Lock-free heartbeat state observed by [`RankWedgeWatchdog`]. +struct WatchdogState { + activity: CacheAligned, + busy: CacheAligned, + closing: CacheAligned, + stopped: CacheAligned, + wake_lock: Mutex<()>, + wake: Condvar, +} + +impl WatchdogState { + fn new() -> Self { + Self { + activity: CacheAligned(AtomicU64::new(0)), + busy: CacheAligned(AtomicBool::new(false)), + closing: CacheAligned(AtomicBool::new(false)), + stopped: CacheAligned(AtomicBool::new(false)), + wake_lock: Mutex::new(()), + wake: Condvar::new(), + } + } + + fn wake(&self) { + let _guard = self.wake_lock.lock().unwrap_or_else(|e| e.into_inner()); + self.wake.notify_all(); + } + + fn mark_busy(&self) { + if !self.busy.0.swap(true, Ordering::AcqRel) { + self.wake(); + } + } + + fn record_progress(&self) { + self.activity.0.fetch_add(1, Ordering::Release); + } + + fn begin_close(&self) { + self.closing.0.store(true, Ordering::Release); + self.activity.0.fetch_add(1, Ordering::Release); + self.wake(); + } + + fn stop(&self) { + self.stopped.0.store(true, Ordering::Release); + self.wake(); + } +} + +struct WatchdogCallGuard { + state: Arc, + keep_busy: bool, +} + +impl WatchdogCallGuard { + fn enter(state: &Arc, keep_busy: bool) -> Self { + state.mark_busy(); + Self { + state: Arc::clone(state), + keep_busy, + } + } +} + +impl Drop for WatchdogCallGuard { + fn drop(&mut self) { + if !self.keep_busy { + self.state.busy.0.store(false, Ordering::Release); + } + } +} + +/// Background monitor that detects unrecoverable CUDA driver wedges on rank zero +/// (when software deadlines in `poll_ranks` or `coordinate_step` cannot execute because +/// the coordinator thread is blocked inside `libcuda.so`). +struct RankWedgeWatchdog { + state: Arc, + thread: Option>, +} + +impl RankWedgeWatchdog { + fn spawn( + ring: Arc, + state: Arc, + stall_timeout: Duration, + peer_exit_grace: Duration, + poll_interval: Duration, + on_wedge: impl FnOnce(WedgeReason) + Send + 'static, + ) -> Result { + let thread_state = state.clone(); + let thread = thread::Builder::new() + .name("flare-watchdog".into()) + .spawn(move || { + let mut last_activity = thread_state.activity.0.load(Ordering::Acquire); + let mut stall_since: Option = None; + let mut peer_exit_since: Option = None; + let mut close_since: Option = None; + let mut on_wedge = Some(on_wedge); + loop { + if thread_state.stopped.0.load(Ordering::Acquire) { + break; + } + let busy = thread_state.busy.0.load(Ordering::Acquire); + let closing = thread_state.closing.0.load(Ordering::Acquire); + let peer_exited = ring.peer_exited(); + if !busy && !closing && !peer_exited { + stall_since = None; + peer_exit_since = None; + close_since = None; + let guard = thread_state + .wake_lock + .lock() + .unwrap_or_else(|e| e.into_inner()); + drop(thread_state.wake.wait_while(guard, |_| { + !thread_state.stopped.0.load(Ordering::Acquire) + && !thread_state.busy.0.load(Ordering::Acquire) + && !thread_state.closing.0.load(Ordering::Acquire) + && !ring.peer_exited() + })); + continue; + } + let now = Instant::now(); + 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; + if peer_exited { + let since = *peer_exit_since.get_or_insert(now); + let elapsed = now.saturating_duration_since(since); + if elapsed >= peer_exit_grace { + if let Some(fire) = on_wedge.take() { + fire(WedgeReason::PeerExitedWithoutRecovery { elapsed }); + } + break; + } + } else { + peer_exit_since = None; + } + if busy { + let current = thread_state.activity.0.load(Ordering::Acquire); + if current != last_activity { + last_activity = current; + stall_since = Some(now); + } else { + let since = *stall_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::CoordinatorStalled { elapsed }); + } + break; + } + } + } else { + stall_since = None; + } + } + let guard = thread_state + .wake_lock + .lock() + .unwrap_or_else(|e| e.into_inner()); + if thread_state.stopped.0.load(Ordering::Acquire) { + break; + } + let _ = thread_state.wake.wait_timeout(guard, poll_interval); + } + }) + .map_err(|e| invalid(format!("cannot start rank wedge watchdog: {e}")))?; + Ok(Self { + state, + thread: Some(thread), + }) + } + + 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(); + } + } +} + +struct PeerExitGuard { + ring: Arc, + watchdog: Arc, +} impl Drop for PeerExitGuard { fn drop(&mut self) { - self.0.mark_peer_exited(); + self.ring.mark_peer_exited(); + self.watchdog.wake(); } } @@ -553,7 +771,7 @@ enum Command { enum Reply { Initialized, Tuned(usize, Result<()>), - Started, + Started(Result<()>), Complete(FrameCompletion), Drained, } @@ -615,6 +833,8 @@ pub(crate) struct ThreadedExecutor { local: GraphExecutor, peers: Vec, ring: Arc, + watchdog_state: Arc, + watchdog: Option, started: bool, next_epoch: u64, pending: VecDeque, @@ -651,10 +871,13 @@ impl ThreadedExecutor { .max(16); let ring = Arc::new(DispatchRing::new(manifest.input_frame_bytes, max_uploads)); let local = unsafe { GraphExecutor::new_unstarted(manifest)? }; + let watchdog_state = Arc::new(WatchdogState::new()); let mut result = Self { local, peers: Vec::new(), ring, + watchdog_state, + watchdog: None, started: false, next_epoch: 1, pending: VecDeque::with_capacity(2), @@ -665,10 +888,14 @@ impl ThreadedExecutor { let (sender, commands) = mpsc::channel(); let (replies, receiver) = mpsc::channel(); let peer_ring = result.ring.clone(); + let peer_watchdog = result.watchdog_state.clone(); let thread = thread::Builder::new() .name(format!("flare-rank-{}", index + 1)) .spawn(move || { - let _exit_guard = PeerExitGuard(peer_ring.clone()); + let _exit_guard = PeerExitGuard { + ring: peer_ring.clone(), + watchdog: peer_watchdog, + }; let mut executor = match unsafe { GraphExecutor::new_unstarted(manifest) } { Ok(executor) => executor, Err(error) => { @@ -765,52 +992,13 @@ impl ThreadedExecutor { return Err(error); } } - for peer in &result.peers { - peer.send(Command::FinishStartup)?; - } - result.local.finish_startup()?; - for peer in &result.peers { - if !matches!(peer.receive()?, Reply::Started) { - return Err(invalid("rank startup did not complete")); - } - } - Ok(()) + finish_startup_handshake(&result.peers, || result.local.finish_startup()) })(); if let Err(error) = startup { // Every issued tuning command has a completed acknowledgement here. - result.ring.request_drain(); - let sent: Vec<_> = result - .peers - .iter() - .map(|peer| peer.send(Command::Drain).is_ok()) - .collect(); - for (peer, sent) in result.peers.iter_mut().zip(sent) { - if sent { - loop { - match peer.receive() { - Ok(Reply::Drained) => break, - Ok(Reply::Started) => continue, - reply => { - eprintln!( - "startup rank cleanup was not confirmed: {:?}; terminating the CUDA process", - reply.err() - ); - std::process::abort(); - } - } - } - } - if let Some(thread) = peer.thread.take() { - match thread.join() { - Ok(shutdown) if shutdown.drained => {} - _ => { - eprintln!( - "startup rank thread did not confirm drain; terminating the CUDA process" - ); - std::process::abort(); - } - } - } + if let Err(cleanup_error) = cleanup_failed_startup(&result.ring, &mut result.peers) { + eprintln!("{cleanup_error}; terminating the CUDA process"); + std::process::abort(); } let shutdown = result.local.close(); if !shutdown.drained { @@ -823,6 +1011,22 @@ impl ThreadedExecutor { return Err(error); } result.started = true; + let ring_for_log = result.ring.clone(); + result.watchdog = Some(RankWedgeWatchdog::spawn( + result.ring.clone(), + result.watchdog_state.clone(), + TIMEOUT + WATCHDOG_GRACE, + WATCHDOG_GRACE, + WATCHDOG_POLL, + move |reason| { + eprintln!( + "tensor-parallel rank coordinator wedged ({reason:?}, peer_exited={}, drain_requested={}); terminating the CUDA process", + ring_for_log.peer_exited(), + ring_for_log.drain_requested(), + ); + std::process::abort(); + }, + )?); Ok(result) } #[cfg(feature = "server")] @@ -863,6 +1067,7 @@ impl ThreadedExecutor { uploads: &[Upload<'_>], grammar: bool, ) -> Result> { + let mut wd_guard = WatchdogCallGuard::enter(&self.watchdog_state, !self.pending.is_empty()); self.next_fence()?; if self.ring.peer_exited() { let error = Self::surface_peer_error(&self.peers); @@ -918,6 +1123,8 @@ impl ThreadedExecutor { world_size: self.peers.len() + 1, completions: std::array::from_fn(|_| None), }); + self.watchdog_state.record_progress(); + wd_guard.keep_busy = true; Ok(Some(submitted_fence)) } Ok(None) => Ok(None), @@ -931,14 +1138,20 @@ impl ThreadedExecutor { if let Some(error) = &self.poison { return Err(error.clone()); } - match self.poll_ranks() { + let mut wd_guard = WatchdogCallGuard::enter(&self.watchdog_state, !self.pending.is_empty()); + let outcome = match self.poll_ranks() { Ok(None) => Ok(None), - Ok(Some(completion)) => Ok(Some(completion)), + Ok(Some(completion)) => { + self.watchdog_state.record_progress(); + Ok(Some(completion)) + } Err(error) => { self.poison = Some(error.clone()); Err(error) } - } + }; + wd_guard.keep_busy = !self.pending.is_empty(); + outcome } fn poll_ranks(&mut self) -> Result> { if let Some((frame, elapsed)) = self.pending.iter().find_map(|frame| { @@ -995,6 +1208,7 @@ impl ThreadedExecutor { if let Some(shutdown) = &self.shutdown { return shutdown.clone(); } + self.watchdog_state.begin_close(); let result = (|| { while !self.pending.is_empty() { self.poll()?; @@ -1014,6 +1228,9 @@ impl ThreadedExecutor { Ok(()) => self.local.close(), Err(error) => self.local.abandon(error), }; + if let Some(watchdog) = self.watchdog.take() { + watchdog.stop_and_join(); + } self.shutdown = Some(shutdown.clone()); shutdown } @@ -1072,11 +1289,11 @@ fn best_effort_drain_peers( } } } + let deadline = Instant::now() + timeout; for peer in peers.iter_mut() { if peer.thread.is_none() { continue; } - let deadline = Instant::now() + timeout; let mut exited = false; while let Some(remaining) = deadline.checked_duration_since(Instant::now()) { match receive(&peer.receiver, Some(remaining)) { @@ -1124,6 +1341,69 @@ fn drain_rank( Ok(()) } +/// Coordinator side of the `Command::FinishStartup` handshake across all peer ranks. +fn finish_startup_handshake( + peers: &[Peer], + local_finish: impl FnOnce() -> Result<()>, +) -> Result<()> { + for peer in peers { + peer.send(Command::FinishStartup)?; + } + let mut failure = local_finish().err(); + for peer in peers { + match peer.receive()? { + Reply::Started(Ok(())) => {} + Reply::Started(Err(error)) => { + failure.get_or_insert(error); + } + _ => { + failure.get_or_insert_with(|| invalid("rank startup did not complete")); + } + } + } + match failure { + Some(error) => Err(error), + None => Ok(()), + } +} + +/// Drain and join every peer rank after a failed startup phase (`Tune` or `FinishStartup`). +/// Peers that succeeded `FinishStartup` drain via `ring.request_drain()`; peers that stayed +/// in `run_startup_phase` (including peers whose `finish_startup` returned `Err`) drain via +/// `Command::Drain`. +fn cleanup_failed_startup(ring: &DispatchRing, peers: &mut [Peer]) -> Result<()> { + ring.request_drain(); + let sent: Vec<_> = peers + .iter() + .map(|peer| peer.send(Command::Drain).is_ok()) + .collect(); + for (peer, sent) in peers.iter_mut().zip(sent) { + if sent { + loop { + match peer.receive() { + Ok(Reply::Drained) => break, + Ok(Reply::Started(_)) => continue, + reply => { + return Err(invalid(format!( + "startup rank cleanup was not confirmed: {:?}", + reply.err() + ))); + } + } + } + } + if let Some(thread) = peer.thread.take() { + match thread.join() { + Ok(shutdown) if shutdown.drained => {} + _ => { + return Err(invalid("startup rank thread did not confirm drain")); + } + } + } + } + Ok(()) +} + /// Startup control loop executed by each peer rank before entering `DispatchRing` serving. /// Returns `Ok(true)` once `Command::FinishStartup` succeeds, or `Ok(false)` on drain/exit. fn run_startup_phase( @@ -1146,14 +1426,15 @@ fn run_startup_phase( let status = run_tuning(executor, index); send(Reply::Tuned(index, status))?; } - Ok(Command::FinishStartup) => { - if let Err(error) = finish_startup(executor) { - let _ = replies.send(Err(error)); - return Ok(false); + Ok(Command::FinishStartup) => match finish_startup(executor) { + Ok(()) => { + send(Reply::Started(Ok(())))?; + return Ok(true); } - send(Reply::Started)?; - return Ok(true); - } + Err(error) => { + send(Reply::Started(Err(error)))?; + } + }, Ok(Command::Drain) => { drain(executor, &send)?; return Ok(false); @@ -1816,7 +2097,10 @@ mod tests { let (tx, rx) = mpsc::channel(); let peer_ring = ring.clone(); let worker = thread::spawn(move || { - let _guard = PeerExitGuard(peer_ring.clone()); + let _guard = PeerExitGuard { + ring: peer_ring.clone(), + watchdog: Arc::new(WatchdogState::new()), + }; assert_eq!(peer_ring.wait_next(1), DispatchEvent::Step); peer_ring.mark_peer_ready(0, 1); assert_eq!( @@ -1880,7 +2164,10 @@ mod tests { let launches = peer_launches.clone(); let peer_err_tx = err_tx.clone(); workers.push(thread::spawn(move || { - let _guard = PeerExitGuard(peer_ring.clone()); + let _guard = PeerExitGuard { + ring: peer_ring.clone(), + watchdog: Arc::new(WatchdogState::new()), + }; let mut next_epoch = 1u64; loop { match peer_ring.wait_next(next_epoch) { @@ -3017,8 +3304,12 @@ mod tests { let (replies, receiver) = mpsc::channel(); let drained = drained_count.clone(); let peer_ring = ring.clone(); + let peer_watchdog = Arc::new(WatchdogState::new()); let thread = thread::spawn(move || { - let _exit_guard = PeerExitGuard(peer_ring); + let _exit_guard = PeerExitGuard { + ring: peer_ring, + watchdog: peer_watchdog, + }; let mut state = (); let entered = run_startup_phase( &mut state, @@ -3090,8 +3381,12 @@ mod tests { let (live_replies, live_receiver) = mpsc::channel(); let drained = drained_count.clone(); let peer_ring = ring.clone(); + let peer_watchdog = Arc::new(WatchdogState::new()); let live_thread = thread::spawn(move || { - let _exit_guard = PeerExitGuard(peer_ring); + let _exit_guard = PeerExitGuard { + ring: peer_ring, + watchdog: peer_watchdog, + }; let mut state = (); let entered = run_startup_phase( &mut state, @@ -3150,8 +3445,12 @@ mod tests { let (sender, commands) = mpsc::channel(); let (replies, receiver) = mpsc::channel(); let peer_ring = ring.clone(); + let peer_watchdog = Arc::new(WatchdogState::new()); let thread = thread::spawn(move || { - let _exit_guard = PeerExitGuard(peer_ring.clone()); + let _exit_guard = PeerExitGuard { + ring: peer_ring.clone(), + watchdog: peer_watchdog, + }; let mut state = (); let entered = run_startup_phase( &mut state, @@ -3186,7 +3485,7 @@ mod tests { for peer in &peers { assert!(matches!( peer.receiver.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), - Reply::Started + Reply::Started(Ok(())) )); } let started = Instant::now(); @@ -3195,6 +3494,87 @@ mod tests { assert!(peers.iter().all(|peer| peer.thread.is_none())); } + #[test] + fn finish_startup_peer_error_drains_mixed_peers_cleanly_without_abort() { + for (peer_fails, local_fails, expected_err) in [ + ([true, false], false, "peer 0 finish_startup failed"), + ([true, true], false, "peer 0 finish_startup failed"), + ([false, true], false, "peer 1 finish_startup failed"), + ([true, false], true, "local finish_startup failed"), + ] { + let ring = Arc::new(DispatchRing::new(64, 4)); + let drained_count = Arc::new(AtomicUsize::new(0)); + let mut peers = Vec::new(); + for (idx, fail_peer) in peer_fails.into_iter().enumerate() { + let (sender, commands) = mpsc::channel(); + let (replies, receiver) = mpsc::channel(); + let peer_ring = ring.clone(); + let peer_watchdog = Arc::new(WatchdogState::new()); + let drained = drained_count.clone(); + let thread = thread::spawn(move || { + let _exit_guard = PeerExitGuard { + ring: peer_ring.clone(), + watchdog: peer_watchdog, + }; + let mut state = (); + let entered = run_startup_phase( + &mut state, + &commands, + &replies, + |_, _| Ok(()), + |_| { + if fail_peer { + Err(invalid(format!("peer {idx} finish_startup failed"))) + } else { + Ok(()) + } + }, + |_, send| { + drained.fetch_add(1, Ordering::SeqCst); + send(Reply::Drained) + }, + ) + .unwrap(); + if entered { + assert_eq!(peer_ring.wait_next(1), DispatchEvent::Drain); + drained.fetch_add(1, Ordering::SeqCst); + replies.send(Ok(Reply::Drained)).unwrap(); + } + Shutdown { + drained: true, + error: None, + } + }); + assert!(matches!( + receiver.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), + Reply::Initialized + )); + peers.push(Peer { + sender, + receiver, + thread: Some(thread), + }); + } + + let err = finish_startup_handshake(&peers, || { + if local_fails { + Err(invalid("local finish_startup failed")) + } else { + Ok(()) + } + }) + .expect_err("failed FinishStartup must return error"); + assert!( + err.to_string().contains(expected_err), + "unexpected error: {err}" + ); + cleanup_failed_startup(&ring, &mut peers) + .expect("failed FinishStartup cleanup must drain all peers cleanly"); + assert_eq!(drained_count.load(Ordering::SeqCst), 2); + assert!(peers.iter().all(|peer| peer.thread.is_none())); + } + } + #[test] fn dispatch_ring_matches_model_edges() { const MAX_EPOCHS: u64 = 3; @@ -3630,6 +4010,114 @@ mod tests { assert_eq!(next_epoch, 1); } } + + #[test] + fn watchdog_fires_when_peer_exits_and_coordinator_stays_wedged() { + let ring = Arc::new(DispatchRing::new(16, 2)); + let state = Arc::new(WatchdogState::new()); + let (tx, rx) = mpsc::channel(); + let watchdog = RankWedgeWatchdog::spawn( + ring.clone(), + state.clone(), + Duration::from_secs(5), + Duration::from_millis(25), + Duration::from_millis(5), + move |reason| { + let _ = tx.send(reason); + }, + ) + .unwrap(); + + // Simulate peer hitting 120s timeout and dropping PeerExitGuard while rank zero is wedged. + { + let _guard = PeerExitGuard { + ring: ring.clone(), + watchdog: state.clone(), + }; + } + + let reason = rx + .recv_timeout(Duration::from_secs(2)) + .expect("watchdog must detect wedged coordinator after peer exit"); + assert!( + matches!(reason, WedgeReason::PeerExitedWithoutRecovery { .. }), + "unexpected wedge reason: {reason:?}" + ); + watchdog.stop_and_join(); + } + + #[test] + fn watchdog_fires_when_busy_coordinator_stalls_without_progress() { + let ring = Arc::new(DispatchRing::new(16, 2)); + let state = Arc::new(WatchdogState::new()); + let (tx, rx) = mpsc::channel(); + let watchdog = RankWedgeWatchdog::spawn( + ring, + state.clone(), + Duration::from_millis(30), + Duration::from_secs(5), + Duration::from_millis(5), + move |reason| { + let _ = tx.send(reason); + }, + ) + .unwrap(); + + // Coordinator enters a blocking CUDA call (busy=true) and never advances activity. + let _call = WatchdogCallGuard::enter(&state, true); + let reason = rx + .recv_timeout(Duration::from_secs(2)) + .expect("watchdog must detect stalled busy coordinator"); + assert!( + matches!(reason, WedgeReason::CoordinatorStalled { .. }), + "unexpected wedge reason: {reason:?}" + ); + watchdog.stop_and_join(); + } + + #[test] + fn watchdog_fires_when_close_stalls_and_stays_silent_when_idle_or_progressing() { + let ring = Arc::new(DispatchRing::new(16, 2)); + let state = Arc::new(WatchdogState::new()); + let (tx, rx) = mpsc::channel(); + let watchdog = RankWedgeWatchdog::spawn( + ring, + state.clone(), + Duration::from_millis(40), + Duration::from_millis(20), + Duration::from_millis(5), + move |reason| { + let _ = tx.send(reason); + }, + ) + .unwrap(); + + // Idle longer than stall_timeout must never fire. + thread::sleep(Duration::from_millis(65)); + assert!(rx.try_recv().is_err(), "idle watchdog must not fire"); + + // Regular progress while busy must keep resetting the stall timer. + state.mark_busy(); + for _ in 0..5 { + state.record_progress(); + thread::sleep(Duration::from_millis(12)); + } + assert!( + rx.try_recv().is_err(), + "watchdog must not fire while progress advances" + ); + + // Stalling inside close() must fire CloseStalled. + state.begin_close(); + let reason = rx + .recv_timeout(Duration::from_secs(2)) + .expect("watchdog must detect stalled close"); + assert!( + matches!(reason, WedgeReason::CloseStalled { .. }), + "unexpected wedge reason: {reason:?}" + ); + watchdog.stop_and_join(); + } } #[cfg(all(test, feature = "runtime-core"))] diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index e794e3732..759be45d2 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -75,7 +75,7 @@ pub use model::{ }; pub use selection::LoadOptions; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ffi::CString; use std::ptr::{null, null_mut}; use std::sync::Arc; @@ -115,7 +115,18 @@ pub struct NativeResources { templates: Vec, executables: Vec, names: Vec, + /// Graphs containing at least one Copy Engine `Node::Copy` with a `Memory::Peer` endpoint. peer_copy_graphs: Vec, + /// Graphs referencing `Memory::Peer` through any copy, memset, kernel argument/attribute, + /// indirect peer-pointer table allocation, or module global. + peer_access_graphs: Vec, + /// True on single-host PCIe multi-rank deployments where all peer-access graphs must + /// serialize against host prefix-cache Copy Engine batches. + gate_peer_access: bool, + /// Allocations whose stored payload bytes contain an address inside a `Memory::Peer` range. + peer_table_allocations: HashSet, + /// Loaded CUDA modules whose globals reference `Memory::Peer` storage. + peer_modules: HashSet, reservations: Vec<(u64, usize)>, execution: Option, // An integrated GPU (GB10) registers host memory without pinning it. @@ -134,6 +145,187 @@ pub struct NativeResources { // owning context, and mutable ownership serializes loading and destruction. unsafe impl Send for NativeResources {} +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 +} + +fn peer_address_intervals(allocations: &HashMap) -> 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) +} + +#[inline] +fn address_in_intervals(value: u64, intervals: &[(u64, u64)], floor: u64, ceiling: u64) -> bool { + if value < floor || value >= ceiling { + return false; + } + let idx = intervals.partition_point(|&(start, _)| start <= value); + idx > 0 && value < intervals[idx - 1].1 +} + +/// Returns true if any little-endian 64-bit value in `bytes` falls inside a sorted, disjoint +/// address interval in `intervals`. +/// +/// When `aligned_start` is `Some(alloc_offset)`, scans 8-byte boundaries aligned to the +/// allocation start (fast path for large stored payload buffers such as pointer tables). +/// When `None`, scans every 8-byte window (used for small kernel parameter blobs). +pub(super) fn contains_interval_address( + bytes: &[u8], + intervals: &[(u64, u64)], + aligned_start: Option, +) -> bool { + if intervals.is_empty() || bytes.len() < 8 { + return false; + } + let floor = intervals[0].0; + let ceiling = intervals.last().unwrap().1; + if let Some(alloc_offset) = aligned_start { + let skip = (8 - (alloc_offset % 8)) % 8; + if skip >= bytes.len() { + return false; + } + for chunk in bytes[skip..].chunks_exact(8) { + let value = u64::from_le_bytes(chunk.try_into().unwrap()); + if address_in_intervals(value, intervals, floor, ceiling) { + return true; + } + } + false + } else { + for window in bytes.windows(8) { + let value = u64::from_le_bytes(window.try_into().unwrap()); + if address_in_intervals(value, intervals, floor, ceiling) { + return true; + } + } + false + } +} + +/// Computes the set of allocation names that are `Memory::Peer` or hold pointers to `Memory::Peer` +/// (either via explicit `Allocation.relocations` or scanned payload tables), together with their +/// sorted address intervals for matching inline fixed-address kernel parameters. +fn collect_peer_referencing_allocations( + core: &Core, + allocations: &HashMap, + payload_peer_tables: &HashSet, +) -> (HashSet, Vec<(u64, u64)>) { + let mut peer_refs: HashSet = allocations + .iter() + .filter(|(_, storage)| matches!(storage.memory, Memory::Peer)) + .map(|(name, _)| name.clone()) + .collect(); + for name in payload_peer_tables { + if allocations.contains_key(name) { + peer_refs.insert(name.clone()); + } + } + loop { + let before = peer_refs.len(); + for allocation in &core.allocations { + if !peer_refs.contains(&allocation.name) + && allocation + .relocations + .iter() + .any(|rel| peer_refs.contains(&rel.target.allocation)) + { + peer_refs.insert(allocation.name.clone()); + } + } + if peer_refs.len() == before { + break; + } + } + let intervals = peer_refs + .iter() + .filter_map(|name| allocations.get(name)) + .filter(|storage| storage.nbytes > 0) + .filter_map(|storage| { + storage + .address + .checked_add(storage.nbytes as u64) + .map(|end| (storage.address, end)) + }) + .collect(); + (peer_refs, merge_sorted_intervals(intervals)) +} + +/// Inspect one graph node and return `(has_peer_copy_node, has_peer_access)`. +/// +/// `has_peer_copy_node` is true strictly for `Node::Copy` with a `Memory::Peer` endpoint. +/// `has_peer_access` is true whenever the node references `Memory::Peer` through a copy, +/// memset, kernel argument or attribute relocation, inline fixed address into a peer or +/// peer-pointer-table allocation, or a module whose globals reference `Memory::Peer`. +fn node_peer_usage( + node: &Node, + function_modules: &HashMap, + allocations: &HashMap, + peer_refs: &HashSet, + peer_ref_intervals: &[(u64, u64)], + peer_modules: &HashSet, +) -> (bool, bool) { + let is_direct_peer = |reference: &Reference| { + allocations + .get(&reference.allocation) + .is_some_and(|storage| matches!(storage.memory, Memory::Peer)) + }; + let blob_references_peer = |blob: &Blob| { + blob.relocations + .iter() + .any(|rel| peer_refs.contains(&rel.target.allocation)) + || contains_interval_address(&blob.data, peer_ref_intervals, None) + }; + match node { + Node::Copy { + source, + destination, + .. + } => { + let copy_peer = is_direct_peer(source) || is_direct_peer(destination); + let access_peer = copy_peer + || peer_refs.contains(&source.allocation) + || peer_refs.contains(&destination.allocation); + (copy_peer, access_peer) + } + Node::Memset { destination, .. } => (false, peer_refs.contains(&destination.allocation)), + Node::Kernel { + function, + arguments, + attributes, + .. + } => { + let module_peer = function_modules + .get(function) + .is_some_and(|module| peer_modules.contains(*module)); + let arg_peer = arguments.iter().any(blob_references_peer) + || attributes + .iter() + .any(|attr| blob_references_peer(&attr.value)); + (false, module_peer || arg_peer) + } + Node::Empty | Node::EventWait { .. } => (false, false), + } +} + fn clamp_cooperative_grid(mut grid: [u32; 3], capacity: u64) -> Result<[u32; 3]> { let axis = (0..3).max_by_key(|&axis| grid[axis]).unwrap(); let plane = u64::from(grid[(axis + 1) % 3]) * u64::from(grid[(axis + 2) % 3]); @@ -418,6 +610,10 @@ impl NativeResources { executables: vec![], names: vec![], peer_copy_graphs: vec![], + peer_access_graphs: vec![], + gate_peer_access: false, + peer_table_allocations: HashSet::new(), + peer_modules: HashSet::new(), reservations: vec![], execution: core.execution.clone(), integrated: integrated != 0, @@ -731,9 +927,11 @@ impl NativeResources { ranks: usize, ) -> Result<()> { let driver = self.driver.clone(); + let peer_intervals = peer_address_intervals(&self.allocations); unsafe { driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; - payload::load(self, files, core, phase, ranks)?; + let peer_tables = payload::load(self, files, core, phase, ranks, &peer_intervals)?; + self.peer_table_allocations.extend(peer_tables); for allocation in &core.allocations { for relocation in &allocation.relocations { let address = @@ -793,6 +991,11 @@ impl NativeResources { } } driver.check("cuCtxSetCurrent", (driver.context_set)(self.context))?; + let (peer_refs, peer_ref_intervals) = collect_peer_referencing_allocations( + core, + &self.allocations, + &self.peer_table_allocations, + ); let mut modules = HashMap::new(); for module in &core.modules { if skip_module == Some(module.name.as_str()) { @@ -810,6 +1013,7 @@ impl NativeResources { )?; self.modules.push(handle); modules.insert(&module.name, handle); + let mut module_uses_peer = false; for global in &module.globals { let symbol = CString::new(global.symbol.as_str()).unwrap(); let (mut address, mut size) = (0, 0); @@ -824,6 +1028,15 @@ impl NativeResources { global.symbol ))); } + if !peer_ref_intervals.is_empty() + && (global + .relocations + .iter() + .any(|rel| peer_refs.contains(&rel.target.allocation)) + || contains_interval_address(&contents, &peer_ref_intervals, Some(0))) + { + module_uses_peer = true; + } for relocation in &global.relocations { self.relocate(&mut contents, relocation, relocation.offset)?; } @@ -832,6 +1045,9 @@ impl NativeResources { (driver.upload)(address, contents.as_ptr().cast(), size), )?; } + if module_uses_peer { + self.peer_modules.insert(module.name.clone()); + } phase.advance(1); } for function in &core.functions { @@ -898,6 +1114,16 @@ impl NativeResources { )?; dynamic_shared.insert(function as usize, bytes as u32); } + let (peer_refs, peer_ref_intervals) = collect_peer_referencing_allocations( + core, + &self.allocations, + &self.peer_table_allocations, + ); + let function_modules: HashMap = core + .functions + .iter() + .map(|entry| (entry.id, entry.module.as_str())) + .collect(); let worker_graph_name = core .execution .as_ref() @@ -928,6 +1154,7 @@ impl NativeResources { self.templates.push(handle); let mut nodes = Vec::with_capacity(graph.node_count); let mut has_peer_copies = false; + let mut has_peer_access = false; let mut records = files.records(core, &graph.resource)?; for _ in 0..graph.node_count { let node = protobuf::node(records.read()?)?; @@ -939,6 +1166,16 @@ impl NativeResources { )); } } + let (node_copy_peer, node_access_peer) = node_peer_usage( + &node, + &function_modules, + &self.allocations, + &peer_refs, + &peer_ref_intervals, + &self.peer_modules, + ); + has_peer_copies |= node_copy_peer; + has_peer_access |= node_access_peer; let node = &node; let mut result = null_mut(); match node { @@ -1157,14 +1394,6 @@ impl NativeResources { destination, nbytes, } => { - let is_peer = |reference: &Reference| { - self.allocations - .get(&reference.allocation) - .is_some_and(|storage| matches!(storage.memory, Memory::Peer)) - }; - if is_peer(source) || is_peer(destination) { - has_peer_copies = true; - } let endpoint = |reference| CopyEndpoint { memory_type: 2, device: self.address(reference), @@ -1247,6 +1476,7 @@ impl NativeResources { self.executables.push(executable); self.names.push(graph.name.clone()); self.peer_copy_graphs.push(has_peer_copies); + self.peer_access_graphs.push(has_peer_access); driver.check( "cuGraphUpload", (driver.graph_upload)(executable, upload_stream), @@ -1355,10 +1585,34 @@ impl NativeResources { Ok(()) } + /// True when at least one graph contains a Copy Engine `Node::Copy` targeting `Memory::Peer`. + /// Used by `Execution.async_transfers` compatibility validation, independent of PCIe + /// kernel-collective `CopyEngineGate` gating. pub(super) fn has_any_peer_copy_graphs(&self) -> bool { self.peer_copy_graphs.iter().any(|&has_peer| has_peer) } + /// True when at least one graph touches `Memory::Peer` via copy, memset, kernel arguments, + /// indirect pointer tables, or module globals. + pub(super) fn has_any_peer_access_graphs(&self) -> bool { + self.peer_access_graphs.iter().any(|&has_peer| has_peer) + } + + /// Configure whether single-host PCIe multi-rank `CopyEngineGate` gating covers all + /// peer-access graphs (`peer_access_graphs`) rather than only `Node::Copy(Memory::Peer)`. + 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) + } + } + unsafe fn clamp_cooperative_launch( &self, params: &mut KernelParams, @@ -1485,6 +1739,7 @@ impl NativeResources { files: &F, core: &Core, planned_host_cap: u64, + global_rank: usize, ) -> Result<()> { let Some(execution) = core.execution.as_ref() else { return Ok(()); @@ -1595,6 +1850,7 @@ impl NativeResources { let cfg = crate::async_transfer::ChannelConfig { name: channel.name.clone(), + rank: global_rank, device_pool_base: device_pool.address as u64, device_pool_bytes: device_pool.nbytes as u64, host_pool_bytes, @@ -1776,16 +2032,31 @@ impl NativeResources { } } +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 +} + impl NativeResources { - /// Phase 1 of teardown: stop any persistent worker, synchronize this rank's context, - /// and destroy all graphs, modules, events, streams, device/host mappings, and green contexts - /// while peer contexts and shared VA reservations stay alive. - /// Returns `false` when the worker or context cannot be drained, retaining the driver until process exit. - pub(super) fn release_execution_resources(&mut self) -> bool { + /// Phase 1 of teardown: stop any persistent worker and all async transfer channels without + /// short-circuiting, then synchronize this rank's CUDA context while all peer-accessible + /// device memory, `MappedHost` mailboxes, and host workers remain live. + /// + /// Returns `false` when any worker, channel, or context fails to confirm drain, retaining + /// the driver and preventing subsequent teardown phases from unmapping live memory. + pub(super) fn drain_execution_context(&mut self) -> bool { if self.context.is_null() { return true; } - if self.stop_persistent_worker().is_err() || self.stop_async_transfers().is_err() { + let workers_drained = stop_rank_workers( + || self.stop_persistent_worker(), + || self.stop_async_transfers(), + ); + if !workers_drained { std::mem::forget(self.driver.clone()); self.context = null_mut(); return false; @@ -1793,7 +2064,31 @@ impl NativeResources { unsafe { let mut previous = null_mut(); let had_previous = (self.driver.context_get)(&mut previous) == 0; - if (self.driver.context_set)(self.context) != 0 || (self.driver.context_sync)() != 0 { + let synced = (self.driver.context_set)(self.context) == 0 + && (self.driver.context_sync)() == 0; + if had_previous && previous != self.context { + let _ = (self.driver.context_set)(previous); + } + if !synced { + std::mem::forget(self.driver.clone()); + self.context = null_mut(); + return false; + } + true + } + } + + /// Phase 2 of teardown: destroy all graphs, modules, events, streams, and device/host + /// mappings after every rank has drained and host offload/Engram threads have joined, + /// while peer contexts and shared VA reservations remain alive. + pub(super) fn destroy_execution_resources(&mut self) -> bool { + if self.context.is_null() { + return true; + } + unsafe { + let mut previous = null_mut(); + let had_previous = (self.driver.context_get)(&mut previous) == 0; + if (self.driver.context_set)(self.context) != 0 { if had_previous && previous != self.context { let _ = (self.driver.context_set)(previous); } @@ -1857,7 +2152,7 @@ impl NativeResources { } } - /// Phase 2 of teardown: destroy green contexts, release VA reservations, and destroy or + /// Phase 3 of teardown: destroy green contexts, release VA reservations, and destroy or /// release this rank's CUDA context. pub(super) fn release_reservations_and_context(&mut self) { if self.context.is_null() { @@ -1903,7 +2198,7 @@ impl Drop for NativeResources { fn drop(&mut self) { // SAFETY: This owner is the sole resource destroyer. On a failed drain, // retain the driver and all GPU resources until process termination. - if self.release_execution_resources() { + if self.drain_execution_context() && self.destroy_execution_resources() { self.release_reservations_and_context(); } } @@ -1936,3 +2231,339 @@ unsafe fn apply_context_settings( configured } } + +#[cfg(test)] +mod peer_usage_tests { + use super::*; + use format::{Allocation, Attribute, Function, Module}; + + fn storage(address: u64, nbytes: usize, memory: Memory) -> Storage { + Storage { + base: address, + address, + nbytes, + memory, + fixed: true, + mappings: Vec::new(), + } + } + + fn minimal_core(allocations: Vec, functions: Vec) -> Core { + Core { + resources: HashMap::new(), + architecture: [12, 0], + allocations, + modules: vec![Module { + name: "mod0".into(), + file: "mod0.cubin".into(), + globals: Vec::new(), + }], + functions, + graphs: Vec::new(), + reservations: Vec::new(), + execution: None, + context: format::Context::default(), + events: Vec::new(), + external_extents: Vec::new(), + } + } + + fn alloc_desc(name: &str, address: u64, nbytes: usize, memory: Memory, relocations: Vec) -> Allocation { + Allocation { + name: name.into(), + nbytes, + alignment: 256, + file: None, + data_spans: Vec::new(), + sources: Vec::new(), + relocations, + address: Some(address), + memory, + sizing: None, + } + } + + #[test] + fn node_peer_usage_distinguishes_peer_copy_nodes_from_kernel_and_table_peer_access() { + let peer_addr = 0x0000_7f00_1000_0000u64; + let table_addr = 0x0000_7f00_2000_0000u64; + let reloc_table_addr = 0x0000_7f00_3000_0000u64; + let local_addr = 0x0000_7f00_4000_0000u64; + + let mut allocations = HashMap::new(); + allocations.insert("peer_slab".into(), storage(peer_addr, 4096, Memory::Peer)); + allocations.insert("rank_data".into(), storage(table_addr, 4096, Memory::Device)); + allocations.insert( + "reloc_table".into(), + storage(reloc_table_addr, 4096, Memory::Device), + ); + allocations.insert("local_buf".into(), storage(local_addr, 4096, Memory::Device)); + + let core = minimal_core( + vec![ + alloc_desc("peer_slab", peer_addr, 4096, Memory::Peer, vec![]), + alloc_desc("rank_data", table_addr, 4096, Memory::Device, vec![]), + alloc_desc( + "reloc_table", + reloc_table_addr, + 4096, + Memory::Device, + vec![Relocation { + offset: 0, + target: Reference { + allocation: "peer_slab".into(), + offset: 64, + }, + kind: RelocationKind::Pointer, + }], + ), + alloc_desc("local_buf", local_addr, 4096, Memory::Device, vec![]), + ], + vec![ + Function { + id: 0, + module: "mod0".into(), + symbol: "k0".into(), + parameter_sizes: vec![], + attributes: vec![], + }, + Function { + id: 1, + module: "peer_mod".into(), + symbol: "k1".into(), + parameter_sizes: vec![], + attributes: vec![], + }, + ], + ); + + let peer_intervals = peer_address_intervals(&allocations); + let mut table_bytes = vec![0u8; 32]; + table_bytes[8..16].copy_from_slice(&(peer_addr + 128).to_le_bytes()); + assert!(contains_interval_address(&table_bytes, &peer_intervals, Some(0))); + assert!(!contains_interval_address(&[0u8; 32], &peer_intervals, Some(0))); + + let payload_peer_tables: HashSet = ["rank_data".to_string()].into_iter().collect(); + let (peer_refs, peer_ref_intervals) = + collect_peer_referencing_allocations(&core, &allocations, &payload_peer_tables); + assert!(peer_refs.contains("peer_slab")); + assert!(peer_refs.contains("rank_data")); + assert!(peer_refs.contains("reloc_table")); + assert!(!peer_refs.contains("local_buf")); + + let function_modules: HashMap = + core.functions.iter().map(|f| (f.id, f.module.as_str())).collect(); + let peer_modules: HashSet = ["peer_mod".to_string()].into_iter().collect(); + + // 1. Copy Engine Node::Copy with Memory::Peer sets BOTH flags. + let peer_copy = Node::Copy { + source: Reference { + allocation: "local_buf".into(), + offset: 0, + }, + destination: Reference { + allocation: "peer_slab".into(), + offset: 0, + }, + nbytes: 64, + }; + assert_eq!( + node_peer_usage( + &peer_copy, + &function_modules, + &allocations, + &peer_refs, + &peer_ref_intervals, + &peer_modules, + ), + (true, true) + ); + + // 2. Local Node::Copy sets neither flag. + let local_copy = Node::Copy { + source: Reference { + allocation: "local_buf".into(), + offset: 0, + }, + destination: Reference { + allocation: "local_buf".into(), + offset: 128, + }, + nbytes: 64, + }; + assert_eq!( + node_peer_usage( + &local_copy, + &function_modules, + &allocations, + &peer_refs, + &peer_ref_intervals, + &peer_modules, + ), + (false, false) + ); + + // 3. Kernel passing raw fixed Memory::Peer address (e.g., PCIeTwoShotBF16) sets peer_access only. + let kernel_inline_peer = Node::Kernel { + function: 0, + grid: [1, 1, 1], + block: [32, 1, 1], + shared: 0, + arguments: vec![Blob { + data: (peer_addr + 256).to_le_bytes().to_vec(), + relocations: vec![], + }], + attributes: vec![], + }; + assert_eq!( + node_peer_usage( + &kernel_inline_peer, + &function_modules, + &allocations, + &peer_refs, + &peer_ref_intervals, + &peer_modules, + ), + (false, true) + ); + + // 4. Kernel passing raw address into payload-scanned rank_data table (e.g., PCIeOneshotAllReducePool). + let kernel_rank_data = Node::Kernel { + function: 0, + grid: [1, 1, 1], + block: [32, 1, 1], + shared: 0, + arguments: vec![Blob { + data: (table_addr + 128).to_le_bytes().to_vec(), + relocations: vec![], + }], + attributes: vec![], + }; + assert_eq!( + node_peer_usage( + &kernel_rank_data, + &function_modules, + &allocations, + &peer_refs, + &peer_ref_intervals, + &peer_modules, + ), + (false, true) + ); + + // 5. Kernel with relocation into reloc_table or peer_slab via attribute. + let kernel_attr_reloc = Node::Kernel { + function: 0, + grid: [1, 1, 1], + block: [32, 1, 1], + shared: 0, + arguments: vec![Blob { + data: local_addr.to_le_bytes().to_vec(), + relocations: vec![], + }], + attributes: vec![Attribute { + id: 1, + value: Blob { + data: vec![0u8; 64], + relocations: vec![Relocation { + offset: 0, + target: Reference { + allocation: "reloc_table".into(), + offset: 0, + }, + kind: RelocationKind::Pointer, + }], + }, + }], + }; + assert_eq!( + node_peer_usage( + &kernel_attr_reloc, + &function_modules, + &allocations, + &peer_refs, + &peer_ref_intervals, + &peer_modules, + ), + (false, true) + ); + + // 6. Kernel in a module whose global references Memory::Peer. + let kernel_peer_module = Node::Kernel { + function: 1, + grid: [1, 1, 1], + block: [32, 1, 1], + shared: 0, + arguments: vec![Blob { + data: local_addr.to_le_bytes().to_vec(), + relocations: vec![], + }], + attributes: vec![], + }; + assert_eq!( + node_peer_usage( + &kernel_peer_module, + &function_modules, + &allocations, + &peer_refs, + &peer_ref_intervals, + &peer_modules, + ), + (false, true) + ); + + // 7. Purely local kernel sets neither flag. + let local_kernel = Node::Kernel { + function: 0, + grid: [1, 1, 1], + block: [32, 1, 1], + shared: 0, + arguments: vec![Blob { + data: local_addr.to_le_bytes().to_vec(), + relocations: vec![], + }], + attributes: vec![], + }; + assert_eq!( + node_peer_usage( + &local_kernel, + &function_modules, + &allocations, + &peer_refs, + &peer_ref_intervals, + &peer_modules, + ), + (false, false) + ); + } + + #[test] + fn stop_rank_workers_evaluates_both_stops_without_short_circuiting() { + let mut transfers_stopped = false; + let ok = stop_rank_workers( + || Err(invalid("persistent worker drain failed")), + || { + transfers_stopped = true; + Ok(()) + }, + ); + assert!(!ok); + assert!( + transfers_stopped, + "stop_async_transfers must run even when stop_persistent_worker fails" + ); + + let mut worker_stopped = false; + let ok = stop_rank_workers( + || { + worker_stopped = true; + Ok(()) + }, + || Err(invalid("async transfer drain failed")), + ); + assert!(!ok); + assert!(worker_stopped); + + assert!(stop_rank_workers(|| Ok(()), || Ok(()))); + } +} diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index a996ddfab..e20b9ad75 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -129,12 +129,57 @@ fn validate_persistent_worker_topology( Ok(()) } +/// Returns true only when every distinct pair of local GPUs has pairwise NVLink P2P access. +/// Falls back to `false` (treat as PCIe) when fewer than two ranks are local or NVML cannot +/// confirm NVLink connectivity. +fn all_nvlink_p2p(pci_bus_ids: &[String]) -> bool { + if pci_bus_ids.len() < 2 { + return false; + } + let Ok(nvml) = crate::nvml::Nvml::load() else { + return false; + }; + let mut handles = Vec::with_capacity(pci_bus_ids.len()); + for bus_id in pci_bus_ids { + let Ok(c_bus_id) = std::ffi::CString::new(bus_id.as_str()) else { + return false; + }; + let Ok(handle) = nvml.device_by_pci_bus_id(&c_bus_id) else { + return false; + }; + handles.push(handle); + } + 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; + } + } + } + true +} + +/// Decides whether `CopyEngineGate` is required and whether single-host PCIe multi-rank +/// kernel peer-access graphs must be gated alongside Copy Engine `Node::Copy(Memory::Peer)` graphs. +fn copy_gate_policy( + local_ranks: usize, + all_nvlink: bool, + has_peer_copy_nodes: bool, + has_peer_access_graphs: bool, +) -> (bool, bool) { + let gate_peer_access = local_ranks > 1 && !all_nvlink; + let enable_gate = has_peer_copy_nodes || (gate_peer_access && has_peer_access_graphs); + (gate_peer_access, enable_gate) +} + /// Reject cores that combine `Execution.async_transfers` with graphs containing Copy Engine /// peer-to-peer copy nodes (`Memory::Peer`). Captured in-graph demand waits cannot yield to /// `CopyEngineGate` without circular deadlock, and ungated concurrent Copy Engine H2D transfers /// trigger PCIe TP>=2 Copy Engine deadlock. fn validate_async_transfer_peer_copy_compatibility( - has_peer_copy_graphs: bool, + has_peer_copy_nodes: bool, cores: &[Core], ) -> Result<()> { let has_async_transfers = cores.iter().any(|core| { @@ -142,7 +187,7 @@ fn validate_async_transfer_peer_copy_compatibility( .as_ref() .is_some_and(|execution| !execution.async_transfers.is_empty()) }); - if has_peer_copy_graphs && has_async_transfers { + 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", @@ -873,12 +918,27 @@ impl NativeModel { model.parallel(&cores, &files, |rank, core, files| { rank.prepare_graphs(files, core, &phase) })?; - let has_peer_copy_graphs = model + let has_peer_copy_nodes = model .ranks .iter() .any(NativeResources::has_any_peer_copy_graphs); - validate_async_transfer_peer_copy_compatibility(has_peer_copy_graphs, &cores)?; - model.copy_gate = has_peer_copy_graphs + validate_async_transfer_peer_copy_compatibility(has_peer_copy_nodes, &cores)?; + let has_peer_access_graphs = model + .ranks + .iter() + .any(NativeResources::has_any_peer_access_graphs); + 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(|| std::sync::Arc::new(crate::offload::CopyEngineGate::new())); phase.finish(format!("concurrency {active}")); if !engram.is_empty() { @@ -1001,10 +1061,12 @@ impl NativeModel { return Ok(()); } let phase = progress.phase("Prepare async transfers", None); + let cluster_rank = self.cluster.as_ref().map(|cluster| cluster.rank); for (idx, (rank, core)) in self.ranks.iter_mut().zip(cores.iter()).enumerate() { let planned_cap = planned_host_caps.get(idx).copied().unwrap_or(0); + let global_rank = cluster_rank.unwrap_or(idx); unsafe { - rank.prepare_async_transfers(files, core, planned_cap)?; + rank.prepare_async_transfers(files, core, planned_cap, global_rank)?; } rank.start_async_transfers()?; } @@ -1202,26 +1264,61 @@ impl NativeModel { } } +/// Three-phase cross-rank teardown barrier: +/// 1. Drain every rank (stop workers/transfers without short-circuiting and synchronize contexts) +/// before any rank unmaps peer-accessible `Memory::Device` or `Memory::MappedHost` allocations. +/// 2. Join Engram threads and reset host offload while `MappedHost` mailboxes and CUDA contexts +/// remain live, then destroy graphs, modules, and allocations across every rank. +/// 3. Release green contexts, shared VA reservations, and CUDA contexts (rank zero last). +/// +/// Returns `false` without executing later phases if any rank fails to confirm drain. +fn teardown_model_ranks( + ranks: &mut Vec, + 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 { + let mut all_drained = true; + for rank in ranks.iter_mut().rev() { + let drained = drain_rank(rank); + all_drained &= drained; + } + if !all_drained { + return false; + } + release_host_subsystems(); + let mut all_destroyed = true; + for rank in ranks.iter_mut().rev() { + let destroyed = destroy_rank(rank); + all_destroyed &= destroyed; + } + if !all_destroyed { + return false; + } + while let Some(rank) = ranks.pop() { + release_rank_context(rank); + } + true +} + impl Drop for NativeModel { fn drop(&mut self) { - // Phase 1: stop persistent workers, drain contexts, and destroy graphs, modules, - // and peer-accessible mappings across every rank before releasing host offload/Engram - // buffers, shared VA reservations, or CUDA contexts. - let mut all_drained = true; - for rank in self.ranks.iter_mut().rev() { - all_drained &= rank.release_execution_resources(); - } - // Phase 2: once every rank drained, tear down host offload and Engram resources while - // primary and green contexts remain live, then destroy green contexts, release shared - // VA reservations, and destroy CUDA contexts (rank zero last). If any rank failed drain, - // retain offload, Engram, and remaining contexts until process exit. - if all_drained { - self.offload.reset(); - self.engram.clear(); - while let Some(mut rank) = self.ranks.pop() { - rank.release_reservations_and_context(); - } - } else { + let engram = &mut self.engram; + let offload = &mut self.offload; + let completed = teardown_model_ranks( + &mut self.ranks, + NativeResources::drain_execution_context, + || { + // Join background Engram reader threads and tear down host prefix offload while + // `MappedHost` mailboxes and CUDA contexts remain live on every rank. + engram.clear(); + offload.reset(); + }, + NativeResources::destroy_execution_resources, + |mut rank| rank.release_reservations_and_context(), + ); + if !completed { let retained_offload = std::mem::take(&mut self.offload); let retained_engram = std::mem::take(&mut self.engram); let retained = std::mem::take(&mut self.ranks); @@ -1551,6 +1648,89 @@ mod tests { // Peer-copy graphs without async_transfers succeed. validate_async_transfer_peer_copy_compatibility(true, &[make_core(false)]).unwrap(); } + + #[test] + fn copy_gate_policy_gates_pcie_kernel_peer_access_without_blocking_nvlink_or_single_rank() { + // Single-host PCIe TP>=2 with kernel-only Memory::Peer access (no Node::Copy(Peer)) + // must enable CopyEngineGate and gate all peer-access graphs. + assert_eq!(copy_gate_policy(4, false, false, true), (true, true)); + // Single-host PCIe TP>=2 with both Node::Copy(Peer) and kernel peer access. + assert_eq!(copy_gate_policy(4, false, true, true), (true, true)); + // Single-host PCIe TP>=2 with no peer-touching graphs does not enable the gate. + assert_eq!(copy_gate_policy(4, false, false, false), (true, false)); + // All-NVLink TP>=2 with SM kernel P2P (no Node::Copy(Peer)) skips PCIe gating. + assert_eq!(copy_gate_policy(4, true, false, true), (false, false)); + // All-NVLink TP>=2 with explicit Node::Copy(Peer) still gates those copy graphs. + assert_eq!(copy_gate_policy(4, true, true, true), (false, true)); + // Single-rank / multi-host RoCE rank does not enable PCIe peer-access gating. + assert_eq!(copy_gate_policy(1, false, false, false), (false, false)); + } + + #[test] + fn teardown_model_ranks_enforces_three_phase_cross_rank_barrier() { + let events = std::cell::RefCell::new(Vec::new()); + let mut ranks = vec![0usize, 1, 2, 3]; + let ok = teardown_model_ranks( + &mut ranks, + |rank| { + events.borrow_mut().push(format!("drain-{rank}")); + true + }, + || events.borrow_mut().push("host-subsystems".into()), + |rank| { + events.borrow_mut().push(format!("destroy-{rank}")); + true + }, + |rank| events.borrow_mut().push(format!("release-ctx-{rank}")), + ); + assert!(ok); + assert!(ranks.is_empty()); + assert_eq!( + events.into_inner(), + vec![ + "drain-3", + "drain-2", + "drain-1", + "drain-0", + "host-subsystems", + "destroy-3", + "destroy-2", + "destroy-1", + "destroy-0", + "release-ctx-3", + "release-ctx-2", + "release-ctx-1", + "release-ctx-0", + ] + ); + } + + #[test] + fn teardown_model_ranks_drains_all_ranks_and_retains_resources_on_failed_drain() { + let events = std::cell::RefCell::new(Vec::new()); + let mut ranks = vec![0usize, 1, 2, 3]; + let ok = teardown_model_ranks( + &mut ranks, + |rank| { + events.borrow_mut().push(format!("drain-{rank}")); + *rank != 2 + }, + || events.borrow_mut().push("host-subsystems".into()), + |rank| { + events.borrow_mut().push(format!("destroy-{rank}")); + true + }, + |rank| events.borrow_mut().push(format!("release-ctx-{rank}")), + ); + assert!(!ok); + assert_eq!(ranks, vec![0, 1, 2, 3]); + // Every rank still attempts Phase 1 drain without short-circuiting, while Phases 2 and 3 + // are skipped so P2P Device memory, MappedHost mailboxes, and Engram/offload stay live. + assert_eq!( + events.into_inner(), + vec!["drain-3", "drain-2", "drain-1", "drain-0"] + ); + } } /// Verified identity of an authorized core, taken from signed metadata only. diff --git a/helios/src/runtime_core/payload.rs b/helios/src/runtime_core/payload.rs index 4bac0cb31..987743942 100644 --- a/helios/src/runtime_core/payload.rs +++ b/helios/src/runtime_core/payload.rs @@ -8,11 +8,15 @@ use crate::os::FileReadAt; use std::{ - collections::VecDeque, + collections::{HashSet, VecDeque}, fs::File, io, ptr::null_mut, - sync::{Arc, Mutex, mpsc}, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + mpsc, + }, thread, }; @@ -205,6 +209,8 @@ struct Chunk { destination: u64, nbytes: usize, memory: Memory, + alloc_index: usize, + alloc_offset: usize, } impl Chunk { @@ -236,16 +242,21 @@ impl Chunk { } /// The owner's mapped allocations must be live and unused by graph execution. +/// +/// When `peer_intervals` is nonempty, scans loaded 8-byte aligned payload words and returns the +/// names of allocations whose stored bytes contain an address within a `Memory::Peer` interval +/// (such as kernel-P2P pointer tables). pub(super) unsafe fn load( owner: &NativeResources, files: &F, core: &Core, phase: &Phase, ranks: usize, -) -> Result<()> { - let chunk_bytes = CHUNK / ranks; + peer_intervals: &[(u64, u64)], +) -> Result> { + let chunk_bytes = ((CHUNK / ranks) & !7).max(8); let mut chunks = Vec::new(); - for allocation in &core.allocations { + for (alloc_index, allocation) in core.allocations.iter().enumerate() { if allocation.is_payload_bound() { // Every span names the payload resource that supplies it, so initializations that draw // from several payloads stay exact: no ordering or contiguity is assumed across spans. @@ -264,6 +275,8 @@ pub(super) unsafe fn load( + (offset + start) as u64, nbytes, memory: allocation.memory, + alloc_index, + alloc_offset: offset + start, }); file_offset += nbytes as u64; } @@ -285,14 +298,19 @@ pub(super) unsafe fn load( + (offset + start) as u64, nbytes, memory: allocation.memory, + alloc_index, + alloc_offset: offset + start, }); file_offset += nbytes as u64; } } } if chunks.is_empty() { - return Ok(()); + return Ok(HashSet::new()); } + let peer_flagged: Vec = (0..core.allocations.len()) + .map(|_| AtomicBool::new(false)) + .collect(); let count = SLOTS.min(chunks.len()); let chunk_size = chunks .iter() @@ -311,12 +329,13 @@ pub(super) unsafe fn load( let available = Arc::new(Mutex::new(available)); let (ready, finished) = mpsc::sync_channel(count); for index in 0..READERS.min(count) { - let (available, chunks, buffers, ready, path) = ( + let (available, chunks, buffers, ready, path, peer_flagged) = ( available.clone(), &chunks, &buffers, ready.clone(), files.path().to_path_buf(), + &peer_flagged, ); thread::Builder::new() .name(format!("flare-reader-{index}")) @@ -356,6 +375,16 @@ pub(super) unsafe fn load( chunk.file_offset )) })?; + if !peer_intervals.is_empty() + && !peer_flagged[chunk.alloc_index].load(Ordering::Relaxed) + && super::contains_interval_address( + bytes, + peer_intervals, + Some(chunk.alloc_offset), + ) + { + peer_flagged[chunk.alloc_index].store(true, Ordering::Relaxed); + } if matches!(chunk.memory, Memory::MappedHost) { unsafe { std::ptr::copy_nonoverlapping( @@ -436,7 +465,14 @@ pub(super) unsafe fn load( } drop(work); Ok(()) - }) + })?; + let mut peer_tables = HashSet::new(); + for (alloc_index, flag) in peer_flagged.into_iter().enumerate() { + if flag.into_inner() { + peer_tables.insert(core.allocations[alloc_index].name.clone()); + } + } + Ok(peer_tables) } #[cfg(test)] @@ -470,6 +506,8 @@ mod tests { destination: 0, nbytes: payload.len(), memory: Memory::Device, + alloc_index: 0, + alloc_offset: 0, }; let mut buffer = Aligned([0xa5; 3 * BLOCK]); assert_eq!(chunk.read(&reader, &mut buffer.0).unwrap(), payload); diff --git a/helios/src/runtime_core/serving.rs b/helios/src/runtime_core/serving.rs index 4f44d6da3..c95d191b7 100644 --- a/helios/src/runtime_core/serving.rs +++ b/helios/src/runtime_core/serving.rs @@ -56,7 +56,7 @@ impl NativeResources { .iter() .position(|name| *name == g.name) .ok_or_else(|| invalid("execution references an unknown graph"))?; - peer_copy_graphs.push(self.peer_copy_graphs.get(index).copied().unwrap_or(false)); + peer_copy_graphs.push(self.graph_uses_copy_gate(index)); Ok(GraphDescriptor { tuned_bindings: g.tuned_bindings.iter().map(|binding| TunedBinding { buffer: binding.buffer.clone(), tuning_graph: binding.tuning_graph.clone(), diff --git a/helios/src/server/metrics.rs b/helios/src/server/metrics.rs index b8fd9b513..c9a545840 100644 --- a/helios/src/server/metrics.rs +++ b/helios/src/server/metrics.rs @@ -1531,6 +1531,15 @@ fn render_persistent_worker_metrics( fn render_async_transfer_metrics( text: &mut String, channels: &[std::sync::Arc], +) { + let snapshots: Vec<_> = channels.iter().map(|c| c.snapshot()).collect(); + render_async_transfer_snapshots(text, &snapshots); +} + +#[cfg(feature = "runtime-core")] +fn render_async_transfer_snapshots( + text: &mut String, + snapshots: &[crate::async_transfer::AsyncTransferSnapshot], ) { text.push_str( "# HELP flare_async_transfer_device_pool_bytes Mapped device pool capacity in bytes.\n\ @@ -1554,8 +1563,8 @@ fn render_async_transfer_metrics( # HELP flare_async_transfer_last_error Most recent non-zero async transfer error code (0 when error-free).\n\ # TYPE flare_async_transfer_last_error gauge\n", ); - for (rank, channel) in channels.iter().enumerate() { - let s = channel.snapshot(); + for s in snapshots { + let rank = s.rank; let label = escape_prometheus_label(&s.name); let _ = writeln!( text, @@ -1587,6 +1596,47 @@ fn render_async_transfer_metrics( mod tests { use super::*; + #[cfg(feature = "runtime-core")] + #[test] + fn async_transfer_metrics_label_true_rank_ids_not_flat_vector_indices() { + use crate::async_transfer::{AsyncTransferSnapshot, ChannelState}; + + let make = |name: &str, rank: usize, submitted: u64| AsyncTransferSnapshot { + name: name.into(), + rank, + state: ChannelState::Running, + device_pool_bytes: 1024, + host_pool_bytes: 2048, + extent_count: 4, + submitted_cmds: submitted, + completed_cmds: submitted, + canceled_cmds: 0, + rejected_cmds: 0, + bytes_disk_to_host: 0, + bytes_host_to_dev: 0, + bytes_disk_to_dev: 0, + last_error: 0, + }; + let snapshots = vec![ + make("experts_a", 0, 11), + make("experts_b", 0, 22), + make("experts_a", 3, 33), + ]; + let mut text = String::new(); + render_async_transfer_snapshots(&mut text, &snapshots); + assert!(text.contains( + "flare_async_transfer_submitted_cmds_total{channel=\"experts_a\",rank=\"0\"} 11\n" + )); + assert!(text.contains( + "flare_async_transfer_submitted_cmds_total{channel=\"experts_b\",rank=\"0\"} 22\n" + )); + assert!(text.contains( + "flare_async_transfer_submitted_cmds_total{channel=\"experts_a\",rank=\"3\"} 33\n" + )); + assert!(!text.contains("rank=\"1\"")); + assert!(!text.contains("rank=\"2\"")); + } + #[test] fn checkpoint_metrics_report_capture_roles_rejection_reasons_work_and_reservations() { let metrics = Metrics::new(0, 0, 0, 16); diff --git a/verification/helios-lifecycle/AsyncTransfer.cfg b/verification/helios-lifecycle/AsyncTransfer.cfg index 01546ef0a..5b25bc364 100644 --- a/verification/helios-lifecycle/AsyncTransfer.cfg +++ b/verification/helios-lifecycle/AsyncTransfer.cfg @@ -19,3 +19,5 @@ INVARIANTS DrainingHasEmptyQueues CanReleaseExact FaultedDmaRetainsOwnership + UnflushedIoBounded + HwSignaledFaultedSafe diff --git a/verification/helios-lifecycle/AsyncTransfer.tla b/verification/helios-lifecycle/AsyncTransfer.tla index f3021768b..6b87d0e35 100644 --- a/verification/helios-lifecycle/AsyncTransfer.tla +++ b/verification/helios-lifecycle/AsyncTransfer.tla @@ -25,7 +25,9 @@ Initial == bInDma |-> 0, freeBounce |-> BounceSlots, canRelease |-> 1, - faultedDma |-> 0] + faultedDma |-> 0, + unflushedIo |-> 0, + hwSignaledFaulted |-> 0] Init == state = Initial @@ -75,7 +77,14 @@ DispatchIo(before, after) == !.inDemIo = @ + IF isBg THEN 0 ELSE 1, !.inBgIo = @ + IF isBg THEN 1 ELSE 0, !.bInIo = @ + takeBounce, - !.freeBounce = @ - takeBounce]) + !.freeBounce = @ - takeBounce, + !.unflushedIo = @ + 1]) + +FlushIo(before, after) == + /\ before.phase \in {RUNNING, DRAINING} + /\ before.unflushedIo > 0 + /\ \E flushed \in 1..before.unflushedIo : + after = WithRelease([before EXCEPT !.unflushedIo = @ - flushed]) DispatchDma(before, after) == /\ before.phase = RUNNING @@ -94,38 +103,49 @@ DispatchDma(before, after) == CompleteIo(before, after) == /\ before.phase \in {RUNNING, DRAINING, FAILED_DRAIN} - /\ \E isBg \in BOOLEAN, promoteDma \in BOOLEAN, hasBounce \in 0..1 : + /\ \E isBg \in BOOLEAN, promoteDma \in BOOLEAN, hasBounce \in 0..1, wasUnflushed \in 0..1 : /\ IF isBg THEN before.inBgIo > 0 ELSE before.inDemIo > 0 /\ hasBounce <= before.bInIo /\ (before.bInIo - hasBounce) <= (before.inDemIo + before.inBgIo - 1) + /\ wasUnflushed <= before.unflushedIo + /\ (before.unflushedIo - wasUnflushed) <= (before.inDemIo + before.inBgIo - 1) + /\ (wasUnflushed = 1 => ~promoteDma) /\ (promoteDma => before.phase = RUNNING /\ before.qDma < MaxQueue + MaxTotalIo) /\ after = WithRelease([before EXCEPT !.inDemIo = @ - IF isBg THEN 0 ELSE 1, !.inBgIo = @ - IF isBg THEN 1 ELSE 0, !.bInIo = @ - hasBounce, + !.unflushedIo = @ - wasUnflushed, !.qDma = @ + IF promoteDma THEN 1 ELSE 0, !.bQDma = @ + IF promoteDma THEN hasBounce ELSE 0, !.freeBounce = @ + IF promoteDma THEN 0 ELSE hasBounce]) CompleteDma(before, after) == /\ before.phase \in {RUNNING, DRAINING, FAILED_DRAIN} - /\ \E isBg \in BOOLEAN, hasBounce \in 0..1, wasFaulted \in 0..1 : + /\ \E isBg \in BOOLEAN, hasBounce \in 0..1, wasFaulted \in 0..1, wasHwSignaled \in 0..1 : /\ IF isBg THEN before.inBgDma > 0 ELSE before.inDemDma > 0 /\ hasBounce <= before.bInDma /\ (before.bInDma - hasBounce) <= (before.inDemDma + before.inBgDma - 1) /\ wasFaulted <= before.faultedDma /\ (before.faultedDma - wasFaulted) <= (before.inDemDma + before.inBgDma - 1) + /\ wasHwSignaled <= wasFaulted + /\ wasHwSignaled <= before.hwSignaledFaulted + /\ (before.hwSignaledFaulted - wasHwSignaled) <= (before.faultedDma - wasFaulted) /\ after = WithRelease([before EXCEPT !.inDemDma = @ - IF isBg THEN 0 ELSE 1, !.inBgDma = @ - IF isBg THEN 1 ELSE 0, !.bInDma = @ - hasBounce, !.freeBounce = @ + hasBounce, - !.faultedDma = @ - wasFaulted]) + !.faultedDma = @ - wasFaulted, + !.hwSignaledFaulted = @ - wasHwSignaled]) MarkDmaFaulted(before, after) == /\ before.phase \in {RUNNING, DRAINING} /\ before.faultedDma < before.inDemDma + before.inBgDma - /\ after = WithRelease([before EXCEPT !.faultedDma = @ + 1]) + /\ \E hwSignaled \in 0..1 : + after = WithRelease([before EXCEPT + !.faultedDma = @ + 1, + !.hwSignaledFaulted = @ + hwSignaled]) BeginDrain(before, after) == \/ /\ before.phase = IDLE @@ -142,6 +162,8 @@ FinishDrainOk(before, after) == /\ before.phase = DRAINING /\ before.inDemIo = 0 /\ before.inBgIo = 0 /\ before.inDemDma = 0 /\ before.inBgDma = 0 + /\ before.unflushedIo = 0 + /\ before.faultedDma = 0 /\ before.hwSignaledFaulted = 0 /\ before.freeBounce = BounceSlots /\ after = WithRelease([before EXCEPT !.phase = STOPPED]) @@ -161,6 +183,7 @@ Step(before, after) == \/ FinishDrainOk(before, after) \/ FinishDrainFail(before, after) \/ MarkDmaFaulted(before, after) + \/ FlushIo(before, after) Next == Step(state, state') \/ UNCHANGED state @@ -179,6 +202,8 @@ WellTyped(st) == /\ st.freeBounce \in 0..BounceSlots /\ st.canRelease \in 0..1 /\ st.faultedDma \in 0..MaxTotalDma + /\ st.unflushedIo \in 0..MaxTotalIo + /\ st.hwSignaledFaulted \in 0..MaxTotalDma NoUnmapWhileInflightAt(st) == (st.inDemIo + st.inBgIo + st.inDemDma + st.inBgDma > 0) => st.canRelease = 0 @@ -190,7 +215,9 @@ StoppedHasZeroInflightAt(st) == st.phase = STOPPED => /\ st.inDemIo = 0 /\ st.inBgIo = 0 /\ st.inDemDma = 0 /\ st.inBgDma = 0 + /\ st.unflushedIo = 0 /\ st.faultedDma = 0 + /\ st.hwSignaledFaulted = 0 /\ st.qIo = 0 /\ st.qDma = 0 /\ st.freeBounce = BounceSlots @@ -217,6 +244,16 @@ FaultedDmaRetainsOwnershipAt(st) == /\ st.faultedDma > 0 => st.canRelease = 0 /\ st.phase = STOPPED => st.faultedDma = 0 +UnflushedIoBoundedAt(st) == + /\ st.unflushedIo <= st.inDemIo + st.inBgIo + /\ st.unflushedIo > 0 => st.canRelease = 0 + /\ st.phase = STOPPED => st.unflushedIo = 0 + +HwSignaledFaultedSafeAt(st) == + /\ st.hwSignaledFaulted <= st.faultedDma + /\ st.hwSignaledFaulted > 0 => st.canRelease = 0 + /\ st.phase = STOPPED => st.hwSignaledFaulted = 0 + ObservedSafe(st) == /\ WellTyped(st) /\ NoUnmapWhileInflightAt(st) @@ -227,6 +264,8 @@ ObservedSafe(st) == /\ DrainingHasEmptyQueuesAt(st) /\ CanReleaseExactAt(st) /\ FaultedDmaRetainsOwnershipAt(st) + /\ UnflushedIoBoundedAt(st) + /\ HwSignaledFaultedSafeAt(st) TypeOK == WellTyped(state) NoUnmapWhileInflight == NoUnmapWhileInflightAt(state) @@ -237,12 +276,14 @@ BounceSlotConservation == BounceSlotConservationAt(state) DrainingHasEmptyQueues == DrainingHasEmptyQueuesAt(state) CanReleaseExact == CanReleaseExactAt(state) FaultedDmaRetainsOwnership == FaultedDmaRetainsOwnershipAt(state) +UnflushedIoBounded == UnflushedIoBoundedAt(state) +HwSignaledFaultedSafe == HwSignaledFaultedSafeAt(state) Projection(st) == <> + st.faultedDma, st.unflushedIo, st.hwSignaledFaulted>> Decode(v) == [phase |-> v[1], @@ -258,7 +299,9 @@ Decode(v) == bInDma |-> v[11], freeBounce |-> v[12], canRelease |-> v[13], - faultedDma |-> v[14]] + faultedDma |-> v[14], + unflushedIo |-> v[15], + hwSignaledFaulted |-> v[16]] ObservedState(v) == Decode(v) @@ -274,6 +317,7 @@ ActionMatches(before, kind, after) == \/ /\ kind = 9 /\ FinishDrainOk(before, after) \/ /\ kind = 10 /\ FinishDrainFail(before, after) \/ /\ kind = 11 /\ MarkDmaFaulted(before, after) + \/ /\ kind = 12 /\ FlushIo(before, after) AllowedEdge(edge) == LET before == ObservedState(edge[1]) diff --git a/verification/helios-lifecycle/README.md b/verification/helios-lifecycle/README.md index 919eb3039..f24508d53 100644 --- a/verification/helios-lifecycle/README.md +++ b/verification/helios-lifecycle/README.md @@ -358,19 +358,24 @@ in flight (`NoUnmapWhileInflight`), permanent retention after failed drain (`StoppedHasZeroInflight`), bounded total and background hardware concurrency (`BoundedHardwareDepth`), exact conservation of internal bounce slots across in-flight I/O, queued follow-on DMA, and in-flight DMA (`BounceSlotConservation`), -drained queues once shutdown begins (`DrainingHasEmptyQueues`), and retained +drained queues once shutdown begins (`DrainingHasEmptyQueues`), retained in-flight and bounce ownership after partial CUDA DMA submission faults until -confirmed hardware drain (`FaultedDmaRetainsOwnership`). +confirmed hardware drain (`FaultedDmaRetainsOwnership`), bounded unflushed +storage SQE counts (`UnflushedIoBounded`), and suppression of host error-sentinel +writes for faulted DMAs whose completion slot was already signaled by hardware +(`HwSignaledFaultedSafe`). `async_transfer::lifecycle_tests::async_transfer_scheduler_matches_lifecycle_model` drives production `TransferScheduler` transitions (`start`, `enqueue`, -`cancel_epoch`, `dispatch_io`, `complete_io`, `dispatch_dma`, `complete_dma`, -`mark_dma_faulted`, `begin_drain`, `finish_drain`, `fail_drain`) across priority -preemption, epoch cancellation, fused bounce-staged transfers, partial-DMA fault -retention, error-sentinel completion notices, and confirmed vs. failed drain. -Its 14-integer projection carries the phase, active epoch, queued I/O and DMA -counts, demand/background in-flight I/O and DMA counts, bounce-slot partition, -release predicate, and faulted in-flight DMA count. Linux `io_uring` submission, +`cancel_epoch`, `dispatch_io`, `mark_io_flushed`, `complete_io`, `dispatch_dma`, +`complete_dma`, `mark_dma_faulted`, `begin_drain`, `finish_drain`, `fail_drain`) +across priority preemption, epoch cancellation, partial and full SQE flushes, +unflushed-completion rejection, fused bounce-staged transfers, partial-DMA fault +retention, hardware-signaled vs. host-signaled faulted DMA notices, and confirmed +vs. failed drain. Its 16-integer projection carries the phase, active epoch, +queued I/O and DMA counts, demand/background in-flight I/O and DMA counts, +bounce-slot partition, release predicate, faulted in-flight DMA count, unflushed +I/O count, and hardware-signaled faulted DMA count. Linux `io_uring` submission, CUDA Copy Engine ordering, `cuStreamWriteValue64` completion signaling, and pinned host memory registration require their separate CUDA integration tests. diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index fa97626b3..2a09c68b8 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -33,7 +33,7 @@ ("CheckpointReservation", "scheduler::checkpoint_lifecycle_tests::", "CHECKPOINT_RESERVATION_EDGE ", 16), ("AsyncTransfer", "async_transfer::lifecycle_tests::async_transfer_scheduler_matches_lifecycle_model", - "ASYNC_TRANSFER_EDGE ", 14)] + "ASYNC_TRANSFER_EDGE ", 16)] MODELS = [check[0] for check in CHECKS] + ["RankDispatch"] @@ -422,12 +422,36 @@ def run_aux(test): "MarkDmaFaulted(before, after) ==\n" " /\\ before.phase \\in {RUNNING, DRAINING}\n" " /\\ before.faultedDma < before.inDemDma + before.inBgDma\n" - " /\\ after = WithRelease([before EXCEPT !.faultedDma = @ + 1])", + " /\\ \\E hwSignaled \\in 0..1 :\n" + " after = WithRelease([before EXCEPT\n" + " !.faultedDma = @ + 1,\n" + " !.hwSignaledFaulted = @ + hwSignaled])", "MarkDmaFaulted(before, after) ==\n" " /\\ before.phase \\in {RUNNING, DRAINING}\n" " /\\ before.faultedDma < before.inDemDma + before.inBgDma\n" - " /\\ after = WithRelease([before EXCEPT !.faultedDma = @ + 1, !.inDemDma = 0, !.inBgDma = 0])", + " /\\ \\E hwSignaled \\in 0..1 :\n" + " after = WithRelease([before EXCEPT\n" + " !.faultedDma = @ + 1,\n" + " !.hwSignaledFaulted = @ + hwSignaled,\n" + " !.inDemDma = 0, !.inBgDma = 0])", "FaultedDmaRetainsOwnership"), + ("AsyncTransfer", + "FlushIo(before, after) ==\n" + " /\\ before.phase \\in {RUNNING, DRAINING}\n" + " /\\ before.unflushedIo > 0\n" + " /\\ \\E flushed \\in 1..before.unflushedIo :\n" + " after = WithRelease([before EXCEPT !.unflushedIo = @ - flushed])", + "FlushIo(before, after) ==\n" + " /\\ before.phase \\in {RUNNING, DRAINING}\n" + " /\\ before.unflushedIo > 0\n" + " /\\ after = WithRelease([before EXCEPT !.unflushedIo = @ + 1])", + "UnflushedIoBounded"), + ("AsyncTransfer", + " !.faultedDma = @ - wasFaulted,\n" + " !.hwSignaledFaulted = @ - wasHwSignaled])", + " !.faultedDma = @ - wasFaulted,\n" + " !.hwSignaledFaulted = @])", + "HwSignaledFaultedSafe"), ] with ThreadPoolExecutor(max_workers=min(args.jobs, len(model_mutations))) as pool: futures = [ @@ -741,9 +765,17 @@ def run_aux(test): " op.signal_value\n },\n error: if ok {\n ErrorCode::Ok\n } else {\n ErrorCode::CudaFailure\n },", "failed transfer must signal error sentinel, not success value"), ("faulted dma freed bounce slot early", - " op.faulted = true;\n let completion_slot = op.completion_slot;", - " op.faulted = true;\n if let Some(slot) = op.bounce_slot.take() { self.free_bounce_slots.push(slot); }\n let completion_slot = op.completion_slot;", + " op.faulted = true;\n op.hardware_signaled = hardware_signaled;", + " op.faulted = true;\n op.hardware_signaled = hardware_signaled;\n if let Some(slot) = op.bounce_slot.take() { self.free_bounce_slots.push(slot); }", "faulted DMA must retain inflight and bounce ownership"), + ("unflushed io completed ok before flush", + " if ok && !self.inflight_io[pos].flushed {\n return None;\n }", + " if false && ok && !self.inflight_io[pos].flushed {\n return None;\n }", + "unflushed IO must not complete with ok=true before kernel submission"), + ("hardware-signaled faulted dma clobbered completion slot", + " let completion_slot = if hardware_signaled {\n None\n } else {\n op.completion_slot\n };", + " let completion_slot = op.completion_slot;", + "hardware-signaled faulted DMA must not overwrite live/reused completion slot"), ]) restored_bin = build_test_binary(cargo) run_observed_checks(restored_bin, directory, args.java, jar, args.jobs) From c9df77bd61a10fe39f94f3f072f60c4a6ddcb245 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Fri, 4 Dec 2026 10:47:17 -0800 Subject: [PATCH 2/3] helios: preserve AsyncTransfer SQ FIFO order, watchdog close progress, 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 --- docs/api.md | 2 +- helios/src/async_transfer/io_backend.rs | 23 ++- helios/src/async_transfer/scheduler.rs | 54 +++++- helios/src/async_transfer/worker.rs | 4 - helios/src/execution/threaded.rs | 240 +++++++++++++++++++----- helios/src/runtime_core/mod.rs | 52 +++-- helios/src/runtime_core/model.rs | 14 +- 7 files changed, 309 insertions(+), 80 deletions(-) diff --git a/docs/api.md b/docs/api.md index 3eb869522..6206eae9e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -402,7 +402,7 @@ local store's measured restore rate. When a loaded core declares `Execution.async_transfers` channels, `/metrics` also exports lock-free per-channel gauges and counters labeled by `channel` and -`rank`: `flare_async_transfer_device_pool_bytes`, +the global `rank` ID: `flare_async_transfer_device_pool_bytes`, `flare_async_transfer_host_pool_bytes`, `flare_async_transfer_submitted_cmds_total`, `flare_async_transfer_completed_cmds_total`, diff --git a/helios/src/async_transfer/io_backend.rs b/helios/src/async_transfer/io_backend.rs index 21ed2d119..65f0ca39a 100644 --- a/helios/src/async_transfer/io_backend.rs +++ b/helios/src/async_transfer/io_backend.rs @@ -143,17 +143,26 @@ pub mod linux_uring { } } + const MAX_EINTR_RETRIES: usize = 16; + pub(super) fn flush_queued_sqes( queued_sqes: &mut usize, mut submit: impl FnMut() -> io::Result, ) -> io::Result<()> { + let mut eintr_retries = 0usize; while *queued_sqes > 0 { match submit() { Ok(0) => break, Ok(submitted) => { *queued_sqes = queued_sqes.saturating_sub(submitted); + eintr_retries = 0; + } + Err(err) if err.raw_os_error() == Some(libc::EINTR) => { + eintr_retries += 1; + if eintr_retries >= MAX_EINTR_RETRIES { + return Err(err); + } } - Err(err) if err.raw_os_error() == Some(libc::EINTR) => continue, Err(err) => return Err(err), } } @@ -448,5 +457,17 @@ mod tests { .expect_err("EBUSY propagates"); assert_eq!(err.raw_os_error(), Some(libc::EBUSY)); assert_eq!(queued, 1); + + // Consecutive EINTR retries are bounded so the worker loop still polls shutdown state. + let mut queued = 2usize; + let mut eintr_calls = 0usize; + let err = flush_queued_sqes(&mut queued, || { + eintr_calls += 1; + Err(std::io::Error::from_raw_os_error(libc::EINTR)) + }) + .expect_err("bounded EINTR retry returns EINTR"); + assert_eq!(err.raw_os_error(), Some(libc::EINTR)); + assert_eq!(eintr_calls, 16); + assert_eq!(queued, 2); } } diff --git a/helios/src/async_transfer/scheduler.rs b/helios/src/async_transfer/scheduler.rs index a0543d5fb..c2e4da807 100644 --- a/helios/src/async_transfer/scheduler.rs +++ b/helios/src/async_transfer/scheduler.rs @@ -580,7 +580,9 @@ impl TransferScheduler { if ok && !self.inflight_io[pos].flushed { return None; } - let op = self.inflight_io.swap_remove(pos); + // Preserve submission order matching the kernel io_uring SQ FIFO so + // `mark_io_flushed` always marks the oldest unsubmitted reads. + let op = self.inflight_io.remove(pos); if let Some(device_offset) = op.device_offset { let stale_bg = op.priority.is_background() && op.epoch < self.active_epoch; @@ -1121,4 +1123,54 @@ mod tests { assert!(sched.complete_dma(dma.op_id, true).is_none()); assert_eq!(sched.hw_signaled_faulted_dma_count(), 0); } + + #[test] + fn partial_flush_preserves_sq_fifo_order_across_completions() { + let mut sched = TransferScheduler::new(4, 2, 2, 1, 1); + sched.start().unwrap(); + for (slot, sig) in [(0, 101), (1, 202), (2, 303)] { + sched.enqueue(ValidatedCommand::DiskToHost { + priority: Priority::Demand, + extent: ext(4096), + host_offset: u64::from(slot) * 4096, + epoch: 1, + completion_slot: Some(slot), + signal_value: sig, + }); + } + let op_a = sched.pop_next_io().unwrap(); + let op_b = sched.pop_next_io().unwrap(); + let op_c = sched.pop_next_io().unwrap(); + assert_eq!(sched.unflushed_io_count(), 3); + + // Partial flush submits only A. + assert_eq!(sched.mark_io_flushed(1), 1); + assert!(sched.is_io_flushed(op_a.op_id)); + assert!(!sched.is_io_flushed(op_b.op_id)); + assert!(!sched.is_io_flushed(op_c.op_id)); + + // Completing A removes index 0 without swapping C ahead of B. + let notice_a = sched.complete_io(op_a.op_id, true).unwrap(); + assert_eq!(notice_a.error, ErrorCode::Ok); + assert_eq!(notice_a.signal_value, 101); + + // Next partial flush submits B (oldest remaining SQE), not C. + assert_eq!(sched.mark_io_flushed(1), 1); + assert!(sched.is_io_flushed(op_b.op_id)); + assert!(!sched.is_io_flushed(op_c.op_id)); + + // B's real kernel CQE must be accepted and never silently dropped. + let notice_b = sched.complete_io(op_b.op_id, true).unwrap(); + assert_eq!(notice_b.error, ErrorCode::Ok); + assert_eq!(notice_b.signal_value, 202); + + // C remains unflushed until the final flush, then completes cleanly. + assert!(sched.complete_io(op_c.op_id, true).is_none()); + assert_eq!(sched.mark_io_flushed(1), 1); + let notice_c = sched.complete_io(op_c.op_id, true).unwrap(); + assert_eq!(notice_c.error, ErrorCode::Ok); + assert_eq!(notice_c.signal_value, 303); + assert_eq!(sched.inflight_io_count(), 0); + assert_eq!(sched.unflushed_io_count(), 0); + } } diff --git a/helios/src/async_transfer/worker.rs b/helios/src/async_transfer/worker.rs index a5e188f8b..4a9760be1 100644 --- a/helios/src/async_transfer/worker.rs +++ b/helios/src/async_transfer/worker.rs @@ -490,10 +490,6 @@ impl AsyncTransferRuntime { &self.config.name } - pub fn rank(&self) -> usize { - self.config.rank - } - pub fn state(&self) -> ChannelState { ChannelState::from_u32(self.atomic_state.load(Ordering::Acquire)) } diff --git a/helios/src/execution/threaded.rs b/helios/src/execution/threaded.rs index 120949bb1..ea91df22f 100644 --- a/helios/src/execution/threaded.rs +++ b/helios/src/execution/threaded.rs @@ -677,13 +677,19 @@ impl RankWedgeWatchdog { } let now = Instant::now(); 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 }); + let current = thread_state.activity.0.load(Ordering::Acquire); + if current != last_activity { + last_activity = current; + close_since = Some(now); + } else { + 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; } - break; } } else { close_since = None; @@ -734,13 +740,6 @@ impl RankWedgeWatchdog { thread: Some(thread), }) } - - fn stop_and_join(mut self) { - self.state.stop(); - if let Some(thread) = self.thread.take() { - let _ = thread.join(); - } - } } impl Drop for RankWedgeWatchdog { @@ -1214,23 +1213,36 @@ impl ThreadedExecutor { self.poll()?; thread::sleep(Duration::from_micros(50)); } + self.watchdog_state.record_progress(); if let Some(error) = &self.poison { return Err(error.clone()); } - close_peers(&self.ring, &mut self.peers, self.started, TIMEOUT) + close_peers( + &self.ring, + &mut self.peers, + self.started, + TIMEOUT, + Some(&self.watchdog_state), + ) })(); if result.is_err() { + self.watchdog_state.record_progress(); // Best-effort drain and join of any peers that can still exit cleanly so live // peer threads are not detached on poisoned teardown. - best_effort_drain_peers(&self.ring, &mut self.peers, self.started, TIMEOUT); + best_effort_drain_peers( + &self.ring, + &mut self.peers, + self.started, + TIMEOUT, + Some(&self.watchdog_state), + ); } + self.watchdog_state.record_progress(); let shutdown = match result { Ok(()) => self.local.close(), Err(error) => self.local.abandon(error), }; - if let Some(watchdog) = self.watchdog.take() { - watchdog.stop_and_join(); - } + drop(self.watchdog.take()); self.shutdown = Some(shutdown.clone()); shutdown } @@ -1246,6 +1258,7 @@ fn close_peers( peers: &mut [Peer], started: bool, timeout: Duration, + watchdog: Option<&WatchdogState>, ) -> Result<()> { ring.request_drain(); if !started { @@ -1265,6 +1278,9 @@ fn close_peers( .unwrap() .join() .map_err(|_| invalid("rank thread panicked"))?; + if let Some(watchdog) = watchdog { + watchdog.record_progress(); + } if !shutdown.drained { return Err(invalid("rank thread did not confirm drain")); } @@ -1280,6 +1296,7 @@ fn best_effort_drain_peers( peers: &mut [Peer], started: bool, timeout: Duration, + watchdog: Option<&WatchdogState>, ) { ring.request_drain(); if !started { @@ -1290,28 +1307,53 @@ fn best_effort_drain_peers( } } let deadline = Instant::now() + timeout; - 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)) { - Ok(Ok(Reply::Drained)) - | Ok(Err(_)) - | Err(mpsc::RecvTimeoutError::Disconnected) => { - exited = true; - break; + loop { + let mut remaining_live = 0usize; + let mut made_progress = false; + for peer in peers.iter_mut() { + if peer.thread.is_none() { + continue; + } + 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, } - Ok(Ok(_)) => continue, - Err(mpsc::RecvTimeoutError::Timeout) => break, } - } - if exited { - if let Some(thread) = peer.thread.take() { - let _ = thread.join(); + if exited { + if let Some(thread) = peer.thread.take() { + let _ = thread.join(); + } + if let Some(watchdog) = watchdog { + watchdog.record_progress(); + } + made_progress = true; + } else { + remaining_live += 1; } } + if remaining_live == 0 { + break; + } + let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { + break; + }; + if remaining.is_zero() { + break; + } + if !made_progress { + thread::sleep(Duration::from_millis(1).min(remaining)); + } } } @@ -3340,7 +3382,7 @@ mod tests { }); } let started = Instant::now(); - close_peers(&ring, &mut peers, false, Duration::from_secs(5)).unwrap(); + close_peers(&ring, &mut peers, false, Duration::from_secs(5), None).unwrap(); assert!( started.elapsed() < Duration::from_secs(1), "pre-start close should wake peers immediately via Command::Drain" @@ -3427,8 +3469,8 @@ mod tests { } let started = Instant::now(); - assert!(close_peers(&ring, &mut peers, false, Duration::from_secs(5)).is_err()); - best_effort_drain_peers(&ring, &mut peers, false, Duration::from_secs(5)); + assert!(close_peers(&ring, &mut peers, false, Duration::from_secs(5), None).is_err()); + best_effort_drain_peers(&ring, &mut peers, false, Duration::from_secs(5), None); assert!( started.elapsed() < Duration::from_secs(1), "best-effort pre-start drain should wake surviving peers immediately" @@ -3489,7 +3531,7 @@ mod tests { )); } let started = Instant::now(); - close_peers(&ring, &mut peers, true, Duration::from_secs(5)).unwrap(); + close_peers(&ring, &mut peers, true, Duration::from_secs(5), None).unwrap(); assert!(started.elapsed() < Duration::from_secs(1)); assert!(peers.iter().all(|peer| peer.thread.is_none())); } @@ -4043,7 +4085,7 @@ mod tests { matches!(reason, WedgeReason::PeerExitedWithoutRecovery { .. }), "unexpected wedge reason: {reason:?}" ); - watchdog.stop_and_join(); + drop(watchdog); } #[test] @@ -4072,7 +4114,7 @@ mod tests { matches!(reason, WedgeReason::CoordinatorStalled { .. }), "unexpected wedge reason: {reason:?}" ); - watchdog.stop_and_join(); + drop(watchdog); } #[test] @@ -4107,8 +4149,18 @@ mod tests { "watchdog must not fire while progress advances" ); - // Stalling inside close() must fire CloseStalled. + // Multi-stage close() that keeps advancing progress past stall_timeout must stay silent. state.begin_close(); + for _ in 0..6 { + state.record_progress(); + thread::sleep(Duration::from_millis(12)); + } + assert!( + rx.try_recv().is_err(), + "watchdog must not fire during progressing multi-stage close" + ); + + // Once close() stops making progress, CloseStalled must fire. let reason = rx .recv_timeout(Duration::from_secs(2)) .expect("watchdog must detect stalled close"); @@ -4116,7 +4168,107 @@ mod tests { matches!(reason, WedgeReason::CloseStalled { .. }), "unexpected wedge reason: {reason:?}" ); - watchdog.stop_and_join(); + drop(watchdog); + } + + #[test] + fn best_effort_drain_peers_joins_healthy_peers_even_when_earlier_peer_is_wedged() { + let ring = Arc::new(DispatchRing::new(16, 4)); + let release_wedged = Arc::new((Mutex::new(false), Condvar::new())); + + // Peer 0 stays wedged past the shared timeout and never sends Reply::Drained. + let (cmd_tx0, _cmd_rx0) = mpsc::channel::(); + let (_rep_tx0, rep_rx0) = mpsc::channel::>(); + let release0 = release_wedged.clone(); + let t0 = thread::spawn(move || { + let (lock, cv) = &*release0; + let guard = lock.lock().unwrap(); + drop(cv.wait_while(guard, |done| !*done)); + Shutdown { + drained: false, + error: Some(invalid("wedged")), + } + }); + + // Peer 1 already queued Reply::Drained before best_effort_drain_peers runs. + let (cmd_tx1, _cmd_rx1) = mpsc::channel::(); + let (rep_tx1, rep_rx1) = mpsc::channel::>(); + rep_tx1.send(Ok(Reply::Drained)).unwrap(); + let t1 = thread::spawn(move || Shutdown { + drained: true, + error: None, + }); + + // Peer 2 drains asynchronously after a short delay while peer 0 is wedged. + let (cmd_tx2, cmd_rx2) = mpsc::channel::(); + let (rep_tx2, rep_rx2) = mpsc::channel::>(); + let t2 = thread::spawn(move || { + let _ = cmd_rx2.recv_timeout(Duration::from_secs(2)); + thread::sleep(Duration::from_millis(10)); + let _ = rep_tx2.send(Ok(Reply::Drained)); + Shutdown { + drained: true, + error: None, + } + }); + + let mut peers = vec![ + Peer { + sender: cmd_tx0, + receiver: rep_rx0, + thread: Some(t0), + }, + Peer { + sender: cmd_tx1, + receiver: rep_rx1, + thread: Some(t1), + }, + Peer { + sender: cmd_tx2, + receiver: rep_rx2, + thread: Some(t2), + }, + ]; + + let watchdog = WatchdogState::new(); + let started = Instant::now(); + best_effort_drain_peers( + &ring, + &mut peers, + false, + Duration::from_millis(50), + Some(&watchdog), + ); + let elapsed = started.elapsed(); + + assert!( + peers[0].thread.is_some(), + "wedged peer without confirmed exit must not be joined" + ); + assert!( + peers[1].thread.is_none(), + "already-drained peer behind a wedged peer must be joined" + ); + assert!( + peers[2].thread.is_none(), + "promptly draining peer behind a wedged peer must be joined" + ); + assert!( + watchdog.activity.0.load(Ordering::Acquire) >= 2, + "joining drained peers must record watchdog progress" + ); + assert!( + elapsed < Duration::from_secs(1), + "shared drain timeout must stay bounded (elapsed={elapsed:?})" + ); + + // Clean up the synthetic wedged thread so test exit does not leak it. + { + let (lock, cv) = &*release_wedged; + *lock.lock().unwrap() = true; + cv.notify_all(); + } + let _ = peers[0].thread.take().unwrap().join(); } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 759be45d2..6aca05b23 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -125,6 +125,9 @@ pub struct NativeResources { gate_peer_access: bool, /// Allocations whose stored payload bytes contain an address inside a `Memory::Peer` range. peer_table_allocations: HashSet, + /// Transitive closure of `Memory::Peer` and peer-pointer-table allocations, computed in + /// `prepare_kernels` and consumed in `prepare_graphs`. + peer_refs: Option<(HashSet, Vec<(u64, u64)>)>, /// Loaded CUDA modules whose globals reference `Memory::Peer` storage. peer_modules: HashSet, reservations: Vec<(u64, usize)>, @@ -159,10 +162,9 @@ fn merge_sorted_intervals(mut intervals: Vec<(u64, u64)>) -> Vec<(u64, u64)> { merged } -fn peer_address_intervals(allocations: &HashMap) -> Vec<(u64, u64)> { - let intervals = allocations - .values() - .filter(|storage| matches!(storage.memory, Memory::Peer) && storage.nbytes > 0) +fn storage_intervals<'a>(storages: impl Iterator) -> Vec<(u64, u64)> { + let intervals = storages + .filter(|storage| storage.nbytes > 0) .filter_map(|storage| { storage .address @@ -173,6 +175,14 @@ fn peer_address_intervals(allocations: &HashMap) -> Vec<(u64, u merge_sorted_intervals(intervals) } +fn peer_address_intervals(allocations: &HashMap) -> Vec<(u64, u64)> { + storage_intervals( + allocations + .values() + .filter(|storage| matches!(storage.memory, Memory::Peer)), + ) +} + #[inline] fn address_in_intervals(value: u64, intervals: &[(u64, u64)], floor: u64, ceiling: u64) -> bool { if value < floor || value >= ceiling { @@ -255,18 +265,8 @@ fn collect_peer_referencing_allocations( break; } } - let intervals = peer_refs - .iter() - .filter_map(|name| allocations.get(name)) - .filter(|storage| storage.nbytes > 0) - .filter_map(|storage| { - storage - .address - .checked_add(storage.nbytes as u64) - .map(|end| (storage.address, end)) - }) - .collect(); - (peer_refs, merge_sorted_intervals(intervals)) + let intervals = storage_intervals(peer_refs.iter().filter_map(|name| allocations.get(name))); + (peer_refs, intervals) } /// Inspect one graph node and return `(has_peer_copy_node, has_peer_access)`. @@ -613,6 +613,7 @@ impl NativeResources { peer_access_graphs: vec![], gate_peer_access: false, peer_table_allocations: HashSet::new(), + peer_refs: None, peer_modules: HashSet::new(), reservations: vec![], execution: core.execution.clone(), @@ -1087,6 +1088,7 @@ impl NativeResources { self.functions.insert(function.id, handle); phase.advance(1); } + self.peer_refs = Some((peer_refs, peer_ref_intervals)); } Ok(()) } @@ -1114,11 +1116,13 @@ impl NativeResources { )?; dynamic_shared.insert(function as usize, bytes as u32); } - let (peer_refs, peer_ref_intervals) = collect_peer_referencing_allocations( - core, - &self.allocations, - &self.peer_table_allocations, - ); + let (peer_refs, peer_ref_intervals) = self.peer_refs.take().unwrap_or_else(|| { + collect_peer_referencing_allocations( + core, + &self.allocations, + &self.peer_table_allocations, + ) + }); let function_modules: HashMap = core .functions .iter() @@ -1747,12 +1751,6 @@ impl NativeResources { if execution.async_transfers.is_empty() { return Ok(()); } - 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", - )); - } let mut remaining_host = planned_host_cap; for channel in &execution.async_transfers { let device_pool = self.allocation(&channel.device_pool)?; diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index e20b9ad75..dd682c9a8 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -151,8 +151,18 @@ fn all_nvlink_p2p(pci_bus_ids: &[String]) -> bool { } 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)) + let forward = nvml.device_p2p_status( + handles[i], + handles[j], + crate::nvml::P2P_CAPS_INDEX_NVLINK, + ); + let reverse = nvml.device_p2p_status( + handles[j], + handles[i], + crate::nvml::P2P_CAPS_INDEX_NVLINK, + ); + if forward != Some(Ok(crate::nvml::P2P_STATUS_OK)) + || reverse != Some(Ok(crate::nvml::P2P_STATUS_OK)) { return false; } From f7b83ae29521a4bd5f97fb4d3f72ca42b8282f50 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Fri, 4 Dec 2026 15:31:09 -0800 Subject: [PATCH 3/3] helios: guard Err-before-exit joins in best_effort_drain_peers and preserve 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 --- helios/src/async_transfer/lifecycle_tests.rs | 6 +- helios/src/async_transfer/worker.rs | 38 ++++++++-- helios/src/execution/threaded.rs | 77 +++++++++++++++++++- helios/src/runtime_core/host.rs | 12 +-- helios/src/runtime_core/mod.rs | 2 +- 5 files changed, 108 insertions(+), 27 deletions(-) diff --git a/helios/src/async_transfer/lifecycle_tests.rs b/helios/src/async_transfer/lifecycle_tests.rs index f5b821168..a65a36d16 100644 --- a/helios/src/async_transfer/lifecycle_tests.rs +++ b/helios/src/async_transfer/lifecycle_tests.rs @@ -49,11 +49,7 @@ fn project(sched: &TransferScheduler) -> Projection { } 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] - ) + format!("{v:?}") } fn dummy_extent() -> ExtentEntry { diff --git a/helios/src/async_transfer/worker.rs b/helios/src/async_transfer/worker.rs index 4a9760be1..c83e896bc 100644 --- a/helios/src/async_transfer/worker.rs +++ b/helios/src/async_transfer/worker.rs @@ -312,6 +312,15 @@ enum EventCompletionAction { HostAndDevice(u32, u64), } +impl EventCompletionAction { + fn host_mirror_on_drain(self, hardware_signaled: bool) -> Option<(u32, u64)> { + match self { + Self::HostOnly(slot, val) if hardware_signaled => Some((slot, val)), + _ => None, + } + } +} + struct PendingEventDma { op_id: OpId, event: Handle, @@ -1040,7 +1049,9 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { op_id: done.op_id, pending_notice: None, hardware_signaled: done.hardware_signaled, - host_mirror_on_drain: None, + host_mirror_on_drain: done + .completion_action + .host_mirror_on_drain(done.hardware_signaled), }); } } @@ -1177,12 +1188,8 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { // Retain `dma` and its bounce slot in `scheduler.inflight_dma` until `copy_stream` // confirms drain (or permanently into `FailedDrain`). free_events.push(ev); - let host_mirror_on_drain = match completion_action { - EventCompletionAction::HostOnly(slot, val) if hardware_signaled => { - Some((slot, val)) - } - _ => None, - }; + let host_mirror_on_drain = + completion_action.host_mirror_on_drain(hardware_signaled); let pending_notice = scheduler.mark_dma_faulted(dma.op_id, hardware_signaled); untracked_faulted_dmas.push(UntrackedFaultedDma { op_id: dma.op_id, @@ -1929,4 +1936,21 @@ mod unit_tests { guard.invalidate(); assert_eq!(guard.read_counters(), live_counters); } + + #[test] + fn host_mirror_on_drain_preserves_hardware_signaled_host_only_completions() { + assert_eq!( + EventCompletionAction::HostOnly(4, 999).host_mirror_on_drain(true), + Some((4, 999)) + ); + assert_eq!( + EventCompletionAction::HostOnly(4, 999).host_mirror_on_drain(false), + None + ); + assert_eq!( + EventCompletionAction::HostAndDevice(4, 999).host_mirror_on_drain(true), + None + ); + assert_eq!(EventCompletionAction::None.host_mirror_on_drain(true), None); + } } diff --git a/helios/src/execution/threaded.rs b/helios/src/execution/threaded.rs index ea91df22f..c67cac425 100644 --- a/helios/src/execution/threaded.rs +++ b/helios/src/execution/threaded.rs @@ -1317,13 +1317,11 @@ fn best_effort_drain_peers( let mut exited = false; loop { match peer.receiver.try_recv() { - Ok(Ok(Reply::Drained)) - | Ok(Err(_)) - | Err(mpsc::TryRecvError::Disconnected) => { + Ok(Ok(Reply::Drained)) | Err(mpsc::TryRecvError::Disconnected) => { exited = true; break; } - Ok(Ok(_)) => { + Ok(Ok(_)) | Ok(Err(_)) => { made_progress = true; continue; } @@ -4270,6 +4268,77 @@ mod tests { } let _ = peers[0].thread.take().unwrap().join(); } + + #[test] + fn best_effort_drain_peers_does_not_block_joining_peer_that_sent_err_before_exiting() { + let ring = Arc::new(DispatchRing::new(16, 3)); + let release_draining = Arc::new((Mutex::new(false), Condvar::new())); + + // Peer 0 sends Err(...) (matching validate_submission failure) while still blocked + // draining outstanding frames and not yet exited. + let (cmd_tx0, _cmd_rx0) = mpsc::channel::(); + let (rep_tx0, rep_rx0) = mpsc::channel::>(); + rep_tx0 + .send(Err(invalid("validation failed while frame in flight"))) + .unwrap(); + let release0 = release_draining.clone(); + let t0 = thread::spawn(move || { + let _keep_sender_open = rep_tx0; + let (lock, cv) = &*release0; + let guard = lock.lock().unwrap(); + drop(cv.wait_while(guard, |done| !*done)); + Shutdown { + drained: false, + error: Some(invalid("still draining")), + } + }); + + // Peer 1 drains cleanly while peer 0 stays blocked after sending Err(...). + let (cmd_tx1, _cmd_rx1) = mpsc::channel::(); + let (rep_tx1, rep_rx1) = mpsc::channel::>(); + rep_tx1.send(Ok(Reply::Drained)).unwrap(); + let t1 = thread::spawn(move || Shutdown { + drained: true, + error: None, + }); + + let mut peers = vec![ + Peer { + sender: cmd_tx0, + receiver: rep_rx0, + thread: Some(t0), + }, + Peer { + sender: cmd_tx1, + receiver: rep_rx1, + thread: Some(t1), + }, + ]; + + let started = Instant::now(); + best_effort_drain_peers(&ring, &mut peers, false, Duration::from_millis(50), None); + let elapsed = started.elapsed(); + + assert!( + peers[0].thread.is_some(), + "peer that sent Err(...) but has not exited or disconnected must not block in join()" + ); + assert!( + peers[1].thread.is_none(), + "healthy peer behind an Err-sending blocked peer must still be joined" + ); + assert!( + elapsed < Duration::from_secs(1), + "best_effort_drain_peers must remain bounded by timeout (elapsed={elapsed:?})" + ); + + { + let (lock, cv) = &*release_draining; + *lock.lock().unwrap() = true; + cv.notify_all(); + } + let _ = peers[0].thread.take().unwrap().join(); + } } #[cfg(all(test, feature = "runtime-core"))] diff --git a/helios/src/runtime_core/host.rs b/helios/src/runtime_core/host.rs index 384a5588d..11ebba476 100644 --- a/helios/src/runtime_core/host.rs +++ b/helios/src/runtime_core/host.rs @@ -50,7 +50,7 @@ fn ranges( if !granularity.is_power_of_two() { return Err(invalid("invalid host allocation granularity")); } - let mut ranges = allocations + let ranges = allocations .map(|(address, bytes)| { let end = address .checked_add(bytes as u64) @@ -59,15 +59,7 @@ fn ranges( Ok((address & !(granularity - 1), end & !(granularity - 1))) }) .collect::>>()?; - 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)); - } - } + let merged = super::merge_sorted_intervals(ranges); Ok(merged .into_iter() .map(|(start, end)| (start, (end - start) as usize)) diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 6aca05b23..ddf69ef55 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -148,7 +148,7 @@ pub struct NativeResources { // owning context, and mutable ownership serializes loading and destruction. unsafe impl Send for NativeResources {} -fn merge_sorted_intervals(mut intervals: Vec<(u64, u64)>) -> Vec<(u64, u64)> { +pub(super) 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();