Code correctness report · NVIDIA/hyperflare-inference #709

Raw Markdown for agents: https://autobot.eidonix.com/p/fcb9037d-52dd-4b8d-84d8-674042f28fba.md

Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #709 @ eb6c1e1

Verdict: no Blocker and no Major defect found. The three riskiest claims in the PR (inverted packed-capability guards, a still-broken single-host TP≥2 world() check, and a context/ordering hazard introduced by moving offload::open before RankExecutor::new) are all disproved by the callee definitions, with citations below. What remains are six Minor defects, five of which are real but bounded, and one host-dependent flaky test.

18 files / ~2,240 changed lines across 3 subsystems, so the audit was partitioned into three disjoint slices (helios, ignition, selene-manager) run concurrently, then the open leads from each slice were verified by me directly against the files at eb6c1e1.


Negative results — hypotheses disproved in code (do not re-derive)

N1. permits_holding(None, …) / permits_offer(None, …) mean raw-only, not "allow all" — the new selene-manager guards are correct, not inverted

selene/src/shared/packed.rs:50-67:

pub fn permits<'a>(caps: Option<&CodecCaps>, profiles: impl IntoIterator<Item = &'a Vec<u8>>) -> bool {
    caps.is_some_and(|c| {
        c.envelope_revision == REVISION
            && !c.receive_profiles.is_empty()
            && profiles.into_iter().all(|p| c.receive_profiles.contains(p))
    })
}
pub fn permits_holding(caps: Option<&CodecCaps>, packed: bool, profiles: &[Vec<u8>]) -> bool {
    (!packed && profiles.is_empty()) || permits(caps, profiles)
}

caps = None ⇒ permits == false ⇒ permits_holding(None, true, _) == false and permits_offer(None, _) == false. So claims.rs:640-642 and lookup.rs:226-228 passing None genuinely excludes every packed record (including all-literal v4, since permits_offer only needs the literal-filtered profile list to pass permits), and raw v3 records still pass via the !packed && profiles.is_empty() arm. Intent matches implementation.

N2. claim.mp.req.layout.world() is a process count, so single-host TP≥2 packed PinAck really is now allowed

selene/src/shared/slice.rs:88-105 — Layout::world() is self.ranks.len() of the slice layout, which is collapsed for single-process sessions:

For single-process TP=2 (ranks == None, descriptor.ranks.len() == 2): req.layout.world() == 1 and src.layout.world() == 1, so the new guard at claims.rs:1181 (if any_packed && (claim.mp.req.layout.world() > 1 || claim.mp.src.layout.world() > 1)) evaluates false and the packed PinAck is accepted — the claimed fix. For true multi-process TP=2 (ranks = Some, world 2) it is rejected. core.rs:646-653 mirrors this and still revision-filters offered_codec for the reconnect comparison at core.rs:667 (old_sess.offered_codec == offered_codec && … && old_sess.ranks == ranks), so reconnect compatibility is unaffected.

N3. Moving offload::open before RankExecutor::new introduces no context hazard

offload::open (helios/src/offload/mod.rs:137-146) delegates to flare_selene::offload::open, whose transfer threads call RankWorker::open (helios/src/offload/transfer.rs:397-408). Stream::open_lowest_priority (helios/src/cuda.rs:785-786) calls Self::bind, which does cuCtxSetCurrent(codec_context) and does not restore the previous context — so the model thread is left on the codec context after offload::open returns. This is harmless here because every subsequent consumer in RankExecutor::new re-binds explicitly: Stream::bind (cuda.rs:740-756) and Stream::open (cuda.rs:758-764), used by transport.rs:623-624; else GraphExecutor::finish_startup issues cuLaunchKernel bound to the stream's context. The deadlock fix is also correctly placed: the worker launch happens in GraphExecutor::finish_startup → control.start(), still strictly after the store is opened.

helios/src/cuda.rs:445-471 registers with HOST_REGISTER_PORTABLE:

const HOST_REGISTER_PORTABLE: c_uint = 0x1;
…
driver.check("cuCtxSetCurrent", (driver.set_context)(context as Handle))?;
driver.check(
    "cuMemHostRegister_v2",
    (driver.host_register)(address as Handle, nbytes, HOST_REGISTER_PORTABLE),
)?;

memory.rs:1010 now passes self.ranks[0].context (primary) as registration_context while model.rs:966-969 passes rank.offload_context() (codec green context) to the transfer streams (transfer.rs:408). PORTABLE makes the registration visible to every context in the process, which is exactly the requirement — the two contexts differ, so non-portable registration would have been the bug; it isn't.

