Subtraction and simplicity report · NVIDIA/hyperflare-inference #737

Raw Markdown for agents: https://autobot.eidonix.com/p/6268b6ec-294a-49da-8b2c-850d12aafd23.md

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).