Subtraction & Simplicity audit — PR #709 (head eb6c1e1)
Verdict: the production change is lean — the selene-manager policy change is a net −4 lines across four files, ignition/preparation/contract.py adds no knob that isn't needed, and the Helios 3-way partition reuses the existing plan_sm_split/split_sm_groups machinery rather than forking it. The real bloat is (a) one hand-rolled duplicate test fixture that already exists four times in the same file, (b) a test/CI-unreachable validation branch, (c) a second cpability-gating predicate that duplicates the one introduced in the same PR, and (d) an undeclared/derived flag that could be one expression instead of a 3-way threaded parameter. Details below, highest value first.
1. HIGH — 5th copy of struct TestFiles / impl Files: ~50 duplicated lines, and the existing 4 copies prove the fixture should be extracted once
helios/src/runtime_core/persistent_worker.rs at PR head contains five literally-identical test fixtures:
:1285struct TestFiles(HashMap<String, Vec<u8>>);+:1287impl Files for TestFiles(pre-existing, 50 lines):1859same (pre-existing):2306same (pre-existing):2615same — added by this PR (the new CUDA test), 50 lines
The new copy is byte-for-byte the fixture at :1285–1336 (only the "missing test …" message text differs: "missing test resource {key}" at :2628 vs identical at :1298 — I diffed the two blocks and they are the same except for that string and block ordering). Extracting one #[cfg(test)] struct TestFiles at module scope and deleting all four bodies is ~200 lines removed from persistent_worker.rs for ~55 added; this PR should at minimum not add the fifth. That is the single largest subtraction available in the whole diff, and it is squarely in the +868 that strains "keep the runtime small".
2. HIGH — expect() in a #[ignore]d test keeps ~650 lines of test-only code and three pub(crate) visibility relaxations alive for nothing in CI
The authored #[ignore]d test (persistent_worker.rs:2595, "requires an assigned CUDA_VISIBLE_DEVICES GPU supporting Green Contexts and nvcc") is the sole reason for three production-file visibility changes that ship to every build:
helios/src/offload/transfer/gpu_codec.rs:2667pub(super) use imp::GpuRankCodec;→pub(crate) use imp::GpuRankCodec;helios/src/offload/transfer.rs:#[cfg(test)] pub(crate) use gpu_codec::GpuRankCodec;helios/src/offload/mod.rs:#[cfg(test)] pub(crate) use transfer::GpuRankCodec;
Two of those are #[cfg(test)] (free), but the pub(super) → pub(crate) widening on gpu_codec.rs:2667 is not, and it loosens a module boundary so a test can name an internal type. Worth flagging: the test's own assert!(total_sms >= 24) (:2688) and hardcoded nvcc search list ["/usr/local/cuda-13.2/bin/nvcc", "/opt/cuda/bin/nvcc"] (:2691) duplicate the existing pre-existing list shape at :1435 (which is if Path::new("/usr/local/cuda-13.2/bin/nvcc").exists() — so the PR already has two different nvcc-resolution helpers in the same file, and the new one is the better one; keep the new one, delete the old inline conditional).
Also the new test re-embeds the entire worker_spin + coop_all_sms CUDA source as a string literal at :2732–2770 that already exists verbatim at :1375–1424, and re-builds the whole wire::Execution / Core graph that :1596's build_core already builds. Hoisting the CUDA source into a const TEST_KERNELS_CU: &str removes ~40 lines and removes the risk of the two drifting.
3. MEDIUM — state_buffer parameter is dead for the only caller shape that exists, and its two error branches are unreachable in-tree
ignition/preparation/contract.py:249 adds state_buffer=None, with two new validation branches:
276 if state_buffer is not None and continuation_buffer is not None and state_buffer != continuation_buffer:
277 raise ValueError(
278 f"state_buffer {state_buffer!r} disagrees with CONTINUATION_STATE buffer {continuation_buffer!r}"
codec_layout has exactly one in-tree call site pattern (recipes call it directly; contract.py:198 only forwards the result as codec_layout= to model_contract). search_code over ignition/ finds no caller passing state_buffer — the only references are the definition (:249), the docstring (:254), the validation (:259, :276) and the new tests (test_codec_layout.py:195 (not opened)). So the parameter exists solely to be tested, and :276–279 exists solely to make the parameter's interaction with :269 well-defined.
Two clean options, both smaller:
- Keep
state_bufferand delete the conflict check at:276–279by defining precedence once:if state_buffer is not None: continuation_buffer = state_bufferbefore the loop — but that changes semantics. Better: - Since the docstring already says
CONTINUATION_STATE"select[s] the buffer name … whenstate_bufferis omitted", the explicit override is speculative generality. Deletingstate_bufferentirely removes:259–260,:276–279, and theor state_bufferterm at:280;row_buffer = continuation_buffer or "state_pool"is then the whole rule, andstate_buffer="other_state"(the test at:190–195) is indistinguishable from a recipe that just names its buffer correctly.
If the author wants it kept for external recipe authors, then at least collapse :280 — see #5.
4. MEDIUM — the same "multi-process ⇒ raw only" predicate is written three different ways in three files; one helper (or one accessor) would cover all of them
The PR's central policy is "requester or source is multi-process ⇒ no packed caps", and it is spelled differently every time:
selene-manager/src/pool/claims.rs:637-642let requester_mp = self.sessions[&sid].ranks.is_some(); let source_mp = matches!(source, SourceId::Instance(_)) && self.sessions[&source_sid].ranks.is_some(); let packed_caps = (!requester_mp && !source_mp) .then_some(self.sessions[&sid].codec.as_ref()) .flatten();selene-manager/src/pool/lookup.rs:217-228— resolvessource_mpby a four-stepOptionchain throughinstances → current → sessions, thenlet packed_caps = (session.ranks.is_none() && !source_mp) .then_some(session.codec.as_ref()) .flatten();selene-manager/src/pool/claims.rs:922-929(get_answer) — a third form, keyed on the layout instead of the flag: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();
Notes that make this concrete work, not taste:
core.rs:646already madesession.codecNonewhenever the session is multi-process:
Thereforelet codec = if ranks.is_some() { None } else { offered_codec… };session.codec.as_ref()is alreadyNonefor a multi-process session, andrequester_mpinclaims.rs:637andsession.ranks.is_none()inlookup.rs:226and.filter(|s| s.ranks.is_none())inclaims.rs:926are all redundant re-checks of an invariantOpenSessionestablishes. Only the source side genuinely needs a gate (a single-process requester can still claim a packed record from a multi-process source). Deleting the requester-side conjuncts leaves the semantics identical and shortens all three sites.- After that, all three reduce to one shape. A single
Corehelper beside the existingrequester_slices(claims.rs:805) — e.g.fn packed_caps(&self, sid: u64, source_mp: bool) -> Option<&v2::CodecCaps>gated only on!source_mp— replaces three inline computations, andlookup.rs's four-linkOptionchain gets one home.SourceId::Manager => false(lookup.rs:218) hardcoding "the manager is single-process" is the same assumptionclaims.rs:638encodes withmatches!(source, SourceId::Instance(_)); a helper removes the risk of the two disagreeing. - Also
.then_some(x).flatten()atclaims.rs:640-642andlookup.rs:226-228isbool::then(|| x)— or simplylet packed_caps = (!source_mp).then(|| session.codec.as_ref()).flatten();. Cosmetic, but the same two-line.then_some(...).flatten()idiom now appears twice in the same PR;claims.rs:922already uses the.then(|| …).flatten()form, so the PR is internally inconsistent about it.
5. MEDIUM — reserved_sms / aligned_codec: 0 sentinel forces a branch that Option<u32> would delete
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)
.ok_or_else(|| invalid("persistent worker SM request overflows alignment"))?;
if reserved_sms >= total_sms || total_sms - reserved_sms < min_partition {
if reserve_codec_partition {
return Err(invalid(format!(
"persistent worker ({aligned_worker} SMs) and GPU codec partition ({aligned_codec} SMs) …
The 0 sentinel buys nothing: aligned_worker.checked_add(0) can never overflow, so the second ok_or_else at :102 is dead whenever reserve_codec_partition is false, and the duplicated 6-line error message with if reserve_codec_partition { … } return Err( … ) at :104-112 is two nearly identical messages differing only in whether the codec count is mentioned. aligned_codec: Option<u32> (with reserved_sms = aligned_worker + aligned_codec.unwrap_or(0)) plus one message that interpolates an empty-or-nonempty codec clause collapses :94-116 to about half its length. Marginal, but it is the kind of 0-means-absent that makes the "12 branches on codec_index" below grow.
Related, same file: codec_index: Option<usize> plus compute_index: usize in SmSplitPlan (:56-60) encode a fact that is fully determined by reserve_codec_partition (codec_index == Some(1) iff reserved, compute_index == 1 or 2). Every consumer then re-branches on codec_index.is_some() — :259, :284, :308, :355 — and each of those guards a block that duplicates the worker/compute block above it (dev_resource_generate_desc, green_ctx_create, green_ctx_get_dev_resource, ctx_from_green_ctx, each with its own driver.check("…(codec)") string). Since the groups array is already a Vec of uniform DevSmResourceGroupParams, the codec group can be created in the same loop that creates compute — one for (idx, name) in groups.enumerate().skip(1) — instead of four if codec_index.is_some() clones. That removes ~35 lines from GreenContextPartition::create and removes the codec_index/compute_index pair from SmSplitPlan entirely.
6. LOW — codec_sm_count is write-only in production
persistent_worker.rs:45 pub(super) codec_sm_count: u32 is set at :368 and read only at :369 (if partition.codec_sm_count == 0), :3001 and :3221 (both in the new #[ignore]d test) and :3004. Compare worker_sm_count/compute_sm_count, which are genuinely consumed (mod.rs:905, :911, :1336, :1379, metrics.rs:1454 (not opened)). The field can be a local let codec_sm_count = actual_codec_sm.sm_count; if codec_sm_count == 0 { … } — no field, one fewer invariant to keep in sync with codec_context.is_null(). Note too that offload_context() (mod.rs:1418-1420) and teardown (mod.rs:1641) both gate on !partition.codec_context.is_null() while create gates on codec_index.is_some() — three different "is there a codec partition" predicates on the same object.
7. LOW — reserve_codec_partition is a threaded parameter where the callee already has both inputs (model.rs:820-821)
let reserve_codec_partition =
options.prefix_cache.enabled() && !model.gpu_codec_cubins.is_empty();
This is threaded as a new 5th parameter through prepare_kernels (mod.rs:761), down to GreenContextPartition::create (persistent_worker.rs:196), and the non-model call site must pass a literal false (mod.rs:334: owner.prepare_kernels(files, &core, &phase, None, false)?;). Observations worth reporting to the author:
- The predicate is a pure function of
options.prefix_cache+model.gpu_codec_cubins, both of whichNativeModel::prepare_offloadand the kernel preparation already have. Nothing in the chain computes it — it is derived in one place and hand-carried three frames. - The condition is a proxy, not the actual requirement.
gpu_codec_cubinsis non-empty iffoptions.prefix_cache.compression == KvCompression::Gpu(set atmodel.rs:629-658: theifbranch produces the cubins, theelsereturnsVec::new()). So!model.gpu_codec_cubins.is_empty()⇒compression == Gpu, andenabled()is already implied byvalidate_compression(selene/src/offload.rs:86-93:if self.compression != KvCompression::Off && !self.enabled() { return Err(…) }). The whole predicate therefore reduces tooptions.prefix_cache.compression == crate::offload::KvCompression::Gpu— the same expression already used two spots up atselection.rs:431andmodel.rs:629. Writing that directly removes theenabled() &&term (which reads, wrongly, as if acpu-mode core could reserve a codec partition) and removes the "does acpucore with embedded cubins reserve a partition?" ambiguity the review dossier flagged as an open question. That is a simplification that also closes a correctness question, which is why I rank it above its line count. - The
falseliteral atmod.rs:334is the tell: a boolean parameter that one of two call sites hardcodes is a flag that should be a field on the receiver (NativeResources/NativeModel) or a default-falsemethod (prepare_kernels+prepare_kernels_with_codec_partition), not a positional bool.
8. LOW — close_store free function is correct and worth keeping; the triple call site can shrink
helios/src/server/runtime.rs:1172 extracts the body of Worker::close_store (:1357) into a free fn close_store(store, shutdown), and Worker::close_store becomes close_store(self.store.take(), shutdown);. That is a genuine de-duplication (this PR deletes 22 lines and adds 22, net 0, while removing a copy). Positive finding — worth stating plainly.
The three early-error paths (:706, :719, :783) each open-code
close_store(store, &mut shutdown);
shutdown.error.get_or_insert(error.clone());
let _ = ready_tx.send(Err(error));
return shutdown;
That 4-line tail now appears three times verbatim; the :706 instance differs only by constructing let mut shutdown = Shutdown { drained: true, error: Some(error.clone()) } first. A closure let fail = |mut shutdown: Shutdown, error| { close_store(store, &mut shutdown); shutdown.error.get_or_insert(error.clone()); let _ = ready_tx.send(Err(error)); shutdown }; removes ~8 lines and makes "every early error closes the store and reports it" a single readable invariant instead of three copies a future edit can miss. Note this is exactly the class of bug #698's review blocked on, so making it structurally impossible to forget is worth more than the line count.
9. Confirmed lean (no action)
selene-manager/src/pool/store_bridge.rs: the whole change is one predicate,+1/−1(:412m.packed.is_some() && self.sessions[&sid].ranks.is_some()); thedescriptorclone at:411is still needed for theStoreCommand::PutBegin { descriptor, … }at:452, so it is not dead after the guard rewrite. No subtraction available.selene-manager/src/pool/core.rs:+10/−4, and theoffered_codecfield is genuinely still needed —:667let compatible = old_sess.offered_codec == offered_codecuses it for the reconnect check while:743codec: codec.clone()ships the possibly-Nonevalue. Retaining both fields is the minimum, not speculative generality.ignition/preparation/contract.pyCodecEncoding(IntEnum)+_CODEC_BLOCK_BYTES: 11 IDs, no dead members (the new test attest_codec_layout.py:75-87(not opened) assertsset(contract.CodecEncoding) == expected, so membership is checked).block_bytes/offset_alignmentas properties over one dict is the right shape — no simplification to offer._validate_codec_encoding(:208-229) is called from both loops (:291,:312) — correctly factored, not duplicated.default_field_encoding(:232-246) is a single fall-through classifier with no dead arms;BYTESdefault is the documented conservative choice.selene-manager/tests/support/pool.rs (not opened) (+3)and the+645intests/packed.rs(not opened) are test-only; nothing to subtract without losing coverage.
Recommended triage for the author
- Extract the
TestFilesfixture (5th copy) to one shared test struct — ~200 lines removed, no behavior change. - Hoist the duplicated CUDA kernel source into a
const(removes ~40 lines and a drift hazard) and drop the older of the twonvcc-resolution snippets (persistent_worker.rs:1435inline conditional vs:2691list search — keep the list). - Delete the requester-side
ranks.is_some()re-checks inclaims.rs:637/926andlookup.rs:226; they re-verify whatcore.rs:646already guaranteed by writingcodec = None. - Replace
reserve_codec_partitionwithoptions.prefix_cache.compression == KvCompression::Gpuevaluated where it is used, and drop the positionalfalseatmod.rs:334. This also answers the reviewer's "can acpucore reserve a codec partition?" question. - Either delete
state_buffer(speculative, no in-tree caller) or delete its conflict branch atcontract.py:276-279. - Optional polish:
Option<u32>foraligned_codec, one codec-group creation loop instead of fourif codec_index.is_some()blocks, localcodec_sm_count, onefail(...)closure for the three early-error tails.
Nothing in this report argues the change is wrong — only that roughly 150–250 lines of the authored +2,032 (≈60% of which is #[ignore]d test code and duplicated fixtures) can be removed without touching a single assertion or behavior.