Skip to content

helios,flare-cli: harden AsyncTransfer startup, DMA and teardown lifetimes, unified DRAM, and Copy Engine safety - #721

Merged
lukealonso merged 1 commit into
mainfrom
harden-async-transfer-hardware-memor
Dec 4, 2026
Merged

lukealonso merged 1 commit into
mainfrom
harden-async-transfer-hardware-memor

Conversation

@lukealonso

Copy link
Copy Markdown
Collaborator

Why

The asynchronous extent-transfer runtime (helios/src/async_transfer/) and runtime-sized device weight pool allocator (Capacity::DEVICE_POOL) introduced in #711 cross four hardware and OS boundaries—CUDA streams and events, Linux io_uring, unified-DRAM memory sizing, and Copy Engine peer-to-peer transfers—where eight boundary defects break correctness or stability under live serving and multi-rank bring-up:

  1. Startup readiness race and dropped CUDA context errors: AsyncTransferRuntime::start() transitioned its host state to ChannelState::Running and returned Ok(()) immediately after spawning the worker thread, before the worker bound the rank's CUDA context (cuCtxSetCurrent), created its CUDA event pool, or wrote ChannelState::Running into the mapped-host control header (ControlHeader::worker_state). Startup kernels that validate a live channel header (such as tiered MoE initialization in local-inference-lab/hyperflare-recipes#150) can observe ChannelState::Idle, and cuCtxSetCurrent failures were silently ignored.
  2. Partial-DMA bounce-slot use-after-free: When cuMemcpyHtoDAsync_v2 succeeded on copy_stream while the subsequent cuStreamWriteValue64_v2 or cuEventRecord failed, the worker immediately called scheduler.complete_dma(..., false), releasing the staging bounce slot and decrementing inflight_dma while the GPU Copy Engine was still reading that pinned host buffer.
  3. Dual-stream completion race and host completion regression: Device completion writes ran on a separate unsynchronized signal_stream while DMAs and inline completion writes ran on copy_stream, allowing out-of-order writes on reused completion slots. On the host mirror (host_comp), deferred EventCompletionAction::HostOnly updates used plain release stores that could overwrite a newer completion value backwards after slot reuse.
  4. Silent weight corruption on transfer errors: On ErrorCode::IoFailure or ErrorCode::CudaFailure, TransferScheduler and the worker wrote the caller's requested success cookie (signal_value) into completion slots, allowing GPU waiters spinning on signal_value to treat unwritten or stale destination memory as valid payload data.
  5. Unbounded io_uring shutdown hang: IoUringBackend::cancel_and_drain() called blocking ring.submit_and_wait(1) with no kernel timeout, defeating the DRAIN_TIMEOUT bound when storage operations stalled during teardown.
  6. Post-munmap use-after-free in AsyncTransferRuntime::snapshot(): NativeResources::release_execution_resources() unmapped the channel's MappedHost control region while retained Arc<AsyncTransferRuntime> metric handles could still call safe snapshot(), which dereferenced the raw control_address pointer.
  7. Unified-DRAM double-spend, missing prefix-cache coordination, and missing multi-host DEVICE_POOL agreement: On integrated unified-DRAM GPUs (such as GB10 and Jetson), memory sizing deducted only pinned.div_ceil(512) + 256 MiB rather than full pinned HOST_POOL and bounce-pool bytes from the shared physical RAM budget, failed to reserve HOST_POOL and bounce memory against host prefix-cache growth (host_future) and vision offload windows, and sized DEVICE_POOL using only the local host minimum without exchanging sizes across multi-host ranks via CacheAgreement.
  8. Unguarded PCIe TP>=2 Copy Engine deadlock: Cores combining Execution.async_transfers with CUDA graphs containing Copy Engine peer-to-peer copy nodes (Memory::Peer) were accepted at load time without Copy Engine serialization. Captured graphs that wait on in-graph demand transfers cannot yield to CopyEngineGate without circular deadlock, and ungated concurrent Copy Engine host-to-device transfers deadlock PCIe peer copies.

