Skip to content

Commit 0c25e88

Browse files
authored
helios: fix deferred_prefill checkpoints, shared_pages accounting, drop teardown, and >64 MiB wire prepares (#613)
Why: Four runtime defects affect Helios scheduling, KV cache accounting, CUDA resource teardown, and tensor-parallel wire transport: 1. On cores declaring `GraphKind::TerminalPrefill`, a non-terminal `GraphKind::Prefill` chunk skips trailing continuation layers and sets `request.deferred_prefill = true` until a `TerminalPrefill` graph completes. Previously, `resolve_prefill_kind`, `prefill_requires_terminal_completion`, `plan_checkpoints`, `complete_inner`, `allocate_terminal_capture`, `RefreshStart` filtering, and `resize_prefill` ignored `request.deferred_prefill` when remaining tokens fit in a smaller regular `Prefill` graph outside `terminal_prefill_catalog`. A dynamically selected checkpoint cut or short prompt tail could therefore run regular `Prefill` while `deferred_prefill` remained true, publishing prefix checkpoints missing continuation state and entering `Decode` with `deferred_prefill` permanently set. `CheckpointReservation.tla` did not model `deferred_prefill`. 2. In `RequestScheduler::refill_reservations`, held KV pages were counted as `private_pages.len() + reserved_pages.len()`, omitting `shared_pages.len()` (unlike `pages_through` and `admit`). A growable decoding request holding cached prefix pages that reached `limits.pages` was treated as starved instead of at the physical pool ceiling, triggering spurious preemption of active decoders and readmission failure with `AdmissionError::Context` for streaming requests. 3. In `NativeModel::drop`, `self.offload.reset()` and `self.engram.clear()` ran before `rank.release_execution_resources()` stopped persistent workers and synchronized CUDA contexts, risking deadlock or use-after-free against host slabs and staging buffers; `prepare_offload` and pool registration bound the primary context instead of `execution_context()` (`compute_context` under green-context partitions); and `Event::drop`, `PinnedHost::drop`, and `Stream::drop` did not bind or restore their allocating CUDA context, silently failing and leaking pinned host memory when dropped on another thread. 4. `wire::prepare` splits >64 MiB uploads across `PREPARE_MORE` and `PREPARE` packets, but `wire::receive_prepare` appended fragments without coalescing. Peer ranks rejected split logprob gate/count/ID uploads in `transport::validate_uploads` and silently truncated split Engram `table.hashes` uploads via `.find(...)` in `engram.rs`. In addition, `TensorParallelExecutor::poll` and `ThreadedExecutor::poll_ranks` only selected `agree_speculative` for `GraphKind::Speculative`, omitting speculative `GraphKind::Mixed` graphs (`token_capacity > 1`). What exactly changed: - Deferred prefill & checkpoint safety (`helios/src/scheduler.rs`, `helios/src/scheduler/checkpoints.rs`, `helios/src/scheduler/policy.rs`, `verification/helios-lifecycle/CheckpointReservation.{tla,cfg}`, `verification/helios-lifecycle/check.py`, `verification/helios-lifecycle/README.md`, `helios/src/scheduler/checkpoint_lifecycle_tests.rs`, `helios/src/scheduler/policy_tests.rs`): - `resolve_prefill_kind` now returns `GraphKind::TerminalPrefill` when `request.deferred_prefill` is true and a candidate step reaches `next_stop` or enters the tail window, even for capacities outside `terminal_prefill_catalog`. - `prefill_requires_terminal_completion` now requires terminal completion whenever `request.deferred_prefill` is true and remaining work fits in `terminal_prefill_catalog.last()`. - `plan_checkpoints`, `allocate_terminal_capture`, and `complete_inner` refuse to arm, allocate, or capture checkpoints while `deferred_prefill` remains set after the step. - `select_plan` (`RefreshStart`), `available_plan`, and `resize_prefill` now enforce `prefill_requires_terminal_completion` and resize against `terminal_prefill_catalog` when terminal completion is required. - Extended `CheckpointReservation.tla` (`MaxFence = 3`, 16-integer projection) with `deferred` request state, `DeferredHasNoReadyCapture`, `DeferPrefill`, `ArmAndProduceTerminal`, and `CompleteTerminal`, plus Rust conformance and TLA+/Rust mutation coverage. Updated `retiring_boundary_capture_stamps_terminal_start_and_resuming_capture_leaves_it_unset` and added `deferred_prefill_requires_terminal_prefill_for_small_cuts_refresh_and_decode`. - KV page accounting (`helios/src/scheduler.rs`, `helios/src/scheduler/tests.rs`): - Included `request.shared_pages.len()` in `held` inside `refill_reservations` and added `growable_request_with_shared_prefix_longer_than_pool_finishes_instead_of_preempting`. - CUDA teardown and context RAII (`helios/src/runtime_core/model.rs`, `helios/src/runtime_core/memory.rs`, `helios/src/runtime_core/mod.rs`, `helios/src/cuda.rs`): - Reordered `NativeModel::drop` so Phase 1 runs `rank.release_execution_resources()` across all ranks first, then calls `self.offload.reset()` and `self.engram.clear()` only if every rank drained (retaining them via `mem::forget` alongside undrained ranks otherwise), followed by Phase 2 `rank.release_reservations_and_context()`. - Moved `GreenContextPartition::destroy_green_contexts` from Phase 1 to Phase 2 so compute green contexts remain live while offload host registrations and handles unregister. - Updated `prepare_offload` and pool registration to pass `rank.execution_context()`. - Recorded the allocating CUDA context on `Stream`, `Event`, and `PinnedHost`, added `Driver::with_context`, bound/restored context on `Drop` and `Stream::destroy`, and added GPU test `pinned_host_event_and_stream_release_when_dropped_on_another_thread`. - Wire prepare coalescing and Mixed speculative agreement (`helios/src/execution/parallel/wire.rs`, `helios/src/execution/transport.rs`, `helios/src/execution/parallel.rs`, `helios/src/execution/threaded.rs`, `helios/src/execution/parallel/tests.rs`): - Coalesced contiguous same-buffer fragments in `wire::receive_prepare` and updated `transport::validate_uploads` to slice `logprob_token_ids` by offset range inside covering uploads. - Shared `uses_speculative_agreement` across `TensorParallelExecutor::poll` and `ThreadedExecutor::poll_ranks` to apply `agree_speculative` to both `GraphKind::Speculative` and `GraphKind::Mixed` with `token_capacity > 1`. - Updated `prepare_packets_preserve_large_and_partial_uploads_on_both_transports` and added `receive_prepare_coalesces_split_uploads_across_64mib_packet_boundaries` and `speculative_agreement_applies_to_speculative_and_speculative_mixed_graphs`. Claimed benefit: Prevents corrupted prefix checkpoints and stuck `deferred_prefill` state on `TerminalPrefill` cores, prevents spurious preemptions and `AdmissionError::Context` failures on growable decoders reusing cached prefixes, prevents teardown UAF/deadlock and cross-thread pinned-host leaks during CUDA shutdown, and prevents >64 MiB prepare-upload truncation and unchecked speculative `Mixed` peer divergence. Supporting evidence and limitations: - Helios CPU unit suite on rebased `origin/main` (`f7256584`): `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- scheduler:: execution::parallel::tests:: execution::threaded::tests:: execution::tests:: cuda::tests:: runtime_core:: engram:: offload::` passed (`709 passed, 0 failed, 30 ignored`). - Flare library suite on rebased `origin/main`: `cargo test --locked --release --manifest-path flare/Cargo.toml --target-dir flare-cli/target` passed (`242 passed, 0 failed, 4 ignored`). - CUDA cross-thread drop tests on RTX PRO 6000 Blackwell (GPU 0): `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target --lib -- --ignored cuda::tests::pinned_host_event_and_stream_release_when_dropped_on_another_thread cuda::tests::host_registration_unregisters_when_dropped_on_another_thread` passed (`2 passed, 0 failed`). - Formal lifecycle verification and mutation suite (`python3 verification/helios-lifecycle/check.py --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar --target-dir flare-cli/target --mutations`, run against the same scheduler/TLA+ diff prior to rebasing onto Selene-only commits): passed all 9 TLA+ models + `Speculation16.cfg` (`CheckpointReservation.tla`: 502,765 states generated, 45,448 distinct), all 8 observed-edge Rust conformance suites (40 observed transitions for `CheckpointReservation.tla`), all 12 auxiliary tests, and all TLA+ and Rust mutations (including `DeferredHasNoReadyCapture`, `deferred prefill terminal capture bypass`, and `deferred prefill small cut bypass`). - Unrelated pre-existing failures observed during broader runs: `helios` `model::tests::packed_combined_budget_keeps_width_one_batches_without_a_useful_packed_shape` and `flare-cli` `distribution::tests::source_waits_for_receiver_file_verification` (broken pipe after 130s). - Limitations: live exported-core serving with persistent workers + host offload teardown, multi-GPU TP `GraphKind::Mixed` collective execution, and cross-host >64 MiB socket Engram runs were not executed in this pass. Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b Signed-off-by: Luke Alonso <lalonso@gmail.com>
1 parent 9a054b4 commit 0c25e88

19 files changed

Lines changed: 888 additions & 113 deletions

File tree

‎helios/src/cuda.rs‎

Lines changed: 175 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,26 @@ impl Driver {
348348
self.check("cuCtxGetDevice", unsafe { (self.get_device)(&mut device) })?;
349349
Ok((context as usize, device))
350350
}
351+
352+
unsafe fn with_context<T>(
353+
&self,
354+
context: usize,
355+
operation: impl FnOnce() -> Result<T>,
356+
) -> Result<T> {
357+
let mut previous: Handle = std::ptr::null_mut();
358+
let had_previous = unsafe { (self.get_context)(&mut previous) == 0 };
359+
let target = context as Handle;
360+
let outcome = if !had_previous || previous != target {
361+
self.check("cuCtxSetCurrent", unsafe { (self.set_context)(target) })
362+
.and_then(|()| operation())
363+
} else {
364+
operation()
365+
};
366+
if had_previous && previous != target {
367+
let _ = unsafe { (self.set_context)(previous) };
368+
}
369+
outcome
370+
}
351371
}
352372

353373
pub fn current_context() -> Result<(usize, i32)> {
@@ -677,6 +697,7 @@ pub(crate) fn map_device_host_parts(requests: &[(usize, i32, usize)]) -> Result<
677697

678698
pub(crate) struct Stream {
679699
driver: Arc<Driver>,
700+
context: usize,
680701
handle: usize,
681702
}
682703

@@ -743,6 +764,7 @@ impl Stream {
743764
})?;
744765
Ok(Self {
745766
driver,
767+
context,
746768
handle: handle as usize,
747769
})
748770
}
@@ -774,6 +796,7 @@ impl Stream {
774796
})?;
775797
Ok(Self {
776798
driver,
799+
context,
777800
handle: handle as usize,
778801
})
779802
}
@@ -848,6 +871,15 @@ impl Stream {
848871
}
849872

850873
fn allocate_host(&self, nbytes: usize, flags: u32) -> Result<PinnedHost> {
874+
let mut ctx: Handle = std::ptr::null_mut();
875+
self.driver
876+
.check("cuCtxGetCurrent", unsafe { (self.driver.get_context)(&mut ctx) })?;
877+
if ctx.is_null() {
878+
return Err(Error::execution(
879+
ExecutionError::State,
880+
"pinned host allocation requires a current CUDA context",
881+
));
882+
}
851883
let mut handle = std::ptr::null_mut();
852884
self.driver.check("cuMemHostAlloc", unsafe {
853885
(self.driver.host_alloc)(&mut handle, nbytes, flags)
@@ -857,6 +889,7 @@ impl Stream {
857889
}
858890
Ok(PinnedHost {
859891
driver: self.driver.clone(),
892+
context: ctx as usize,
860893
handle: handle as usize,
861894
nbytes,
862895
})
@@ -878,13 +911,23 @@ impl Stream {
878911
}
879912

880913
fn create_event(&self, flags: c_uint) -> Result<Event> {
914+
let mut ctx: Handle = std::ptr::null_mut();
915+
self.driver
916+
.check("cuCtxGetCurrent", unsafe { (self.driver.get_context)(&mut ctx) })?;
917+
if ctx.is_null() {
918+
return Err(Error::execution(
919+
ExecutionError::State,
920+
"CUDA event creation requires a current CUDA context",
921+
));
922+
}
881923
let mut handle = std::ptr::null_mut();
882924
// SAFETY: The driver owns the ABI and `handle` is a valid output pointer.
883925
self.driver.check("cuEventCreate", unsafe {
884926
(self.driver.event_create)(&mut handle, flags)
885927
})?;
886928
Ok(Event {
887929
driver: self.driver.clone(),
930+
context: ctx as usize,
888931
handle: handle as usize,
889932
})
890933
}
@@ -1059,9 +1102,17 @@ impl Stream {
10591102

10601103
pub(crate) fn destroy(mut self) -> Result<()> {
10611104
let handle = std::mem::take(&mut self.handle);
1062-
self.driver.check("cuStreamDestroy_v2", unsafe {
1063-
(self.driver.stream_destroy)(handle as Handle)
1064-
})
1105+
if handle == 0 {
1106+
return Ok(());
1107+
}
1108+
unsafe {
1109+
self.driver.with_context(self.context, || {
1110+
self.driver.check(
1111+
"cuStreamDestroy_v2",
1112+
(self.driver.stream_destroy)(handle as Handle),
1113+
)
1114+
})
1115+
}
10651116
}
10661117

10671118
pub(crate) fn alloc_device(&self, bytes: usize) -> Result<DeviceBuffer> {
@@ -1272,6 +1323,7 @@ impl Drop for LoadedModule {
12721323

12731324
pub(crate) struct Event {
12741325
driver: Arc<Driver>,
1326+
context: usize,
12751327
handle: usize,
12761328
}
12771329

@@ -1310,14 +1362,26 @@ impl Event {
13101362

13111363
impl Drop for Event {
13121364
fn drop(&mut self) {
1313-
unsafe {
1314-
(self.driver.event_destroy)(self.handle as Handle);
1365+
if self.handle == 0 {
1366+
return;
1367+
}
1368+
let result = unsafe {
1369+
self.driver.with_context(self.context, || {
1370+
self.driver.check(
1371+
"cuEventDestroy_v2",
1372+
(self.driver.event_destroy)(self.handle as Handle),
1373+
)
1374+
})
1375+
};
1376+
if let Err(error) = result {
1377+
eprintln!("warning: cannot destroy CUDA event: {error}");
13151378
}
13161379
}
13171380
}
13181381

13191382
pub(crate) struct PinnedHost {
13201383
driver: Arc<Driver>,
1384+
context: usize,
13211385
handle: usize,
13221386
nbytes: usize,
13231387
}
@@ -1336,8 +1400,22 @@ impl PinnedHost {
13361400

13371401
impl Drop for PinnedHost {
13381402
fn drop(&mut self) {
1339-
unsafe {
1340-
(self.driver.host_free)(self.handle as Handle);
1403+
if self.handle == 0 {
1404+
return;
1405+
}
1406+
let result = unsafe {
1407+
self.driver.with_context(self.context, || {
1408+
self.driver.check(
1409+
"cuMemFreeHost",
1410+
(self.driver.host_free)(self.handle as Handle),
1411+
)
1412+
})
1413+
};
1414+
if let Err(error) = result {
1415+
eprintln!(
1416+
"warning: cannot free pinned host memory at {:#x}: {error}",
1417+
self.handle
1418+
);
13411419
}
13421420
}
13431421
}
@@ -1346,8 +1424,16 @@ impl Drop for Stream {
13461424
fn drop(&mut self) {
13471425
if self.handle != 0 {
13481426
// Explicit synchronization reports errors; Drop only releases the stream handle.
1349-
unsafe {
1350-
(self.driver.stream_destroy)(self.handle as Handle);
1427+
let result = unsafe {
1428+
self.driver.with_context(self.context, || {
1429+
self.driver.check(
1430+
"cuStreamDestroy_v2",
1431+
(self.driver.stream_destroy)(self.handle as Handle),
1432+
)
1433+
})
1434+
};
1435+
if let Err(error) = result {
1436+
eprintln!("warning: cannot destroy CUDA stream: {error}");
13511437
}
13521438
}
13531439
}
@@ -1694,4 +1780,84 @@ mod tests {
16941780
"the configured test directory refused direct I/O"
16951781
);
16961782
}
1783+
1784+
#[cfg(feature = "runtime-core")]
1785+
#[test]
1786+
#[ignore = "requires CUDA device 0"]
1787+
fn pinned_host_event_and_stream_release_when_dropped_on_another_thread() {
1788+
use crate::runtime_core::driver::Driver as Loader;
1789+
let loader = Loader::load().unwrap();
1790+
let mut context = std::ptr::null_mut();
1791+
// SAFETY: Driver signatures match cuda.h and the output pointers are valid.
1792+
unsafe {
1793+
loader.check("cuInit", (loader.init)(0)).unwrap();
1794+
let mut device = 0;
1795+
loader
1796+
.check("cuDeviceGet", (loader.device)(&mut device, 0))
1797+
.unwrap();
1798+
loader
1799+
.check(
1800+
"cuCtxCreate_v2",
1801+
(loader.context_create)(&mut context, 0, device),
1802+
)
1803+
.unwrap();
1804+
}
1805+
let context_usize = context as usize;
1806+
let (stream, event, pinned, pinned_addr) = std::thread::spawn(move || {
1807+
let stream = Stream::open(context_usize, 0).unwrap();
1808+
let event = stream.event().unwrap();
1809+
let pinned = stream.host_buffer(64 * 1024).unwrap();
1810+
let addr = pinned.address();
1811+
(stream, event, pinned, addr)
1812+
})
1813+
.join()
1814+
.unwrap();
1815+
std::thread::spawn(move || {
1816+
let driver = Driver::load().unwrap();
1817+
// SAFETY: Clearing the thread context guarantees Drop must bind and restore it.
1818+
driver
1819+
.check("cuCtxSetCurrent", unsafe {
1820+
(driver.set_context)(std::ptr::null_mut())
1821+
})
1822+
.unwrap();
1823+
drop(pinned);
1824+
drop(event);
1825+
drop(stream);
1826+
let mut after: Handle = std::ptr::null_mut();
1827+
driver
1828+
.check("cuCtxGetCurrent", unsafe {
1829+
(driver.get_context)(&mut after)
1830+
})
1831+
.unwrap();
1832+
assert!(
1833+
after.is_null(),
1834+
"cross-thread CUDA resource drop must restore null thread context"
1835+
);
1836+
// Re-bind the allocating context and verify the pinned pointer was actually freed.
1837+
driver
1838+
.check("cuCtxSetCurrent", unsafe {
1839+
(driver.set_context)(context_usize as Handle)
1840+
})
1841+
.unwrap();
1842+
let mut kind: c_int = 0;
1843+
let status = unsafe {
1844+
(driver.pointer_attribute)(
1845+
(&mut kind as *mut c_int).cast(),
1846+
2, // CU_POINTER_ATTRIBUTE_MEMORY_TYPE
1847+
pinned_addr as u64,
1848+
)
1849+
};
1850+
assert_ne!(
1851+
status, 0,
1852+
"pinned host allocation must be freed by cross-thread drop"
1853+
);
1854+
})
1855+
.join()
1856+
.unwrap();
1857+
unsafe {
1858+
loader
1859+
.check("cuCtxDestroy_v2", (loader.context_destroy)(context))
1860+
.unwrap();
1861+
}
1862+
}
16971863
}

‎helios/src/execution/parallel.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ impl TensorParallelExecutor {
378378
let mut root = frame.completions[0].take().unwrap();
379379
for (index, completion) in frame.completions.into_iter().skip(1).enumerate() {
380380
let completion = completion.unwrap();
381-
let agreement = if self.local.manifest().graphs[root.graph_index].kind == super::GraphKind::Speculative {
381+
let agreement = if uses_speculative_agreement(&self.local.manifest().graphs[root.graph_index]) {
382382
agree_speculative
383383
} else { agree };
384384
agreement(&root, &completion).map_err(|error| invalid(format!("rank {}: {error}", index + 1)))?;
@@ -499,6 +499,11 @@ pub(super) fn agree(root: &FrameCompletion, peer: &FrameCompletion) -> Result<()
499499
Ok(())
500500
}
501501

502+
pub(super) fn uses_speculative_agreement(graph: &super::GraphDescriptor) -> bool {
503+
graph.kind == super::GraphKind::Speculative
504+
|| (graph.kind == super::GraphKind::Mixed && graph.token_capacity > 1)
505+
}
506+
502507
pub(super) fn agree_speculative(root: &FrameCompletion, peer: &FrameCompletion) -> Result<()> {
503508
agree(root, peer)?;
504509
for (a, b) in root.records.iter().zip(peer.records.iter()) {

0 commit comments

Comments
 (0)