N5. Other probes that came back clean


Findings

1. Minor — the new codec Green Context never receives the core's Context settings

helios/src/runtime_core/mod.rs:780-785:

let (worker_context, compute_context) =
    (partition.worker_context, partition.compute_context);
self.green_partition = Some(partition);
apply_context_settings(&driver, worker_context, &core.context)?;
apply_context_settings(&driver, compute_context, &core.context)?;

Callee apply_context_settings (helios/src/runtime_core/mod.rs:1675-1695) applies core.context.limits via cuCtxSetLimit and core.context.cache via cuCtxSetCacheConfig. codec_context now exists (helios/src/runtime_core/persistent_worker.rs:388-396, cuCtxFromGreenCtx(codec)) and from this PR onward runs every GPU codec kernel and every offload DMA stream (mod.rs:1416-1421 → transfer.rs:408), yet it is omitted from both calls. CUDA context limits and cache config are per-context, and green-context-derived contexts are distinct contexts. Counterexample: a core whose Context.cache selects a preference the codec kernels are tuned for, served with --lossless-kv-compression gpu on a persistent-worker GPU: the same kv_codec_gpu kernels run with the declared setting on a non-persistent-worker core and with driver defaults on a persistent-worker core — a mode-dependent divergence in kernel-visible context state. Fix: inside the if let Some(worker) arm, apply_context_settings(&driver, partition.codec_context, &core.context)?; guarded by !partition.codec_context.is_null(), before self.green_partition = Some(partition).

2. Minor — the 3-way split hard-fails where the pre-existing 2-way split succeeds, with no fallback

helios/src/runtime_core/persistent_worker.rs:94-113:

let aligned_codec = if reserve_codec_partition {
    min_partition
        .checked_next_multiple_of(coscheduled)
        .ok_or_else(|| invalid("GPU codec SM partition overflows alignment"))?
} else { 0 };
let reserved_sms = aligned_worker.checked_add(aligned_codec)…;
if reserved_sms >= total_sms || total_sms - reserved_sms < min_partition {
    if reserve_codec_partition {
        return Err(invalid(format!(
            "… leave insufficient structured compute SMs; use --lossless-kv-compression cpu"
        )));
    }

(The arithmetic itself is sound — no underflow, aligned_codec ≥ min_partition ≥ 2 > 0, and groups 0/1 are explicit sm_count while the last uses sm_count = 0 + CU_DEV_SM_RESOURCE_GROUP_BACKFILL at :135-141, so ranges cannot overlap. (188, 8, 8, 8) → worker 8, codec 8, compute 172 reproduces the PR's example exactly.) Counterexamples where plan_sm_split(dev, r, false) returns Ok but (…, true) errors:

The only remedy offered is a global downgrade to --lossless-kv-compression cpu, so upgrading an existing gpu deployment on a small-partition device loses GPU compression entirely, even though the degrade path already exists: offload_context() (mod.rs:1416-1421) falls back to self.context whenever codec_context.is_null(). Fix: on reserve_codec_partition failure, retry plan_sm_split(device_sm_info, requested_worker_sms, false) and record that no codec partition was reserved, so offload_context() degrades to the base context; keep the hard error only for the genuinely unsatisfiable 2-way case.

3. Minor — _validate_codec_encoding rejects numpy integer scalars

ignition/preparation/contract.py:209-210 and :215-218:

if isinstance(value, bool) or not isinstance(value, int):
    raise ValueError(f"codec encoding for {label} must be an integer CodecEncoding")
…
if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
    raise ValueError(f"codec field offset for {label} must be a nonnegative integer")

numpy.int64 / numpy.uint32 — the natural output of recipe dtype/table lookups and of tensor.shape products — fail the isinstance(..., int) test even though CodecEncoding(value) and int(...) would accept them, so a legitimate recipe is rejected at export with a misleading "must be an integer" message. Fix: keep the bool rejection, then accept numbers.Integral (or operator.index(value) in a try) for value, offset, and length.

4. Minor — the duplicate-buffer guard rejects a legitimate page buffer named state_pool

ignition/preparation/contract.py:280, 299-304:

row_buffer = state_buffer or continuation_buffer or "state_pool"
…
seen_buffers = {row_buffer}
for region in page_regions:
    view = region["storage"]
    name = view["buffer"]
    if name in seen_buffers:
        raise ValueError(f"duplicate codec layout buffer {name!r}")

Seeding seen_buffers with row_buffer conflates "the row buffer is named state_pool" with "this page region duplicates the row buffer". Because state_buffer or continuation_buffer or "state_pool" falls back to the literal, the guard fires for a recipe that declares no CONTINUATION_STATE region at all and declares a paged KV plane whose view is named state_pool — the shape history_region(buffers, "state_pool", tensor, kind=…) (contract.py:329) produces. Pre-PR code emitted a field for it and Selene built two valid plans: selene/src/shared/codec_layout.rs:52-61 accepts any field.buffer matching g.row.name or a plane name, and build_plan is invoked separately for g.planes and for [g.row] (codec_layout.rs:108), so the name may legitimately appear in both. Counterexample: codec_layout(pool, [history_region(bufs, "state_pool", kv_tensor, kind=PAGED_KEY_VALUE)], bufs, field_encoding=default_field_encoding) → ValueError: duplicate codec layout buffer 'state_pool', where it previously returned a valid layout. Fix: start with seen_buffers = set() and reject only a duplicate between two page regions; if name == row_buffer is meant to be an error, gate it on an actual CONTINUATION_STATE entry or an explicit state_buffer having been supplied.

5. Minor — new validation is unreachable on two paths, so the documented contract silently does not hold

ignition/preparation/contract.py:256-260:

row_regions = getattr(pool.layout, "regions", ())
if field_encoding is None or not row_regions:
    return None
if state_buffer is not None and (not isinstance(state_buffer, str) or not state_buffer):
    raise ValueError("state_buffer must be a nonempty string")

(a) The state_buffer type check does not depend on row_regions, yet sits after the early return: codec_layout(pool_with_no_regions, [], {}, field_encoding=f, state_buffer="") returns None rather than raising. (b) row_bytes (contract.py:281, bounds check at :289-290) is defined by no producer in this repository — the only definitions anywhere are the SimpleNamespace fixtures inside the new test file (tests/preparation/test_codec_layout.py:12, 98, 145, 177, 203); the real row extent lives Helios-side (row.unit_bytes). So the check is dead for every in-repo caller and the four tests that appear to cover it pass trivially. Fix: move the state_buffer validation above the early return; either wire row_bytes to a real attribute or drop the check and the corresponding test claim.

6. Minor — get_answer re-derives the multi-process predicate with only the requester side

selene-manager/src/pool/claims.rs:922-929:

let caps = (claim.mp.req.layout.world() == 1)
    .then(|| {
        self.sessions
            .get(&claim.requester_sid)
            .filter(|s| s.ranks.is_none())
            .and_then(|s| s.codec.as_ref())
    })
    .flatten();

This is a third, narrower formulation of the rule than claim_begin (claims.rs:637-642, !requester_mp && !source_mp) and lookup.rs:217-228 (session.ranks.is_none() && !source_mp). It omits the source term. It is not exploitable today only because get_answer is gated on claim.manager.is_some() (claims.rs:914) and a manager-sourced claim is always given MpSide::whole(..) (claims.rs:878, world 1) — i.e. the correctness rests on an invariant held in a different function. Counterexample if that invariant ever changes: requester single-process TP=2 with valid v4 caps, source a multi-process TP=2 instance ⇒ caps = Some(..), permits_offer passes, and a packed offer from a per-rank-assembled source is leased into claim.records[…].packed at claims.rs:937-939. Fix: extract fn packed_caps(&self, requester_sid: u64, source_mp: bool) -> Option<&CodecCaps> and call it from all three sites, passing source = claim.mp.src.layout.world() > 1 here. (Same root cause as the three-way duplication; one helper removes the drift.)

7. Minor — the new CUDA test hardcodes a device VA, the exact fragility the PR blames for other failures

helios/src/runtime_core/persistent_worker.rs:2891 inside cuda_green_context_three_way_gpu_codec_runs_concurrently_with_persistent_worker_and_cooperative_compute:

let host_va = 0xc20_0000_0000u64;
…
    address: Some(host_va),
    memory: Memory::MappedHost,

The PR body attributes the pre-existing persistent_worker::tests::cuda_* failures to fixed device VAs (0x800_0000_0000, used at persistent_worker.rs:1357, 2114, 2466) colliding with CUDA UVA placement on its 16-GPU host, and those tests use 0xc00_0000_0000 for the host allocation (:1358, 2115, 2467). The new test merely picks a different constant (0xc20_…), so its stated "1 passed" evidence is host-configuration dependent and it will fail on the same class of host. Fix: obtain the mapped-host range through the runtime's own allocator (address: None) and relocate the stop_flag/metrics references, or reserve the VA with cuMemAddressReserve instead of a literal.


What was positively verified as correct

No instructions-addressed-to-the-agent or prompt-injection attempts were present in the material read.