What changed

Worker startup, DMA lifetime, completion ordering, and control-region lifetime (helios/src/async_transfer/{ring,scheduler,worker,mod}.rs, helios/src/runtime_core/mod.rs)

  • Synchronous startup readiness barrier: Previously, AsyncTransferRuntime::start() published ChannelState::Running locally and returned before the worker thread initialized CUDA. Now start() blocks on a synchronous mpsc::sync_channel until worker_main binds the CUDA context (cuCtxSetCurrent), creates all DEFAULT_MAX_TOTAL_DMA CUDA events, and writes ChannelState::Running into ControlHeader::worker_state with Release ordering. Initialization errors return Err(...), restore io_backend, and leave the channel ChannelState::Idle.
  • Faulted-DMA bounce-slot retention: Previously, post-enqueue CUDA errors (cuStreamWriteValue64_v2, cuEventRecord, or sticky cuEventQuery errors) immediately released the bounce slot. Now InflightDma tracks a faulted flag and TransferScheduler::mark_dma_faulted() keeps both inflight_dma and bounce-slot ownership pinned while pausing new DMA submissions until cuEventQuery (for tracked events) or cuStreamQuery(copy_stream) == 0 (for untracked faulted DMAs) confirms the Copy Engine has drained. On ChannelState::FailedDrain, faulted DMA events and any undrained io_backend remain pinned rather than being destroyed while hardware may still reference their buffers.
  • Single-stream completion ordering and monotonic host mirrors: Previously, worker_main maintained both copy_stream and an unsynchronized signal_stream and updated host_comp with plain atomic stores. Now signal_stream is removed; all device completion writes serialize on copy_stream (including host-only completions when device_completions_base == 0 and stream-memory writes are active), signal_completion_slot() checks CUDA return statuses, and update_host_completion() updates host_comp with AtomicU64::fetch_max.
  • Explicit fault sentinels on transfer errors (ABI refinement): Previously, failed transfers signaled the caller's requested signal_value. Now ring.rs reserves bit 63 (COMPLETION_ERROR_BIT = 1u64 << 63) for fault sentinels via completion_error_sentinel(ErrorCode), adds ErrorCode::InvalidSignalValue = 12, and rejects commands with (signal_value & COMPLETION_ERROR_BIT) != 0 when completion_slot != NO_COMPLETION_SLOT. On IoFailure or CudaFailure, TransferScheduler and the worker emit completion_error_sentinel(...) rather than the caller's success cookie so GPU waiters observe a non-success fault value without silently consuming invalid bytes.
  • Safe post-teardown snapshots: Previously, snapshot() dereferenced control_address unconditionally. Now ControlRegionGuard (RwLock<ControlAccess>) guards control-region reads and writes, and NativeResources::release_execution_resources() calls channel.invalidate_control() before unmapping MappedHost allocations, capturing final ring counters so subsequent snapshot() calls never touch unmapped memory.

Bounded io_uring shutdown (helios/src/async_transfer/io_backend.rs)

  • Previously, IoUringBackend::cancel_and_drain() called blocking self.ring.submit_and_wait(1) in a loop.
  • Now it computes the remaining duration until deadline and calls submitter().submit_with_args(1, &SubmitArgs::new().timespec(&ts)), handling ETIME, EINTR, and bounded sleep/poll fallback when submit_with_args returns another error.

