PR #737: async_transfer: add DevToHost, dual-stream H2D, DEFER_TASKRUN io_uring, and host-wide RAM pool budgeting

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/5c9cd724-b0c1-4d1f-9814-cc2264e9df69

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:

Full report · Notes

Classify intake

Selected: triage:review, performance, enhancement, area:memory

Threshold: 65%

Triage

Priority

Type

Area

Model

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.

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:

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


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

  1. Fix the --pool-ram-memory contradiction: docs/cli-design.md:1418 must say per-host (divided across local discrete ranks), matching :761.
  2. 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 and DEFAULT_MAX_D2H = 2 in the description.
  3. Update verification/helios-lifecycle/README.md:353-384 to the 20-integer projection, MaxD2h, and the three D2H transitions.
  4. Confirm the CI kani job passes on this head (.github/workflows/helios-lifecycle.yml:49 (not opened)), since docs/design-review.md:247-251 makes it blocking, and add a D2H byte/failure counter or document its absence in docs/api.md.

Full report · Notes

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:

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


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


Where the diff is appropriately lean

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

  1. 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 the FaultedStreamKind enum already added.
  2. Merge InflightD2h/InflightDma and mark_d2h_faulted/complete_d2h with their DMA twins (§3), and merge ValidatedCommand::DevToHost with HostToDev in ring.rs — this deletes the duplicated Kani arm and the impl-disagreement it hid.
  3. 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.
  4. Drop with_max_d2h in favour of a constructor argument, and drop async_transfer_host_ram as a passthrough (§2, §7).
  5. Flatten the spin loop and pass the rank instead of NEXT_WORKER_ORDINAL (§5, §6).

Full report

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

Verified clean (explicit negative results)

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

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

  1. Resolve the docs/cli-design.md self-contradiction on --pool-ram-memory / pool_ram (docs/cli-design.md:761 vs docs/cli-design.md:1418):

    • Line 761 updates --pool-ram-memory to "Per-host ceiling ... (divided evenly across local discrete ranks)" matching helios/src/runtime_core/memory.rs:115-130 and flare-cli/src/cli.rs:961-962, but the sample flare.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:1418 to describe pool_ram as a per-host ceiling divided across local discrete ranks.
  2. Document the new per-slot monotonic non-regression contract on device_completions and 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 via fetch_max on host mirrors while device_completions[slot] was written unconditionally on the single stream. With stream_comp_max, device_completions now also permanently latches the highest written value per slot and silently skips any later write with signal_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 regressing device_completions after a higher-value demand op finishes and is harvested (worker.rs:2176-2229), but neither helios/manifest.md nor docs/runtime-core-design.md documents it — both only state fetch_max monotonicity for host mirrors. An ABI-v1 core that only polls device_completions and resets/reuses slots with smaller cookies would silently hang without an error.
    • Fix: Update helios/manifest.md:188-196 and docs/runtime-core-design.md:767-772 to specify that device_completions enforces per-slot monotonic non-regression (matching host fetch_max, with sticky bit-63 error sentinels), and extract a small testable helper (e.g. StreamCompWatermark) with a CPU unit test in worker.rs::unit_tests covering equal/greater writes, skipped regressions, and sticky error sentinels.
  3. 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-owned DEFER_TASKRUN without 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 a 50 ms ACTIVE_SPIN_WINDOW — both of which directly affect NVMe contention and stall spread. In addition, the 32 -> 16 / 8 -> 4 IO-depth halving and DEFAULT_MAX_D2H = 2 default 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) per docs/design-review.md:106-115, or state the latency reduction as an expected benefit rather than an isolated measurement; explicitly note DEFAULT_MAX_TOTAL_IO (32 -> 16), DEFAULT_MAX_BG_IO (8 -> 4), and DEFAULT_MAX_D2H = 2 in the PR description.
  4. Update verification/helios-lifecycle/README.md to match the 20-integer AsyncTransfer model (verification/helios-lifecycle/README.md:353-384; docs/verification.md:118-119):

    • AsyncTransfer.tla, AsyncTransfer.cfg, check.py, and lifecycle_tests.rs now use a 20-integer projection with MaxD2h = 1 and three new transitions (dispatch_d2h, complete_d2h, mark_d2h_faulted), while README.md:357-382 still documents a 16-integer projection and omits MaxD2h and the D2H transitions.
    • Fix: Update verification/helios-lifecycle/README.md:353-384 to list MaxD2h = 1, the three D2H transitions, and all 20 projection fields.

Subtract / Simplify

Nits

Dropped on verification

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

Apply labels

No label changes