Opened by a workflow run, Dec 4, 2026 10:35 PM EST. decide malicious: all_clear (100%): No malicious content found
explore
Author: lukealonso (COLLABORATOR, charter-listed priority contributor; dominant committer in helios/src, docs and verification/helios-lifecycle); Discord lukealonso
Motivation: Helios's brand-new AsyncTransfer primitive could only move data disk→host, host→device and disk→device, all on one CUDA stream, with an io_uring ring built off the worker thread; this PR adds device→host demotion, splits demand from background copies, hardens the Linux io_uring path, fixes host-wide --pool-ram-memory scaling and starts rank workers in parallel.
Scale: +1769 / −268 in 16 files
Proposal:
- Add
Opcode::DevToHost = 5with validation,cuMemcpyDtoHAsync_v2and a thirdd2h_stream, plus schedulerd2h_queues/inflight_d2hand D2H drain ownership. - Split Copy Engine work into high-priority demand, normal background H2D and D2H streams, arbitrated by
cuStreamWaitEventslot reuse and a per-slotstream_comp_maxthat can skip stale completion writes. - Build the io_uring ring on the worker thread with
SINGLE_ISSUER|DEFER_TASKRUN, register 1 GiB fixed buffers forReadFixed, add a taskrun/getevents poll watchdog, and rotate storage read order per worker. - Apply
--pool-ram-memoryhost-wide before dividing across discrete ranks, skip Selene's implicit reserve when the flag is explicit, and charge peer-UVA page tablespinned*ranks/512. - Start all rank workers concurrently with
std::thread::scope; update manifest.md, cli-design.md and runtime-core-design.md. Touches: helios/src/async_transfer/worker.rs(+710/−131) — three-stream completion arbitration replaces the single-stream invariant #721/#727 relied on.helios/src/async_transfer/scheduler.rsandverification/helios-lifecycle/AsyncTransfer.tla— new D2H lifecycle, demand-gated background dispatch, 20-int projection.helios/src/runtime_core/memory.rs— rewrites the two-day-old discrete pool budget math, changing--pool-ram-memorysemantics for existing multi-rank users. Related items:- #711 helios,flare-cli: add domain-agnostic AsyncTransfer primitive (merged): created the whole subsystem this PR extends.
- #721 harden AsyncTransfer startup, DMA and teardown lifetimes (merged): supplied the single-stream completion invariant and flush accounting #737 rewrites/refines.
- #727 gate PCIe peer-access graphs and fix teardown/startup drain races (merged): merged 4h before #737 opened; same TLA model and files.
- #726 overlap startup allocation, registration and setup (open): rewrites the same
prepare_async_transfers#737 parallelizes. - #628 helios: gate offload Copy Engine batches during peer-copy graphs (merged): adjacent Copy Engine history, not competing.
Link: https://github.com/NVIDIA/hyperflare-inference/pull/737
Autobot comments: Undisclosed default changes: per-channel NVMe read depth halves (32→16, bg 8→4) and bounce pinning rises to 512 MiB for 16 MiB extents, entangled with the PR's own NVMe claim. No telemetry exists for D2H bytes or D2H failures.
docs/cli-design.mdcontradicts itself (per-host at :761, per-rank sample at :1418) and the flag's behaviour changes without its--helptext changing. The perf headline (>5,000 ms → 1,202 ms) names no baseline or raw data, againstdocs/design-review.md:106-115; the Kani proof was not run, which the same document says blocks acceptance; the model is checked atMaxD2h = 1while production defaults to 2. Background prefetch can now be starved indefinitely by continuous demand. No in-repo issue asks for any of this — the consumer is the companion hyperflare-recipes PR.
Classify intake
Selected: triage:review, performance, enhancement, area:memory
Threshold: 65%
Triage
- [✓]
triage:review: 98.9% -
triage:design-review: 0.6% -
triage:validation: 0.4% -
triage:integration: 0.0% -
none: 0.0% -
triage:investigate: 0.0% -
triage:partial: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Priority
-
none: 99.9% -
priority:P1: 0.1% -
priority:P2: 0.0%
Type
- [✓]
enhancement: 98.0% - [✓]
performance: 97.1% -
community: 59.3% -
bug: 29.4% -
duplicate: 4.7% -
documentation: 0.1%
Area
- [✓]
area:memory: 67.9% -
area:selene: 56.2% -
area:scheduling: 40.7% -
area:preparation: 37.8% -
area:api: 26.9% -
area:caching: 26.9% -
area:kernels: 1.6% -
area:rocenante: 1.4% -
area:orbit: 0.4% -
area:packaging: 0.2% -
area:engram: 0.1%
Model
-
model:mimo-v2.6: 2.3% -
model:glm-5.3: 1.2% -
model:deepseek-v4: 0.8% -
model:muse-glimmer: 0.8% -
model:nemotron-3.5-bolt: 0.7% -
model:kimi-k3.1: 0.6% -
model:qwen3.8-flash-next: 0.5% -
model:inkling-small: 0.4% -
model:qwen3.8-27b: 0.4% -
model:deepseek-v4.1: 0.2% -
model:gemma4: 0.1%
Value Proposition
Value Proposition — PR #737 (async_transfer: DevToHost, dual-stream H2D, DEFER_TASKRUN io_uring, host-wide RAM pool budgeting)
Charter alignment — met. Every change stays inside Helios's hardware/OS/lifecycle boundary: no per-model branches, no new captured-graph op contracts, no aliases or recipes, and it supports the charter's host-memory cache goal. Items 4–5 (host-wide --pool-ram-memory, peer-UVA page-table charging, sequential startup) are root-cause fixes to code this author merged 48 hours earlier (#711/#721), matching the charter's "bug fixes need to address the root cause."
Novelty & status — additive. main has no D2H opcode, no multi-stream split, no DEFER_TASKRUN/ReadFixed path; no merged commit covers them, so it is not obsolete. Open #726 touches prepare_async_transfers but restructures teardown/startup rather than transfer semantics — it conflicts, it does not supersede.
Value vs maintenance cost — real but thinly evidenced.
- Who benefits: operators of multi-rank SM120 hosts with NVMe offload. The
-8G→8 GiB host-wide and64G-per-rank budget behaviour is a genuine, unit-verified correctness fix that misconfigures existing users today. - Evidence strength for the headline: weak. ">5,000 ms → 1,202 ms" cites no baseline commit, no raw per-rank data and no log for the 2,198,299-transfer smoke, and is entangled with this PR's undeclared IO-depth halving (32→16, bg 8→4) and a new 50 ms per-channel spin. That falls short of
docs/design-review.md:106-115and the charter's "bring real evidence." - Cost: high. Three streams deliberately reverse the single-stream completion invariant #721/#727 relied on, restored via
cuStreamWaitEventplus a per-slotstream_comp_maxthat can silently skip a completion write — covered by one live GPU test, no CPU test, and no per-slot stream dimension in the TLA model. D2H traffic and failures have no telemetry. ModelledMaxD2h = 1vs runtime default 2. Kani unrun, whichdocs/design-review.md:247-251treats as blocking acceptance. - Process risk: zero reviews, no in-repo demand (consumer lives in the companion recipes PR), and
--pool-ram-memorysemantics change for existing multi-rank configs with unchanged--helptext and self-contradicting docs.
Verdict: Worth it with changes. The author is a named priority contributor and owner of this subsystem, and the budgeting fix alone justifies the increment. Required first: real baseline and raw measurements for the stall-spread claim (or drop it); Kani green; disclose and re-justify the IO-depth and bounce-footprint changes; add D2H counters; a CPU-level test for the stream_comp_max skip path; align MaxD2h; fix docs/--help; and settle merge order with #726.
Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.
Apply Labels (Intake)
Applied: +triage:review, +performance, +enhancement, +area:memory
Gates and contracts
Contracts, Charter & Verification Gates Audit — PR #737 (46e6a3b)
Scope: only hard governance/contract/vendored-dependency/mandatory-verification gates. No algorithm-correctness findings (separate lens).
Verdict: no Blocker. Two Major findings (one verification-evidence gate, one contract-document contradiction), plus three Minor/Info notes. No chapter of the charter, core-format, wire, or captured-graph contract is structurally violated.
Gate 1 — Signed core / wire / captured-graph / public contract boundaries: PASS with one Major doc defect
No proto, core-format, signing, or captured-graph change. The 16 changed files contain no helios/proto/*.proto, no core.proto (not opened), no verification/helios-lifecycle schema change beyond the model, no helios/native/*. ExternalExtentTable is untouched (docs/core-format-design.md:224). PayloadDescriptor/signing domain separators untouched.
The new opcode is inside the already-approved subsystem, not a new captured-graph operation family. Opcode::DevToHost = 5 (helios/src/async_transfer/ring.rs:64, from_u32 :75, ValidatedCommand::DevToHost :259, validate_command :497-514). design-review.md:22-26 requires owner approval for a new captured-graph operation family; AsyncTransfer commands are a mapped-host control ring, not graph nodes, and main treating opcodes 1..=4 as an open enum domain means 5 is a shape/variant extension of an existing contract. Approval gate not triggered.
Backward compatibility verified as claimed. ABI_VERSION remains 1 (ring.rs:12), ControlHeader stays 256 bytes (:14), and an older runtime rejects value 5 cleanly through Opcode::from_u32.
Normative docs updated where contradicted. helios/manifest.md:170-230 gains DEV_TO_HOST (5), the demand/background stream split, cross-stream cuStreamWaitEvent slot reuse, and the drain-over-all-streams wording. docs/runtime-core-design.md:729-780 gains host-wide --pool-ram-memory, pinned.saturating_mul(discrete_ranks).div_ceil(512), worker-owned io_uring, and concurrent rank startup. No contradiction exists in docs/scheduling-theory.md (not opened) or docs/scheduling-runtime-design.md — neither mentions async transfer, HOST_POOL, or offload stream policy (grep returns no async-transfer reference in scheduling-runtime-design.md).
MAJOR — docs/cli-design.md contradicts itself on a shipped, operator-visible default in the same file the PR edits:
docs/cli-design.md:761(changed by this PR): "Per-host ceiling … (divided evenly across local discrete ranks)".docs/cli-design.md:1418(unchanged): "# pool_ram = "" # Per-rank ceiling for pinned AsyncTransfer host pools".
This is not a phrasing nit: the semantics genuinely changed for existing multi-rank users. On main, async_transfer_host_ram divided host_pool_budget_and_total(host_future) (implicit Selene reserve always applied) by discrete_ranks before --pool-ram-memory was applied, so -8G meant 8 GiB per rank. At head, helios/src/runtime_core/memory.rs:113-131 applies the MemoryLimit::Reserve host-wide and subtracts the aggregate bounce before dividing (:118-124), so -8G now means 8 GiB per host. --pool-ram-memory 64G becomes 8 GiB/rank on 8 ranks. The same PR updates the flag table but not the flare.toml (not opened) sample that operators copy, leaving two contradictory authoritative statements about one flag. docs/cli-design.md is the CLI contract, so this is a contract-document defect, not pedantry. Fix: update :1418 to "Per-host ceiling (divided across local discrete ranks)". (--help at flare-cli/src/cli.rs:961-962 already said "Per-host", so no CLI-text change is required.)
Nothing else in Gate 1: no normative invariant in scheduling-theory.md (not opened) / scheduling-runtime-design.md / core-format-design.md is contradicted on a shipped default, and no supports_*/can_* model-allowlist flag was added (design-review.md:58-61).
Gate 2 — Vendored upstream dependencies and cross-PR pinning: PASS
- No vendored upstream file is forked.
helios/native/roce_proxy.c(not opened) (theROCE_ABI_VERSION 14vendored proxy) is untouched; the diff touches nohelios/native/path, andPROXY_ABI/roce_abi_versionare unchanged. - No new dependencies. Everything added is via the existing dynamic-driver table (
helios/src/runtime_core/driver.rs:cuCtxGetStreamPriorityRange,cuStreamCreateWithPriority,cuStreamWaitEvent,cuMemcpyDtoHAsync_v2), which is the repository's standard mechanism. NoCargo.toml(not opened) change in the file list. - The external dependency points the right way. The
local-inference-lab/hyperflare-recipescompanion PR is downstream (its consumer depends on this ABI), and the description states the required merge order explicitly ("Merge this PR before the companion recipes PR"), which is exactly whatAGENTS.md:126-128requires for stacked work. Nothing here consumes an unmerged upstream or an unpinned external artifact. - Info (not a violation): no in-repo producer emits opcode 5 (
helios/manifest.md,ring.rs, and the worker tests are the only references); the graph-side consumer lives in the companion recipes repository. That is a demand-evidence question, already covered by the Value lens, not a vendored-dependency violation.
Gate 3 — Mandatory verification evidence and failing tests: one Major
TLA+ layer: satisfied (Round-1 evidence, not re-flagged). verification/helios-lifecycle/AsyncTransfer.tla:158-186 adds DispatchD2h/CompleteD2h/MarkD2hFaulted; the projection grows to 20 (:336-341), matching AsyncTransfer.cfg:6 (MaxD2h = 1), verification/helios-lifecycle/check.py (ASYNC_TRANSFER_EDGE …, 20), and helios/src/async_transfer/lifecycle_tests.rs (type Projection = [i64; 20], with_max_d2h). New TLA+ and Rust mutations cover the D2H drain gate and the hardware-signaled D2H sentinel (check.py additions). The model was run per the description (check.py --tlc-jar … --mutations, exit 0, 1,847,851 generated / 125,668 distinct states, 4,410 observed transitions, 64/64 mutations). DEFAULT_MAX_D2H = 2 (worker.rs:52) vs modelled MaxD2h = 1 follows the model's existing convention (MaxTotalDma = 2 vs runtime DEFAULT_MAX_TOTAL_DMA = 16, MaxBgDma = 1 vs 4), so it is not an "aligned bounds" violation — design-review.md:241-246 is aimed at protocol states the model cannot reach at all, and D2h states are all reachable at MaxD2h = 1. Info only.
Kani: not flagged. kani_proofs.rs:199-217 adds the ValidatedCommand::DevToHost arm, and docs/design-review.md:247-251 treats an unrun applicable Kani proof as blocking. The author discloses cargo-kani is unavailable locally. The repository CI runs exactly this proof set — .github/workflows/helios-lifecycle.yml:49 (not opened) executes cargo kani --manifest-path helios/Cargo.toml (not opened) --features runtime-core --lib, which compiles async_transfer::kani_proofs (helios/src/async_transfer/mod.rs:11-12) behind #[cfg(kani)]. Per calibration I do not flag an unobservable Actions result, and the PR reports no Kani failure; the gate is dischargeable on CI rather than structurally missing.
Crate tests: satisfied as reported. --locked --release runs for eos, selene, selene-manager, flare, flare-cli, targeted helios async_transfer:: / runtime_core::memory:: / runtime_core::model:: (60/60 under RUSTFLAGS="-D warnings"), full helios --lib (1,973) and integration targets. The 6 disclosed failures are helios --lib frontend-template tests failing on an HTTP 403 while fetching an unrelated Hugging Face model through tests/frontend/prepare_templates.py (not opened) — hermeticity, unrelated to this diff, same disclosure pattern as #727. Not a failing-test gate failure on this change's paths, and the PR reports no CI failure.
MAJOR — the performance claim does not satisfy the mandatory evidence rule. The headline "cross-rank demand-stall spread >5,000 ms → 1,202 ms" (37.75–38.95 s across 8 ranks) has no baseline commit or main revision, no raw log, and no per-rank table; it is a single isolated run. Worse, it is not attributable to the claimed mechanism: the same PR halves per-channel NVMe read concurrency — DEFAULT_MAX_TOTAL_IO 32 → 16 and DEFAULT_MAX_BG_IO 8 → 4 (helios/src/async_transfer/worker.rs:48-49) — and adds a 50 ms active spin window (worker.rs:43), both of which independently change the measured stall spread. docs/design-review.md:106-115 requires "equivalent baselines, complete GPU steps across all ranks, and actual Helios service measurements … keep raw measurements", and the charter requires a benchmark showing a speedup over main on a served workload. A combined-effect number presented as the effect of DEFER_TASKRUN fails that rule. Either attach the baseline commit, the raw per-rank stall data and the configuration for a main-vs-branch A/B, or drop the quantitative claim and state the change as expected rather than measured. The 2,198,299-transfer, 0-error, 9.1 s-drain 8-GPU smoke run is likewise self-reported with no log attached, so the cross-rank execution evidence (design-review.md:252-259) is asserted but unattributable.
Gate 4 — Material scope and claim contradictions: one Major (disclosure), nothing else
MAJOR — the description omits material numerical and resource changes, against the required-description contract. AGENTS.md:92-94 requires the "what changed" section to "Identify material numerical, compatibility, and resource-lifetime changes." Undeclared in the description: (a) per-channel IO depth halving, DEFAULT_MAX_TOTAL_IO 32 → 16 and DEFAULT_MAX_BG_IO 8 → 4 (worker.rs:48-49) — directly entangled with the PR's own NVMe argument; (b) pinned bounce footprint growth: bounce_pool_geometry now returns (MAX_BOUNCE_POOL_BYTES / slot_bytes).clamp(16, 32) (worker.rs:93-94) with MAX_BOUNCE_SLOTS = 32 (:54), so 16 MiB extents pin 32 × 16 MiB = 512 MiB per channel instead of 256 MiB; (c) new DEFAULT_MAX_D2H = 2 (:52). The description's five "what changed" bullets are otherwise accurate — I verified the budget math in helios/src/runtime_core/memory.rs:75-164 (-8G → 8 GiB host-wide; 64G → host-wide then ÷ ranks = 8 GiB/rank on 8 ranks; under MemoryLimit::Reserve the aggregate bounce is subtracted before the reserve so the requested free reserve is preserved: host_bounce = total_bounce * ranks, host_cap = available - host_bounce - reserve, then / ranks), the Selene helper (selene/src/offload.rs:979-988, host_pool_budget still forwards with apply_reserve = true, so existing callers are behaviour-preserving), the peer-UVA page-table charge (pinned.saturating_mul(ranks).div_ceil(512) on discrete only, integrated unchanged), and the concurrent rank startup (helios/src/runtime_core/model.rs:1080-1110, std::thread::scope with first-error propagation). No claim of a test or benchmark that is absent from the diff; no unrelated tooling bundle; +1769/−268 matches the file list.
MINOR — the lifecycle verification README was not updated with the model it documents. docs/verification.md:118-119 requires the check documentation to "Document the functions, state projection, bounds, and external contracts needed to interpret the check." verification/helios-lifecycle/README.md:353-384 still states a "16-integer projection", lists bounds without MaxD2h, and enumerates the driven transitions without dispatch_d2h, complete_d2h or mark_d2h_faulted — every one of which this PR changes. The model, cfg, check.py and Rust fixture are all updated; only their human-readable specification is stale, so the next reviewer reading the README will be told the wrong projection width.
MINOR — the published metric contract does not describe the new traffic. docs/api.md:417-429 enumerates the flare_async_transfer_* series and includes only bytes_disk_to_host, bytes_host_to_dev and bytes_disk_to_dev; ControlHeader likewise (ring.rs:200-204), and complete_d2h/mark_d2h_faulted zero all three (scheduler.rs:994-996 (not opened), :1021-1023) while mark_d2h_faulted publishes an error sentinel. The doc is consistent with the code, so this is not a contradiction — but full-duplex D2H bytes and D2H failures are now invisible in the documented metric surface, and that gap should either be documented or closed with a D2H counter.
Info / Nit — open #726 restructures the same prepare_async_transfers (model.rs:1080-1110) that this PR parallelizes; merge order needs settling, with no contract gate of its own.
Required before merge
- Fix the
--pool-ram-memorycontradiction:docs/cli-design.md:1418must say per-host (divided across local discrete ranks), matching:761. - Make the stall-spread claim attributable — baseline commit, raw per-rank data and configuration for a
main-vs-branch A/B — or demote it to an expectation, and disclose the IO-depth halving, the up-to-512-MiB bounce increase andDEFAULT_MAX_D2H = 2in the description. - Update
verification/helios-lifecycle/README.md:353-384to the 20-integer projection,MaxD2h, and the three D2H transitions. - Confirm the CI
kanijob passes on this head (.github/workflows/helios-lifecycle.yml:49(not opened)), sincedocs/design-review.md:247-251makes it blocking, and add a D2H byte/failure counter or document its absence indocs/api.md.
Subtraction and simplicity
Subtraction & Simplicity Lens — PR #737 audit
Verdict: the diff is not lean. It adds ~1,770 lines to a subsystem that is two days old, and a large share of the growth is duplicated logic that could collapse into one helper, plus dead/speculative surface. Concrete, high-signal items below, ordered by value.
1. The largest duplication: completion-slot signalling is now written three times in worker_main
The same 30-line block — should_write_stream_comp → wait_other_streams_on_slot → use_write_value64 branch → stream_write_value64/upload_async → record_stream_comp → EventCompletionAction selection — is copy-pasted verbatim for each stream:
- H2D DMA path:
helios/src/async_transfer/worker.rs:1418-1475 - D2H path:
helios/src/async_transfer/worker.rs:1539-1587 - Host-initiated path:
helios/src/async_transfer/worker.rs:998-1042
Verbatim, H2D (:1438-1473):
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(target_stream, target_addr, dma.signal_value, CU_STREAM_WRITE_VALUE_DEFAULT)
};
if signal_status == 0 {
record_stream_comp(slot, dma.signal_value);
...
…and D2H (:1550-1577) is the same text with d2h_stream/d2h.signal_value. Three copies of address computation, three copies of the signals_device_word → HostOnly vs HostAndDevice rule, three copies of the stream_comp_max gate.
Simplification: extract one closure/fn
fn submit_with_completion(stream, slot, value, target_stream_others) -> (signal_status, hardware_signaled, EventCompletionAction)
and call it from all three sites. This removes ~100 duplicated lines and, more importantly, makes the "monotonic skip" rule exist in exactly one place — currently a reader must diff three blocks to convince themselves the streams agree.
Same story one level up: publish_notice takes (&VecDeque, &VecDeque) "other queues" purely so it can forward them to signal_completion_slot, which forwards them to wait_other_streams_on_slot. Every one of ~14 call sites must pass the correct pair, and the pairs are chosen by hand at each site, e.g. worker.rs:1423-1436:
if is_dem {
wait_other_streams_on_slot(target_stream, slot, &pending_bg_dma_events, &pending_d2h_events);
} else {
wait_other_streams_on_slot(target_stream, slot, &pending_dem_dma_events, &pending_d2h_events);
}
Simplification: replace the three parallel VecDeques + hand-picked pairs with one array indexed by stream kind — pending_dma_events: [VecDeque<PendingEventDma>; 3] with FaultedStreamKind already giving you the index (the PR introduces exactly that enum at worker.rs:332-337 and then does not use it for the queues). wait_other_streams_on_slot then becomes "iterate the two other indices", the bg_q/d2h_q parameters disappear from publish_notice and signal_completion_slot, and the if is_dem { … } else { … } blocks vanish. That deletes a parameter from two hot closures and ~10 call sites, and removes a real footgun (passing the wrong queue pair is currently silent).
2. Dead / unreachable generality added by this diff
with_max_d2his speculative generality.scheduler.rs:227-232adds a builder, defaulted to2atscheduler.rs:211(a bare magic literal innew()), and the only production caller re-supplies the same value:worker.rs:929.with_max_d2h(DEFAULT_MAX_D2H)whereDEFAULT_MAX_D2H = 2(worker.rs:52). Two constants, one builder, one default, all saying2, and the TLA+ model is checked atMaxD2h = 1. Simplify: makemax_d2ha plain argument ofTransferScheduler::newalongsidemax_total_dma/max_bg_dma(where every other cap already lives), or drop the builder and keep one constant. The pattern is also inconsistent:max_total_io/max_bg_io/max_total_dma/max_bg_dmaare constructor args,max_d2halone is a.with_override.- Three near-identical
IoBackendtrait methods default to no-ops.io_backend.rs:33-42addsbind_worker_thread()andunsafe fn register_buffers(...)with emptyOk(())bodies, and the only other implementor,PreadBackend(io_backend.rs:484), uses both defaults. That is fine, but note the call sites also swallow every error:worker.rs:895-906
combined withlet _ = args.io_backend.bind_worker_thread(); ... let _ = unsafe { args.io_backend.register_buffers(®_regions) };register_buffersitself returningOk(())on failure (io_backend.rs:317-323: theErr(_)arm retries smaller and then falls through toOk(())even when nothing was registered). Simplify:bind_worker_thread/register_buffersshould be one methodprepare_worker(&mut self, regions: &[(*mut u8, usize)])returning whether the fast path is active, and the worker should record that boolean once (it is needed anyway — nothing today can tell whetherReadFixed/DEFER_TASKRUNis live). One trait method instead of two, and one honest signal instead of twolet _ =. dem_io_inflight/dem_dma_inflightare one-line helpers used only as> 0.scheduler.rs:335-341and:351-357exist solely to be compared against zero at:634,:789,:924.bg_io_inflight/bg_dma_inflighthave the same shape. Four counting accessors for a two-way predicate;fn demand_inflight(&self) -> bool(or reusinginflight_*.iter().any(|op| !op.priority.is_background())) collapses both pairs.queued_d2h_count,inflight_d2h_count,faulted_d2h_count,hw_signaled_faulted_d2h_count,is_d2h_faulted(scheduler.rs:255, 265, 278, 320, 369) are test/projection-only (all uses are inlifecycle_tests.rs, per grep). Acceptable aspub(crate), but they arepubon a public type and mirror the DMA set one-for-one; theproject()helper (lifecycle_tests.rs:52-55) would be just as clear computing them inline, andis_d2h_faultedduplicates theop.faultedpredicate thatmark_d2h_faulted/complete_d2halready encode.
3. mark_d2h_faulted + complete_d2h are byte-for-byte clones of mark_dma_faulted + complete_dma
scheduler.rs:851-880 vs :969-998 differ only in the container (inflight_dma vs inflight_d2h) and in that D2H has no bounce slot; complete_dma (:887-914) vs complete_d2h (:1001-1025) differ only in the bounce-slot return and the two byte counters that D2H hardcodes to 0. That is ~90 net duplicated lines, and it is the third pairing in the file (InflightDma/InflightD2h structs at :118-136/:140-153 are already nearly identical).
Simplification: one InflightOp with kind: TransferKind {Io, H2d, D2h} plus Option<bounce_slot>/Option<host_offset> (as InflightIo already does), one inflight: Vec<InflightOp>, and pop_next_io/pop_next_dma/pop_next_d2h collapsed to one dispatcher over a per-kind cap. The PR already established the pattern it should follow: InflightIo uses Option pairing (host_offset: Option<u64>, bounce_slot: Option<usize>, device_offset: Option<u64>, ring.rs-style) precisely so invalid states are unrepresentable — InflightD2h instead spells out eight always-present fields and then the code immediately adds an unreachable!() (scheduler.rs:945) to reject the wrong variant, which is the tell that the enum was not needed.
Same for QueuedOp::DevToHost (scheduler.rs:58-67), which duplicates QueuedOp::HostToDev field-for-field, and forces four match arms to grow a | Self::DevToHost { .. } clause (:73-77, :83-87, :92, :704, :79).
And in ring.rs: ValidatedCommand::DevToHost (:256-264) and validate_command's Opcode::DevToHost arm (:497-517) are character-identical to HostToDev (:438-457) except for the variant name — the nbytes == 0, host-range, device-range checks are the same four lines twice. Simplify: one match arm Opcode::HostToDev | Opcode::DevToHost => computing the shared validation once and constructing the variant by direction, and one ValidatedDma { direction: H2d|D2h, .. }.
The Kani proof inherits the duplication: the new DevToHost arm (kani_proofs.rs:199-218) is a copy of the HostToDev arm (:180-198) with two extra asserts (alignment >= MIN_ALIGNMENT && alignment.is_power_of_two(), which the code does not actually check for either direction — see below). If ValidatedCommand had one DMA variant, this arm would not exist at all.
Concrete consequence of the copy-paste worth flagging: the Kani DevToHost arm asserts alignment >= MIN_ALIGNMENT && alignment.is_power_of_two() (kani_proofs.rs:210), but validate_command's DevToHost arm discards the align mask — let (priority, _) = validate_transfer_header(cmd.priority, alignment)?; (ring.rs:498) — and only checks alignment indirectly via that helper. HostToDev does exactly the same (ring.rs:439) but its Kani arm (kani_proofs.rs:188-198) does not assert alignment. So the two proof arms disagree about the same behaviour on the same helper; the D2H arm is the stricter one, which suggests at least one is wrong. Merging the variants removes the discrepancy instead of proving two slightly different things.
4. stream_comp_max — a monotonicity mechanism that the simpler design makes unnecessary
worker.rs:977-990 introduces a per-slot Cell<u64> array plus two closures, checked at five sites (:1000, :1024, :1422, :1543), to guarantee device_completions never regresses when a Demand op preempts a Prefetch op that reused the same slot. The skip is silent — a completion write is dropped, not deferred (:1000-1002, :1024-1026).
This whole mechanism is a workaround for splitting one ordered stream into three. Simpler equivalent: keep per-transfer completion writes on the device stream only for reads (as today's fetch_max host mirror already handles host-side monotonicity), or gate dispatch rather than the write — refuse to dispatch an op whose signal_value is below the slot's pending value, which is a scheduler-side check on data the scheduler already has (inflight_d2h/inflight_dma carry completion_slot + signal_value). Then no Cell array, no two extra closures, and no silent drop path. The current shape also means the correctness argument lives only in a live-GPU test (worker.rs cuda_tests slots 6/7, :2140-2230) — the CPU lifecycle model has no per-slot stream dimension, so nothing else can check it. Moving the rule into the scheduler makes it modellable; leaving it in the worker means it cannot be.
Related dead-ish weight: the two if !should_write_stream_comp(slot, value) { return; } guards inside signal_completion_slot (:1000, :1024) return before the update_host_comp call at :1041/:999 order is respected — note :999 does update_host_comp first and :1024/:1041 do it in the else branch, so the two arms of the same closure have different ordering. Three copies again (§1).
5. Simplicity in the spin loop: a nested condition that is one condition
worker.rs:1685-1697:
if has_inflight || last_active.elapsed() < ACTIVE_SPIN_WINDOW {
if idle_spins < BUSY_SPIN_LIMIT || last_active.elapsed() < ACTIVE_SPIN_WINDOW {
std::hint::spin_loop();
} else if idle_spins < IDLE_SPIN_LIMIT { thread::yield_now(); }
else { thread::sleep(BUSY_PARK_INTERVAL); }
} else if idle_spins < IDLE_SPIN_LIMIT {
std::hint::spin_loop();
} else { thread::sleep(IDLE_PARK_INTERVAL); }
The inner || last_active.elapsed() < ACTIVE_SPIN_WINDOW is implied by the outer condition in the branch where has_inflight is false, and doubly redundant when has_inflight is true. The whole thing reduces to: "if within the 50 ms active window or work is in flight → spin; else if under IDLE_SPIN_LIMIT → spin; else sleep (50 µs while active, 200 µs while idle)". One let active = has_inflight || last_active.elapsed() < ACTIVE_SPIN_WINDOW; followed by a flat three-way if active && spins < LIMIT { spin } else if spins < IDLE_LIMIT { yield } else { sleep(if active {BUSY} else {IDLE}) }. Four branches and a duplicated elapsed() call collapse to three.
Also: BUSY_SPIN_LIMIT and 50 ms ACTIVE_SPIN_WINDOW now overlap in purpose with the io_uring DEFER_TASKRUN fast path — the PR adds a third latency mechanism (worker-side spinning) to the same tail-latency claim it attributes to the second (kernel-side taskrun). Worth asking whether the spin change belongs in this PR at all; nothing in the description's five defects requires it, and the perf headline is attributed to DEFER_TASKRUN.
6. rotate_storage_runs — a process-global counter and a whole extra buffer, for a 15-line rotate
worker.rs:826-850 (storage_io_priority + rotate_storage_runs) plus static NEXT_WORKER_ORDINAL: AtomicUsize (:59) plus drained_cmds: Vec<ValidatedCommand> (:947) plus the clear/collect/replay restructure of the ring-drain loop (:1130-1165), replacing the previous direct scheduler.enqueue(validated) call. Net: ~40 lines and a process-global mutable, to rotate_left(worker_ordinal % len) a contiguous run.
The drained_cmds buffer exists only because a single command cannot be rotated in isolation — but the loop already knows the whole batch, so a two-pass form (collect count, then enqueue starting at an offset for the first run) would need no Vec allocation reuse and no drain(..). And storage_io_priority returns Option<Priority> only to be compared == Some(prio) at :840; Priority is Copy + Eq and the "not storage" case can be folded into the run predicate directly.
The process-global NEXT_WORKER_ORDINAL is the most questionable part: it makes worker behaviour depend on process-global thread-start order (tests are order-dependent and Ordinal values are not reproducible across restart), where the channel already has a stable identity available at construction (global_rank, passed to prepare_async_transfers in model.rs:1080-1082). Passing the rank through WorkerThreadArgs would delete the static and make the rotation deterministic and testable.
7. async_transfer_host_ram collapsed to a passthrough — and the host-wide division done in two places
memory.rs:37-43 reduces the function to
fn async_transfer_host_ram(host_future: u64, apply_reserve: bool) -> (u64, u64) {
flare_selene::offload::host_pool_budget_and_total_with_reserve(host_future, apply_reserve)
.unwrap_or((0, 0))
}
i.e. a wrapper whose only content is unwrap_or((0, 0)). Subtract it: call flare_selene::offload::host_pool_budget_and_total_with_reserve(host_future, options.pool_ram_limit.is_none()).unwrap_or((0, 0)) at the single call site (memory.rs:1360). The doc comment above it (12 lines) describes semantics that are now entirely Selene's.
In Selene, host_pool_budget_and_total_with_reserve (selene/src/offload.rs:984-987) is likewise a two-line body that duplicates host_pool_budget_with_reserve (:991-994) except for returning total; and host_pool_budget_and_total (:978-980) is now a pure forwarder. The three exported functions (host_pool_budget, host_pool_budget_and_total, host_pool_budget_and_total_with_reserve) + host_pool_budget_with_reserve are four public entry points over one private helper host_pool_budget_from. Simplify to one: pub fn host_pool_budget_from(available, total, future, apply_reserve) already exists and is pub — callers that need total can call host_memory_bytes()'s public neighbour or take (budget, total) from one function with an Option. The PR adds a fourth public symbol where a caller-side (host_pool_budget_from(...), total) would do.
Separately, the host-wide-vs-per-rank split is now expressed in two different idioms in the same function (memory.rs:113-131):
let host_bounce = total_bounce.saturating_mul(ranks);
let max_host_pool = (host_ram_available / ranks).saturating_sub(total_bounce);
match pool_ram_limit {
Some(limit) => {
let host_cap = match limit.0 {
MemoryLimit::Reserve(reserve) => host_ram_available.saturating_sub(host_bounce).saturating_sub(reserve),
_ => limit.cap_bytes(host_ram_available, host_ram_total),
};
(host_cap / ranks).min(max_host_pool)
}
None => max_host_pool,
}
The MemoryLimit::Reserve arm bypasses cap_bytes entirely and reimplements the reserve subtraction with a different bounce term (host_bounce, host-wide) than max_host_pool uses (per-rank total_bounce). Simplify: one host_cap computation that always subtracts host-wide bounce and always divides by ranks once — i.e. compute let host_cap = limit.map_or(host_ram_available - host_bounce, |l| l.cap_bytes(...) - host_bounce_for_reserve) and then (host_cap / ranks).min(max_host_pool) outside the match. As written, the reader must verify that the Bytes path and the Reserve path treat bounce consistently, which they do not structurally (one subtracts per-rank later, one subtracts host-wide here) — and the new test at memory.rs:2752-2775 pins both behaviours separately rather than one rule.
8. Cargo-level / trait-level surface that could be deleted
IoBackend::bind_worker_threadreturningio::Result<()>whoseErris never observed (§2) — either the error matters (log it, expose fast-path state) or the method should returnbool.IoUringBackend::empty_polls: u32(io_backend.rs:99) withwrapping_addand a(x & 0x3fff) == 0magic watchdog (:381-392), reset at three separate places (:352, :359, :398). The periodicenter(GETEVENTS)is a belt-and-braces fallback for a case thetaskrun() || cq_overflow()check is supposed to cover. If thetaskrun()path is correct, the watchdog is dead weight; if it is needed,taskrun()is not sufficient and the code should say which. Either way,empty_pollsas a counter insidepoll_completionsis state the caller never sees — a locallast_enter: Option<Instant>compared against a named interval constant would be the same behaviour with a name that explains itself.
Where the diff is appropriately lean
driver.rs(not opened) (+4) — bare binding declarations, nothing to cut.AsyncTransfer.tla/AsyncTransfer.cfg/check.py(not opened) /lifecycle_tests.rs— the D2H state variables are added uniformly to every property that already mentionsinDma; the 20-int projection is mechanical and consistent withproject(). Boilerplate, but the kind that must be written out.model.rs:1083-1110— thestd::thread::scopefan-out is the shortest correct form of the parallel-start requirement (comparehelios/src/frontend/mod.rs:750-762(not opened), the same idiom already in the repo).docs/— thecli-design.md:761table row is a one-word change;manifest.md/runtime-core-design.mdedits are prose matched to the diff.
One documented inconsistency worth fixing while here: docs/cli-design.md:761 is changed to "Per-host ceiling … (divided evenly across local discrete ranks)" but the sample flare.toml (not opened) four hundred lines down still reads # pool_ram = "" # Per-rank ceiling for pinned AsyncTransfer host pools (docs/cli-design.md:1418) — the same file contradicts itself after this PR, and the --help text in flare-cli/src/cli.rs (not opened) is unchanged.
Ranked recommendation
- Unify the three completion-signal blocks into one helper (§1) — biggest line-count and biggest correctness win; also fold the three
VecDeque+ queue-pair plumbing into an indexed array using theFaultedStreamKindenum already added. - Merge
InflightD2h/InflightDmaandmark_d2h_faulted/complete_d2hwith their DMA twins (§3), and mergeValidatedCommand::DevToHostwithHostToDevinring.rs— this deletes the duplicated Kani arm and theimpl-disagreement it hid. - Reconsider
stream_comp_max(§4): move the monotonicity rule into dispatch where it is checkable by the CPU lifecycle model, or drop the mechanism if per-stream ordering is not actually needed for reads. - Drop
with_max_d2hin favour of a constructor argument, and dropasync_transfer_host_ramas a passthrough (§2, §7). - Flatten the spin loop and pass the rank instead of
NEXT_WORKER_ORDINAL(§5, §6).
Code correctness
Audit report — PR #737 @ 46e6a3b (async_transfer: DevToHost, dual-stream H2D, DEFER_TASKRUN, host-wide RAM pool)
Method. 16 files / ~2,080 changed lines across three subsystems, so the diff was partitioned into three disjoint slices (async_transfer ring/scheduler/TLA; worker.rs+io_backend.rs+driver.rs; runtime_core memory/model + selene) audited in parallel under the four-part protocol (callee/enum resolution, same-loop state-order tracing, adversarial small-N/boundary, hot-path big-O), then synthesized and cross-checked for contradictions. All findings quote files read at head 46e6a3b.
Blocker
B1. stream_comp_max is a permanent, submit-time high-water mark → reused completion slot silently stops publishing completions
helios/src/async_transfer/worker.rs:977-990 (declaration/gates), consumed at :1000-1002, :1024-1026, :1421-1475, :1543; recorded at :1013, :1033, :1459, :1571.
let stream_comp_max: Vec<std::cell::Cell<u64>> =
vec![std::cell::Cell::new(0); args.config.completion_slots as usize];
let should_write_stream_comp = |slot: u32, value: u64| -> bool {
value >= stream_comp_max[slot as usize].get()
};
let record_stream_comp = |slot: u32, value: u64| {
let cell = &stream_comp_max[slot as usize];
if value > cell.get() { cell.set(value); }
};
The cell is written at submission (:1459), before the transfer runs, and is never cleared for the channel's lifetime — only record_stream_comp's monotone max ever writes it. It is a cumulative maximum over every signal_value ever submitted on that slot, not an in-flight check like the neighbouring wait_other_streams_on_slot (:964-975), which correctly scans only pending queues. Any later legal command on the same slot carrying a smaller signal_value is dropped wholesale: no cuStreamWaitEvent, no cuStreamWriteValue64_v2, and — because completion_action stays EventCompletionAction::None — not even the host-mirror update_host_comp (:1210-1223, :1283-1296). validate_command imposes no monotonicity on signal_value (only the bit-63 exclusion, ring.rs:497-508), so this is a legal command stream.
Counterexample (completion ring of 32): slot 3 with signal_value = 9000 for request A (record_stream_comp → 9000, word written, consumer advances). New epoch, same slot, request B with signal_value = 1000 → 1_000 >= 9_000 false → nothing written; B's event completes → complete_dma(op, true) → publish_notice(notice, false, …) (:1224-1231) → no device word and no host mirror. last_error stays Ok and completed_cmds increments, so telemetry is healthy while the captured graph spins forever on device_completions[3] == 1000. Same swallow for signal_completion_slot used by DiskToHost/CancelEpoch/error notices (:999-1002): host mirror advances, device word skipped, observability diverges. The PR's live test only uses increasing values per slot (6006, 7007→7008, 7009/7010, 7011, :2090-2235), so it cannot catch this.
Fix. Derive "may I write this slot?" from the in-flight set exactly as wait_other_streams_on_slot does — scan pending_dem_dma_events/pending_bg_dma_events/pending_d2h_events for completion_slot == Some(slot) and compare against only those entries' signal_value (≤18 entries; the scan is already being done for the wait, so free). If a high-water mark is kept, reset stream_comp_max[slot] when the slot's last pending entry is harvested/drained (:1201-1205, :1278, begin_drain/finish_drain) and record at completion, not submission. Keep an unconditional device-word write for the HostAndDevice fallback.
Major
M1. Shared CUDA event pool is drained by the H2D loop first → DevToHost starves exactly when VRAM pressure needs it
helios/src/async_transfer/worker.rs:874-891 (pool size), :1384 (H2D loop), :1520 (D2H loop).
let event_pool_cap = DEFAULT_MAX_TOTAL_DMA + DEFAULT_MAX_D2H; // 16 + 2 = 18
let mut free_events: Vec<Handle> = Vec::with_capacity(event_pool_cap);
...
while !has_faulted_h2d && !free_events.is_empty() { // up to 16
...
while !has_faulted_d2h && !free_events.is_empty() { // leftovers
One pool, three streams; H2D runs first with concurrency cap DEFAULT_MAX_TOTAL_DMA = 16 out of 18 events. With 16 H2D in flight, step 5b returns immediately and no DevToHost can ever be dispatched — while D2H is precisely what frees the VRAM those H2Ds need (motivation #1). Counterexample: 16 demand HostToDev + 2 DevToHost demotions → demotions wait forever with d2h_stream idle, and pop_next_d2h's gate (scheduler.rs:920-928) adds a second starvation axis. Fix: dedicated free_d2h_events deque of DEFAULT_MAX_D2H handles that the H2D loop cannot consume.
M2. pop_next_d2h is priority-blind and its demand-yield gating keys off H2D only → demand DevToHost head-of-line blocked behind background demotions
helios/src/async_transfer/scheduler.rs:920-934 (new); with_max_d2h at :229-232, dem_dma_inflight at :351-356, fields at :177/:183, default DEFAULT_MAX_D2H = 2 at worker.rs:52 applied at worker.rs:929.
pub fn pop_next_d2h(&mut self) -> Option<InflightD2h> {
if self.state != ChannelState::Running || self.inflight_d2h.len() >= self.max_d2h {
return None;
}
let dem_dma_active = self.dem_dma_inflight() > 0;
for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] {
if prio.is_background() && dem_dma_active { continue; }
pub fn dem_dma_inflight(&self) -> usize {
self.inflight_dma.iter().filter(|op| !op.priority.is_background()).count()
}
(a) dem_dma_inflight() counts only inflight_dma (H2D), so the new "background yields to demand" rule never fires for a background DevToHost; (b) the capacity gate is priority-blind, so once max_d2h background D2H ops are in flight a queued Demand D2H is refused although it is the only queued D2H op — and even when admitted it is appended to the single FIFO d2h_stream (worker.rs:1529), so it cannot preempt, unlike H2D which the PR split into two streams.
Counterexample (max_d2h = 1, the configuration the PR's own harness uses, lifecycle_tests.rs:82): enqueue(DevToHost{Priority::Warm}); pop_next_d2h() → Some, inflight_d2h.len() == 1; enqueue(DevToHost{Priority::Demand}); pop_next_d2h() → None because 1 >= max_d2h. At production depth 2, two Warm demotions block a Demand demotion for two full PCIe copies. Not a deadlock or memory-safety bug (ready_retention/can_release_memory stay correct), but a real inversion against the PR's stated invariant.
Fix:
let dem_d2h_pending = !self.d2h_queues[Priority::Demand.index()].is_empty()
|| self.inflight_d2h.iter().any(|op| !op.priority.is_background());
...
if prio.is_background()
&& (dem_dma_active || dem_d2h_pending || self.inflight_d2h.len() + 1 >= self.max_d2h)
{ continue; }
plus a max_d2h = 2 test: one Warm D2H in flight + one Demand D2H queued ⇒ the background arm must not take the last slot.
M3. Background completions are written on the high-priority stream, so device_completions correctness depends entirely on B1's permanent latch
helios/src/async_transfer/worker.rs:1209-1239 (bg-queue harvest) and :992-1043 (signal_completion_slot always writes on copy_stream).
EventCompletionAction::HostAndDevice(slot, val) => {
signal_completion_slot(slot, val, &pending_bg_dma_events, &pending_d2h_events);
}
A bg bg_copy_stream transfer whose inline write could not be issued is later written by the worker onto copy_stream at harvest. Counterexample: demand 7010 queued on copy_stream, then a late bg 7009 write appended to the same stream's tail → device_completions[slot] regresses to 7009. The permanent latch in B1 is the only thing masking this, so B1 and M3 must be fixed together: an in-flight-set comparison alone re-opens the regression unless the bg harvest path writes on bg_copy_stream after a cuStreamWaitEvent on the demand stream's event for that slot, or gates on the actual last write the worker issued to that slot.
M4. Concurrent startup makes NEXT_WORKER_ORDINAL → rank mapping racy, removing determinism of the cross-rank storage stagger
helios/src/runtime_core/model.rs:1086-1092; assignment helios/src/async_transfer/worker.rs:948; consumer worker.rs:1149-1155.
let handles = self.async_transfer_handles();
let mut first_err: Option<crate::Error> = None;
std::thread::scope(|scope| {
let joins: Vec<_> = handles.iter().map(|ch| scope.spawn(move || ch.start())).collect();
let worker_ordinal = NEXT_WORKER_ORDINAL.fetch_add(1, Ordering::Relaxed);
...
rotate_storage_runs(&mut drained_cmds, worker_ordinal);
Pre-PR, start_async_transfers() ran in strict rank order (runtime_core/mod.rs:1987-1992), so rank k deterministically got ordinal k and rotate_storage_runs staggered rank k by k against the striped RAID-0 set. Now eight scope.spawned threads race into worker_main. Counterexample with run length len = 3: pre-PR maps rank 0→0, 1→1, 2→2, 3→0…; a racy run can map 0→5, 1→2, 2→7, so which physical drive each rank's demand reads hit changes boot to boot with no ordinal % len separation. This makes the PR's 1,202 ms stall-spread result non-reproducible. Fix: thread the ordinal through WorkerThreadArgs (worker.rs:610-628, add one field) computed from (rank, channel index) in prepare_async_transfers, or reserve it in start() before spawning (worker.rs:567-639, per-channel mutex).
Minor
find_fixed_buflinear scan per submitted read —io_backend.rs:157-167, called frompush_read_sqe(:177) for every read atworker.rs:1635-1643; withFIXED_BUF_CHUNK_BYTES = 1 << 30(:283-291) a large--pool-ram-memoryrank has hundreds of spans, and cost grows with pool size on the submit path. Spans are ascending/non-overlapping: usebinary_search_byonb_start, or computeidx = span_start + (dst - pool_base) / chunk_bytesin O(1) and verifyend <= span_end.- 50 ms
ACTIVE_SPIN_WINDOWpegs a core per rank —worker.rs:43,:1674-1698;last_activerefreshes on anydid_work, so one command every 40 ms keepsspin_loop()forever (8 pegged cores on TP8),BUSY_SPIN_LIMIT = 512becomes unreachable, and:1686redundantly re-readslast_active.elapsed()inside a branch already guarded at:1685. Cache the predicate once per iteration; extend the window only on a burst. - Stale
has_faulted_d2hinside the dispatch loop —worker.rs:1517-1537(mirrored:1381-1384/:1496-1512):event_recordfailurebreaks but thecuMemcpyDtoHAsync_v2rejection pathcontinues without setting a fault flag, re-issuing a failing copy each iteration (three streams now amplify it). Addd2h_poisoned = trueto the guard. MemoryLimit::Reserveduplicated, not shared —memory.rs:118-129vsPoolMemoryLimit::cap_bytes(limits.rs:174-180); the RAM arm also subtracts aggregatehost_bounce, so--pool-vram-memory -8G --pool-ram-memory -8Ggives VRAMavailable − 8 GiBbut RAMavailable − 8·512 MiB − 8 GiB, and a futurecap_bytesedit changes only one tier. Addcap_bytes_less(available, total, extra_pinned)used by all threeReservesites.- Startup pinning still serial —
model.rs:1077-1083vs:1086-1109: the ~27 GiBcuMemHostRegister_v2per rank (worker.rs:419-435→:145-182) dominatesPrepare async transfersand stays 8× serial; the parallel section only coversbind_worker_thread/best-effortregister_buffers. Motivation #5 is thus addressed only for fixed-buffer registration. - TLA+/mutation model does not encode the two new scheduler predicates —
AsyncTransfer.tla:158-186,:76-110,MaxD2h = 1atAsyncTransfer.cfg:6, mutations atcheck.py:816-819:DispatchD2hmodels a priority-free FIFO andDispatchIo/DispatchDmacarry no demand-in-flight component, soscheduler.rs:636,:791,:926are unconstrained (conformance is Rust→model only) — exactly why M2 passes TLC.MaxD2h = 1withMaxQueue = 2makes production depth 2 and any slot reservation unreachable; the only gating mutation sets the whole term toif falseand is never applied topop_next_io;Spec == Init /\ [][Next]_state(:394) has no fairness, so no anti-starvation property is checked despite the preemption claim.
Verified clean (explicit negative results)
Opcode::DevToHost = 5bounds roles are correct, not swapped —ring.rs:497-517:host_offsetvalidated againsthost_pool_bytes(HostRangeOutOfBounds),device_offsetagainstdevice_pool_bytes(DeviceRangeOutOfBounds), identical toHostToDev(:438-457) and matchingcuMemcpyDtoHAsync_v2(host dst, device src atworker.rs:1526-1530).fits_rangeuseschecked_add(:369-374) soptr + lennearu64::MAXerrors instead of wrapping;nbytes == 0→LengthMismatch; bit-63COMPLETION_ERROR_BITexcluded by the shared check (:405-407); opcodes 6/0/255 →InvalidOpcode(:69-78).kani_proofs.rs:199-218matches the implementation and is not vacuous (only reached viavalidate_transfer_header, which guarantees alignment/power-of-two).- All four new CUDA bindings have correct signatures/argument order (
driver.rs:301,325,326,338):cuCtxGetStreamPriorityRange(least, greatest)called with&mut least_prio, &mut greatest_prio, usinggreatest_prio(numerically smallest = highest priority) inmake_stream(worker.rs:446-464) with a correctgreatest_prio < least_priono-range guard;cuStreamCreateWithPriority(out, CU_STREAM_NON_BLOCKING, prio);cuStreamWaitEvent(target_stream, pending.event, 0). - Cross-stream slot synchronization ordered correctly — the wait is always issued on the target stream before its write edge, against an event owned by a different stream (
worker.rs:964-975,:1003,:1027,:1424-1437,:1544-1549); no site lets two streams touch a slot without a wait. - Faulted-DMA retention/drain correct for all three streams (
worker.rs:1325-1378,:1401-1409,:1742-1762;scheduler.rs:410-415,:1051-1054,:1072-1076,:704): bounce slots retained until drain,host_mirror_on_drainpreserved,DevToHostowns no bounce slot (bounce_slot()→None,scheduler.rs:92-97),mark_d2h_faulted/complete_d2hmirror H2D semantics with no duplicate drain notice, andcan_release_memory/epoch/drain all includeinflight_d2h. bounce_pool_geometry(worker.rs:78-96) cannot exceed the 512 MiB ceiling for anyslot_bytes ∈ (0, 32 MiB];ReadFixedfallback (io_backend.rs:158-167,:177-209,:298-322) never issuesReadFixedwith an unregistered index, including after partial registration failure, andqueued_sqesaccounting stays exact;update_host_completionusesfetch_max.- Host-wide
--pool-ram-memoryarithmetic sound (memory.rs:118-158,selene/src/offload.rs:945-994): no bounce double-count, aggregate identity holds in bothReserveandNonearms,discrete_ranks = 0unreachable (:1359-1363,local_ranks.max(1)),--pool-ram-memory 400Gon 251 GiB still clamps per rank,pinned.saturating_mul(ranks).div_ceil(512)cannot overflow and is charged once, integrated/unified-DRAM andhost_futuregenuinely unchanged,discrete_ranks = 1bit-identical to pre-PR except the intended− bouncereserve fix. Thestd::thread::scope(model.rs:1086-1109) is sound: allResults and panics propagated (:1099-1106), no shared mutable state crossed unlocked,O(channels)threads. - No hot-path allocation regression in the scheduler:
d2h_queuesareVecDequewithpop_front/push_back,complete_d2husesswap_remove,InflightD2hisCopy,queue_shape_key(scheduler.rs:419-434) distinguishes priority/bounce classes, and the BFS harness (lifecycle_tests.rs:94-190, assertions:308-319,:390-415,:466-501) genuinely reaches the D2H fault/drain branches.
Not verifiable here: cargo-kani not run (B1/M2 are runtime logic, unaffected); the io-uring 0.7 builder surface (setup_no_sqarray, sq.taskrun(), sq.cq_overflow()) was read, not compiled, so a builder/return-type mismatch would not have surfaced; the new io_backend.rs:663-713 test asserts data correctness only and would pass through the plain-Read path, so it does not prove the ReadFixed/DEFER_TASKRUN claims.
Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.
Final review
Recommendation: Changes Requested
The core runtime implementation at 46e6a3b is solid — adversarial verification found no Blocker code bugs (all upstream blocker/major concurrency and event-pool claims were disproven on direct inspection of worker.rs, scheduler.rs, and memory.rs), and the host-wide --pool-ram-memory and multi-rank UVA page-table budgeting fixes are cleanly implemented and unit-tested. Changes are requested for four concrete, verified contract/documentation/evidence gaps before merge: an internal contradiction in docs/cli-design.md on pool_ram, an undocumented per-slot monotonicity narrowing on device_completions (with no CPU unit test), an unattributed/confounded performance claim alongside undisclosed IO-depth default halving, and a stale lifecycle verification README.
Merge Risk
Level: Medium
- Multi-stream completion ordering: Splitting the single
copy_streaminto three Copy Engine streams (copy_stream,bg_copy_stream,d2h_stream) withcuStreamWaitEventandstream_comp_maxchangesdevice_completionsfrom unconditional stream-order writes to lifetime per-slot monotonic non-regression; this path is currently exercised only by the gated live-CUDA test. - Operator-visible flag semantics & defaults:
--pool-ram-memorychanges from per-rank to host-wide on multi-rank discrete hosts (fixing a real bug, but altering existing multi-rank invocations), and per-channel NVMe concurrency defaults are halved (DEFAULT_MAX_TOTAL_IO32 -> 16,DEFAULT_MAX_BG_IO8 -> 4) with a new50 msactive spin window per worker. - Linux fast path & Kani coverage:
DEFER_TASKRUN/ReadFixedfallbacks are silent (let _ =), non-Linux/Windows paths are unexercised, and the updated Kani proof awaits CI execution.
Walkthrough
- CUDA bindings & ABI v1 ring (
helios/src/runtime_core/driver.rs,helios/src/async_transfer/ring.rs,helios/src/async_transfer/kani_proofs.rs): AddscuCtxGetStreamPriorityRange,cuStreamCreateWithPriority,cuStreamWaitEvent, andcuMemcpyDtoHAsync_v2, plusOpcode::DevToHost = 5andValidatedCommand::DevToHostwith full bounds, alignment, nonzero-length, and bit-63 error-sentinel validation while preservingABI_VERSION = 1and the 256-byteControlHeader. - Scheduler & formal model (
helios/src/async_transfer/scheduler.rs,lifecycle_tests.rs,verification/helios-lifecycle/AsyncTransfer.{tla,cfg},check.py): Addsd2h_queues/inflight_d2h(pop_next_d2h,mark_d2h_faulted,complete_d2h), gates background IO/H2D/D2H dispatch when demand work of the gated class is in flight, extends drain/release ownership to cover in-flight D2H, widens the TLA+ projection to 20 integers (MaxD2h = 1), switches Rust conformance exploration to BFS withqueue_shape_key(), and adds D2H TLA+/Rust mutations. - Multi-stream worker & Linux
io_uringbackend (helios/src/async_transfer/worker.rs,io_backend.rs): Splits Copy Engine execution across high-prioritycopy_stream, normal-prioritybg_copy_stream, and normal-priorityd2h_streamwith cross-streamcuStreamWaitEventslot synchronization and per-slotstream_comp_maxmonotonicity; widensbounce_pool_geometryup to 32 slots within512 MiB; halves default IO depth (32 -> 16, bg8 -> 4); adds a50 msACTIVE_SPIN_WINDOWand per-worker contiguous storage-run rotation; bindsio_uringon the worker thread withSINGLE_ISSUER | DEFER_TASKRUN | TASKRUN_FLAG | NO_SQARRAY(with fallbacks) and 1 GiB-chunkReadFixedbuffer registration. - Host-wide RAM budgeting, parallel worker startup, and docs (
selene/src/offload.rs,helios/src/runtime_core/memory.rs,model.rs,docs/cli-design.md,docs/runtime-core-design.md,helios/manifest.md): Addshost_pool_budget_and_total_with_reserve(omitting Selene's implicit host reserve when--pool-ram-memoryis explicitly supplied), applies--pool-ram-memoryhost-wide before dividing across local discrete ranks (preserving free reserve after aggregate bounce underMemoryLimit::Reserve), charges peer-UVA page tables aspinned.saturating_mul(ranks).div_ceil(512)on discrete multi-rank hosts, starts rank workers concurrently viastd::thread::scope, and updates runtime/manifest docs.
Pre-merge Checks
- [PASS] Security / malicious screen: No suspicious code, credential/network exfiltration, or prompt-injection vectors;
validate_commandenforces overflow-freechecked_addrange checks and bit-63 exclusion forOpcode::DevToHost. - [PASS] Charter & value fit: Stays strictly inside Helios's model-agnostic hardware/OS/lifecycle boundary (no per-model branches, no new captured-graph op families, no vendored-file forks, ABI v1 backward compatible); the host-wide
--pool-ram-memoryand multi-rank UVA page-table fixes resolve real bugs on multi-GPU hosts. - [WARN] Related / duplicate / conflict check: Additive over
main(building on #711/#721/#727); overlaps with open #726 inNativeModel::prepare_async_transfers(helios/src/runtime_core/model.rs:1080-1110) — coordinate merge order. Merge this PR before the companionhyperflare-recipesPR as stated. - [WARN] Tests & verification evidence: TLA+ conformance/mutations and crate/GPU tests are reported passing (6 unrelated HF HTTP 403 frontend template tests disclosed), but CI's
kanijob (.github/workflows/helios-lifecycle.yml:49(not opened)) must confirm green on head46e6a3bsincedocs/design-review.md:247-251treats applicable Kani proofs as mandatory, and theDEFER_TASKRUNstall-spread measurement lacks an isolated equivalent baseline (see Should Fix #3).
Blockers
None.
Should Fix
-
Resolve the
docs/cli-design.mdself-contradiction on--pool-ram-memory/pool_ram(docs/cli-design.md:761vsdocs/cli-design.md:1418):- Line 761 updates
--pool-ram-memoryto"Per-host ceiling ... (divided evenly across local discrete ranks)"matchinghelios/src/runtime_core/memory.rs:115-130andflare-cli/src/cli.rs:961-962, but the sampleflare.toml(not opened) in the same file at line 1418 still states# pool_ram = "" # Per-rank ceiling for pinned AsyncTransfer host pools. - Fix: Update
docs/cli-design.md:1418to describepool_ramas a per-host ceiling divided across local discrete ranks.
- Line 761 updates
-
Document the new per-slot monotonic non-regression contract on
device_completionsand add CPU unit-test coverage (helios/src/async_transfer/worker.rs:977-990,:1000,:1024,:1422,:1543;helios/manifest.md:188-196;docs/runtime-core-design.md:767-772):- Before this PR,
update_host_completion(worker.rs:313-314) enforced per-slot lifetime monotonicity viafetch_maxon host mirrors whiledevice_completions[slot]was written unconditionally on the single stream. Withstream_comp_max,device_completionsnow also permanently latches the highest written value per slot and silently skips any later write withsignal_value < stream_comp_max[slot](and makes bit-63 error sentinels sticky on device slots). That behavior is necessary to prevent priority-preempted background ops from regressingdevice_completionsafter a higher-value demand op finishes and is harvested (worker.rs:2176-2229), but neitherhelios/manifest.mdnordocs/runtime-core-design.mddocuments it — both only statefetch_maxmonotonicity for host mirrors. An ABI-v1 core that only pollsdevice_completionsand resets/reuses slots with smaller cookies would silently hang without an error. - Fix: Update
helios/manifest.md:188-196anddocs/runtime-core-design.md:767-772to specify thatdevice_completionsenforces per-slot monotonic non-regression (matching hostfetch_max, with sticky bit-63 error sentinels), and extract a small testable helper (e.g.StreamCompWatermark) with a CPU unit test inworker.rs::unit_testscovering equal/greater writes, skipped regressions, and sticky error sentinels.
- Before this PR,
-
Fix performance-claim attribution and disclose changed IO-depth defaults (
helios/src/async_transfer/worker.rs:43,48-49,52;docs/design-review.md:106-115;AGENTS.md:92-108):- The PR attributes
"reduced cross-rank demand-stall spread from >5,000 ms to 1,202 ms"to worker-ownedDEFER_TASKRUNwithout a baseline commit/config or raw per-rank data, while the same diff halves per-channel NVMe read concurrency (DEFAULT_MAX_TOTAL_IO: 32 -> 16,DEFAULT_MAX_BG_IO: 8 -> 4) and adds a50 msACTIVE_SPIN_WINDOW— both of which directly affect NVMe contention and stall spread. In addition, the32 -> 16/8 -> 4IO-depth halving andDEFAULT_MAX_D2H = 2default are omitted from the "What changed" section (AGENTS.md:92-94). - Fix: Either provide the equivalent baseline commit, configuration, and raw per-rank measurements isolating
DEFER_TASKRUN(or clearly attributing the combined diff) perdocs/design-review.md:106-115, or state the latency reduction as an expected benefit rather than an isolated measurement; explicitly noteDEFAULT_MAX_TOTAL_IO(32 -> 16),DEFAULT_MAX_BG_IO(8 -> 4), andDEFAULT_MAX_D2H = 2in the PR description.
- The PR attributes
-
Update
verification/helios-lifecycle/README.mdto match the 20-integerAsyncTransfermodel (verification/helios-lifecycle/README.md:353-384;docs/verification.md:118-119):AsyncTransfer.tla,AsyncTransfer.cfg,check.py, andlifecycle_tests.rsnow use a 20-integer projection withMaxD2h = 1and three new transitions (dispatch_d2h,complete_d2h,mark_d2h_faulted), whileREADME.md:357-382still documents a 16-integer projection and omitsMaxD2hand the D2H transitions.- Fix: Update
verification/helios-lifecycle/README.md:353-384to listMaxD2h = 1, the three D2H transitions, and all 20 projection fields.
Subtract / Simplify
- Deduplicate completion-slot signaling and stream queues in
worker_main(helios/src/async_transfer/worker.rs:938-943,:992-1043,:1418-1475,:1539-1587): Theshould_write_stream_comp/wait_other_streams_on_slot/use_write_value64/record_stream_comp/EventCompletionActionblock is duplicated three times (host-initiated, H2D, D2H), andpublish_notice/signal_completion_slotmanually forward two&VecDeque<PendingEventDma>arguments across ~14 call sites. Indexing pending queues byFaultedStreamKind([VecDeque<PendingEventDma>; 3]) and extracting one completion-signaling helper eliminates ~100 lines of duplication and removes manual queue-pair selection. - Replace process-global
NEXT_WORKER_ORDINALwith deterministic rank/channel identity (helios/src/async_transfer/worker.rs:59,948):args.config.rankis already passed intoworker_main(worker.rs:102,611). Deriving the rotation offset from(args.config.rank, channel_idx)removes the process-global atomic, makes per-rank stagger reproducible across restarts/tests, and also staggers multi-host single-local-rank setups where a process-local counter always starts at0. - Flatten the redundant
ACTIVE_SPIN_WINDOWcheck (helios/src/async_transfer/worker.rs:1685-1697):last_active.elapsed() < ACTIVE_SPIN_WINDOWis evaluated twice per tight spin iteration; bindinglet in_active_window = last_active.elapsed() < ACTIVE_SPIN_WINDOW;once removes redundant clock reads and simplifies the branching. - Trim single-use wrappers and duplicated validation:
async_transfer_host_ram(helios/src/runtime_core/memory.rs:41-44) is a single-callerunwrap_or((0, 0))passthrough;TransferScheduler::with_max_d2h(scheduler.rs:229-232) is inconsistent with the constructor caps and only called in production with its own default2(worker.rs:929); andOpcode::HostToDev/Opcode::DevToHostinring.rs:438-458,497-517share identical validation logic. - Surface
DEFER_TASKRUN/ReadFixedactivation status instead oflet _ =(helios/src/async_transfer/worker.rs:895-905,io_backend.rs:32-43,258-323): Combining or returning activation flags frombind_worker_thread/register_bufferslets startup logs andio_uring_bind_worker_thread_and_register_buffers_read_fixed(io_backend.rs:663-713, which currently passes even on silent fallback to plainRead) verify the fast path is actually active.
Nits
pop_next_d2hdemand reservation (helios/src/async_transfer/scheduler.rs:920-928): Unlikepop_next_io/pop_next_dma,pop_next_d2hyields background ops only todem_dma_inflight() > 0(H2D) and allows background D2H to fill allmax_d2hslots (matching its doc comment). IfDemandD2H is ever mixed withWarmevictions, yielding todem_d2h_inflight() > 0and adding an explicitmax_bg_d2hcap (ensuringmax_d2h = 1in tests/TLA+ still allows background D2H) would align D2H with IO/H2D priority rules.find_fixed_buflinear scan (helios/src/async_transfer/io_backend.rs:158-167): Scanning 1 GiB spans is negligible at ~28 entries (27 GiB/rank) vs NVMe latency, butpartition_pointon sorted spans or O(1) offset math scales cleanly to 512+ GiB single-rank pools.- D2H byte telemetry (
helios/src/async_transfer/ring.rs:200-205,scheduler.rs:994-996,1021-1023,docs/api.md:417-429): D2H completes with zeroed byte counters (keeping ABI v1ControlHeadercache line 3 intact and matchingdocs/api.md); consider documenting or adding a D2H counter if operators need visibility into demotion traffic. - Serial host pinning during startup (
helios/src/runtime_core/model.rs:1077-1109):std::thread::scopeparallelizesch.start()(bind_worker_thread+register_buffers) as described, whilePinnedHostRegion::allocate(cuMemHostRegister_v2) inrank.prepare_async_transfersremains sequential per rank. MemoryLimit::Reservehelper sharing (helios/src/runtime_core/memory.rs:120-126vslimits.rs:174-180): Extracting a sharedcap_byteshelper that accepts extra pinned bytes would keep allReservepaths structurally aligned.
Dropped on verification
- Upstream B1 as a Blocker + proposed in-flight-only fix (
stream_comp_max): Disproven as a Blocker and proposed fix is broken.update_host_completion(worker.rs:313-314) already enforced permanent per-slotfetch_maxmonotonicity onmain(worker.rs:2458-2471), and resettingstream_comp_maxon harvest (or checking only in-flight queues) breaks the PR's own preemption test (worker.rs:2176-2229) becauseDemand (7010)finishes and is harvested beforePrefetch (7009)is even popped from the scheduler (dem_activegates bg dispatch), allowing7009to regressdevice_completions[7]. Retained only as Should Fix #2 to document thedevice_completionsmonotonicity contract and add CPU test coverage. - Upstream M1 (Shared CUDA event pool starving
DevToHost): Mathematically false.event_pool_cap = DEFAULT_MAX_TOTAL_DMA + DEFAULT_MAX_D2H = 16 + 2 = 18(worker.rs:876), whileTransferSchedulercapsinflight_dma.len() <= 16(scheduler.rs:785,worker.rs:925). With 16 H2D ops in flight,18 - 16 = 2events remain infree_eventsfor step 5b (D2H), and every submission failure returns its event immediately (:1399, :1411, :1497). - Upstream M3 (
HostAndDevicebg harvest oncopy_streamregressingdevice_completionswithoutstream_comp_max): False.EventCompletionAction::HostAndDeviceis only set when!use_write_value64(worker.rs:1471) or when bothdevice_completions_base == 0andhost_comp_gpu_base == 0(:1467). In the latter casesignal_completion_slotonly runsupdate_host_comp(fetch_max,:1041); in the former case it runsupdate_host_comp(fetch_max,:999) beforeupload_asyncfromhost_comp_base[slot]on FIFOcopy_stream(:1010), which cannot regress even withoutstream_comp_max. - Upstream M4 (
NEXT_WORKER_ORDINALracing understd::thread::scopedestroying cross-rankordinal % lenseparation): False. Atomicfetch_add(1)across 8 concurrently spawned threads assigns a permutation of{k..k+8}, whose multiset ofordinal % lenresidues is identical to{0..8} % len— cross-rank RAID-0 stagger is preserved on a single host. Retained only as a Simplify item for determinism and multi-host clarity. - Upstream Minor 3 ("Stale
has_faulted_d2hinside dispatch loop re-issuing failing copies"): False. Oncopy_status != 0(worker.rs:1531-1536),scheduler.complete_d2h(d2h.op_id, false)removes the failed op and emitsCudaFailure(nothing was enqueued ond2h_stream, so it is neither re-issued nor an untracked faulted DMA); the only path pushing tountracked_faulted_dmas(event_recordfailure at:1603-1615) immediatelybreaks. - Upstream Kani
DevToHostalignment assertion mismatch (kani_proofs.rs:210): False.validate_transfer_header(ring.rs:377-383) checksalignment >= MIN_ALIGNMENT && alignment.is_power_of_two()for bothHostToDevandDevToHost, so the assertion is strictly true and provable. - Upstream Gate 4 claim that
bounce_pool_geometry512 MiB expansion was undeclared and increasesmemory.rsreserves: False. The PR description explicitly discloses"widened bounce_pool_geometry to up to 32 slots within 512 MiB", andmemory.rs:95-99already budgetedmax_bounce_pool_bytes(alignment) == 512 MiBbefore this PR. - Upstream
MaxD2h = 1vsDEFAULT_MAX_D2H = 2formal-bounds violation: Overstated/false.AsyncTransfer.cfguses the same bounded small-model convention for all queues (MaxTotalDma = 2vs16,MaxBgDma = 1vs4,MaxTotalIo = 2vs16), and all D2H lifecycle states are reachable atMaxD2h = 1.
Full report Decision to Test: no (89%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.
Classify triage
Selected: triage:review
Threshold: 65%
Triage
- [✓]
triage:review: 99.9% -
triage:design-review: 0.0% -
triage:validation: 0.0% -
none: 0.0% -
triage:integration: 0.0% -
triage:partial: 0.0% -
triage:investigate: 0.0% -
triage:verify-for-closure: 0.0% -
triage:superseded: 0.0%
Apply labels
No label changes