Unified-DRAM accounting, prefix-cache coordination, and multi-host DEVICE_POOL agreement (helios/src/runtime_core/{memory,model}.rs, helios/src/execution/rendezvous.rs, flare-cli/src/cluster.rs)

  • Integrated unified-DRAM sizing and prefix-cache coordination: Previously, memory.rs deducted only pinned.div_ceil(512) + 256 MiB for integrated ranks and did not account for HOST_POOL or bounce pools when planning host prefix-cache growth (host_future) or prepare_offload. Now AsyncTransferBudget and async_transfer_host_ram() account for full pinned + pinned.div_ceil(512) + 256 MiB on integrated GPUs, default HOST_POOL to 0 on integrated GPUs unless --pool-ram-memory is explicitly provided (preventing HOST_POOL from competing with DEVICE_POOL in the same physical DRAM while still permitting explicit 3-tier sizing clamped against minimum KV reserves), and deduct async_transfer_host_total + device_pool_integrated_bytes from host prefix-cache growth budgets.
  • Cluster-wide DEVICE_POOL agreement: Previously, each host sized DEVICE_POOL using only its local rank minimum. Now CacheAgreement gains a device_pools(&mut self, local: &[u64]) -> Result<Vec<u64>> method (defaulting to Ok(local.to_vec()) for single-host callers), implemented in flare-cli/src/cluster.rs (Membership::device_pools) over helios/src/execution/rendezvous.rs (agree_device_pools / propose_device_pools). memory.rs gathers canonical sorted device_pool_names, exchanges local minima across cluster ranks, and validates agreed sizes via validate_agreed_device_pools before map_device_pool. Multi-host cores without Capacity::DEVICE_POOL never invoke this exchange, preserving wire compatibility.

Load-time rejection of async_transfers with Copy Engine peer-copy graphs (helios/src/runtime_core/{model,mod}.rs)

  • Previously, NativeModel::load_agreeing() constructed CopyEngineGate when has_any_peer_copy_graphs() was true without checking for Execution.async_transfers.
  • Now validate_async_transfer_peer_copy_compatibility() fails fast after prepare_graphs (with a matching defensive guard in NativeResources::prepare_async_transfers) whenever any rank has Copy Engine peer-copy graphs alongside Execution.async_transfers. Single-GPU, NVLink SM P2P, and RoCE cores without Copy Engine peer-copy nodes continue to load normally.

