Deep Code Correctness / Invariants / Hot-Path Audit — PR #723 @ 275b7a5
Large multi-crate PR (27 files, ~1.3k changed lines across helios, heliopause, ignition), so it was partitioned into 3 concurrent crate slices (spawn_agent s1 helios runtime_core, s2 heliopause+helios-core manifest fields, s3 ignition Python). I then re-read every cited site myself at the PR head and dropped two sub-agent findings that did not survive verification (see "Rejected" at the end). Only the findings below are directly proved from the code.
F1 — MAJOR: compute_coscheduled_alignment is fabricated with .max(), making the alignment re-check dead and feeding a fabricated ceiling into load-time cluster validation
Sites (all re-read by me): assignment helios/src/runtime_core/persistent_worker.rs:455-457; dead guard :490-496; plan-side producer :186-200; consumer helios/src/runtime_core/mod.rs:958 and the cluster check mod.rs:1087-1094.
// helios/src/runtime_core/persistent_worker.rs:454-457
partition.compute_sm_count = actual_compute_sm.sm_count;
partition.compute_coscheduled_alignment = actual_compute_sm
.sm_coscheduled_alignment
.max(group_params[compute_index].coscheduled_sm_count);
...
// :490-496
if actual_compute_sm.sm_coscheduled_alignment < baseline_coscheduled
|| partition.compute_coscheduled_alignment < required_compute_coscheduled
{
return Err(invalid(
"compute green context partition lost required co-scheduled SM alignment",
));
}
Callee/semantics resolution. group_params[compute_index].coscheduled_sm_count is set to either required_compute_coscheduled (:189) or PREFERRED_COMPUTE_COSCHEDULED_SMS = 16, and the latter branch is only taken when required_compute_coscheduled < PREFERRED_COMPUTE_COSCHEDULED_SMS (:196). So group_params[compute].coscheduled_sm_count >= required_compute_coscheduled always, and .max() guarantees partition.compute_coscheduled_alignment >= required_compute_coscheduled. The second half of the || is therefore true by construction and can never fire: this is precisely the "always-true guard half" case.
Counterexample (SM120-class, 188 SMs, min_sm_partition_size=8, sm_coscheduled_alignment=8). A core declares one graph with max_cluster_size=16 ⇒ required_compute_coscheduled=16 (:108-114), the preferred-16 branch is skipped (16 < 16 is false) so fallback = None. Suppose cuDevSmResourceSplit downgrades the 16-CTA request to an 8-SM-aligned compute resource instead of failing (the exact case the error text "lost required co-scheduled SM alignment" exists for):
:4908 < 8→ false;:491max(8,16)=16 < 16→ false ⇒ no error, partition accepted.partition.compute_coscheduled_alignmentis reported as16.prepare_graphspassesSome(partition.compute_coscheduled_alignment)=Some(16)ascompute_coscheduled(mod.rs:958), and the per-node check atmod.rs:1087-1094(if cluster_size > alignment) then accepts a 16-CTA cluster:
// helios/src/runtime_core/mod.rs:1087-1094
if let Some(alignment) = compute_coscheduled
&& cluster_size > alignment
{
return Err(invalid(format!(
"graph {} kernel cluster size {cluster_size} exceeds compute partition co-scheduled alignment {alignment}",
graph.name
)));
}
So a 16-CTA cluster node passes load-time validation on a partition whose real alignment is 8 — the PR's stated invariant ("no fallback below max_cluster_size") is silently defeated, and the diagnostic printed by the new SM120 tests (:3037-3040, :3592-3595) cannot distinguish requested from actual alignment.
Fix: stop laundering the value; check the driver's real output once.
partition.compute_coscheduled_alignment = actual_compute_sm.sm_coscheduled_alignment;
if actual_compute_sm.sm_coscheduled_alignment < required_compute_coscheduled {
return Err(invalid(format!(
"compute green context partition returned co-scheduled alignment {}, below required {}",
actual_compute_sm.sm_coscheduled_alignment, required_compute_coscheduled)));
}
(baseline_coscheduled <= required_compute_coscheduled, so a single comparison suffices.) Note the create-time check at :359-369 is not dead — it compares group_params[...].coscheduled_sm_count with required_compute_coscheduled, i.e. the plan with itself — so this :490 guard is the only place a downgrade could have been caught.
F2 — MINOR: heliopause fabricates min_compute_sms >= 1 (and max_cluster_size >= 1) for every exported graph, destroying the documented 0 = unspecified sentinel
Sites: heliopause/src/export/capture.rs:465-500, write site :3438-3448, contract helios/proto/runtime_core.proto:750-753 (+ helios/proto/core.proto same shape), test pinning it heliopause/src/export/capture.rs (assert_eq!(graph_sm_requirements(&nodes[..1], 0)?, (1, 1));).
// heliopause/src/export/capture.rs:465-472
fn kernel_cluster_size(kernel: &wire::Kernel) -> ExportResult<u32> {
let Some(attribute) = kernel
.attributes
.iter()
.find(|attr| attr.id == CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION)
else {
return Ok(1); // <-- "no cluster declared" reported as size 1
};
...
// :491-499
fn graph_sm_requirements(nodes: &[wire::Node], declared_min_compute_sms: u32) -> ExportResult<(u32, u32)> {
let mut max_cluster_size = 0u32;
for node in nodes {
if let Some(wire::node::Operation::Kernel(kernel)) = &node.operation {
max_cluster_size = max_cluster_size.max(kernel_cluster_size(kernel)?);
}
}
let min_compute_sms = declared_min_compute_sms.max(max_cluster_size);
Ok((min_compute_sms, max_cluster_size))
}
// helios/proto/runtime_core.proto:750-753
// Minimum compute SMs required for resident execution of this graph; 0 means unspecified.
uint32 min_compute_sms = 7;
// Maximum CTA cluster size declared by kernel nodes in this graph; 0 means unspecified.
uint32 max_cluster_size = 8;
Counterexample. A plain Qwen3.8 decode graph with N unclustered kernels and no b12x floor: every kernel_cluster_size returns Ok(1) (node-type filter is correct; record_kernel at :580-607 only stores attributes whose 8-word value is non-zero, so the x==0&&y==0&&z==0 and < 12 branches are unreachable) ⇒ max_cluster_size = 1 ⇒ min_compute_sms = max(0,1) = 1. Every graph of every newly exported core now serialises (1, 1), so a reader can never distinguish "no floor declared" from a real 1-SM floor, and a genuine 1-SM floor from a 16-CTA cluster's implicit 16-SM floor. The second half of the defect is the .max(max_cluster_size) fold: the two bounds are consumed independently downstream (persistent_worker.rs:108-114 derives required_compute_coscheduled from max_cluster_size; :134-136 derives required_compute_sms from min_compute_sms), so folding cluster size into the SM floor double-counts it and makes "floor > cluster" inexpressible.
Behaviourally this is currently benign (the floor only ever raises required_compute_sms toward min_partition), hence Minor — but it permanently voids a documented forward-compatibility contract for all future cores and the new unit test locks the wrong behaviour in.
Fix: return 0 (not 1) when attribute 4 is absent, and drop the fold: let min_compute_sms = declared_min_compute_sms;. Update the test to (0,0) / (128,0).
F3 — MINOR: register_cooperative_plan aggregates a floor with min(), so a re-registration silently weakens the recorded requirement
Sites: ignition/preparation/scratch.py:163-164, guard :157-162; correct-direction siblings for comparison :135 (max) and :186-187 (max).
# ignition/preparation/scratch.py:156-164
key = id(plan)
if self.overlap:
required = max(self._min_reserve_sms, self._parallel_reserve_sms.get(key, 0))
if reserve_sms < required:
raise ValueError(
f"cooperative plan requires reserve_sms >= {required} for active overlap, got {reserve_sms}"
)
prev = self._cooperative_plans.get(key)
self._cooperative_plans[key] = reserve_sms if prev is None else min(prev, reserve_sms)
required never includes prev, so a lowering re-registration always passes the guard, and min is the wrong aggregate for a floor invariant (a reservation floor must be monotone: max).
Counterexample (runs against the head implementation):
arena = ScratchArena("cpu")
arena.register_cooperative_plan(p, reserve_sms=8) # records 8 (required = max(0,0) = 0)
arena.register_cooperative_plan(p, reserve_sms=4) # required = 0 → records min(8,4) = 4
arena.register_parallel(p, q, reserve_sms=6) # :178-183 sees declared=4 < 6 → ValueError
The caller's strongest statement (8) is discarded, and a correctly annotated 6-SM overlap is rejected. Fail-closed, hence Minor, but it is the only place in the new contract where the aggregation direction is inverted. Note the min(prev, ...) branch is never exercised by tests/preparation/test_scratch.py:548-584, so no test catches it.
Fix: self._cooperative_plans[key] = max(prev or 0, reserve_sms).
F4 — MINOR: release_preparation() clears the plan maps but leaves a stale reserve_sms_floor
Site: ignition/preparation/scratch.py:228-235; reader :113-118.
# ignition/preparation/scratch.py:231-235
self.tensor = torch.empty(0, dtype=torch.uint8, device=self.device)
self._parallel_plans.clear()
self._parallel_reserve_sms.clear()
self._cooperative_plans.clear()
self._released = True
self._min_reserve_sms and self._max_parallel_reserve_sms are not reset, so after release the property still reports a floor derived from dicts that are now empty:
arena = ScratchArena("cpu", min_reserve_sms=4)
arena.register_parallel(a, b, reserve_sms=8); arena.freeze(); arena.finalize()
arena.release_preparation()
arena._parallel_reserve_sms # {}
arena.reserve_sms_floor # 8 <-- stale, contradicts the cleared state
Even the arena's own ctor argument (min_reserve_sms=4) survives release, so a half-reset arena reports a reservation that nothing declares. Idempotency itself is safe (if self._released: return, :224-225). Fix: reset both aggregates to 0 (or route reserve_sms_floor through _require_active()).
F5 — MINOR: resolve_reserve_sms never reads the cooperative declarations, so the cooperative direction is write-only
Sites: ignition/preparation/scratch.py:137-146; reserve_sms_floor :113-118; writer :148-164.
# ignition/preparation/scratch.py:143-146
floor = self.reserve_sms_floor
if plan is not None:
floor = max(floor, self._parallel_reserve_sms.get(id(plan), 0))
return max(requested, floor)
reserve_sms_floor is max(self._min_reserve_sms, self._max_parallel_reserve_sms); _cooperative_plans is never consulted. A plan that declared reserve_sms=8 therefore resolves to 0:
arena = ScratchArena("cpu")
arena.register_cooperative_plan(moe_plan, reserve_sms=8)
arena.reserve_sms_floor # 0
arena.resolve_reserve_sms(0, plan=moe_plan) # 0, not 8
This is arguably consistent with the docstring ("at least requested and any active overlap SM floor"), and there is no production caller in this repo (grep for resolve_reserve_sms|register_cooperative_plan|require_reserve_sms hits only scratch.py and tests/preparation/test_scratch.py), which is why this is Minor rather than Major. But if the companion recipes PR (#157) uses resolve_reserve_sms to size its own cooperative launch, it will launch under-reserved — the exact failure the PR claims to make impossible. Fix: fold self._cooperative_plans.get(id(plan), 0) into floor before the final max, or reject a plan= that is registered cooperatively unless its own declaration is returned.
F6 — MINOR: the payload-format single-rank loader hardcodes reserve_codec_partition = false, so GPU codec isolation (and the new min_compute_sms/max_cluster_size enforcement) is skipped on that path
Sites (self-verified): helios/src/runtime_core/mod.rs:335 (prepare_kernels(..., false) — the PR added this explicit false), mod.rs:342-344 (initialize → initialize_with_options(.., false)), callers mod.rs:218, mod.rs:241, helios/src/runtime_core/protection.rs:2836 (PayloadAuthorizedCore::load).
// helios/src/runtime_core/mod.rs:330-336
let mut owner = unsafe { Self::initialize(&core, ordinal)? };
unsafe {
owner.reserve(&core)?;
owner.allocate(&core, &phase)?;
owner.load_payload(files, &core, &phase, 1)?;
owner.prepare_kernels(files, &core, &phase, None, false)?;
owner.prepare_graphs(files, &core, &phase)?;
}
// :342-344
unsafe fn initialize(core: &Core, ordinal: i32) -> Result<Self> {
unsafe { Self::initialize_with_options(core, ordinal, false) }
}
Trace. For a codec-enabled, non-worker core (DeepSeek-V4.1/GLM-5.3/Qwen3.8/Ergo/Gemma) loaded through NativeResources::load/load_any/PayloadAuthorizedCore::load, initialize_with_options(.., false) takes primary_context = wants_worker.is_some() || false (:386) ⇒ false, and prepare_kernels takes the partition branch only under worker.is_some() || reserve_codec_partition (:793) ⇒ green_partition stays None. Then every graph is instantiated on self.context (:962), offload_context() falls back to self.context (:1511-1516), and neither min_compute_sms (:964-980) nor the cluster check (:1067-1096) is ever applied — silently, with no diagnostic.
Reachability caveat (verified, so this stays Minor): the main serving path is correct — helios/src/runtime_core/model.rs:718-733 computes reserve_codec_partition = options.prefix_cache.enabled() && compression == KvCompression::Gpu and passes it to initialize_with_options + prepare_kernels (model.rs:859-867); NativeModel::load_agreeing routes payload cores to that path (model.rs:339+). No in-repo production caller of the load_prepared/load_any path exists (only helios/src/runtime_core/event_tests.rs:19 (not opened) and in-module tests). Fix: thread the flag (or a LoadOptions/KvCompression argument) through load_prepared/initialize/PayloadAuthorizedCore::load, or fail closed when the core needs codec SMs but the flag is absent.
F7 — MINOR: cuDevResourceGenerateDesc handles leak on every partial-failure path in create()
Sites: helios/src/runtime_core/persistent_worker.rs:370-392 (three descs; the worker/codec if wrapping and codec_desc are new in this PR), cleanup :545-552, destroy_streams :556-568, destroy_green_contexts :570-595 — none of which release worker_desc/codec_desc/compute_desc.
// helios/src/runtime_core/persistent_worker.rs:545-552
if let Err(error) = setup {
// SAFETY: No work was launched on these newly created streams or contexts.
unsafe {
partition.destroy_streams(driver);
partition.destroy_green_contexts(driver);
}
return Err(error);
}
Trace: 3-way plan; cuDevResourceGenerateDesc(worker) and (codec) succeed, cuGreenCtxCreate(compute) (:415) returns CUDA_ERROR_NOT_SUPPORTED ⇒ green contexts/streams are destroyed but all three descs are dropped with the stack frame. Same after codec_split.sm_count < group_params[idx].sm_count (:344-357). Up to 3 leaked desc resources per failed rank per attempt; bounded and freed at context destroy, hence Minor. (The pre-PR code had the same gap for 2 descs; the PR adds a third handle and three more failure points.) Fix: store the descs in GreenContextPartition and destroy them in destroy_green_contexts, or wrap each in a Drop guard.
F8 — MINOR: a nonzero min_reserve_sms is accepted and then silently ignored when overlap=False
ignition/preparation/scratch.py:59-63 accepts min_reserve_sms=4 with overlap=False; reserve_sms_floor then returns 0 (:116-117) and resolve_reserve_sms returns the bare requested (:141-142) with no diagnostic — asymmetric with require_reserve_sms, which does raise in serial mode (:126-127). The new test encodes this as intended (tests/preparation/test_scratch.py:588-590), so it is a contract wart rather than a crash. Fix: reject a nonzero min_reserve_sms when overlap is false in __init__.
Verified correct (checked, not assumed — no finding)
plan_sm_splitarithmetic (persistent_worker.rs:92-223):total_sms - reserved_smsat:194is unreachable forreserved > total(the:137guard short-circuits onreserved_sms >= total_sms); thesaturating_subat:138only feeds the message. Substitutedtotal_sms ∈ {1,2,3,16,20,132,188},coscheduled ∈ {2,4,8,16},min_sm_partition_size ∈ {0,1,8},min_compute_sms ∈ {0,1,7,148,1000},max_cluster_size ∈ {0,1,2,8,16,17,33,u32::MAX}:checked_next_multiple_ofrounds up (17→24 at alignment 8), returnsNoneonly foru32::MAX(cleaninvalid), andmax_cluster_size = 0never reaches it (:108guard). ThePREFERRED_COMPUTE_COSCHEDULED_SMS=16preference can never request more than the SMs actually left (:195-197gates onremaining_sms), and itsfallbackalways still satisfiesrequired_compute_coscheduled, so the fallback cannot be "too wide".groups[]index/retry safety (:285-310): indices derive from the singlebase_paramsvec;compute_index == base_params.len()-1;primary.len() == fallback.len();groups.fill(DevResource::zeroed())resets all entries on the fallback retry andgroup_countis re-passed tocuDevSmResourceSplit;split_sm_groups(:227-240) returns the params that actually succeeded, sogroup_params[idx]is never the rejected primary.- Per-graph aggregation direction (
mod.rs:795-808):min_compute_sms/max_cluster_sizeare merged withmax()across graphs (never sum, never last-wins), so a graph declaring0cannot erase another graph's floor — correct even given F2. - No graph is skipped (
mod.rs:943,:964-980,:1067-1096); the worker graph is excluded only from the plan aggregation, which is correct since it runs in its own partition.bytes[0..12]reads on the attribute blob are in-bounds (format.rsrequires the 64-byte value; the loop already copies 64 bytes). - Cluster-dimension parsing (
capture.rs:479-488,mod.rs:1068-1078): uses the 3-D product withchecked_mul(so(2,8,1)and(16,1,1)both give 16), applies only toOperation::Kernelnodes (Copy/Memset/EventWait are skipped), and size 1 cannot be misread as "unspecified" in this direction (see F2 for the reverse). - Proto numbering/back-compat:
min_compute_sms = 7/max_cluster_size = 8are the highest field numbers in bothGraphIndex(runtime_core.proto:743-754) andGraph(core.proto:244-255); noreservedstatement covers 7/8 and nothing was renumbered;0defaults make old readers/writers no-ops. Registration sites all populated:protobuf.rs(encode/decode),metadata.rs,describe.rs,format.rs:219-228,heliopause/src/export/{capture,core,mod}.rs; thehelios/src/core/*.rs+2/+2/+6hunks are struct-literal test fixtures only. register_parallelis order-safe: the validation loop over all plans completes before any write, and both writes are monotonemax(:176-188) — no partially-applied state. Bidirectional fail-closure holds in the tested orders (plan→parallel, parallel→plan, require→plan). Bool/float/numpy-int rejection viatype(x) is not intis correct (type(True) is not int).- Python→proto plumbing:
capture.py:232-246enters_track_capture_min_compute_sms()inside the per-graph loop and outsidetorch.cuda.graph(...), so it exits on theexcept Exceptionpath and cannot leak between graphs;runtime_core.py:296-320validatesmin_compute_sms(type is int,>= 0) and attaches it only when> 0to all three handle shapes. (track_capture_min_compute_smsitself is an external b12x API — not verifiable in this repo.) - Hot path / Big-O: nothing changed here runs per token or per step.
plan_sm_split/create/prepare_kernelsrun once per rank;prepare_graphsandgraph_sm_requirementsare single O(nodes) passes with oneVec::clone()of a 2–3 element params vec (the pre-existingbase_paramscopy, now explicit). No per-iteration allocation or O(N·span) scan was introduced.ScratchArenaadditions are preparation-only. - All new tests at the head are internally consistent with the implementation (
tests/preparation/test_scratch.py:548-608,tests/preparation/test_capture_graph_metadata.py,persistent_worker.rsplan_sm_splitmatrix,capture.rsgraph_sm_requirements_extracts_cluster_dimension_and_merges_declared_floor) — their weakness is coverage (they pin F2's(1,1)and never exercisemin(prev, reserve_sms)), not correctness.
Rejected after verification (sub-agent findings that do not hold)
- "
max_cluster_sizeis never captured/plumbed from Python (Major)" — wrong.heliopause/src/export/capture.rs:3438callsgraph_sm_requirements(&nodes, graph.min_compute_sms), which derivesmax_cluster_sizefrom the exported graph's own kernel node attributes. Inferring it from the recorded graph is authoritative; a Python-declared value would be redundant. NoGraphHandlefield is needed. - "
resolve_reserve_smsignoring_cooperative_plansis a Major fail-open" — downgraded to F5 (Minor): the docstring matches the behaviour and no production caller exists in this repo.
No prompt-injection content was found in the PR body, comments, or changed code; nothing in the reviewed material attempted to direct my actions.