From d612cd1c6f1032675f0cb563d87c4611598afa78 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Thu, 3 Dec 2026 21:51:40 -0800 Subject: [PATCH] helios,flare-cli: harden AsyncTransfer startup, DMA/teardown lifetimes, unified DRAM, and CopyEngine safety AsyncTransfer channels sit directly at the CUDA, Linux io_uring, unified-DRAM, and Copy Engine hardware boundaries. Eight boundary defects threaten live serving and multi-rank bring-up: 1. AsyncTransferRuntime::start() previously marked the channel Running and returned Ok(()) before worker_main bound its CUDA context, allocated its event pool, or wrote ControlHeader::worker_state = Running, causing startup tuning kernels that require Running headers to fail spuriously and silently dropping cuCtxSetCurrent failures. 2. When cuMemcpyHtoDAsync_v2 succeeded on copy_stream while a subsequent cuStreamWriteValue64_v2 or cuEventRecord failed, the worker immediately called scheduler.complete_dma(..., false), recycling the bounce slot and clearing inflight_dma while the Copy Engine was still reading src_ptr. 3. Writing device completions from a separate unsynchronized signal_stream raced copy_stream on reused completion slots, and deferred EventCompletionAction::HostOnly stores could regress host_comp[slot] backwards after slot reuse. 4. On IoFailure or CudaFailure, TransferScheduler and worker_main published the caller's requested success signal_value into completion slots, allowing GPU waiters to treat failed transfers as valid payload data. 5. IoUringBackend::cancel_and_drain called blocking submit_and_wait(1) without a kernel timeout, defeating DRAIN_TIMEOUT when storage reads did not finish. 6. AsyncTransferRuntime::snapshot() dereferenced raw control_address after NativeResources::release_execution_resources() unmapped MappedHost storage, leaving retained metrics Arc handles exposed to use-after-free. 7. On integrated unified-DRAM GPUs (such as GB10 and Jetson), memory sizing only subtracted pinned/512 + 256 MiB from the shared budget instead of full HOST_POOL + bounce_pool bytes, ignored planned host_future prefix-cache and vision windows, and sized DEVICE_POOL via local rank min() without cluster-wide CacheAgreement across multi-host ranks. 8. Cores combining Execution.async_transfers with graphs containing Copy Engine Memory::Peer copy nodes were allowed to load without CopyEngineGate protection, risking Copy Engine deadlock because in-graph demand waits cannot yield to CopyEngineGate. What changed: - Startup readiness, single-stream completions, partial-DMA retention, and control-lifetime guard (helios/src/async_transfer/{ring,scheduler,worker, mod}.rs, helios/src/runtime_core/mod.rs): - Added a synchronous startup readiness channel in AsyncTransferRuntime::start so start() blocks until worker_main binds the CUDA context, creates all DEFAULT_MAX_TOTAL_DMA CUDA events, and publishes ControlHeader::worker_state = Running; initialization errors propagate cleanly and restore io_backend while keeping the channel Idle. - Added TransferScheduler::mark_dma_faulted and InflightDma::faulted so post-enqueue CUDA failures (cuStreamWriteValue64_v2, cuEventRecord, or sticky cuEventQuery errors) retain inflight_dma and bounce-slot ownership until cuEventQuery or cuStreamQuery(copy_stream) confirms hardware drain (or remain pinned through FailedDrain). - Removed signal_stream and serialized all device completion writes on copy_stream (routing device_completions_base == 0 writes through copy_stream when cuStreamWriteValue64_v2 is active), updated CPU host completion mirrors via AtomicU64::fetch_max, and checked CUDA return statuses in signal_completion_slot. - Reserved bit 63 (COMPLETION_ERROR_BIT) in ring.rs for fault sentinels (completion_error_sentinel(ErrorCode)), rejected caller signal_value values with bit 63 set when a completion slot is active, and emitted fault sentinels instead of requested success cookies on IoFailure/CudaFailure. - Added ControlRegionGuard (RwLock) and AsyncTransferRuntime::invalidate_control(), called in NativeResources::release_execution_resources() before unmapping MappedHost allocations, so post-teardown snapshot() returns captured final counters without dereferencing unmapped memory. - Bounded io_uring drain (helios/src/async_transfer/io_backend.rs, worker.rs): - Replaced submit_and_wait(1) in IoUringBackend::cancel_and_drain with submitter().submit_with_args(1, &SubmitArgs::new().timespec(&ts)), handling ETIME and EINTR cleanly; retained io_backend on unconfirmed drain so IoUring::drop cannot block thread join. - Unified-DRAM budgeting, multi-host DEVICE_POOL agreement, and peer-copy load gate (helios/src/runtime_core/{memory,model,mod,cache_memory}.rs, helios/src/execution/rendezvous.rs, flare-cli/src/cluster.rs): - Coordinated discrete-GPU async_transfer_host_ram with host_future and bounce-pool headroom, deducted full pinned + page_tables + margin on integrated GPUs (defaulting integrated HOST_POOL to 0 unless --pool-ram-memory is explicitly configured and clamping explicit requests above min_kv_reserve), and deducted async_transfer and integrated DEVICE_POOL reservations from prefix-cache capture host_growth. - Added CacheAgreement::device_pools, rendezvous::{agree,propose}_device_pools, and Membership::device_pools (invoked only when DEVICE_POOL allocations are present, keeping wire framing unchanged for existing cores) with local bound and alignment validation before map_device_pool. - Added load-time rejection in NativeModel::load_agreeing (and a defensive guard in NativeResources::prepare_async_transfers) when has_any_peer_copy_graphs() and !async_transfers.is_empty(). - Added missing external_extents initializer in a cache_memory.rs unit test. - Formal verification and documentation (verification/helios-lifecycle/ {AsyncTransfer.tla,AsyncTransfer.cfg,check.py,README.md}, helios/src/async_transfer/{lifecycle_tests,kani_proofs}.rs, helios/manifest.md, docs/runtime-core-design.md): - Extended AsyncTransfer.tla with faultedDma, MarkDmaFaulted, and FaultedDmaRetainsOwnership; expanded observed-edge projection to 14 fields and added TLA+ and Rust mutation checks for early bounce release and success-cookie signaling on error; extended Kani validate_command proofs to verify signal_value disjointness from COMPLETION_ERROR_BIT. Claimed benefit and result: Eliminates the eight verified startup-race, bounce-slot/snapshot UAF, dual-stream completion regression, silent error-corruption, unbounded shutdown drain, unified-DRAM over-allocation, multi-host pool divergence, and PCIe peer-copy Copy Engine deadlock hazards on AsyncTransfer channels while keeping existing cores without AsyncTransfer or DEVICE_POOL wire-compatible and unaffected. Supporting evidence and limitations: - Live CUDA integration test (CUDA_VISIBLE_DEVICES=1 FLARE_RUN_CUDA_TESTS=1 helios async_transfer::worker::cuda_tests::live_cuda_async_transfer_end_to_end on NVIDIA RTX PRO 6000 Blackwell Max-Q): 1 passed, 0 failed; verified immediate Running header state after start(), same-slot HostToDev -> DiskToHost reuse, real EOF IoFailure emitting completion_error_sentinel on both host and device completion slots, and post-munmap snapshot() after invalidate_control(). - TLA+ models, Rust trace conformance, and mutation suite (verification/helios-lifecycle/check.py --mutations with tla2tools-1.7.4.jar and OpenJDK 21): all 10 TLA+ models, all 9 conformance suites (359 observed Rust transitions checked against AsyncTransfer.tla), and all TLA+ and Rust mutations (including FaultedDmaRetainsOwnership, failed io/dma error sentinels, and faulted DMA bounce retention) passed. - Kani 0.68.0 (helios --features runtime-core --lib --harness async_transfer::kani_proofs::): 5/5 harnesses verified with 0 failures. - Rust crate tests and release build (Linux x86_64): - eos: 12 passed, 0 failed. - selene (--features test-support): 586 passed, 0 failed. - selene-manager (--features test-support): 448 passed, 0 failed, 1 ignored. - helios (--features runtime-core,server --lib): 1904 passed, 49 ignored, 6 failed exclusively due to unset FLARE_TEST_TEMPLATE_DIR (targeted async_transfer:: 15/15, runtime_core::memory:: 27/27 + 1 GPU-ignored, runtime_core::model:: 7/7, execution::rendezvous:: 6/6 all passed). - flare: 255 passed, 0 failed, 4 ignored. - flare-cli: 249 passed, 0 failed, 3 ignored; release binary built and --features roce check succeeded. - heliopause (export::binding::): 15 passed, 0 failed. - Limitations: live multi-host RoCE cluster loading with DEVICE_POOL, live GB10/Jetson unified-DRAM execution, live TP>=2 PCIe peer-copy rejection on an exported core, and the 6 FLARE_TEST_TEMPLATE_DIR template tests were not run in this pass. Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b Signed-off-by: Luke Alonso --- docs/runtime-core-design.md | 65 +- flare-cli/src/cluster.rs | 26 + helios/manifest.md | 35 +- helios/src/async_transfer/io_backend.rs | 91 ++- helios/src/async_transfer/kani_proofs.rs | 27 +- helios/src/async_transfer/lifecycle_tests.rs | 92 ++- helios/src/async_transfer/mod.rs | 9 +- helios/src/async_transfer/ring.rs | 36 + helios/src/async_transfer/scheduler.rs | 184 ++++- helios/src/async_transfer/worker.rs | 706 ++++++++++++++---- helios/src/execution/rendezvous.rs | 92 +++ helios/src/runtime_core/cache_memory.rs | 1 + helios/src/runtime_core/memory.rs | 413 ++++++++-- helios/src/runtime_core/mod.rs | 11 +- helios/src/runtime_core/model.rs | 81 +- .../helios-lifecycle/AsyncTransfer.cfg | 1 + .../helios-lifecycle/AsyncTransfer.tla | 32 +- verification/helios-lifecycle/README.md | 19 +- verification/helios-lifecycle/check.py | 24 +- 19 files changed, 1625 insertions(+), 320 deletions(-) diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index b3de796f4..a79e26df5 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -699,28 +699,49 @@ Before CUDA initialization or serving worker threads, Flare restricts `CUDA_VISIBLE_DEVICES` to `--gpus`, resolving indices within an inherited mask. When a core declares `Capacity::DEVICE_POOL` allocations and -`Execution.async_transfers` channels, `allocate_caches` first reserves -`pinned_bytes.div_ceil(512) + 256 MiB` of VRAM per rank for `cuMemHostRegister_v2` -GPU MMU page tables and worker streams (covering each channel's planned pinned -`HOST_POOL` and bounded internal bounce pool, which is disabled when channel -alignment exceeds 32 MiB), then sizes and maps each `DEVICE_POOL` at its fixed -reserved CUDA virtual address before computing KV page capacity (leaving space -for execution state rows and the minimum KV cache requirement, bounded by -`--pool-vram-memory` / `[memory] pool_vram`). Across tensor-parallel ranks, -`DEVICE_POOL` physical byte capacity is agreed as the minimum across ranks, and -`Execution.buffers` views backed by that allocation are rewritten to -`floor(agreed_bytes / row_bytes)` leading rows (truncating any partial trailing -row). `NativeResources::prepare_async_transfers` authenticates and opens the -4 KiB-aligned `RankBody.external_extents` payload segments directly (`O_DIRECT` -on Linux), allocates each channel's runtime-sized pinned `HOST_POOL` (clamped to -the planned per-rank host ceiling from `allocate_caches`, with an internal -pinned bounce pool when enabled), writes immutable startup geometry into the -mapped-host `ControlHeader`, and starts the channel workers before executing -`Execution.tuning_graphs`. Shutdown stops and drains all async transfer -channels after compute streams drain and before unmapping device or mapped-host -storage; unconfirmed drain transitions the channel to `FailedDrain` and retains -pinned memory and CUDA handles until process exit. Cores without -`Execution.async_transfers` channels bypass this path completely. +`Execution.async_transfers` channels, `NativeModel` rejects cores whose graphs +also contain Copy Engine `Memory::Peer` copy nodes at load time, preventing +unbounded Copy Engine deadlocks when in-graph demand transfers cannot yield to +`CopyEngineGate`. During `allocate_caches`, discrete-GPU ranks reserve host RAM +after subtracting planned prefix-cache offload and vision input windows +(`host_future`), reserve `pinned_bytes.div_ceil(512) + 256 MiB` of VRAM per +rank for `cuMemHostRegister_v2` GPU MMU page tables and worker streams +(covering each channel's planned pinned `HOST_POOL` and bounded internal bounce +pool, which is disabled when channel alignment exceeds 32 MiB), and deduct the +pinned host reservation from prefix-cache capture growth. On integrated +unified-DRAM GPUs (such as GB10 and Jetson), `HOST_POOL`, `bounce_pool`, +`DEVICE_POOL`, and KV caches draw from the same physical DRAM: `HOST_POOL` +defaults to zero unless `--pool-ram-memory` is explicitly configured, explicit +host-pool limits are bounded above the minimum KV cache requirement, and the +full `pinned_bytes + pinned_bytes.div_ceil(512) + 256 MiB` is deducted from the +unified cache budget before sizing `DEVICE_POOL`. Helios then sizes each +`DEVICE_POOL` (leaving room for execution state rows and the minimum KV cache +requirement, bounded by `--pool-vram-memory` / `[memory] pool_vram`), agrees on +the elementwise minimum across local ranks and across multi-host cluster ranks +through `CacheAgreement::device_pools`, maps each pool at its fixed reserved +CUDA virtual address, and rewrites `Execution.buffers` views backed by that +allocation to `floor(agreed_bytes / row_bytes)` leading rows (truncating any +partial trailing row). `NativeResources::prepare_async_transfers` authenticates +and opens the 4 KiB-aligned `RankBody.external_extents` payload segments +directly (`O_DIRECT` on Linux), allocates each channel's runtime-sized pinned +`HOST_POOL` (clamped to the planned per-rank host ceiling from +`allocate_caches`, with an internal pinned bounce pool when enabled), writes +immutable startup geometry into the mapped-host `ControlHeader`, and blocks in +`start()` until each channel worker binds its CUDA context, allocates its event +pool, and publishes `ControlHeader.worker_state = Running` before executing +`Execution.tuning_graphs`. All device completion writes serialize on the +channel's single Copy Engine stream, host completion mirrors advance +monotonically via `fetch_max`, and storage or CUDA transfer failures publish +the bit-63 fault sentinel (`COMPLETION_ERROR_BIT | error_code`) rather than the +caller's requested success cookie. Partial DMA submission failures after +`cuMemcpyHtoDAsync_v2` retain their in-flight and bounce-slot ownership until +hardware stream drain is confirmed. Shutdown stops and drains all async +transfer channels after compute streams drain (bounding Linux `io_uring` waits +with a kernel timespec), invalidates mapped-host control telemetry before +unmapping device or mapped-host storage, and on unconfirmed drain transitions +the channel to `FailedDrain` while retaining pinned memory, storage handles, +and CUDA handles until process exit. Cores without `Execution.async_transfers` +channels bypass this path completely. When omitted, the list contains the first N visible GPUs for the core's N local ranks, or one GPU per host for a multi-host core. Core loading finishes its progress threads before setting visibility. Hub revision detection queries diff --git a/flare-cli/src/cluster.rs b/flare-cli/src/cluster.rs index 3531faecc..fc623a0fd 100644 --- a/flare-cli/src/cluster.rs +++ b/flare-cli/src/cluster.rs @@ -155,6 +155,14 @@ impl flare_helios::runtime_core::CacheAgreement for Membership { } } + fn device_pools(&mut self, local: &[u64]) -> flare_helios::Result> { + use flare_helios::execution::rendezvous; + match self { + Membership::Zero(peers) => rendezvous::agree_device_pools(peers, local), + Membership::Peer(stream) => rendezvous::propose_device_pools(stream, local), + } + } + fn pool( &mut self, offer: flare_helios::offload::shard::PoolOffer, @@ -309,6 +317,24 @@ mod pool_tests { assert_eq!(zero.join().unwrap(), peer_approved); } } + + #[test] + fn device_pools_agreement_exchanges_cluster_minimum() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let peer = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let zero = listener.accept().unwrap().0; + let zero_handle = std::thread::spawn(move || { + Membership::Zero(vec![RankStream::Tcp(zero)]) + .device_pools(&[80 << 30, 16 << 30]) + .unwrap() + }); + let peer_agreed = Membership::Peer(RankStream::Tcp(peer)) + .device_pools(&[64 << 30, 24 << 30]) + .unwrap(); + let expected = vec![64 << 30, 16 << 30]; + assert_eq!(peer_agreed, expected); + assert_eq!(zero_handle.join().unwrap(), expected); + } } #[cfg(all( diff --git a/helios/manifest.md b/helios/manifest.md index 5f9242039..adb4cb468 100644 --- a/helios/manifest.md +++ b/helios/manifest.md @@ -177,11 +177,13 @@ Each `AsyncTransfer` entry declares: completion words. - `device_completions` (optional): 8-byte-aligned `Reference` inside a fixed `Memory::Device` allocation holding `completion_slots` 64-bit completion - words written in stream order by `cuStreamWriteValue64_v2` (when device - attribute `CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 122` is - supported) after Copy Engine DMA completes. + words written in stream order on the channel's single Copy Engine stream by + `cuStreamWriteValue64_v2` (when device attribute + `CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 122` is supported) after + Copy Engine DMA completes, with monotonic `fetch_max` host completion mirrors + so deferred DMA mirrors cannot regress reused completion slots. - `max_host_pool_bytes`: optional ceiling on the channel's pinned host pool - (`0` allows up to the runtime `--pool-ram-memory` budget). + (`0` disables the host pool). - `alignment`: power-of-two direct-I/O and offset alignment (`>= 4096`). Supported command opcodes are `DISK_TO_HOST` (`1`), `HOST_TO_DEV` (`2`), @@ -190,13 +192,24 @@ Supported command opcodes are `DISK_TO_HOST` (`1`), `HOST_TO_DEV` (`2`), `CANCEL_EPOCH` (`4`). Priorities `DEMAND` (`0`), `PREFETCH` (`1`), and `WARM` (`2`) feed a preemptible host queue with bounded background I/O and DMA depth; `CANCEL_EPOCH` and `ControlHeader.active_epoch` drop queued non-demand commands -from older epochs while preserving `DEMAND`. Helios starts prepared channels -before launching `Execution.tuning_graphs` so startup tuning kernels can read -`device_pool_bytes` and `host_pool_bytes` from `ControlHeader` and partition or -pre-warm pools. Teardown drains serving streams, cancels queued background -transfers, drains in-flight storage I/O and the Copy Engine stream within a -bounded timeout, and retains pinned host memory and CUDA handles until process -exit if drain is not confirmed. +from older epochs while preserving `DEMAND`. Caller-supplied `signal_value` +cookies occupy the lower 63 bits (`(signal_value & (1 << 63)) == 0`); bit 63 +(`COMPLETION_ERROR_BIT`) is reserved for fault sentinels +(`COMPLETION_ERROR_BIT | error_code`) emitted on `IoFailure` or `CudaFailure` +instead of the requested success value. Helios waits for each channel worker to +bind its CUDA context, create its event pool, and publish +`ControlHeader.worker_state = Running` before launching +`Execution.tuning_graphs` so startup tuning kernels read populated +`device_pool_bytes` and `host_pool_bytes` from `ControlHeader` and observe a +live channel. Cores that combine `Execution.async_transfers` with graphs +containing Copy Engine `Memory::Peer` copy nodes are rejected at load time, +because in-graph demand waits cannot serialize behind `CopyEngineGate` without +deadlocking the Copy Engine. Teardown drains serving streams, cancels queued +background transfers, drains in-flight storage I/O (bounded by a kernel timespec +on `io_uring`) and the Copy Engine stream within a bounded timeout, invalidates +mapped-host control telemetry before unmapping allocations, and retains pinned +host memory, storage handles, and CUDA handles until process exit if drain is +not confirmed. Helios implements no model-specific routing, eviction, prefetch policy, or cache directory layout inside `AsyncTransfer`; captured graphs own all slot diff --git a/helios/src/async_transfer/io_backend.rs b/helios/src/async_transfer/io_backend.rs index 41619d05d..ba8a8d0eb 100644 --- a/helios/src/async_transfer/io_backend.rs +++ b/helios/src/async_transfer/io_backend.rs @@ -131,6 +131,11 @@ pub mod linux_uring { self.queued_sqes += 1; Ok(()) } + + #[cfg(test)] + pub(super) fn insert_synthetic_inflight_for_test(&mut self, op_id: OpId, nbytes: u64) { + self.expected.insert(op_id, nbytes); + } } impl IoBackend for IoUringBackend { @@ -201,10 +206,33 @@ pub mod linux_uring { if self.expected.is_empty() { break; } - if Instant::now() >= deadline { + let Some(remaining) = deadline.checked_duration_since(Instant::now()) else { + return false; + }; + if remaining.is_zero() { return false; } - let _ = self.ring.submit_and_wait(1); + let ts = types::Timespec::from(remaining); + let args = types::SubmitArgs::new().timespec(&ts); + match self.ring.submitter().submit_with_args(1, &args) { + Ok(_) => {} + 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(); + let _ = self.poll_completions(out); + if self.expected.is_empty() { + break; + } + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return false; + }; + std::thread::sleep(Duration::from_millis(1).min(left)); + } + } } true } @@ -290,3 +318,62 @@ pub fn from_direct_files(files: Vec) -> io::Result> { Ok(Box::new(PreadBackend::new(files))) } } + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::{IoBackend, IoCompletion, linux_uring::IoUringBackend}; + use std::{ + fs::File, + os::fd::FromRawFd, + time::{Duration, Instant}, + }; + + #[test] + fn uring_cancel_and_drain_bounds_wait_with_timespec() { + let mut pipe_fds = [0i32; 2]; + assert_eq!(unsafe { libc::pipe(pipe_fds.as_mut_ptr()) }, 0); + let read_end = unsafe { File::from_raw_fd(pipe_fds[0]) }; + let write_end = unsafe { File::from_raw_fd(pipe_fds[1]) }; + + let mut pipe_backend = IoUringBackend::new(vec![read_end]).expect("create pipe io_uring"); + let mut buf = [0u8; 64]; + unsafe { + pipe_backend + .submit_read(7, 0, 0, buf.as_mut_ptr(), 64) + .expect("submit pipe read"); + } + pipe_backend.flush().expect("flush pipe read"); + let mut out: Vec = Vec::new(); + let start = Instant::now(); + // Cancelable pipe read must drain promptly and return true. + assert!(pipe_backend.cancel_and_drain(Duration::from_secs(1), &mut out)); + assert!(start.elapsed() < Duration::from_secs(1)); + assert_eq!(pipe_backend.in_flight(), 0); + assert_eq!(out.len(), 1); + assert_eq!(out[0].op_id, 7); + assert!(!out[0].ok); + drop(write_end); + + // Verify timeout expiry via submit_with_args + Timespec when an expected op never + // completes (AsyncCancel emits -ENOENT with user_data 0, then wait hits ETIME). + let mut uncompletable_fds = [0i32; 2]; + assert_eq!(unsafe { libc::pipe(uncompletable_fds.as_mut_ptr()) }, 0); + let r2 = unsafe { File::from_raw_fd(uncompletable_fds[0]) }; + let w2 = unsafe { File::from_raw_fd(uncompletable_fds[1]) }; + let mut stuck = IoUringBackend::new(vec![r2]).expect("create second io_uring"); + stuck.insert_synthetic_inflight_for_test(99, 64); + out.clear(); + let timeout = Duration::from_millis(50); + let t0 = Instant::now(); + let drained = stuck.cancel_and_drain(timeout, &mut out); + let elapsed = t0.elapsed(); + assert!(!drained, "uncompleted op must return false on drain timeout"); + assert!( + elapsed >= Duration::from_millis(35) && elapsed < Duration::from_secs(1), + "cancel_and_drain elapsed {:?} outside bounded timeout window", + elapsed + ); + assert_eq!(stuck.in_flight(), 1); + drop(w2); + } +} diff --git a/helios/src/async_transfer/kani_proofs.rs b/helios/src/async_transfer/kani_proofs.rs index d128a7106..dfeb008da 100644 --- a/helios/src/async_transfer/kani_proofs.rs +++ b/helios/src/async_transfer/kani_proofs.rs @@ -8,10 +8,10 @@ //! and command bounds/alignment validators. use super::ring::{ - BOUNCE_HOST_OFFSET, COMMAND_BYTES, ErrorCode, ExtentEntry, HEADER_BYTES, MAX_RING_CAPACITY, - MIN_ALIGNMENT, MIN_RING_CAPACITY, NO_COMPLETION_SLOT, Opcode, Priority, TransferCommand, - ValidatedCommand, resolve_pool_bytes, validate_command, validate_control_layout, - validate_extent_entry, + BOUNCE_HOST_OFFSET, COMMAND_BYTES, COMPLETION_ERROR_BIT, ErrorCode, ExtentEntry, HEADER_BYTES, + MAX_RING_CAPACITY, MIN_ALIGNMENT, MIN_RING_CAPACITY, NO_COMPLETION_SLOT, Opcode, Priority, + TransferCommand, ValidatedCommand, completion_error_sentinel, resolve_pool_bytes, + validate_command, validate_control_layout, validate_extent_entry, }; #[kani::proof] @@ -136,11 +136,22 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { bounce_slot_bytes, ) { Ok(ValidatedCommand::CancelEpoch { - completion_slot, .. + completion_slot, + signal_value, + .. }) => { assert_eq!(cmd.opcode, Opcode::CancelEpoch as u32); if let Some(slot) = completion_slot { assert!(slot < completion_slots); + assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0); + assert_ne!( + signal_value, + completion_error_sentinel(ErrorCode::IoFailure) + ); + assert_ne!( + signal_value, + completion_error_sentinel(ErrorCode::CudaFailure) + ); } else { assert_eq!(cmd.completion_slot, NO_COMPLETION_SLOT); } @@ -150,6 +161,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { extent, host_offset, completion_slot, + signal_value, .. }) => { assert_eq!(cmd.opcode, Opcode::DiskToHost as u32); @@ -162,6 +174,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { assert!((host_offset as u128) + (extent.nbytes as u128) <= (host_pool_bytes as u128)); if let Some(slot) = completion_slot { assert!(slot < completion_slots); + assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0); } } Ok(ValidatedCommand::HostToDev { @@ -170,6 +183,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { device_offset, nbytes, completion_slot, + signal_value, .. }) => { assert_eq!(cmd.opcode, Opcode::HostToDev as u32); @@ -179,6 +193,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { assert!((device_offset as u128) + (nbytes as u128) <= (device_pool_bytes as u128)); if let Some(slot) = completion_slot { assert!(slot < completion_slots); + assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0); } } Ok(ValidatedCommand::DiskToDev { @@ -187,6 +202,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { host_offset, device_offset, completion_slot, + signal_value, .. }) => { assert_eq!(cmd.opcode, Opcode::DiskToDev as u32); @@ -208,6 +224,7 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { assert!((device_offset as u128) + (extent.nbytes as u128) <= (device_pool_bytes as u128)); if let Some(slot) = completion_slot { assert!(slot < completion_slots); + assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0); } } Err(code) => { diff --git a/helios/src/async_transfer/lifecycle_tests.rs b/helios/src/async_transfer/lifecycle_tests.rs index 28ca8065f..3e3401920 100644 --- a/helios/src/async_transfer/lifecycle_tests.rs +++ b/helios/src/async_transfer/lifecycle_tests.rs @@ -9,15 +9,18 @@ use std::{collections::BTreeSet, fs, path::Path}; use super::{ - ring::{ChannelState, ExtentEntry, Priority, ValidatedCommand}, + ring::{ + COMPLETION_ERROR_BIT, ChannelState, ErrorCode, ExtentEntry, Priority, ValidatedCommand, + completion_error_sentinel, + }, scheduler::TransferScheduler, }; -/// Compact 13-integer projection shared with `AsyncTransfer.tla`. +/// Compact 14-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]` -type Projection = [i64; 13]; +/// b_in_io, b_q_dma, b_in_dma, free_bounce, can_release, faulted_dma]` +type Projection = [i64; 14]; fn project(sched: &TransferScheduler) -> Projection { let in_bg_io = sched.bg_io_inflight(); @@ -38,13 +41,14 @@ fn project(sched: &TransferScheduler) -> Projection { sched.bounce_in_dma() as i64, sched.free_bounce_count() as i64, i64::from(sched.can_release_memory()), + sched.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[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] ) } @@ -95,6 +99,16 @@ fn async_transfer_scheduler_matches_lifecycle_model() { ); assert!(sched.inflight_io_count() <= max_total_io); assert!(sched.inflight_dma_count() <= max_total_dma); + assert!( + sched.faulted_dma_count() <= sched.inflight_dma_count(), + "faulted DMA count exceeded inflight DMA count" + ); + if sched.faulted_dma_count() > 0 { + assert!( + !sched.can_release_memory(), + "faulted DMA must retain inflight and bounce ownership" + ); + } assert_eq!( sched.free_bounce_count() + sched.bounce_in_io() @@ -238,7 +252,17 @@ fn async_transfer_scheduler_matches_lifecycle_model() { for (idx, &op_id) in io_ids.iter().enumerate() { for ok in [true, false] { let mut n = sched.clone(); - let _ = n.complete_io(op_id, ok); + let notice = n.complete_io(op_id, ok); + if !ok { + let notice = notice.expect("failed IO must emit an error completion notice"); + assert_eq!(notice.error, ErrorCode::IoFailure); + assert_eq!( + notice.signal_value, + completion_error_sentinel(ErrorCode::IoFailure), + "failed transfer must signal error sentinel, not success value" + ); + assert_ne!(notice.signal_value & COMPLETION_ERROR_BIT, 0); + } let mut n_io = io_ids.clone(); n_io.remove(idx); push_next(6, n, n_io, dma_ids.clone()); @@ -247,15 +271,67 @@ fn async_transfer_scheduler_matches_lifecycle_model() { // 7. Complete any in-flight DMA for (idx, &op_id) in dma_ids.iter().enumerate() { + let was_faulted = sched.is_dma_faulted(op_id); for ok in [true, false] { let mut n = sched.clone(); - let _ = n.complete_dma(op_id, ok); + let notice = n.complete_dma(op_id, ok); + if was_faulted { + assert!( + notice.is_none(), + "already-faulted DMA must not emit a duplicate or success notice on drain" + ); + } else if !ok { + let notice = notice.expect("failed DMA must emit an error completion notice"); + 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_ne!(notice.signal_value & COMPLETION_ERROR_BIT, 0); + } let mut n_dma = dma_ids.clone(); n_dma.remove(idx); push_next(7, n, io_ids.clone(), n_dma); } } + // 11. Mark an in-flight DMA faulted after partial CUDA submission failure. + 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()); + } + } + // 8. BeginDrain if matches!(sched.state(), ChannelState::Idle | ChannelState::Running) { let mut n = sched.clone(); diff --git a/helios/src/async_transfer/mod.rs b/helios/src/async_transfer/mod.rs index ad63bf613..21c2daa09 100644 --- a/helios/src/async_transfer/mod.rs +++ b/helios/src/async_transfer/mod.rs @@ -18,10 +18,11 @@ pub mod scheduler; pub mod worker; pub use ring::{ - ABI_VERSION, BOUNCE_HOST_OFFSET, COMMAND_BYTES, ChannelState, ControlHeader, EXTENT_ENTRY_BYTES, - ErrorCode, ExtentEntry, FLAG_DEVICE_COMPLETIONS, FLAG_STREAM_WRITE_VALUE64, HEADER_BYTES, - MAX_RING_CAPACITY, MIN_ALIGNMENT, MIN_RING_CAPACITY, NO_COMPLETION_SLOT, Opcode, Priority, - TransferCommand, ValidatedCommand, decode_extent_directory, host_completions_offset, + ABI_VERSION, BOUNCE_HOST_OFFSET, COMMAND_BYTES, COMPLETION_ERROR_BIT, ChannelState, + ControlHeader, EXTENT_ENTRY_BYTES, ErrorCode, ExtentEntry, FLAG_DEVICE_COMPLETIONS, + FLAG_STREAM_WRITE_VALUE64, HEADER_BYTES, MAX_RING_CAPACITY, MIN_ALIGNMENT, MIN_RING_CAPACITY, + NO_COMPLETION_SLOT, Opcode, Priority, TransferCommand, ValidatedCommand, + completion_error_sentinel, decode_extent_directory, host_completions_offset, required_control_bytes, resolve_pool_bytes, validate_command, validate_control_layout, validate_extent_entry, }; diff --git a/helios/src/async_transfer/ring.rs b/helios/src/async_transfer/ring.rs index b64e7e610..b2e94ab38 100644 --- a/helios/src/async_transfer/ring.rs +++ b/helios/src/async_transfer/ring.rs @@ -28,6 +28,20 @@ pub const NO_COMPLETION_SLOT: u32 = u32::MAX; /// Sentinel [`TransferCommand::host_offset`] selecting an internal pinned bounce slot /// for fused [`Opcode::DiskToDev`] transfers when no caller-managed host slot is supplied. pub const BOUNCE_HOST_OFFSET: u64 = u64::MAX; +/// High bit set on a 64-bit completion word when an accepted transfer fails with a storage +/// or CUDA error instead of publishing the caller-requested success `signal_value`. +/// +/// Valid caller-requested `signal_value` cookies occupy the lower 63 bits +/// (`(signal_value & COMPLETION_ERROR_BIT) == 0`). On [`ErrorCode::IoFailure`] or +/// [`ErrorCode::CudaFailure`], the worker publishes [`completion_error_sentinel`] so consumers +/// never mistake a failed transfer for valid payload bytes. +pub const COMPLETION_ERROR_BIT: u64 = 1u64 << 63; + +/// Encode a nonzero [`ErrorCode`] into the 64-bit completion-slot fault sentinel. +#[inline] +pub const fn completion_error_sentinel(code: ErrorCode) -> u64 { + COMPLETION_ERROR_BIT | (code as u32 as u64) +} /// Control header feature bit indicating VRAM completion slots are configured. pub const FLAG_DEVICE_COMPLETIONS: u32 = 1 << 0; @@ -136,6 +150,7 @@ pub enum ErrorCode { IoFailure = 9, CudaFailure = 10, RingOverrun = 11, + InvalidSignalValue = 12, } /// One validated, read-only byte extent backed by an opened core file. @@ -375,6 +390,9 @@ pub fn validate_command( } else { return Err(ErrorCode::CompletionSlotOutOfRange); }; + if completion_slot.is_some() && (cmd.signal_value & COMPLETION_ERROR_BIT) != 0 { + return Err(ErrorCode::InvalidSignalValue); + } match opcode { Opcode::CancelEpoch => Ok(ValidatedCommand::CancelEpoch { @@ -600,6 +618,24 @@ mod tests { validate_command(&fused, &extents, 0, 16384, 8, 4096, 4096), Err(ErrorCode::HostRangeOutOfBounds) ); + // Reserved error-sentinel bit in signal_value is rejected when a completion slot is used. + let mut bad_sig = fused; + bad_sig.signal_value = COMPLETION_ERROR_BIT | 1; + assert_eq!( + validate_command(&bad_sig, &extents, 0, 16384, 8, 4096, 8192), + Err(ErrorCode::InvalidSignalValue) + ); + // Ignored when NO_COMPLETION_SLOT is selected. + bad_sig.completion_slot = NO_COMPLETION_SLOT; + assert!(validate_command(&bad_sig, &extents, 0, 16384, 8, 4096, 8192).is_ok()); + assert_eq!( + completion_error_sentinel(ErrorCode::IoFailure), + COMPLETION_ERROR_BIT | (ErrorCode::IoFailure as u64) + ); + assert_eq!( + completion_error_sentinel(ErrorCode::CudaFailure), + COMPLETION_ERROR_BIT | (ErrorCode::CudaFailure as u64) + ); } #[test] diff --git a/helios/src/async_transfer/scheduler.rs b/helios/src/async_transfer/scheduler.rs index 5625220b2..141fb855f 100644 --- a/helios/src/async_transfer/scheduler.rs +++ b/helios/src/async_transfer/scheduler.rs @@ -12,7 +12,9 @@ use std::collections::VecDeque; -use super::ring::{ChannelState, ErrorCode, ExtentEntry, Priority, ValidatedCommand}; +use super::ring::{ + ChannelState, ErrorCode, ExtentEntry, Priority, ValidatedCommand, completion_error_sentinel, +}; /// Unique monotonic operation ID assigned to every accepted transfer. pub type OpId = u64; @@ -110,6 +112,9 @@ pub struct InflightDma { pub completion_slot: Option, pub signal_value: u64, pub from_disk: bool, + /// 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, } /// Completion notification emitted by the scheduler when an operation finishes. @@ -198,6 +203,18 @@ impl TransferScheduler { self.inflight_dma.len() } + #[inline] + pub fn faulted_dma_count(&self) -> usize { + self.inflight_dma.iter().filter(|op| op.faulted).count() + } + + #[inline] + pub fn is_dma_faulted(&self, op_id: OpId) -> bool { + self.inflight_dma + .iter() + .any(|op| op.op_id == op_id && op.faulted) + } + #[inline] pub fn bg_io_inflight(&self) -> usize { self.inflight_io @@ -544,7 +561,7 @@ impl TransferScheduler { return Some(CompletionNotice { op_id: op.op_id, completion_slot: op.completion_slot, - signal_value: op.signal_value, + signal_value: completion_error_sentinel(ErrorCode::IoFailure), error: ErrorCode::IoFailure, bytes_disk_to_host: 0, bytes_host_to_dev: 0, @@ -559,7 +576,11 @@ impl TransferScheduler { Some(CompletionNotice { op_id: op.op_id, completion_slot: op.completion_slot, - signal_value: op.signal_value, + signal_value: if ok { + op.signal_value + } else { + completion_error_sentinel(ErrorCode::IoFailure) + }, error: if ok { ErrorCode::Ok } else { @@ -620,6 +641,7 @@ impl TransferScheduler { completion_slot, signal_value, from_disk, + faulted: false, }; self.inflight_dma.push(inflight); return Some(inflight); @@ -628,18 +650,56 @@ impl TransferScheduler { None } - /// Record completion of an in-flight Copy Engine DMA transfer. + /// 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 { + if !matches!(self.state, ChannelState::Running | ChannelState::Draining) { + return None; + } + let op = self.inflight_dma.iter_mut().find(|op| op.op_id == op_id)?; + if op.faulted { + return None; + } + op.faulted = true; + let completion_slot = op.completion_slot; + self.completed_cmds = self.completed_cmds.saturating_add(1); + Some(CompletionNotice { + op_id, + completion_slot, + signal_value: completion_error_sentinel(ErrorCode::CudaFailure), + error: ErrorCode::CudaFailure, + bytes_disk_to_host: 0, + bytes_host_to_dev: 0, + bytes_disk_to_dev: 0, + }) + } + + /// Record completion of an in-flight Copy Engine DMA transfer after hardware confirms finish + /// (or immediately when `cuMemcpyHtoDAsync` itself rejected submission). + /// + /// If `op_id` was already recorded via [`Self::mark_dma_faulted`], removes it and returns its + /// bounce slot without emitting a second completion notice or crediting transferred bytes. pub fn complete_dma(&mut self, op_id: OpId, ok: bool) -> Option { let pos = self.inflight_dma.iter().position(|op| op.op_id == op_id)?; let op = self.inflight_dma.swap_remove(pos); if let Some(slot) = op.bounce_slot { self.free_bounce_slots.push(slot); } + if op.faulted { + return None; + } self.completed_cmds = self.completed_cmds.saturating_add(1); Some(CompletionNotice { op_id: op.op_id, completion_slot: op.completion_slot, - signal_value: op.signal_value, + signal_value: if ok { + op.signal_value + } else { + completion_error_sentinel(ErrorCode::CudaFailure) + }, error: if ok { ErrorCode::Ok } else { @@ -854,4 +914,118 @@ mod tests { assert_eq!(sched.state(), ChannelState::FailedDrain); assert!(!sched.can_release_memory()); } + + #[test] + fn failed_transfers_signal_error_sentinel_instead_of_success_value() { + let mut sched = TransferScheduler::new(2, 1, 2, 1, 1); + sched.start().unwrap(); + // DiskToHost failure emits IoFailure sentinel, not requested cookie 101. + sched.enqueue(ValidatedCommand::DiskToHost { + priority: Priority::Demand, + extent: ext(4096), + host_offset: 0, + epoch: 1, + completion_slot: Some(0), + signal_value: 101, + }); + let io = sched.pop_next_io().unwrap(); + let notice = sched.complete_io(io.op_id, false).unwrap(); + assert_eq!(notice.error, ErrorCode::IoFailure); + assert_eq!( + notice.signal_value, + completion_error_sentinel(ErrorCode::IoFailure) + ); + assert_ne!(notice.signal_value, 101); + + // Fused DiskToDev IO failure frees bounce slot and emits IoFailure sentinel. + sched.enqueue(ValidatedCommand::DiskToDev { + priority: Priority::Demand, + extent: ext(4096), + host_offset: None, + device_offset: 0, + epoch: 1, + completion_slot: Some(1), + signal_value: 202, + }); + let io2 = sched.pop_next_io().unwrap(); + let notice2 = sched.complete_io(io2.op_id, false).unwrap(); + assert_eq!(notice2.error, ErrorCode::IoFailure); + assert_eq!( + notice2.signal_value, + completion_error_sentinel(ErrorCode::IoFailure) + ); + assert_eq!(sched.free_bounce_count(), 1); + + // HostToDev failure emits CudaFailure sentinel, not requested cookie 303. + sched.enqueue(ValidatedCommand::HostToDev { + priority: Priority::Demand, + host_offset: 0, + device_offset: 0, + nbytes: 4096, + epoch: 1, + completion_slot: Some(2), + signal_value: 303, + }); + let dma = sched.pop_next_dma().unwrap(); + let notice3 = sched.complete_dma(dma.op_id, false).unwrap(); + assert_eq!(notice3.error, ErrorCode::CudaFailure); + assert_eq!( + notice3.signal_value, + completion_error_sentinel(ErrorCode::CudaFailure) + ); + assert_ne!(notice3.signal_value, 303); + } + + #[test] + fn faulted_dma_retains_bounce_slot_and_blocks_drain_until_hardware_finishes() { + let mut sched = TransferScheduler::new(2, 1, 2, 1, 1); + sched.start().unwrap(); + sched.enqueue(ValidatedCommand::DiskToDev { + priority: Priority::Demand, + extent: ext(4096), + host_offset: None, + device_offset: 0, + epoch: 1, + completion_slot: Some(0), + signal_value: 404, + }); + let io = sched.pop_next_io().unwrap(); + 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(); + assert_eq!(notice.error, ErrorCode::CudaFailure); + 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.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_eq!(sched.completed_cmds, 1); + + // Drain without completing hardware DMA fails into FailedDrain and retains memory. + let mut unconfirmed = sched.clone(); + unconfirmed.begin_drain().unwrap(); + assert!(unconfirmed.finish_drain(true).is_err()); + assert_eq!(unconfirmed.state(), ChannelState::FailedDrain); + assert!(!unconfirmed.can_release_memory()); + + // Completing after hardware drain reclaims the bounce slot without emitting a second notice. + assert!(sched.complete_dma(dma.op_id, true).is_none()); + assert_eq!(sched.inflight_dma_count(), 0); + assert_eq!(sched.faulted_dma_count(), 0); + assert_eq!(sched.free_bounce_count(), 1); + assert_eq!(sched.completed_cmds, 1); + sched.begin_drain().unwrap(); + sched.finish_drain(true).unwrap(); + assert!(sched.can_release_memory()); + } } diff --git a/helios/src/async_transfer/worker.rs b/helios/src/async_transfer/worker.rs index ca1dffa11..ed3ed8cd2 100644 --- a/helios/src/async_transfer/worker.rs +++ b/helios/src/async_transfer/worker.rs @@ -11,8 +11,9 @@ use std::{ collections::VecDeque, ptr::null_mut, sync::{ - Arc, Mutex, + Arc, Mutex, RwLock, atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + mpsc, }, thread::{self, JoinHandle}, time::{Duration, Instant}, @@ -32,7 +33,7 @@ use super::{ ring::{ ABI_VERSION, ChannelState, ControlHeader, ErrorCode, ExtentEntry, FLAG_DEVICE_COMPLETIONS, FLAG_STREAM_WRITE_VALUE64, HEADER_BYTES, TransferCommand, - host_completions_offset, validate_command, + completion_error_sentinel, host_completions_offset, validate_command, }, scheduler::{CompletionNotice, OpId, TransferScheduler}, }; @@ -202,6 +203,107 @@ impl PinnedHostRegion { } } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct ControlCounters { + submitted_cmds: u64, + completed_cmds: u64, + canceled_cmds: u64, + rejected_cmds: u64, + bytes_disk_to_host: u64, + bytes_host_to_dev: u64, + bytes_disk_to_dev: u64, + last_error: u32, +} + +#[derive(Clone, Copy, Debug)] +enum ControlAccess { + Live, + Invalidated(ControlCounters), +} + +unsafe fn read_control_counters(control_address: usize) -> ControlCounters { + // SAFETY: Caller holds a shared read or exclusive write lock proving `control_address` is live. + let header = unsafe { &*(control_address as *const ControlHeader) }; + ControlCounters { + submitted_cmds: header.submitted_cmds.load(Ordering::Relaxed), + completed_cmds: header.completed_cmds.load(Ordering::Relaxed), + canceled_cmds: header.canceled_cmds.load(Ordering::Relaxed), + rejected_cmds: header.rejected_cmds.load(Ordering::Relaxed), + bytes_disk_to_host: header.bytes_disk_to_host.load(Ordering::Relaxed), + bytes_host_to_dev: header.bytes_host_to_dev.load(Ordering::Relaxed), + bytes_disk_to_dev: header.bytes_disk_to_dev.load(Ordering::Relaxed), + last_error: header.last_error.load(Ordering::Relaxed), + } +} + +/// Lifetime guard around the mapped-host `ControlHeader` so teardown drains active telemetry +/// readers and captures final counters before `MappedHost` allocations unmap. +struct ControlRegionGuard { + address: usize, + access: RwLock, +} + +impl ControlRegionGuard { + fn new(address: usize) -> Self { + Self { + address, + access: RwLock::new(ControlAccess::Live), + } + } + + fn is_live(&self) -> bool { + let guard = self + .access + .read() + .unwrap_or_else(|poison| poison.into_inner()); + matches!(*guard, ControlAccess::Live) + } + + fn read_counters(&self) -> ControlCounters { + let guard = self + .access + .read() + .unwrap_or_else(|poison| poison.into_inner()); + match *guard { + ControlAccess::Live => unsafe { read_control_counters(self.address) }, + ControlAccess::Invalidated(cached) => cached, + } + } + + fn store_worker_state(&self, state: ChannelState) { + let guard = self + .access + .read() + .unwrap_or_else(|poison| poison.into_inner()); + if matches!(*guard, ControlAccess::Live) { + // SAFETY: Holding the shared read guard prevents teardown from unmapping `address`. + unsafe { + let header = &*(self.address as *const ControlHeader); + header.worker_state.store(state as u32, Ordering::Release); + } + } + } + + fn invalidate(&self) { + let mut guard = self + .access + .write() + .unwrap_or_else(|poison| poison.into_inner()); + if matches!(*guard, ControlAccess::Live) { + // SAFETY: Called before `MappedHost` unmap while holding the exclusive write guard. + let cached = unsafe { read_control_counters(self.address) }; + *guard = ControlAccess::Invalidated(cached); + } + } +} + +/// Monotonically advance one mapped-host 64-bit completion word so a deferred DMA host mirror +/// cannot regress a reused slot backwards and a fault sentinel (`COMPLETION_ERROR_BIT`) stays sticky. +#[inline] +fn update_host_completion(slot: &AtomicU64, value: u64) { + slot.fetch_max(value, Ordering::AcqRel); +} + enum EventCompletionAction { None, HostOnly(u32, u64), @@ -211,16 +313,26 @@ enum EventCompletionAction { struct PendingEventDma { op_id: OpId, event: Handle, + failed: bool, completion_action: EventCompletionAction, } +struct UntrackedFaultedDma { + op_id: OpId, + pending_notice: Option, +} + +enum WorkerExit { + StartupFailed(Box), + Drained(bool), +} + struct WorkerStateInner { state: ChannelState, stop_requested: Arc, - join_handle: Option>, + join_handle: Option>, io_backend: Option>, copy_stream: Handle, - signal_stream: Handle, host_pool: PinnedHostRegion, bounce_pool: PinnedHostRegion, bounce_slot_bytes: u64, @@ -238,6 +350,7 @@ pub struct AsyncTransferRuntime { driver: Arc, context: Handle, atomic_state: Arc, + control: ControlRegionGuard, inner: Mutex, } @@ -289,7 +402,6 @@ impl AsyncTransferRuntime { }; let mut copy_stream = null_mut(); - let mut signal_stream = null_mut(); let stream_result = unsafe { let mut prev = null_mut(); let had_prev = (driver.context_get)(&mut prev) == 0; @@ -300,22 +412,10 @@ impl AsyncTransferRuntime { "cuStreamCreate(async_transfer)", (driver.stream_create)(&mut copy_stream, CU_STREAM_NON_BLOCKING), ) - }) - .and_then(|()| { - driver.check( - "cuStreamCreate(async_transfer_signal)", - (driver.stream_create)(&mut signal_stream, CU_STREAM_NON_BLOCKING), - ) }); - if res.is_err() { - if !signal_stream.is_null() { - let _ = (driver.stream_destroy)(signal_stream); - signal_stream = null_mut(); - } - if !copy_stream.is_null() { - let _ = (driver.stream_destroy)(copy_stream); - copy_stream = null_mut(); - } + if res.is_err() && !copy_stream.is_null() { + let _ = (driver.stream_destroy)(copy_stream); + copy_stream = null_mut(); } if had_prev && prev != context { let _ = (driver.context_set)(prev); @@ -358,18 +458,19 @@ impl AsyncTransferRuntime { .store(ChannelState::Idle as u32, Ordering::Release); } + let control = ControlRegionGuard::new(config.control_address); Ok(Arc::new(Self { config, driver, context, atomic_state: Arc::new(AtomicU32::new(ChannelState::Idle as u32)), + control, inner: Mutex::new(WorkerStateInner { state: ChannelState::Idle, stop_requested: Arc::new(AtomicBool::new(false)), join_handle: None, io_backend: Some(io_backend), copy_stream, - signal_stream, host_pool, bounce_pool, bounce_slot_bytes, @@ -396,8 +497,17 @@ impl AsyncTransferRuntime { self.config.device_pool_bytes } + /// Drain active control-header readers, capture final telemetry counters, and prevent + /// future dereferences of `control_address` before mapped-host allocations unmap. + pub fn invalidate_control(&self) { + self.control.invalidate(); + } + /// Start the background host polling & transfer thread (`Idle -> Running`). - /// Idempotent when already `Running`. + /// + /// Blocks until the worker thread has bound its CUDA context, created its completion events, + /// and published `ChannelState::Running` into `ControlHeader::worker_state`, propagating any + /// worker initialization error without transitioning out of `Idle`. Idempotent when `Running`. pub fn start(&self) -> Result<()> { let mut inner = self .inner @@ -425,6 +535,12 @@ impl AsyncTransferRuntime { )); } } + if !self.control.is_live() { + return Err(Error::execution( + ExecutionError::Manifest, + "async transfer control region has been invalidated", + )); + } let io_backend = inner.io_backend.take().ok_or_else(|| { Error::execution( @@ -433,13 +549,13 @@ impl AsyncTransferRuntime { ) })?; inner.stop_requested.store(false, Ordering::Release); + let (ready_tx, ready_rx) = mpsc::sync_channel::>(1); let args = WorkerThreadArgs { config: self.config.clone(), driver: self.driver.clone(), context: self.context as usize, copy_stream: inner.copy_stream as usize, - signal_stream: inner.signal_stream as usize, host_pool_ptr: inner.host_pool.ptr as usize, bounce_pool_ptr: inner.bounce_pool.ptr as usize, bounce_slot_bytes: inner.bounce_slot_bytes, @@ -448,6 +564,7 @@ impl AsyncTransferRuntime { stop_requested: inner.stop_requested.clone(), atomic_state: self.atomic_state.clone(), io_backend, + ready_tx, }; let thread_name = format!("flare-xfer-{}", self.config.name); @@ -461,11 +578,31 @@ impl AsyncTransferRuntime { ) })?; - inner.state = ChannelState::Running; - self.atomic_state - .store(ChannelState::Running as u32, Ordering::Release); - inner.join_handle = Some(handle); - Ok(()) + match ready_rx.recv() { + Ok(Ok(())) => { + inner.state = ChannelState::Running; + self.atomic_state + .store(ChannelState::Running as u32, Ordering::Release); + inner.join_handle = Some(handle); + Ok(()) + } + Ok(Err(err)) => { + if let Ok(WorkerExit::StartupFailed(backend)) = handle.join() { + inner.io_backend = Some(backend); + } + Err(err) + } + Err(_) => { + let _ = handle.join(); + Err(Error::execution( + ExecutionError::Manifest, + format!( + "async transfer worker {:?} exited before becoming ready", + self.config.name + ), + )) + } + } } /// Signal the worker to stop, drain all in-flight storage I/O and Copy Engine work within a @@ -483,12 +620,7 @@ impl AsyncTransferRuntime { inner.state = ChannelState::Stopped; self.atomic_state .store(ChannelState::Stopped as u32, Ordering::Release); - unsafe { - let header = &*(self.config.control_address as *const ControlHeader); - header - .worker_state - .store(ChannelState::Stopped as u32, Ordering::Release); - } + self.control.store_worker_state(ChannelState::Stopped); self.release_owned_resources_locked(&mut inner); return Ok(()); } @@ -512,7 +644,8 @@ impl AsyncTransferRuntime { let drained = match inner.join_handle.take() { Some(handle) => match handle.join() { - Ok(ok) => ok, + Ok(WorkerExit::Drained(ok)) => ok, + Ok(WorkerExit::StartupFailed(_)) => true, Err(_) => false, }, None => true, @@ -522,24 +655,14 @@ impl AsyncTransferRuntime { inner.state = ChannelState::Stopped; self.atomic_state .store(ChannelState::Stopped as u32, Ordering::Release); - unsafe { - let header = &*(self.config.control_address as *const ControlHeader); - header - .worker_state - .store(ChannelState::Stopped as u32, Ordering::Release); - } + self.control.store_worker_state(ChannelState::Stopped); self.release_owned_resources_locked(&mut inner); Ok(()) } else { inner.state = ChannelState::FailedDrain; self.atomic_state .store(ChannelState::FailedDrain as u32, Ordering::Release); - unsafe { - let header = &*(self.config.control_address as *const ControlHeader); - header - .worker_state - .store(ChannelState::FailedDrain as u32, Ordering::Release); - } + self.control.store_worker_state(ChannelState::FailedDrain); // Retain driver and pinned memory until process termination so in-flight hardware // operations never access unmapped addresses. std::mem::forget(self.driver.clone()); @@ -568,10 +691,6 @@ impl AsyncTransferRuntime { let _ = (self.driver.stream_destroy)(inner.copy_stream); inner.copy_stream = null_mut(); } - if !inner.signal_stream.is_null() { - let _ = (self.driver.stream_destroy)(inner.signal_stream); - inner.signal_stream = null_mut(); - } } if had_prev && prev != self.context { let _ = (self.driver.context_set)(prev); @@ -581,24 +700,24 @@ impl AsyncTransferRuntime { } } - /// Lock-free telemetry read from the mapped-host control header. + /// Telemetry read from the mapped-host control header, returning the captured final + /// counters after [`Self::invalidate_control`] prevents post-unmap dereferences. pub fn snapshot(&self) -> AsyncTransferSnapshot { - // SAFETY: Validated mapped-host control header stays alive until `NativeResources` teardown. - let header = unsafe { &*(self.config.control_address as *const ControlHeader) }; + let counters = self.control.read_counters(); AsyncTransferSnapshot { name: self.config.name.clone(), state: self.state(), device_pool_bytes: self.config.device_pool_bytes, host_pool_bytes: self.config.host_pool_bytes, extent_count: self.config.extents.len() as u32, - submitted_cmds: header.submitted_cmds.load(Ordering::Relaxed), - completed_cmds: header.completed_cmds.load(Ordering::Relaxed), - canceled_cmds: header.canceled_cmds.load(Ordering::Relaxed), - rejected_cmds: header.rejected_cmds.load(Ordering::Relaxed), - bytes_disk_to_host: header.bytes_disk_to_host.load(Ordering::Relaxed), - bytes_host_to_dev: header.bytes_host_to_dev.load(Ordering::Relaxed), - bytes_disk_to_dev: header.bytes_disk_to_dev.load(Ordering::Relaxed), - last_error: header.last_error.load(Ordering::Relaxed), + submitted_cmds: counters.submitted_cmds, + completed_cmds: counters.completed_cmds, + canceled_cmds: counters.canceled_cmds, + rejected_cmds: counters.rejected_cmds, + bytes_disk_to_host: counters.bytes_disk_to_host, + bytes_host_to_dev: counters.bytes_host_to_dev, + bytes_disk_to_dev: counters.bytes_disk_to_dev, + last_error: counters.last_error, } } } @@ -614,7 +733,6 @@ struct WorkerThreadArgs { driver: Arc, context: usize, copy_stream: usize, - signal_stream: usize, host_pool_ptr: usize, bounce_pool_ptr: usize, bounce_slot_bytes: u64, @@ -623,23 +741,62 @@ struct WorkerThreadArgs { stop_requested: Arc, atomic_state: Arc, io_backend: Box, + ready_tx: mpsc::SyncSender>, } -fn worker_main(mut args: WorkerThreadArgs) -> bool { +fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { let context = args.context as Handle; let copy_stream = args.copy_stream as Handle; - let signal_stream = args.signal_stream as Handle; let driver = &args.driver; // SAFETY: The worker binds the channel's CUDA context once for its entire lifetime. - if unsafe { (driver.context_set)(context) } != 0 { - return false; + if let Err(err) = driver.check( + "cuCtxSetCurrent(async_transfer_worker)", + unsafe { (driver.context_set)(context) }, + ) { + let _ = args.ready_tx.send(Err(err)); + return WorkerExit::StartupFailed(args.io_backend); + } + + let Some(host_comp_offset) = host_completions_offset(args.config.ring_capacity) else { + let _ = args.ready_tx.send(Err(Error::execution( + ExecutionError::Manifest, + "async transfer host completion table offset overflow", + ))); + return WorkerExit::StartupFailed(args.io_backend); + }; + + // Pre-create a bounded pool of CUDA events (CU_EVENT_DISABLE_TIMING = 0x2) before signaling + // readiness so DMA dispatch cannot silently stall with an empty event pool. + let mut free_events: Vec = Vec::with_capacity(DEFAULT_MAX_TOTAL_DMA); + for _ in 0..DEFAULT_MAX_TOTAL_DMA { + let mut ev = null_mut(); + let status = unsafe { (driver.event_create)(&mut ev, 0x2) }; + if let Err(err) = driver.check("cuEventCreate(async_transfer)", status) { + for created in free_events.drain(..) { + unsafe { + let _ = (driver.event_destroy)(created); + } + } + let _ = args.ready_tx.send(Err(err)); + return WorkerExit::StartupFailed(args.io_backend); + } + free_events.push(ev); } let header = unsafe { &*(args.config.control_address as *const ControlHeader) }; let ring_base = (args.config.control_address + HEADER_BYTES) as *const TransferCommand; let ring_mask = (args.config.ring_capacity as u64) - 1; - let host_comp_offset = host_completions_offset(args.config.ring_capacity).unwrap() as usize; - let host_comp_base = (args.config.control_address + host_comp_offset) as *const AtomicU64; + let host_comp_base = (args.config.control_address + host_comp_offset as usize) as *const AtomicU64; + let host_comp_gpu_base = if args.config.device_completions_base == 0 && args.use_write_value64 { + let mut gpu_ptr = 0u64; + if unsafe { (driver.host_device)(&mut gpu_ptr, host_comp_base as Handle, 0) } == 0 { + gpu_ptr + } else { + 0 + } + } else { + 0 + }; let mut scheduler = TransferScheduler::new( DEFAULT_MAX_TOTAL_IO, @@ -652,43 +809,62 @@ fn worker_main(mut args: WorkerThreadArgs) -> bool { header .worker_state .store(ChannelState::Running as u32, Ordering::Release); + args.atomic_state + .store(ChannelState::Running as u32, Ordering::Release); + let _ = args.ready_tx.send(Ok(())); - // Pre-create a bounded pool of CUDA events (CU_EVENT_DISABLE_TIMING = 0x2) to track - // Copy Engine completion for bounce-slot reclamation and non-WriteValue64 fallback. - let mut free_events: Vec = Vec::with_capacity(DEFAULT_MAX_TOTAL_DMA); - for _ in 0..DEFAULT_MAX_TOTAL_DMA { - let mut ev = null_mut(); - if unsafe { (driver.event_create)(&mut ev, 0x2) } == 0 { - free_events.push(ev); - } - } let mut pending_dma_events: VecDeque = VecDeque::with_capacity(DEFAULT_MAX_TOTAL_DMA); + let mut untracked_faulted_dmas: Vec = Vec::new(); + let mut leaked_events: Vec = Vec::new(); let mut io_completions: Vec = Vec::with_capacity(32); let mut head = header.cmd_head.load(Ordering::Relaxed); let mut idle_spins: u32 = 0; - let signal_completion_slot = |slot: u32, value: u64| { - // SAFETY: `slot < completion_slots` was validated before enqueue; `host_comp_base` is - // pinned mapped-host memory owned for the entire `NativeResources` lifetime. + let update_host_comp = |slot: u32, value: u64| { + // SAFETY: `slot < completion_slots` was validated before enqueue; `host_comp_base` stays + // mapped until `stop()` joins this thread and teardown runs `invalidate_control()`. unsafe { - (&*host_comp_base.add(slot as usize)).store(value, Ordering::Release); - if args.config.device_completions_base != 0 { - let dev_addr = args.config.device_completions_base + u64::from(slot) * 8; - if args.use_write_value64 { - let write_fn = driver.stream_write_value64.unwrap(); - let _ = write_fn( - signal_stream, - dev_addr, - value, - CU_STREAM_WRITE_VALUE_DEFAULT, - ); - } else { - let host_ptr = host_comp_base.add(slot as usize) as *const std::ffi::c_void; - let _ = (driver.upload_async)(dev_addr, host_ptr, 8, signal_stream); - } + update_host_completion(&*host_comp_base.add(slot as usize), value); + } + }; + + let signal_completion_slot = |slot: u32, value: u64| { + // All device completion writes serialize on `copy_stream` so DMA writes and host-initiated + // completions (`DiskToHost`, `CancelEpoch`, errors) never race across streams. + if args.config.device_completions_base != 0 { + update_host_comp(slot, value); + let dev_addr = args.config.device_completions_base + u64::from(slot) * 8; + let status = if args.use_write_value64 { + let write_fn = driver.stream_write_value64.unwrap(); + unsafe { write_fn(copy_stream, dev_addr, value, CU_STREAM_WRITE_VALUE_DEFAULT) } + } else { + let host_ptr = unsafe { host_comp_base.add(slot as usize) } as *const std::ffi::c_void; + unsafe { (driver.upload_async)(dev_addr, host_ptr, 8, copy_stream) } + }; + if status != 0 { + header + .last_error + .store(ErrorCode::CudaFailure as u32, Ordering::Release); + update_host_comp(slot, completion_error_sentinel(ErrorCode::CudaFailure)); } + } else if host_comp_gpu_base != 0 { + // When `device_completions_base == 0` with `cuStreamWriteValue64_v2`, route all + // writes to `host_comp` through `copy_stream` so DMA writes and host-side completions + // execute in strict FIFO order without CPU/Copy-Engine races. + let write_fn = driver.stream_write_value64.unwrap(); + let target_addr = host_comp_gpu_base + u64::from(slot) * 8; + let status = + unsafe { write_fn(copy_stream, target_addr, value, CU_STREAM_WRITE_VALUE_DEFAULT) }; + if status != 0 { + header + .last_error + .store(ErrorCode::CudaFailure as u32, Ordering::Release); + update_host_comp(slot, completion_error_sentinel(ErrorCode::CudaFailure)); + } + } else { + update_host_comp(slot, value); } }; @@ -715,7 +891,12 @@ fn worker_main(mut args: WorkerThreadArgs) -> bool { } if write_slot { if let Some(slot) = notice.completion_slot { - signal_completion_slot(slot, notice.signal_value); + let value = if notice.error == ErrorCode::Ok { + notice.signal_value + } else { + completion_error_sentinel(notice.error) + }; + signal_completion_slot(slot, value); } } }; @@ -817,29 +998,72 @@ fn worker_main(mut args: WorkerThreadArgs) -> bool { break; } let done = pending_dma_events.pop_front().unwrap(); - free_events.push(done.event); did_work = true; - let ok = status == 0; - match done.completion_action { - EventCompletionAction::None => {} - EventCompletionAction::HostOnly(slot, val) => { - // Device word was already written in-order via cuStreamWriteValue64_v2; - // mirror the host completion word idempotently so host consumers observe it too. - unsafe { - (&*host_comp_base.add(slot as usize)).store(val, Ordering::Release); + if status == 0 { + free_events.push(done.event); + if !done.failed { + match done.completion_action { + EventCompletionAction::None => {} + EventCompletionAction::HostOnly(slot, val) => { + // Device word was already written in-order via cuStreamWriteValue64_v2; + // advance the host mirror monotonically so slot reuse cannot regress it. + update_host_comp(slot, val); + } + EventCompletionAction::HostAndDevice(slot, val) => { + signal_completion_slot(slot, val); + } } + if let Some(notice) = scheduler.complete_dma(done.op_id, true) { + publish_notice(notice, false); + } + } else if let Some(notice) = scheduler.complete_dma(done.op_id, false) { + // `cuStreamWriteValue64_v2` failed after `cuMemcpyHtoDAsync_v2` succeeded; + // now that `ev` confirmed DMA completion, release the bounce slot and publish + // the explicit error sentinel. + publish_notice(notice, true); } - EventCompletionAction::HostAndDevice(slot, val) => { - signal_completion_slot(slot, val); + } else { + // 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); } + untracked_faulted_dmas.push(UntrackedFaultedDma { + op_id: done.op_id, + pending_notice: None, + }); } - if let Some(notice) = scheduler.complete_dma(done.op_id, ok) { - publish_notice(notice, false); + } + if !untracked_faulted_dmas.is_empty() { + let stream_status = unsafe { (driver.stream_query)(copy_stream) }; + 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() { + 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. + 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); + } + } } } // 5. Submit highest-priority eligible Copy Engine DMAs (DEMAND jumps ahead of background). - while !free_events.is_empty() { + // Pause new DMA submissions while any untracked partial-DMA failure awaits `copy_stream` drain. + while untracked_faulted_dmas.is_empty() && !free_events.is_empty() { let Some(dma) = scheduler.pop_next_dma() else { break; }; @@ -863,64 +1087,78 @@ fn worker_main(mut args: WorkerThreadArgs) -> bool { let copy_status = unsafe { (driver.upload_async)(dst_addr, src_ptr, dma.nbytes as usize, copy_stream) }; + if copy_status != 0 { + // `cuMemcpyHtoDAsync_v2` rejected submission; no Copy Engine DMA reads `src_ptr`, + // so recycling `ev` and the bounce slot immediately is safe. + free_events.push(ev); + if let Some(notice) = scheduler.complete_dma(dma.op_id, false) { + publish_notice(notice, true); + } + continue; + } + let mut completion_action = EventCompletionAction::None; let mut signal_status = 0; - if copy_status == 0 { - if let Some(slot) = dma.completion_slot { - if args.use_write_value64 { - let writes_device_word = args.config.device_completions_base != 0; - let target_addr = if writes_device_word { - args.config.device_completions_base + u64::from(slot) * 8 - } else { - // Mapped host completion word address equals host pointer under UVA. - let mut gpu_ptr = 0u64; - let host_ptr = unsafe { host_comp_base.add(slot as usize) } as Handle; - if unsafe { (driver.host_device)(&mut gpu_ptr, host_ptr, 0) } == 0 { - gpu_ptr - } else { - 0 - } + if let Some(slot) = dma.completion_slot { + if args.use_write_value64 { + let writes_device_word = args.config.device_completions_base != 0; + let target_addr = if writes_device_word { + args.config.device_completions_base + u64::from(slot) * 8 + } else { + host_comp_gpu_base + .checked_add(u64::from(slot) * 8) + .filter(|_| host_comp_gpu_base != 0) + .unwrap_or(0) + }; + if target_addr != 0 { + let write_fn = driver.stream_write_value64.unwrap(); + signal_status = unsafe { + write_fn( + copy_stream, + target_addr, + dma.signal_value, + CU_STREAM_WRITE_VALUE_DEFAULT, + ) }; - if target_addr != 0 { - let write_fn = driver.stream_write_value64.unwrap(); - signal_status = unsafe { - write_fn( - copy_stream, - target_addr, - dma.signal_value, - CU_STREAM_WRITE_VALUE_DEFAULT, - ) - }; - if signal_status == 0 && writes_device_word { - completion_action = - EventCompletionAction::HostOnly(slot, dma.signal_value); - } - } else { + if signal_status == 0 && writes_device_word { completion_action = - EventCompletionAction::HostAndDevice(slot, dma.signal_value); + EventCompletionAction::HostOnly(slot, dma.signal_value); } } else { completion_action = EventCompletionAction::HostAndDevice(slot, dma.signal_value); } + } else { + completion_action = + EventCompletionAction::HostAndDevice(slot, dma.signal_value); } } - let rec_status = if copy_status == 0 && signal_status == 0 { - unsafe { (driver.event_record)(ev, copy_stream) } - } else { - -1 - }; - if copy_status == 0 && signal_status == 0 && rec_status == 0 { + + // Always record `ev` on `copy_stream` after a successful `cuMemcpyHtoDAsync_v2` even + // when `signal_status != 0` so bounce-slot reclamation waits for hardware DMA finish. + let rec_status = unsafe { (driver.event_record)(ev, copy_stream) }; + if rec_status == 0 { pending_dma_events.push_back(PendingEventDma { op_id: dma.op_id, event: ev, - completion_action, + failed: signal_status != 0, + completion_action: if signal_status == 0 { + completion_action + } else { + EventCompletionAction::None + }, }); } else { + // `cuEventRecord` failed while Copy Engine DMA is still in flight on `copy_stream`. + // Retain `dma` and its bounce slot in `scheduler.inflight_dma` until `copy_stream` + // confirms drain (or permanently into `FailedDrain`). free_events.push(ev); - if let Some(notice) = scheduler.complete_dma(dma.op_id, false) { - publish_notice(notice, true); - } + let pending_notice = scheduler.mark_dma_faulted(dma.op_id); + untracked_faulted_dmas.push(UntrackedFaultedDma { + op_id: dma.op_id, + pending_notice, + }); + break; } } @@ -1007,33 +1245,38 @@ fn worker_main(mut args: WorkerThreadArgs) -> bool { let mut stream_drained = false; loop { let copy_status = unsafe { (driver.stream_query)(copy_stream) }; - let sig_status = unsafe { (driver.stream_query)(signal_stream) }; - if copy_status == 0 && sig_status == 0 { + if copy_status == 0 { stream_drained = true; break; } - let copy_ok = copy_status == 0 || copy_status == CUDA_ERROR_NOT_READY; - let sig_ok = sig_status == 0 || sig_status == CUDA_ERROR_NOT_READY; - if !copy_ok || !sig_ok || Instant::now() >= deadline { + if copy_status != CUDA_ERROR_NOT_READY || Instant::now() >= deadline { break; } thread::sleep(Duration::from_millis(1)); } if stream_drained { while let Some(done) = pending_dma_events.pop_front() { - let _ = scheduler.complete_dma(done.op_id, true); + let _ = scheduler.complete_dma(done.op_id, !done.failed); free_events.push(done.event); } - for ev in free_events.drain(..) { + for item in untracked_faulted_dmas.drain(..) { + let _ = scheduler.complete_dma(item.op_id, false); + } + for ev in free_events.drain(..).chain(leaked_events.drain(..)) { unsafe { let _ = (driver.event_destroy)(ev); } } } + if !io_drained { + // Retain the storage backend handle until process exit so dropping `IoUring` cannot block + // thread join on uninterruptible kernel I/O after `DRAIN_TIMEOUT` already expired. + std::mem::forget(args.io_backend); + } let ok = scheduler.finish_drain(io_drained && stream_drained).is_ok(); sync_telemetry(&scheduler); - ok + WorkerExit::Drained(ok) } #[cfg(test)] @@ -1257,6 +1500,11 @@ mod cuda_tests { assert_ne!(header.flags & FLAG_STREAM_WRITE_VALUE64, 0); rt.start().unwrap(); + // Startup readiness barrier guarantees worker_state == Running immediately on return. + assert_eq!( + header.worker_state.load(Ordering::Acquire), + ChannelState::Running as u32 + ); // DISK_TO_HOST extent 1 -> host_offset 0. push_cmd( @@ -1378,10 +1626,30 @@ mod cuda_tests { wait_host_comp(ctrl_ptr as usize, 3, 5005); wait_dev_comp(3, 5005); + // Reuse completion slot 1 immediately across HostToDev (2002) -> DiskToHost (2010) + // so single-stream ordering and monotonic host_comp fetch_max are exercised live. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::DiskToHost as u32, + priority: Priority::Demand as u32, + extent_id: 0, + completion_slot: 1, + host_offset: 2 * extent_bytes as u64, + device_offset: 0, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 2010, + _reserved: 0, + }, + ); + wait_host_comp(ctrl_ptr as usize, 1, 2010); + wait_dev_comp(1, 2010); + let snap = rt.snapshot(); assert_eq!(snap.rejected_cmds, 1); assert_eq!(snap.last_error, ErrorCode::ExtentOutOfRange as u32); - assert_eq!(snap.bytes_disk_to_host, extent_bytes as u64); + assert_eq!(snap.bytes_disk_to_host, 2 * extent_bytes as u64); assert_eq!(snap.bytes_host_to_dev, extent_bytes as u64); assert_eq!(snap.bytes_disk_to_dev, extent_bytes as u64); @@ -1390,13 +1658,22 @@ mod cuda_tests { assert_eq!(header.active_inflight.load(Ordering::Acquire), 0); } - // 2. Test RAM=0 fused DISK_TO_DEV using internal pinned bounce pool (BOUNCE_HOST_OFFSET). - { + // 2. Test RAM=0 fused DISK_TO_DEV using internal pinned bounce pool (BOUNCE_HOST_OFFSET), + // verify explicit IoFailure completion sentinel instead of success cookie, and verify + // `invalidate_control()` prevents UAF when `snapshot()` is called after munmap. + let retained_rt = { unsafe { driver .check("cuMemsetD8_v2(comp)", (driver.zero)(dev_comp, 0, completion_slots as usize * 8)) .unwrap(); } + let mut extents_with_eof = extents.clone(); + // Extent 4 points past end-of-file so io_uring / pread reports short read (IoFailure). + extents_with_eof.push(ExtentEntry { + file_index: 0, + offset: 8 * extent_bytes as u64, + nbytes: extent_bytes as u64, + }); let cfg = ChannelConfig { name: "cuda-ram0-bounce".into(), device_pool_base: dev_pool, @@ -1408,7 +1685,7 @@ mod cuda_tests { completion_slots, ring_capacity, alignment: 4096, - extents: extents.clone(), + extents: extents_with_eof, }; let rt = unsafe { AsyncTransferRuntime::new( @@ -1422,6 +1699,11 @@ mod cuda_tests { }; assert_eq!(rt.host_pool_bytes(), 0); rt.start().unwrap(); + let header = unsafe { &*(ctrl_ptr as *const ControlHeader) }; + assert_eq!( + header.worker_state.load(Ordering::Acquire), + ChannelState::Running as u32 + ); push_cmd( ctrl_ptr as usize, @@ -1455,11 +1737,34 @@ mod cuda_tests { .unwrap(); } assert_eq!(readback, patterns[3]); + + // Trigger a real IoFailure on extent 4: both host and device completion slots must + // observe `completion_error_sentinel(IoFailure)`, never the requested cookie `7777`. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::DiskToDev as u32, + priority: Priority::Demand as u32, + extent_id: 4, + completion_slot: 5, + host_offset: BOUNCE_HOST_OFFSET, + device_offset: 0, + nbytes: extent_bytes as u64, + epoch: 1, + signal_value: 7777, + _reserved: 0, + }, + ); + let io_err_sentinel = completion_error_sentinel(ErrorCode::IoFailure); + wait_host_comp(ctrl_ptr as usize, 5, io_err_sentinel); + wait_dev_comp(5, io_err_sentinel); + rt.stop().unwrap(); assert_eq!(rt.state(), ChannelState::Stopped); - let header = unsafe { &*(ctrl_ptr as *const ControlHeader) }; assert_eq!(header.active_inflight.load(Ordering::Acquire), 0); - } + rt.invalidate_control(); + rt + }; unsafe { let _ = (driver.host_unregister)(ctrl_ptr); @@ -1468,6 +1773,13 @@ mod cuda_tests { let _ = (driver.free)(dev_pool); let _ = (driver.context_destroy)(context); } + // Calling `snapshot()` after `munmap` must return captured final counters without UAF. + let post_unmap = retained_rt.snapshot(); + assert_eq!(post_unmap.state, ChannelState::Stopped); + assert_eq!(post_unmap.bytes_disk_to_dev, extent_bytes as u64); + assert_eq!(post_unmap.completed_cmds, 2); + assert_eq!(post_unmap.last_error, ErrorCode::IoFailure as u32); + drop(retained_rt); let _ = std::fs::remove_dir_all(&dir); } } @@ -1499,4 +1811,66 @@ mod unit_tests { assert_eq!(bounce_pool_geometry(4096, 0), (0, 0)); assert_eq!(bounce_pool_geometry(4096, 6000), (0, 0)); } + + #[test] + fn update_host_completion_is_monotonic_and_preserves_error_sentinels() { + let slot = AtomicU64::new(0); + update_host_completion(&slot, 20); + assert_eq!(slot.load(Ordering::Acquire), 20); + // Deferred older DMA host mirror must not regress slot backwards on reuse. + update_host_completion(&slot, 10); + assert_eq!(slot.load(Ordering::Acquire), 20); + // Error sentinel (bit 63 set) dominates all valid caller cookies and stays sticky. + let sentinel = completion_error_sentinel(ErrorCode::CudaFailure); + update_host_completion(&slot, sentinel); + assert_eq!(slot.load(Ordering::Acquire), sentinel); + update_host_completion(&slot, 999_999); + assert_eq!(slot.load(Ordering::Acquire), sentinel); + } + + #[cfg(unix)] + #[test] + fn control_region_guard_preserves_counters_and_avoids_uaf_after_munmap() { + let len = 4096usize; + let ptr = unsafe { + libc::mmap( + null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + assert_ne!(ptr, libc::MAP_FAILED); + unsafe { + let header = &*(ptr as *const ControlHeader); + header.submitted_cmds.store(12, Ordering::Relaxed); + header.completed_cmds.store(11, Ordering::Relaxed); + header.canceled_cmds.store(1, Ordering::Relaxed); + header.rejected_cmds.store(2, Ordering::Relaxed); + header.bytes_disk_to_host.store(4096, Ordering::Relaxed); + header.bytes_host_to_dev.store(8192, Ordering::Relaxed); + header.bytes_disk_to_dev.store(16384, Ordering::Relaxed); + header + .last_error + .store(ErrorCode::IoFailure as u32, Ordering::Relaxed); + } + let guard = ControlRegionGuard::new(ptr as usize); + assert!(guard.is_live()); + let live_counters = guard.read_counters(); + assert_eq!(live_counters.submitted_cmds, 12); + assert_eq!(live_counters.bytes_disk_to_dev, 16384); + assert_eq!(live_counters.last_error, ErrorCode::IoFailure as u32); + + guard.invalidate(); + assert!(!guard.is_live()); + assert_eq!(unsafe { libc::munmap(ptr, len) }, 0); + + // Post-munmap reads and worker_state stores must not touch unmapped memory. + assert_eq!(guard.read_counters(), live_counters); + guard.store_worker_state(ChannelState::Stopped); + guard.invalidate(); + assert_eq!(guard.read_counters(), live_counters); + } } diff --git a/helios/src/execution/rendezvous.rs b/helios/src/execution/rendezvous.rs index c58e1de8c..a520f8c9f 100644 --- a/helios/src/execution/rendezvous.rs +++ b/helios/src/execution/rendezvous.rs @@ -269,6 +269,56 @@ pub fn propose_capacity(stream: &mut RankStream, local: (u64, u64)) -> Result<(u Ok(agreed) } +fn encode_device_pools(pools: &[u64]) -> Vec { + let mut bytes = Vec::with_capacity(pools.len() * 8); + for &size in pools { + bytes.extend_from_slice(&size.to_le_bytes()); + } + bytes +} + +fn decode_device_pools(bytes: &[u8], expected_len: usize) -> Result> { + let expected_bytes = expected_len + .checked_mul(8) + .ok_or_else(|| failure("rendezvous device pool count overflow"))?; + if bytes.len() != expected_bytes { + return Err(failure("rendezvous device pool sizes are malformed")); + } + Ok(bytes + .chunks_exact(8) + .map(|chunk| u64::from_le_bytes(chunk.try_into().unwrap())) + .collect()) +} + +/// Rank zero: agree on the elementwise minimum byte size of every runtime-sized `DEVICE_POOL` +/// allocation across all ranks, then broadcast the agreed vector to each peer. +pub fn agree_device_pools(peers: &mut [RankStream], local: &[u64]) -> Result> { + let mut agreed = local.to_vec(); + for peer in peers.iter_mut() { + let remote = decode_device_pools(&read_frame(peer)?, local.len())?; + for (dst, src) in agreed.iter_mut().zip(remote) { + *dst = (*dst).min(src); + } + } + let encoded = encode_device_pools(&agreed); + for peer in peers.iter_mut() { + write_frame(peer, &encoded)?; + } + Ok(agreed) +} + +/// A peer: propose this rank's local `DEVICE_POOL` sizes and receive the cluster-wide minimum. +pub fn propose_device_pools(stream: &mut RankStream, local: &[u64]) -> Result> { + write_frame(stream, &encode_device_pools(local))?; + let agreed = decode_device_pools(&read_frame(stream)?, local.len())?; + if agreed.iter().zip(local).any(|(&a, &l)| a > l) { + return Err(failure( + "rank zero agreed on a larger device pool than this rank can back", + )); + } + Ok(agreed) +} + /// Rank zero: collect every peer's transport record and send all of them, in rank order, to each. pub fn share_records(peers: &mut [RankStream], local: Vec) -> Result>> { let mut records = vec![local]; @@ -497,4 +547,46 @@ mod tests { .expect("stalled peer must time out instead of hanging"); assert!(error.to_string().contains("rendezvous read failed"), "{error}"); } + + #[test] + fn device_pools_agree_on_elementwise_minimum_and_reject_oversize_or_mismatch() { + use super::super::rank_stream::test_pair; + + // 3-rank agreement takes elementwise minimum across all pools, including zero sizes. + let (r0_p1, mut p1) = test_pair().unwrap(); + let (r0_p2, mut p2) = test_pair().unwrap(); + let mut peers = vec![r0_p1, r0_p2]; + let zero = std::thread::spawn(move || { + agree_device_pools(&mut peers, &[64 << 30, 8 << 30, 0]).unwrap() + }); + let h1 = std::thread::spawn(move || { + propose_device_pools(&mut p1, &[48 << 30, 12 << 30, 4 << 30]).unwrap() + }); + let h2 = std::thread::spawn(move || { + propose_device_pools(&mut p2, &[56 << 30, 6 << 30, 0]).unwrap() + }); + let expected = vec![48 << 30, 6 << 30, 0]; + assert_eq!(zero.join().unwrap(), expected); + assert_eq!(h1.join().unwrap(), expected); + assert_eq!(h2.join().unwrap(), expected); + + // Peer rejects rank-zero answer exceeding what the peer proposed. + let (mut root, mut peer) = test_pair().unwrap(); + let sender = std::thread::spawn(move || { + let _ = read_frame(&mut root).unwrap(); + write_frame(&mut root, &encode_device_pools(&[64 << 30])).unwrap(); + }); + let err = propose_device_pools(&mut peer, &[32 << 30]).unwrap_err(); + assert!(err.to_string().contains("larger device pool"), "{err}"); + sender.join().unwrap(); + + // Rank zero rejects mismatched pool vector length. + let (mut root, mut peer) = test_pair().unwrap(); + let sender = std::thread::spawn(move || { + write_frame(&mut peer, &encode_device_pools(&[16 << 30, 8 << 30])).unwrap(); + }); + let err = agree_device_pools(std::slice::from_mut(&mut root), &[16 << 30]).unwrap_err(); + assert!(err.to_string().contains("malformed"), "{err}"); + sender.join().unwrap(); + } } diff --git a/helios/src/runtime_core/cache_memory.rs b/helios/src/runtime_core/cache_memory.rs index 4f4052522..9ba82a9c3 100644 --- a/helios/src/runtime_core/cache_memory.rs +++ b/helios/src/runtime_core/cache_memory.rs @@ -1667,6 +1667,7 @@ mod tests { execution: None, context: Context::default(), allocations: vec![], + external_extents: vec![], }; let mut owner = NativeResources::initialize(&core, 0).unwrap(); let properties = AllocationProperties { diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index 604278299..c1a46ae0e 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -34,43 +34,89 @@ pub(super) struct PlannedHostBudgets { pub async_transfer_host_caps: Vec, } -/// Per-rank `(available, total)` host RAM for sizing pinned `AsyncTransfer` host pools. -fn async_transfer_host_ram(local_ranks: usize) -> (u64, u64) { - let local_ranks = local_ranks.max(1) as u64; +/// Per-rank `(available, total)` host RAM for sizing discrete-GPU pinned `AsyncTransfer` host +/// pools after reserving `host_future` bytes for prefix-cache offload and vision input windows. +fn async_transfer_host_ram(discrete_ranks: usize, host_future: u64) -> (u64, u64) { + let discrete_ranks = discrete_ranks.max(1) as u64; let (host_available, host_total) = - flare_selene::offload::host_pool_budget_and_total(0).unwrap_or((0, 0)); - (host_available / local_ranks, host_total / local_ranks) + flare_selene::offload::host_pool_budget_and_total(host_future).unwrap_or((0, 0)); + (host_available / discrete_ranks, host_total / discrete_ranks) } -/// Compute `(device_reserve_bytes, planned_host_cap_bytes)` for one rank's declared -/// `Execution.async_transfers` channels. +/// Per-rank memory reservations planned for declared `Execution.async_transfers` channels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct AsyncTransferBudget { + /// Bytes deducted from the rank's device (or unified DRAM) cache budget before sizing + /// `DEVICE_POOL` and KV caches. + device_reserve: u64, + /// Host RAM (or unified DRAM) bytes reserved for `prepare_async_transfers` so prefix-cache + /// offload and capture sizing do not double-spend the same physical memory. + host_reserve: u64, + /// Host-pool ceiling forwarded to `NativeResources::prepare_async_transfers`. + host_cap: u64, +} + +/// Compute device and host reservations for one rank's declared `Execution.async_transfers` +/// channels. /// -/// Registering pinned host memory with `cuMemHostRegister_v2` consumes 2 MiB of device -/// VRAM per GiB (`bytes / 512`) for GPU MMU page tables. Returning `planned_host_cap_bytes` -/// allows `prepare_async_transfers` to clamp its host-pool allocation to the exact ceiling -/// whose device page-table cost was reserved before sizing `DEVICE_POOL` and KV caches. +/// Registering pinned host memory with `cuMemHostRegister_v2` consumes 2 MiB of device VRAM per +/// GiB (`bytes / 512`) for GPU MMU page tables. On discrete GPUs, `device_reserve` accounts for +/// those page tables plus [`ASYNC_TRANSFER_DEVICE_MARGIN_BYTES`], while `host_reserve` accounts +/// for `HOST_POOL + bounce_pool` in host RAM (coordinated against `host_future`). On integrated +/// (unified-DRAM) GPUs such as GB10 and Jetson, `HOST_POOL`, `bounce_pool`, `DEVICE_POOL`, and KV +/// caches share one physical DRAM pool: `HOST_POOL` defaults to 0 unless `--pool-ram-memory` is +/// explicitly specified, explicit requests are bounded so `host_pool + bounce + page_tables + +/// margin <= host_ram_available`, and `device_reserve` deducts the full `host_pool + bounce_pool +/// + page_tables + margin` from the unified DRAM budget. fn async_transfer_device_reserve( core: &Core, host_ram_available: u64, host_ram_total: u64, pool_ram_limit: Option, -) -> (u64, u64) { + integrated: bool, +) -> AsyncTransferBudget { let Some(channels) = core .execution .as_ref() .map(|exec| exec.async_transfers.as_slice()) .filter(|channels| !channels.is_empty()) else { - return (0, 0); + return AsyncTransferBudget { + device_reserve: 0, + host_reserve: 0, + host_cap: 0, + }; }; - let cap = match pool_ram_limit { - Some(limit) => limit - .cap_bytes(host_ram_available, host_ram_total) - .min(host_ram_available), - None => host_ram_available, + let total_bounce = channels.iter().fold(0u64, |acc, channel| { + acc.saturating_add(crate::async_transfer::worker::max_bounce_pool_bytes( + channel.alignment, + )) + }); + let cap = if integrated { + match pool_ram_limit { + None => 0, + Some(limit) => { + let fixed_cost = total_bounce + .saturating_add(total_bounce.div_ceil(512)) + .saturating_add(ASYNC_TRANSFER_DEVICE_MARGIN_BYTES); + let max_host_dram = host_ram_available.saturating_sub(fixed_cost); + let max_host_pool = ((u128::from(max_host_dram) * 512) / 513) as u64; + limit + .cap_bytes(host_ram_available, host_ram_total) + .min(max_host_pool) + } + } + } else { + let max_host_pool = host_ram_available.saturating_sub(total_bounce); + match pool_ram_limit { + Some(limit) => limit + .cap_bytes(host_ram_available, host_ram_total) + .min(max_host_pool), + None => max_host_pool, + } }; let mut remaining = cap; - let mut pinned = 0u64; + let mut host_pools = 0u64; for channel in channels { let host_pool = crate::async_transfer::resolve_pool_bytes( remaining, @@ -79,17 +125,47 @@ fn async_transfer_device_reserve( 2 << 20, ); remaining = remaining.saturating_sub(host_pool); - pinned = pinned - .saturating_add(host_pool) - .saturating_add(crate::async_transfer::worker::max_bounce_pool_bytes( - channel.alignment, - )); + host_pools = host_pools.saturating_add(host_pool); } + let pinned = host_pools.saturating_add(total_bounce); let page_tables = pinned.div_ceil(512); - ( - page_tables.saturating_add(ASYNC_TRANSFER_DEVICE_MARGIN_BYTES), - cap, - ) + let device_reserve = if integrated { + pinned + .saturating_add(page_tables) + .saturating_add(ASYNC_TRANSFER_DEVICE_MARGIN_BYTES) + } else { + page_tables.saturating_add(ASYNC_TRANSFER_DEVICE_MARGIN_BYTES) + }; + let host_reserve = if integrated { device_reserve } else { pinned }; + AsyncTransferBudget { + device_reserve, + host_reserve, + host_cap: cap, + } +} + +/// Validate cluster-agreed `DEVICE_POOL` byte sizes against local proposals and alignments. +fn validate_agreed_device_pools( + agreed: &[u64], + local: &[u64], + alignments: &[u64], +) -> Result<()> { + if agreed.len() != local.len() || agreed.len() != alignments.len() { + return Err(invalid( + "ranks agreed on a different number of device pools than this rank declared", + )); + } + for ((&chosen, &max_local), &align) in agreed.iter().zip(local).zip(alignments) { + if chosen > max_local { + return Err(invalid( + "ranks agreed on a device pool size this rank cannot back", + )); + } + if align == 0 || chosen % align != 0 { + return Err(invalid("ranks agreed on an unaligned device pool size")); + } + } + Ok(()) } // A GPU that allocates from system memory (GB10, GA10B) shares it with the operating system and // with the server's host allocations made after sizing: frontend workers, tokenizers and request @@ -1121,50 +1197,84 @@ impl NativeModel { } } } - // Reserve per-rank device memory for `Prepare async transfers` (GPU MMU page tables for - // CUDA-registered pinned host and bounce pools plus Copy Engine/signal/replay stream - // headroom) before sizing `DEVICE_POOL` and KV caches so `Start server` cannot OOM. + // Reserve per-rank memory for `Prepare async transfers` (GPU MMU page tables and streams + // on discrete GPUs; full `HOST_POOL + bounce_pool + page_tables + margin` on unified-DRAM + // integrated GPUs, coordinated with `host_future` / prefix-cache offload) before sizing + // `DEVICE_POOL` and KV caches so `Start server` cannot OOM. let has_async_transfers = cores.iter().any(|core| { core.execution .as_ref() .is_some_and(|exec| !exec.async_transfers.is_empty()) }); + let mut device_pool_names: Vec = cores[0] + .allocations + .iter() + .filter(|a| a.sizing.as_ref().is_some_and(|s| s.capacity == 2)) + .map(|a| a.name.clone()) + .collect(); + device_pool_names.sort(); + let min_kv_reserve = if has_async_transfers || !device_pool_names.is_empty() { + let execution_rows = 1 + active as u64 * width; + let mut reserve_vec = Vec::with_capacity(cores.len()); + for core in cores.iter() { + let req = row_backing_bytes(core, execution_rows)? + .checked_add(bytes(core, 1, minimum_pages)?) + .ok_or_else(|| invalid("minimum cache footprint overflow"))?; + reserve_vec.push(req); + } + reserve_vec + } else { + Vec::new() + }; + let mut async_transfer_host_total = 0u64; let async_transfer_host_caps = if has_async_transfers { - let (per_rank_avail, per_rank_total) = async_transfer_host_ram(self.ranks.len()); + let discrete_ranks = self.ranks.iter().filter(|r| !r.integrated).count(); + let (discrete_avail, discrete_total) = if discrete_ranks > 0 { + async_transfer_host_ram(discrete_ranks, host_future) + } else { + (0, 0) + }; let mut caps = Vec::with_capacity(cores.len()); - for (avail, core) in available.iter_mut().zip(cores.iter()) { - let (device_reserve, host_cap) = async_transfer_device_reserve( + for (idx, ((avail, rank), core)) in available + .iter_mut() + .zip(&self.ranks) + .zip(cores.iter()) + .enumerate() + { + let (ram_avail, ram_total) = if rank.integrated { + ( + avail.saturating_sub(min_kv_reserve[idx]), + observations[idx].total, + ) + } else { + (discrete_avail, discrete_total) + }; + let planned = async_transfer_device_reserve( core, - per_rank_avail, - per_rank_total, + ram_avail, + ram_total, options.pool_ram_limit, + rank.integrated, ); - *avail = avail.saturating_sub(device_reserve); - caps.push(host_cap); + *avail = avail.saturating_sub(planned.device_reserve); + async_transfer_host_total = + async_transfer_host_total.saturating_add(planned.host_reserve); + caps.push(planned.host_cap); } caps } else { vec![0; cores.len()] }; - // Size and map any `Capacity::DEVICE_POOL` allocations before choosing KV page count, - // leaving room for execution state rows and minimum KV cache capacity. - let device_pool_names: Vec = cores[0] - .allocations - .iter() - .filter(|a| a.sizing.as_ref().is_some_and(|s| s.capacity == 2)) - .map(|a| a.name.clone()) - .collect(); + // Size, agree cluster-wide, and map any `Capacity::DEVICE_POOL` allocations before + // choosing KV page count, leaving room for execution state rows and minimum KV cache. + let mut device_pool_integrated_bytes = 0u64; if !device_pool_names.is_empty() { - let execution_rows = 1 + active as u64 * width; - let mut min_kv_reserve = Vec::with_capacity(cores.len()); - for core in cores.iter() { - let req = bytes(core, 0, execution_rows)? - .checked_add(bytes(core, 1, minimum_pages)?) - .ok_or_else(|| invalid("minimum cache footprint overflow"))?; - min_kv_reserve.push(req); - } + let mut remaining_for_pools = available.clone(); + let mut local_pools = Vec::with_capacity(device_pool_names.len()); + let mut pool_alignments = Vec::with_capacity(device_pool_names.len()); for pool_name in &device_pool_names { - let mut agreed_bytes = u64::MAX; + let mut local_min = u64::MAX; + let mut pool_align = 0u64; for (idx, core) in cores.iter().enumerate() { let alloc = core .allocations @@ -1176,7 +1286,16 @@ impl NativeModel { .unit_bytes .checked_mul(sizing.maximum) .ok_or_else(|| invalid("device pool extent overflow"))?; - let avail_for_pool = available[idx].saturating_sub(min_kv_reserve[idx]); + let align = alloc.alignment as u64; + if pool_align == 0 { + pool_align = align; + } else if pool_align != align { + return Err(invalid( + "ranks disagree on device pool allocation alignment", + )); + } + let avail_for_pool = + remaining_for_pools[idx].saturating_sub(min_kv_reserve[idx]); let cap = options .pool_vram_limit .map(|limit| limit.cap_bytes(avail_for_pool, observations[idx].total)); @@ -1184,13 +1303,22 @@ impl NativeModel { avail_for_pool, cap, max_pool, - alloc.alignment as u64, + align, ); - agreed_bytes = agreed_bytes.min(chosen); + local_min = local_min.min(chosen); + } + if local_min == u64::MAX { + local_min = 0; } - if agreed_bytes == u64::MAX { - agreed_bytes = 0; + for rem in &mut remaining_for_pools { + *rem = rem.saturating_sub(local_min); } + local_pools.push(local_min); + pool_alignments.push(pool_align); + } + let agreed_pools = agree.device_pools(&local_pools)?; + validate_agreed_device_pools(&agreed_pools, &local_pools, &pool_alignments)?; + for (pool_name, agreed_bytes) in device_pool_names.iter().zip(agreed_pools) { let mapped_usize = usize::try_from(agreed_bytes) .map_err(|_| invalid("device pool size exceeds usize"))?; for (idx, (rank, core)) in self.ranks.iter_mut().zip(cores.iter_mut()).enumerate() { @@ -1215,12 +1343,21 @@ impl NativeModel { } } available[idx] = available[idx].saturating_sub(agreed_bytes); + if rank.integrated { + device_pool_integrated_bytes = + device_pool_integrated_bytes.saturating_add(agreed_bytes); + } } } } let capture_layout = capture.then(|| flare_selene::Layout::new(&geometry)).transpose()?; let host_growth = if capture { - host_budget_for(host_future.saturating_add(pool_host_charge))? + host_budget_for( + host_future + .saturating_add(pool_host_charge) + .saturating_add(async_transfer_host_total) + .saturating_add(device_pool_integrated_bytes), + )? } else { 0 }; @@ -2404,7 +2541,14 @@ mod tests { let mut p = core(65536, 32768, 1024); // No async transfer channels -> zero device reserve and zero host cap. - assert_eq!(async_transfer_device_reserve(&p, 256 * gib, 512 * gib, None), (0, 0)); + assert_eq!( + async_transfer_device_reserve(&p, 256 * gib, 512 * gib, None, false), + AsyncTransferBudget { + device_reserve: 0, + host_reserve: 0, + host_cap: 0, + } + ); let channel = |name: &str, max_host: u64, alignment: u32| AsyncTransfer { name: name.into(), @@ -2421,63 +2565,176 @@ mod tests { }); // 160 GiB pinned host pool consumes 320 MiB of GPU MMU page tables plus bounce + base margin. - let (dev_160, cap_160) = async_transfer_device_reserve( + let b160 = async_transfer_device_reserve( &p, 200 * gib, 256 * gib, Some(PoolMemoryLimit(MemoryLimit::Bytes(160 * gib))), + false, ); - assert_eq!(cap_160, 160 * gib); + assert_eq!(b160.host_cap, 160 * gib); + assert_eq!(b160.host_reserve, 160 * gib + bounce); assert_eq!( - dev_160, + b160.device_reserve, (160 * gib + bounce).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES ); - assert!(dev_160 > 576 * mib); + assert!(b160.device_reserve > 576 * mib); // Zero host pool still reserves bounce-pool page tables plus base stream margin. - let (dev_0, cap_0) = async_transfer_device_reserve( + let b0 = async_transfer_device_reserve( &p, 200 * gib, 256 * gib, Some(PoolMemoryLimit(MemoryLimit::Bytes(0))), + false, ); - assert_eq!(cap_0, 0); + assert_eq!(b0.host_cap, 0); + assert_eq!(b0.host_reserve, bounce); assert_eq!( - dev_0, + b0.device_reserve, bounce.div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES ); // Negative RAM reserve reduces the planned host cap without double-subtracting. - let (dev_res, cap_res) = async_transfer_device_reserve( + let bres = async_transfer_device_reserve( &p, 100 * gib, 256 * gib, Some(PoolMemoryLimit(MemoryLimit::Reserve(20 * gib))), + false, ); - assert_eq!(cap_res, 80 * gib); + assert_eq!(bres.host_cap, 80 * gib); assert_eq!( - dev_res, + bres.device_reserve, (80 * gib + bounce).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES ); // Large alignment (> 32 MiB) disables bounce staging, so reserve charges zero bounce bytes. p.execution.as_mut().unwrap().async_transfers[0].alignment = 64 << 20; - let (dev_big_align, _) = async_transfer_device_reserve( + let b_align = async_transfer_device_reserve( &p, 200 * gib, 256 * gib, Some(PoolMemoryLimit(MemoryLimit::Bytes(0))), + false, ); - assert_eq!(dev_big_align, ASYNC_TRANSFER_DEVICE_MARGIN_BYTES); + assert_eq!(b_align.device_reserve, ASYNC_TRANSFER_DEVICE_MARGIN_BYTES); + assert_eq!(b_align.host_reserve, 0); - // Large host (512 GiB channel on 1 TiB host) scales GPU page-table reserve linearly. + // Large host (512 GiB channel on 1 TiB host) scales GPU page-table reserve linearly + // and leaves bounce-pool headroom in host RAM. p.execution.as_mut().unwrap().async_transfers[0].alignment = 4096; p.execution.as_mut().unwrap().async_transfers[0].max_host_pool_bytes = 512 * gib; - let (dev_512, cap_512) = async_transfer_device_reserve(&p, 700 * gib, 1024 * gib, None); - assert_eq!(cap_512, 700 * gib); + let b512 = async_transfer_device_reserve(&p, 700 * gib, 1024 * gib, None, false); + assert_eq!(b512.host_cap, 700 * gib - bounce); + assert_eq!(b512.host_reserve, 512 * gib + bounce); assert_eq!( - dev_512, + b512.device_reserve, (512 * gib + bounce).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES ); + + // Discrete GPU with tight host RAM reserves bounce pool first so host_pool + bounce <= avail. + let b_tight = async_transfer_device_reserve(&p, 2 * gib, 64 * gib, None, false); + assert!(b_tight.host_reserve <= 2 * gib); + assert_eq!(b_tight.host_cap, 2 * gib - bounce); + } + + #[test] + fn integrated_async_transfer_deducts_full_unified_dram_and_avoids_double_spend() { + use super::super::{ + MemoryLimit, PoolMemoryLimit, + protobuf::wire::{AsyncTransfer, Execution}, + }; + + let gib = 1u64 << 30; + let bounce = crate::async_transfer::worker::max_bounce_pool_bytes(4096); + let mut p = core(65536, 32768, 1024); + p.execution = Some(Execution { + async_transfers: vec![AsyncTransfer { + name: "experts".into(), + device_pool: "pool".into(), + completion_slots: 64, + ring_capacity: 64, + alignment: 4096, + max_host_pool_bytes: 160 * gib, + ..Default::default() + }], + ..Default::default() + }); + + // On GB10/Jetson (integrated == true) with no explicit --pool-ram-memory, HOST_POOL + // defaults to 0 so unified DRAM goes to direct DEVICE_POOL + KV cache, while full bounce + // pool + page tables + stream margin is deducted from unified DRAM. + let avail_above_kv = 76 * gib; + let default_gb10 = + async_transfer_device_reserve(&p, avail_above_kv, 128 * gib, None, true); + assert_eq!(default_gb10.host_cap, 0); + let expected_bounce_only = + bounce + bounce.div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES; + assert_eq!(default_gb10.device_reserve, expected_bounce_only); + assert_eq!(default_gb10.host_reserve, expected_bounce_only); + + // Explicit --pool-ram-memory 16G deducts full 16 GiB + bounce + page tables + margin + // from unified DRAM so DEVICE_POOL + HOST_POOL + bounce + KV cannot exceed physical DRAM. + let explicit_16g = async_transfer_device_reserve( + &p, + avail_above_kv, + 128 * gib, + Some(PoolMemoryLimit(MemoryLimit::Bytes(16 * gib))), + true, + ); + assert_eq!(explicit_16g.host_cap, 16 * gib); + let expected_16g = 16 * gib + + bounce + + (16 * gib + bounce).div_ceil(512) + + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES; + assert_eq!(explicit_16g.device_reserve, expected_16g); + assert_eq!(explicit_16g.host_reserve, expected_16g); + assert!(explicit_16g.device_reserve <= avail_above_kv); + + // Oversized explicit --pool-ram-memory 100G clamps so unified DRAM reserve never eats + // into min_kv_reserve. + let oversized = async_transfer_device_reserve( + &p, + avail_above_kv, + 128 * gib, + Some(PoolMemoryLimit(MemoryLimit::Bytes(100 * gib))), + true, + ); + assert!( + oversized.device_reserve <= avail_above_kv, + "integrated reserve {} exceeded headroom above min_kv {}", + oversized.device_reserve, + avail_above_kv + ); + assert!(oversized.host_cap > 70 * gib); + } + + #[test] + fn validate_agreed_device_pools_enforces_bounds_count_and_alignment() { + let align = 2u64 << 20; + validate_agreed_device_pools(&[32 << 20, 0], &[64 << 20, 16 << 20], &[align, align]) + .unwrap(); + // Exceeding local proposal fails. + assert!( + validate_agreed_device_pools(&[80 << 20], &[64 << 20], &[align]) + .unwrap_err() + .to_string() + .contains("cannot back") + ); + // Misaligned size fails. + assert!( + validate_agreed_device_pools(&[(32 << 20) + 4096], &[64 << 20], &[align]) + .unwrap_err() + .to_string() + .contains("unaligned") + ); + // Length mismatch fails. + assert!( + validate_agreed_device_pools(&[32 << 20], &[64 << 20, 16 << 20], &[align, align]) + .unwrap_err() + .to_string() + .contains("different number") + ); } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index c283261c0..e794e3732 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -1492,6 +1492,12 @@ 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)?; @@ -1784,7 +1790,6 @@ impl NativeResources { self.context = null_mut(); return false; } - self.async_transfers.clear(); unsafe { let mut previous = null_mut(); let had_previous = (self.driver.context_get)(&mut previous) == 0; @@ -1814,6 +1819,9 @@ impl NativeResources { if let Some(worker) = &self.persistent_worker { worker.invalidate_metrics(); } + for channel in &self.async_transfers { + channel.invalidate_control(); + } for (_, allocation) in std::mem::take(&mut self.allocations) { if allocation.nbytes == 0 { continue; @@ -1840,6 +1848,7 @@ impl NativeResources { for (address, bytes) in self.host_mappings.drain(..).rev() { (self.driver.unmap)(address, bytes); } + self.async_transfers.clear(); self.persistent_worker = None; if had_previous && previous != self.context { (self.driver.context_set)(previous); diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index 3a72c768c..a996ddfab 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -129,6 +129,28 @@ fn validate_persistent_worker_topology( Ok(()) } +/// 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, + cores: &[Core], +) -> Result<()> { + let has_async_transfers = cores.iter().any(|core| { + core.execution + .as_ref() + .is_some_and(|execution| !execution.async_transfers.is_empty()) + }); + if has_peer_copy_graphs && 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", + )); + } + Ok(()) +} + /// The cluster an authorized core's ranks form: (world, export id), or None /// when every rank runs on one host. pub fn core_cluster(core: &AuthorizedCore) -> Option<(usize, String)> { @@ -212,11 +234,21 @@ pub fn rank_ranges( archive.rank_ranges(index, rank) } -/// Startup agreement between ranks: register and approve pool memory before choosing the -/// smallest cache capacity every host can back. +/// Startup agreement between ranks: register and approve pool memory, agree on any +/// runtime-sized `DEVICE_POOL` byte budgets, and choose the smallest cache capacity every host +/// can back. pub trait CacheAgreement { fn caches(&mut self, local: (u64, u64)) -> Result<(u64, u64)>; + /// Agree across cluster ranks on the physical byte size of each runtime-sized `DEVICE_POOL` + /// allocation, taking the elementwise minimum before mapping. + /// + /// Single-host callers inherit this default because `allocate_caches` has already computed + /// the minimum across all local ranks. + fn device_pools(&mut self, local: &[u64]) -> Result> { + Ok(local.to_vec()) + } + fn pool( &mut self, offer: crate::offload::shard::PoolOffer, @@ -841,10 +873,12 @@ impl NativeModel { model.parallel(&cores, &files, |rank, core, files| { rank.prepare_graphs(files, core, &phase) })?; - model.copy_gate = model + let has_peer_copy_graphs = model .ranks .iter() - .any(NativeResources::has_any_peer_copy_graphs) + .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 .then(|| std::sync::Arc::new(crate::offload::CopyEngineGate::new())); phase.finish(format!("concurrency {active}")); if !engram.is_empty() { @@ -1478,6 +1512,45 @@ mod tests { assert_eq!(actual_peer_readers(owner_only, &peers)[0][&address], [0]); } } + + #[test] + fn async_transfers_reject_peer_copy_graphs_at_load_time() { + let make_core = |with_xfer: bool| { + let mut core = protobuf::decode(wire::BundleIndex { + architecture: vec![12, 0], + context: Some(Default::default()), + ..Default::default() + }) + .unwrap(); + if with_xfer { + core.execution = Some(wire::Execution { + async_transfers: vec![wire::AsyncTransfer { + name: "experts".into(), + device_pool: "pool".into(), + ..Default::default() + }], + ..Default::default() + }); + } + core + }; + + // Peer-copy graphs + async_transfers must fail fast. + let err = validate_async_transfer_peer_copy_compatibility( + true, + &[make_core(false), make_core(true)], + ) + .unwrap_err(); + assert!( + err.to_string().contains("CopyEngineGate"), + "unexpected error: {err}" + ); + + // Non-peer-copy graphs (single-GPU, NVLink SM P2P, or RoCE) + async_transfers succeed. + validate_async_transfer_peer_copy_compatibility(false, &[make_core(true)]).unwrap(); + // Peer-copy graphs without async_transfers succeed. + validate_async_transfer_peer_copy_compatibility(true, &[make_core(false)]).unwrap(); + } } /// Verified identity of an authorized core, taken from signed metadata only. diff --git a/verification/helios-lifecycle/AsyncTransfer.cfg b/verification/helios-lifecycle/AsyncTransfer.cfg index ce7f2a8c9..01546ef0a 100644 --- a/verification/helios-lifecycle/AsyncTransfer.cfg +++ b/verification/helios-lifecycle/AsyncTransfer.cfg @@ -18,3 +18,4 @@ INVARIANTS BounceSlotConservation DrainingHasEmptyQueues CanReleaseExact + FaultedDmaRetainsOwnership diff --git a/verification/helios-lifecycle/AsyncTransfer.tla b/verification/helios-lifecycle/AsyncTransfer.tla index 6d9bc3982..f3021768b 100644 --- a/verification/helios-lifecycle/AsyncTransfer.tla +++ b/verification/helios-lifecycle/AsyncTransfer.tla @@ -24,7 +24,8 @@ Initial == bQDma |-> 0, bInDma |-> 0, freeBounce |-> BounceSlots, - canRelease |-> 1] + canRelease |-> 1, + faultedDma |-> 0] Init == state = Initial @@ -108,15 +109,23 @@ CompleteIo(before, after) == CompleteDma(before, after) == /\ before.phase \in {RUNNING, DRAINING, FAILED_DRAIN} - /\ \E isBg \in BOOLEAN, hasBounce \in 0..1 : + /\ \E isBg \in BOOLEAN, hasBounce \in 0..1, wasFaulted \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) /\ after = WithRelease([before EXCEPT !.inDemDma = @ - IF isBg THEN 0 ELSE 1, !.inBgDma = @ - IF isBg THEN 1 ELSE 0, !.bInDma = @ - hasBounce, - !.freeBounce = @ + hasBounce]) + !.freeBounce = @ + hasBounce, + !.faultedDma = @ - wasFaulted]) + +MarkDmaFaulted(before, after) == + /\ before.phase \in {RUNNING, DRAINING} + /\ before.faultedDma < before.inDemDma + before.inBgDma + /\ after = WithRelease([before EXCEPT !.faultedDma = @ + 1]) BeginDrain(before, after) == \/ /\ before.phase = IDLE @@ -151,6 +160,7 @@ Step(before, after) == \/ BeginDrain(before, after) \/ FinishDrainOk(before, after) \/ FinishDrainFail(before, after) + \/ MarkDmaFaulted(before, after) Next == Step(state, state') \/ UNCHANGED state @@ -168,6 +178,7 @@ WellTyped(st) == /\ st.bInDma \in 0..BounceSlots /\ st.freeBounce \in 0..BounceSlots /\ st.canRelease \in 0..1 + /\ st.faultedDma \in 0..MaxTotalDma NoUnmapWhileInflightAt(st) == (st.inDemIo + st.inBgIo + st.inDemDma + st.inBgDma > 0) => st.canRelease = 0 @@ -179,6 +190,7 @@ StoppedHasZeroInflightAt(st) == st.phase = STOPPED => /\ st.inDemIo = 0 /\ st.inBgIo = 0 /\ st.inDemDma = 0 /\ st.inBgDma = 0 + /\ st.faultedDma = 0 /\ st.qIo = 0 /\ st.qDma = 0 /\ st.freeBounce = BounceSlots @@ -200,6 +212,11 @@ DrainingHasEmptyQueuesAt(st) == CanReleaseExactAt(st) == st.canRelease = CanReleaseFor(st) +FaultedDmaRetainsOwnershipAt(st) == + /\ st.faultedDma <= st.inDemDma + st.inBgDma + /\ st.faultedDma > 0 => st.canRelease = 0 + /\ st.phase = STOPPED => st.faultedDma = 0 + ObservedSafe(st) == /\ WellTyped(st) /\ NoUnmapWhileInflightAt(st) @@ -209,6 +226,7 @@ ObservedSafe(st) == /\ BounceSlotConservationAt(st) /\ DrainingHasEmptyQueuesAt(st) /\ CanReleaseExactAt(st) + /\ FaultedDmaRetainsOwnershipAt(st) TypeOK == WellTyped(state) NoUnmapWhileInflight == NoUnmapWhileInflightAt(state) @@ -218,11 +236,13 @@ BoundedHardwareDepth == BoundedHardwareDepthAt(state) BounceSlotConservation == BounceSlotConservationAt(state) DrainingHasEmptyQueues == DrainingHasEmptyQueuesAt(state) CanReleaseExact == CanReleaseExactAt(state) +FaultedDmaRetainsOwnership == FaultedDmaRetainsOwnershipAt(state) Projection(st) == <> + st.bInIo, st.bQDma, st.bInDma, st.freeBounce, st.canRelease, + st.faultedDma>> Decode(v) == [phase |-> v[1], @@ -237,7 +257,8 @@ Decode(v) == bQDma |-> v[10], bInDma |-> v[11], freeBounce |-> v[12], - canRelease |-> v[13]] + canRelease |-> v[13], + faultedDma |-> v[14]] ObservedState(v) == Decode(v) @@ -252,6 +273,7 @@ ActionMatches(before, kind, after) == \/ /\ kind = 8 /\ BeginDrain(before, after) \/ /\ kind = 9 /\ FinishDrainOk(before, after) \/ /\ kind = 10 /\ FinishDrainFail(before, after) + \/ /\ kind = 11 /\ MarkDmaFaulted(before, after) AllowedEdge(edge) == LET before == ObservedState(edge[1]) diff --git a/verification/helios-lifecycle/README.md b/verification/helios-lifecycle/README.md index 699f6c3b9..919eb3039 100644 --- a/verification/helios-lifecycle/README.md +++ b/verification/helios-lifecycle/README.md @@ -358,18 +358,21 @@ 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`), -and drained queues once shutdown begins (`DrainingHasEmptyQueues`). +drained queues once shutdown begins (`DrainingHasEmptyQueues`), and retained +in-flight and bounce ownership after partial CUDA DMA submission faults until +confirmed hardware drain (`FaultedDmaRetainsOwnership`). `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`, -`begin_drain`, `finish_drain`, `fail_drain`) across priority preemption, -epoch cancellation, fused bounce-staged transfers, and confirmed vs. failed -drain. Its 13-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, and release predicate. Linux `io_uring` submission, CUDA Copy Engine -ordering, `cuStreamWriteValue64` completion signaling, and pinned host memory -registration require their separate CUDA integration tests. +`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, +CUDA Copy Engine ordering, `cuStreamWriteValue64` completion signaling, and +pinned host memory registration require their separate CUDA integration tests. ## Assumptions and limits diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index e6c43419d..fa97626b3 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 ", 13)] + "ASYNC_TRANSFER_EDGE ", 14)] MODELS = [check[0] for check in CHECKS] + ["RankDispatch"] @@ -418,6 +418,16 @@ def run_aux(test): " !.bQDma = 0,\n" " !.freeBounce = @])", "BounceSlotConservation"), + ("AsyncTransfer", + "MarkDmaFaulted(before, after) ==\n" + " /\\ before.phase \\in {RUNNING, DRAINING}\n" + " /\\ before.faultedDma < before.inDemDma + before.inBgDma\n" + " /\\ after = WithRelease([before EXCEPT !.faultedDma = @ + 1])", + "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])", + "FaultedDmaRetainsOwnership"), ] with ThreadPoolExecutor(max_workers=min(args.jobs, len(model_mutations))) as pool: futures = [ @@ -722,6 +732,18 @@ def run_aux(test): "matches!(self.state, ChannelState::Idle | ChannelState::Stopped)", "matches!(self.state, ChannelState::Idle | ChannelState::Stopped | ChannelState::FailedDrain)", "failed drain must retain pinned memory"), + ("failed io signaled success cookie", + " signal_value: completion_error_sentinel(ErrorCode::IoFailure),", + " signal_value: op.signal_value,", + "failed transfer must signal error sentinel, not success value"), + ("failed dma signaled success cookie", + " completion_error_sentinel(ErrorCode::CudaFailure)\n },\n error: if ok {\n ErrorCode::Ok\n } else {\n ErrorCode::CudaFailure\n },", + " 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;", + "faulted DMA must retain inflight and bounce ownership"), ]) restored_bin = build_test_binary(cargo) run_observed_checks(restored_bin, directory, args.java, jar, args.jobs)