Formal models, tests, documentation, and test-build fix (verification/helios-lifecycle/, helios/src/async_transfer/{lifecycle_tests,kani_proofs}.rs, helios/manifest.md, docs/runtime-core-design.md, helios/src/runtime_core/cache_memory.rs)

  • Extended AsyncTransfer.tla / AsyncTransfer.cfg with faultedDma, MarkDmaFaulted, and FaultedDmaRetainsOwnership; expanded the Rust conformance trace projection to 14 fields; added TLA+ and Rust mutation checks covering early bounce-slot release and success-cookie signaling on error; extended Kani's validate_command_guarantees_bounds_and_alignment_for_all_inputs harness to assert signal_value disjointness from COMPLETION_ERROR_BIT.
  • Updated helios/manifest.md and docs/runtime-core-design.md to specify the COMPLETION_ERROR_BIT contract, synchronous startup readiness, single-stream completion ordering, unified-DRAM deductions, CacheAgreement::device_pools, and the peer-copy load-time rejection.
  • Added the missing external_extents: vec![] field in a Core unit-test literal in helios/src/runtime_core/cache_memory.rs so helios unit tests compile on origin/main (this 1-line fix overlaps with open PR fix(helios): add missing external_extents field in cache_memory test Core literal #714).

Claimed benefit and result

  • Eliminates the eight verified startup-race, bounce-slot and 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 defects in AsyncTransferRuntime and DEVICE_POOL allocation.
  • Preserves wire compatibility and unchanged serving behavior for existing cores that do not declare Execution.async_transfers or Capacity::DEVICE_POOL.
  • Single-GPU end-to-end CUDA execution, TLA+ model checking, Rust trace conformance and mutation suites, Kani proofs, and CPU unit tests for memory sizing, rendezvous agreement, io_uring bounded drain, and peer-copy rejection are verified; live multi-host RoCE, live GB10/Jetson unified-DRAM, and live TP>=2 PCIe exported-core execution remain untested (see limitations below).

Supporting evidence and limitations

All checks ran on Linux x86_64 against commit d612cd1c (branched from origin/main 17961ccd):

  • Live single-GPU CUDA integration test (NVIDIA RTX PRO 6000 Blackwell Max-Q):
    CUDA_VISIBLE_DEVICES=1 FLARE_RUN_CUDA_TESTS=1 cargo test --locked --release \
      --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target \
      --lib async_transfer::worker::cuda_tests::live_cuda_async_transfer_end_to_end -- --exact --nocapture
    Result: 1 passed, 0 failed (0.94 s). Verified ControlHeader::worker_state == ChannelState::Running immediately upon start() returning, same-slot HostToDev followed by DiskToHost reuse on copy_stream, real EOF IoFailure writing completion_error_sentinel(ErrorCode::IoFailure) to both host and device completion slots, and snapshot() returning retained counters after invalidate_control() and MappedHost unmapping.
  • TLA+ model checking, Rust trace conformance, and mutation suite (tla2tools-1.7.4.jar, OpenJDK 21, per docs/verification.md):
    python3 verification/helios-lifecycle/check.py \
      --tlc-jar <path-to-tla2tools-1.7.4.jar> \
      --java <path-to-openjdk-21-java> \
      --target-dir flare-cli/target --mutations
    Result: all 10 TLA+ models, all 9 conformance suites (359 observed Rust transitions checked against AsyncTransfer.tla), and all TLA+ and Rust mutation checks passed (including mutations that violate FaultedDmaRetainsOwnership or emit success cookies on failed I/O or DMA).
  • Kani 0.68.0:
    cargo kani --manifest-path helios/Cargo.toml --features runtime-core --lib \
      --harness 'async_transfer::kani_proofs::'
    Result: 5/5 harnesses verified, 0 failures.
  • Rust crate test suites and release builds (--locked --release --target-dir flare-cli/target):
    • 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. All 6 failures are chat-template tests (frontend::jinja::tests::*, frontend::templates::tests::*, server::protocol::decode::native_prompt_tests::*) that require FLARE_TEST_TEMPLATE_DIR populated by tests/frontend/prepare_templates.py. All targeted suites passed: async_transfer:: (15/15), runtime_core::memory:: (27/27, 1 GPU-ignored), runtime_core::model:: (7/7), and execution::rendezvous:: (6/6).
    • flare: 255 passed, 0 failed, 4 ignored.
    • flare-cli: 249 passed, 0 failed, 3 ignored; cargo build --locked --release --manifest-path flare-cli/Cargo.toml and cargo check --locked --release --manifest-path flare-cli/Cargo.toml --features roce succeeded with 0 warnings.
    • heliopause (export::binding::): 15 passed, 0 failed.
  • Limitations and unrun checks:
    • Live multi-host RoCE cluster loading with Capacity::DEVICE_POOL was not executed (covered by TCP loopback rendezvous and Membership::device_pools unit tests).
    • Live GB10/Jetson unified-DRAM serving was not executed (covered by integrated-rank memory-budget and prefix-cache deduction unit tests).
    • Live TP>=2 PCIe peer-copy load-time rejection on an exported core was not executed (covered by validate_async_transfer_peer_copy_compatibility unit tests).
    • The 6 FLARE_TEST_TEMPLATE_DIR-dependent frontend template tests in helios were not run because the template fixtures were not fetched in this environment.

Discord: lukealonso

…s, 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<ControlAccess>) 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 <lalonso@gmail.com>
@lukealonso
lukealonso merged commit b10e122 into main Dec 4, 2026
3 checks passed
jcartu added a commit to jcartu/hyperflare-inference that referenced this pull request Dec 4, 2026
… inherit orbit memory reserve, and log integrated MemInfo

Why

