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:
selene-manager/src/pool/mp.rs:147—let world = session.ranks.as_ref().map_or(1, |r| r.world);selene-manager/src/pool/mp.rs:114-121—MpSide::wholewrapslayout.whole().selene-manager/src/pool/claims.rs:878—MpState::new(req_mp, MpSide::whole(&self.scopes[&scope].valid.slices))for manager sources.
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.
N4. The base-context vs. codec-context split for host registration is legal
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
reserve_codec_partitionreally means "offload enabled and GPU compression":helios/src/runtime_core/model.rs:629-658populatesgpu_codec_cubinsonly underKvCompression::Gpuand leaves it emptyelse, socpu/offkeep the 2-way split even thoughPrefixCacheOffload::enabled()(selene/src/offload.rs:112-114) is compression-agnostic.close_storeon the three early-error paths cannot double-close:storeis moved intoclose_store(store, &mut shutdown)and each pathreturns beforeworker.attach_store(store)(helios/src/server/runtime.rs:706-708, 719-723, 783-787vs:797, :821); each sendsready_txafter the drain, so no peer can see Ready for a failed runtime. The extraction preservesManuallyDropslab retention byte-for-byte.store_bridge.rs:411descriptoris not dead — it is still consumed at line 452.required_profilesis only non-empty for packed nodes (selene/src/disk_store.rs:2262-2281and:2313-2320,None => (…, Vec::new())), so passingcaps = Nonedoes not accidentally hide raw records — the one scenario that would have made the selene-manager change a Major regression._CODEC_BLOCK_BYTESdefined after theCodecEncodingclass body is fine:block_bytesis a@property, evaluated at call time.helios/src/offload/mod.rs:26(pub(crate) use transfer::GpuRankCodec; #[cfg(test)]) and thegpu_codec.rs/transfer.rsvisibility tweak have no runtime effect.
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:
- 16-SM device,
sm_coscheduled_alignment = 8,worker_sm_count = 8: 2-way → 8 worker + 8 compute (8 < 16,16-8 = 8not< 8) OK; 3-way →reserved = 16 >= 16→ error. - 24-SM device,
worker_sm_count = 16: 2-way → 16 + 8 OK; 3-way →reserved = 24 >= 24→ error.
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
- Ignition enum mirror is exact. All 11 ids and block sizes in
ignition/preparation/contract.py:16-52matchselene/src/shared/codec_layout.rs:17-32and the divisibility/alignment rules inselene/src/shared/codec.rs:611-655(MATRIX_BYTES = 65536, page blocks 135 168 / 8 448 / 32 768 / 33 792 / 18 432 / 73 728, conv widths 20/32, bf16 2, raw 1).offset_alignment = 4forFLOAT32_MATRIX_128and 1 elsewhere is also exact — the other widths are shuffle widths, not offset alignments, so 1 is not too permissive. NoUNSPECIFIED/0 collision exists either: the wire field is a plainuint32(no truthiness test onencodinganywhere). sorted(row_regions, key=offset)is a genuine fix, not noise:Plan::newrejects out-of-order or overlapping fields (selene/src/shared/codec.rs:565-579), so the old unsorted iteration could be rejected at plan build.default_field_encodingmatches the Rust relation: last dim 10 → 20 block bytes, 16 → 32 (PROTOCOL.md:1124);dims[-2:]is safe for 0-D/1-D shapes; an FP32(k,128,128)field always hasnbytes = 65536k, so that branch can only ever fail the alignment test, not divisibility.- selene-manager truth table is coherent across all four files: packed allowed exactly for single-process sessions (TP=1 and TP=4) and denied for multi-process (TP=2 and TP=8) in
store_bridge.rs:412,claims.rs:1181,claims.rs:637-649,lookup.rs:217-241,core.rs:646. No panic surface added (self.sessions[&sid]/self.sessions[&source_sid]cannot be stale;source_sid's session is already dereferenced atclaims.rs:578;get_answeruses panicking-free.get). - Hot path: the new
source_mplookup inlookup.rs:217-228costs three hash probes per candidate and sits afterwalk_chain(…)(lookup.rs:207-216), which dominates by orders of magnitude; no per-node allocation was added (closures only borrow&n.required_profiles).sorted()incodec_layoutruns once per export. No O(N) / O(N·span) regression anywhere in the diff. plan_sm_splitarithmetic is safe at every boundary I substituted (16/20/24/32/48/188 SMs): no subtraction underflow (reserved_sms >= total_smsshort-circuits beforetotal_sms - reserved_sms), no 0-SM partition (aligned_codec ≥ min_partition ≥ coscheduled ≥ 2, plus the driver-side check atpersistent_worker.rs:369-371), no overlapping ranges (backfill group). New test expectations atpersistent_worker.rs:2607-2680match this arithmetic.- Out-of-scope but worth flagging to the human reviewers:
helios/src/server/runtime.rsandphase_tests.rsalso carry an unrelatedPrompt::preserve_message_anchorfeature (field atruntime.rs:52, set atruntime.rs:288, consumed atscheduler/checkpoints.rs:470(not opened)) with two large new tests; it is mechanically sound and threads through everyPrompt/Specliteral, but it is a second feature in a PR that never mentions it.
No instructions-addressed-to-the-agent or prompt-injection attempts were present in the material read.