- On Linux unified-memory GPUs (such as GB10), CUDA allocations and context
  creation can respond to Linux `MemFree` rather than `MemAvailable` when
  tens of gigabytes of clean page cache accumulate from core distribution
  and buffered cache I/O (NVIDIA#630).
- `flare-cli`'s peer-serving path (`distribution::serve_source`) streamed
  core shards via buffered `RangeReader` before dropping page cache,
  leaving multi-GiB bursts in the page cache during transfer, and four
  buffered I/O sites across `flare-cli` and `helios` omitted
  `release_page_cache`.
- `flare orbit run` did not inherit `[memory] reserve` from host
  configuration (`config.rs`), unlike `flare run`, while persistent
  groups still needed their stored `--memory-limit` preserved unless
  overridden on the command line and must not freeze config defaults into
  saved `GroupSpec.serving` definitions.
- When integrated-GPU cache planning was memory-limited or
  `cuDevicePrimaryCtxRetain` / `cuCtxCreate_v2` returned
  `CUDA_ERROR_OUT_OF_MEMORY`, diagnostics did not surface Linux
  `MemFree / MemAvailable / Cached` or hint when reclaimable page cache
  was likely blocking allocation.

What changed

- Direct peer serving and missed `release_page_cache` sites:
  - Re-exported `eos` direct-I/O helpers (`FileReadAt`, `allocate_aligned`,
    `direct_reopen`, `free_aligned`) from `helios/src/lib.rs`.
  - Updated `flare-cli/src/distribution.rs::serve_source` to reopen files
    with `direct_reopen` on Unix and stream 4 MiB aligned chunks from a
    zero-initialized `AlignedBuffer` (handling arbitrary unaligned offsets,
    multi-range requests, and unaligned EOF byte-for-byte identically to
    `cache::RangeReader`), falling back cleanly to buffered `RangeReader`
    when `O_DIRECT` is unsupported or returns `EINVAL`, and executing one
    unconditional post-branch `release_page_cache_range` loop in
    `copy_source_ranges` for every served range (including on error).
  - Added `release_page_cache` / `release_page_cache_range` at the four
    missed buffered I/O sites: `flare-cli/src/orbit/controller.rs`,
    `flare-cli/src/core_cache.rs`, `flare-cli/src/orbit/agent.rs::get`,
    and `helios/src/core/cache.rs` (`write_stream`, `verify_file`,
    `hash_file`, `import_legacy_into`, and non-Windows `copy_file`).
    Collapsed `verify_file` onto `hash_file(path, release: bool)` so
    `import_legacy_into` hashes with `release = false` (avoiding double
    storage reads before `insert_legacy_container`) and releases the
    source file unconditionally after `insert_legacy_container` returns.
- Orbit `[memory] reserve` propagation:
  - Added `#[arg(skip)] pub config_memory_limit: Option<MemoryLimit>` to
    `OrbitRun` (`flare-cli/src/cli.rs`) and `RunOptions`
    (`flare-cli/src/orbit/controller.rs`), populated from `[memory] reserve`
    in `flare-cli/src/config.rs` only when `--memory-limit` is unset on
    the command line.
  - Kept config-derived `--memory-limit` out of `OrbitRun::rank_options`
    and `GroupSpec.serving` so persistent groups never freeze config
    defaults; applied it only at launch via `apply_config_memory_limit`
    when neither the saved group nor the CLI specifies `--memory-limit`.
  - Added a persistent-group round-trip unit test through `save_group` /
    `Orbit::save` / `Orbit::load` verifying config reserve edits take
    effect on reload while explicit saved and CLI `--memory-limit` values
    retain precedence.
- Linux integrated-GPU `/proc/meminfo` diagnostics:
  - Added `LinuxMemInfo { free, available, cached }` parser and
    `CUDA_ERROR_OUT_OF_MEMORY` constant in `helios/src/runtime_core/`.
  - Appended `MemFree / MemAvailable / Cached` to the `Plan cache`
    summary on Linux integrated GPUs and emitted a concise stderr warning
    when `MemAvailable - MemFree > 10 GiB` and KV sizing is limited by
    memory (without repeating the triple already logged in `Plan cache`).
  - Enriched `cuDevicePrimaryCtxRetain` and `cuCtxCreate_v2`
    `CUDA_ERROR_OUT_OF_MEMORY` failures on Linux integrated GPUs via
    `enrich_integrated_ctx_oom(error, meminfo: Option<LinuxMemInfo>)` with
    `MemFree / MemAvailable / Cached` (and a `drop_caches` hint when
    `MemAvailable - MemFree > 4 GiB`) while preserving the structured
    `ExecutionError::Driver(CudaError { code: 2, .. })` error.
- Documentation:
  - Documented `orbit run` `[memory] reserve` inheritance, non-persistence,
    and saved/CLI `--memory-limit` precedence in `docs/orbit.md` and
    `docs/cli-design.md`, and integrated-GPU `Plan cache` / context-OOM
    `/proc/meminfo` diagnostics in `docs/cli-design.md`.

Verification

- Rebased onto `origin/main` (`f705086b`, including `NVIDIA#720` and `NVIDIA#721`).
- CPU-only verification on Linux x86_64 (no live GB10 run yet):
  - Verified `.githooks/commit-msg` passes on the staged diff and message.
  - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`:
    254 passed (228 bin + 9 cache_commands + 6 cli + 4 inspect + 7 unverified_payload), 0 failed, 3 ignored.
  - `cargo test --locked --release --manifest-path flare/Cargo.toml`:
    255 passed (247 lib + 7 packed_canonical_download + 1 reference_workflows), 0 failed, 4 ignored.
  - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib`:
    `core::cache` 106 passed, 0 failed, 2 ignored; `runtime_core::` 206 passed (including `runtime_core::memory` 30 passed), 0 failed, 13 ignored.
  - `rustfmt --edition 2024`: clean on all touched lines across all 12
    Rust files.

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b
Signed-off-by: Joshua Cartu <jcartu@users.noreply.github.com>
lukealonso pushed a commit that referenced this pull request Dec 4, 2026
… inherit orbit memory reserve, and log integrated MemInfo (#713)

Why

- On Linux unified-memory GPUs (such as GB10), CUDA allocations and context
  creation can respond to Linux `MemFree` rather than `MemAvailable` when
  tens of gigabytes of clean page cache accumulate from core distribution
  and buffered cache I/O (#630).
- `flare-cli`'s peer-serving path (`distribution::serve_source`) streamed
  core shards via buffered `RangeReader` before dropping page cache,
  leaving multi-GiB bursts in the page cache during transfer, and four
  buffered I/O sites across `flare-cli` and `helios` omitted
  `release_page_cache`.
- `flare orbit run` did not inherit `[memory] reserve` from host
  configuration (`config.rs`), unlike `flare run`, while persistent
  groups still needed their stored `--memory-limit` preserved unless
  overridden on the command line and must not freeze config defaults into
  saved `GroupSpec.serving` definitions.
- When integrated-GPU cache planning was memory-limited or
  `cuDevicePrimaryCtxRetain` / `cuCtxCreate_v2` returned
  `CUDA_ERROR_OUT_OF_MEMORY`, diagnostics did not surface Linux
  `MemFree / MemAvailable / Cached` or hint when reclaimable page cache
  was likely blocking allocation.

What changed

- Direct peer serving and missed `release_page_cache` sites:
  - Re-exported `eos` direct-I/O helpers (`FileReadAt`, `allocate_aligned`,
    `direct_reopen`, `free_aligned`) from `helios/src/lib.rs`.
  - Updated `flare-cli/src/distribution.rs::serve_source` to reopen files
    with `direct_reopen` on Unix and stream 4 MiB aligned chunks from a
    zero-initialized `AlignedBuffer` (handling arbitrary unaligned offsets,
    multi-range requests, and unaligned EOF byte-for-byte identically to
    `cache::RangeReader`), falling back cleanly to buffered `RangeReader`
    when `O_DIRECT` is unsupported or returns `EINVAL`, and executing one
    unconditional post-branch `release_page_cache_range` loop in
    `copy_source_ranges` for every served range (including on error).
  - Added `release_page_cache` / `release_page_cache_range` at the four
    missed buffered I/O sites: `flare-cli/src/orbit/controller.rs`,
    `flare-cli/src/core_cache.rs`, `flare-cli/src/orbit/agent.rs::get`,
    and `helios/src/core/cache.rs` (`write_stream`, `verify_file`,
    `hash_file`, `import_legacy_into`, and non-Windows `copy_file`).
    Collapsed `verify_file` onto `hash_file(path, release: bool)` so
    `import_legacy_into` hashes with `release = false` (avoiding double
    storage reads before `insert_legacy_container`) and releases the
    source file unconditionally after `insert_legacy_container` returns.
- Orbit `[memory] reserve` propagation:
  - Added `#[arg(skip)] pub config_memory_limit: Option<MemoryLimit>` to
    `OrbitRun` (`flare-cli/src/cli.rs`) and `RunOptions`
    (`flare-cli/src/orbit/controller.rs`), populated from `[memory] reserve`
    in `flare-cli/src/config.rs` only when `--memory-limit` is unset on
    the command line.
  - Kept config-derived `--memory-limit` out of `OrbitRun::rank_options`
    and `GroupSpec.serving` so persistent groups never freeze config
    defaults; applied it only at launch via `apply_config_memory_limit`
    when neither the saved group nor the CLI specifies `--memory-limit`.
  - Added a persistent-group round-trip unit test through `save_group` /
    `Orbit::save` / `Orbit::load` verifying config reserve edits take
    effect on reload while explicit saved and CLI `--memory-limit` values
    retain precedence.
- Linux integrated-GPU `/proc/meminfo` diagnostics:
  - Added `LinuxMemInfo { free, available, cached }` parser and
    `CUDA_ERROR_OUT_OF_MEMORY` constant in `helios/src/runtime_core/`.
  - Appended `MemFree / MemAvailable / Cached` to the `Plan cache`
    summary on Linux integrated GPUs and emitted a concise stderr warning
    when `MemAvailable - MemFree > 10 GiB` and KV sizing is limited by
    memory (without repeating the triple already logged in `Plan cache`).
  - Enriched `cuDevicePrimaryCtxRetain` and `cuCtxCreate_v2`
    `CUDA_ERROR_OUT_OF_MEMORY` failures on Linux integrated GPUs via
    `enrich_integrated_ctx_oom(error, meminfo: Option<LinuxMemInfo>)` with
    `MemFree / MemAvailable / Cached` (and a `drop_caches` hint when
    `MemAvailable - MemFree > 4 GiB`) while preserving the structured
    `ExecutionError::Driver(CudaError { code: 2, .. })` error.
- Documentation:
  - Documented `orbit run` `[memory] reserve` inheritance, non-persistence,
    and saved/CLI `--memory-limit` precedence in `docs/orbit.md` and
    `docs/cli-design.md`, and integrated-GPU `Plan cache` / context-OOM
    `/proc/meminfo` diagnostics in `docs/cli-design.md`.

Verification

- Rebased onto `origin/main` (`f705086b`, including `#720` and `#721`).
- CPU-only verification on Linux x86_64 (no live GB10 run yet):
  - Verified `.githooks/commit-msg` passes on the staged diff and message.
  - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`:
    254 passed (228 bin + 9 cache_commands + 6 cli + 4 inspect + 7 unverified_payload), 0 failed, 3 ignored.
  - `cargo test --locked --release --manifest-path flare/Cargo.toml`:
    255 passed (247 lib + 7 packed_canonical_download + 1 reference_workflows), 0 failed, 4 ignored.
  - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib`:
    `core::cache` 106 passed, 0 failed, 2 ignored; `runtime_core::` 206 passed (including `runtime_core::memory` 30 passed), 0 failed, 13 ignored.
  - `rustfmt --edition 2024`: clean on all touched lines across all 12
    Rust files.

Design-Signed-Off-By: Antigravity (Gemini 3.1 Pro); design-review=2e5b

Signed-off-by: Joshua Cartu <jcartu@users.noreply.github.com>
Co-authored-by: Joshua Cartu <jcartu@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant