Subtraction & Simplicity audit — PR #705 (eec5e95, 6 files, +820/−71)
Verdict: the selene side (composite.rs) is mostly lean and additive in the right places — has_spillable_slots's early exit, writing_spills, the Option<Instant> test seam and the default-true trait method are all cheaper than what they replaced. The helios side is where the cost is: service_store grew from ~30 lines of loop to ~165 lines of bookkeeping that carries four dedup collections and a two-field flag pair, and it contains one duplicated block transcribed verbatim. CompositeStore::can_retry_slabs is 53 lines of which three fragments are copied out of store()'s preamble. I also found one genuinely dead branch and one unreachable branch.
Everything below is behavioural-equivalent unless stated.
1. helios/src/server/runtime.rs:2791-2795 — two fields encode 3 states across 4 combinations, one of them contradictory
struct PendingStore {
publication: flare_selene::PublishedCheckpoint,
prior_retry: Option<flare_selene::StoreReason>,
fresh: bool,
}
fresh exists only to suppress the slab gate at :2880-2883 (if !fresh && prior_retry == Some(StoreReason::Slabs) && …). But fresh: true with prior_retry: Some(_) is a live, legal state (:2823-2826 sets prior_retry on an entry that already has fresh = true), so the reader has to hold "fresh means also came through take_publications() this pass, it does not mean prior_retry is None" in their head. ( =None, fresh=false) (deferred copyout, :2864-2868) and ( =None, fresh=true) both exist too.
Collapse to one field:
enum Prior { Fresh, Copyout, Retried(StoreReason) }
and the gate becomes if matches!(prior, Prior::Retried(StoreReason::Slabs)) && !store.can_retry_slabs(&publication), the progress test at :2933 becomes prior != Prior::Retried(reason), and the retry-success credit at :2947 becomes matches!(prior, Prior::Retried(_)). Four states become three, and the one that cannot happen becomes unrepresentable.
2. helios/src/server/runtime.rs:2803-2819 and :2857-2873 — the same insert-or-set-flag block written twice, plus three collections doing one job
The publication loop and the copyout loop are the same shape:
match publication_index.entry(publication.id) {
std::collections::hash_map::Entry::Vacant(entry) => { entry.insert(publications.len()); publications.push(PendingStore { … }); }
std::collections::hash_map::Entry::Occupied(entry) => { let pending = &mut publications[*entry.get()]; pending.publication = publication; pending.fresh = true; }
}
vs.
if !publication_index.contains_key(&id) && !seen_waiting.contains(&id)
&& let Some(publication) = self.scheduler.publication(id) {
if retry_copyouts { publication_index.insert(id, publications.len()); publications.push(…); }
else if seen_copyouts.insert(id) { self.deferred_copyouts.push(id); }
}
Four collections (publication_index, seen_waiting, seen_copyouts, prev_deferred_copyouts) are used to answer one question — "has this CheckpointId already been claimed this pass?". Since publications is local to the function, the index is used only as "has been pushed", so a small local type collapses all of it:
struct Pending { list: Vec<PendingStore>, at: HashMap<CheckpointId, usize> }
impl Pending {
fn claim(&mut self, publication, prior) -> bool { /* insert if absent, else overwrite */ }
}
seen_copyouts then disappears entirely (the copyout list is rebuilt from scratch anyway — the prev_deferred_copyouts snapshot is the only thing that has to survive), and seen_waiting only needs to exist because waiting is a plain Vec. This is ~50 lines of index/set maintenance reducible to a helper of ~10 plus three call sites, and it removes the chance of the two seen_* sets drifting out of sync with the index.
3. helios/src/server/runtime.rs:2801-2802, 2805, 2813, 2821, 2854, 2856 — fully-qualified paths shadowing an existing import
runtime.rs:8 already has use std::collections::{HashMap, VecDeque};, yet the new code writes std::collections::HashMap::<crate::cache::CheckpointId, usize>::new(), std::collections::HashMap::new(), std::collections::hash_map::Entry::Vacant, std::collections::HashSet::new() (×3), std::collections::HashSet<crate::cache::CheckpointId>. Nine fully-qualified paths for two types; use std::collections::{HashMap, HashSet, VecDeque, hash_map::Entry}; at the top deletes all of them and matches request.rs:92's existing style.
4. helios/src/server/runtime.rs:2941-2943 — the wildcard re-introduces the bug the PR fixes
_ => {
progress = true;
}
The whole point of the change is "progress only on genuine state transitions". A wildcard arm that means "anything I haven't enumerated counts as progress" is exactly the assumption #694 breaks: it adds StoreOutcome::Unprofitable to this same match, and that outcome by construction made no progress — the wildcard will report worker progress for it and the storm returns for that variant. Enumerate the variants that really are progress (Oversize | Present), which is one word longer and can't silently rot.
5. selene/src/composite.rs:903-905 — dead branch
if let Some(started) = self.spill(key) {
…
} else if self.backoff_active() {
break;
}
The enclosing loop is guarded by :892 if writing < MAX_SPILLS && !self.backoff_active() {, and nothing inside the loop can arm the backoff: retry_after is written in exactly two places, disk_stored (:668) and poll (:1658), neither reachable from spill() → thin_rows / reserve_capture / start_write. So self.spill(key) returning None because of backoff is impossible here, and the else if can never fire. Delete it (three lines), or if it is meant as future-proofing, say which future writes retry_after — otherwise it reads as a guard against a state the function does not have.
6. selene/src/composite.rs:1405-1457 — can_retry_slabs copies three fragments of store()'s preamble
can_retry_slabs |
duplicate of |
|---|---|
:1406-1408 if checkpoint.tail_pages > checkpoint.chain_pages.len() { return true; } |
:1263-1270 in store() (which returns Err) |
:1416-1422 let covered = !self.disk.is_failed(&key) && self.disk.covered_endpoint(checkpoint, |n| { n.ready || self.resident(&n.key, n.tail_pages, true) }); |
:1272-1275 — character-for-character |
:1423-1431 let (_, tail) = self.disk.plan_record(checkpoint); let needed = self.memory.layout().record_slots(tail.len(), true); … let short = self.memory.shortfall(needed); if short == 0 { return true; } |
:1328-1333 |
checkpoint.tail_pages > checkpoint.chain_pages.len() is the one that matters: in store() it is a corrupt publication (Err(invalid(…"claims {} tail pages of a {}-page chain"))), here it is "go ahead and retry". If the invariant ever fires, can_retry_slabs returns true, the worker calls store(), gets Err, and bumps host_retry_abandoned[5] — i.e. the gate silently converts an integrity error into a retry loop, which is the storm pattern in miniature.
Simplification: extract the covered/slots/shortfall computation both callers need into one helper, e.g.
/// The memory slots this publication's record would need, and how many it is short.
fn slab_need(&self, checkpoint: &PublishedCheckpoint) -> Option<(Option<PrefixKey>, usize, usize)>;
store() becomes let (parent, needed, short) = self.slab_need(cp)…, can_retry_slabs reuses it, and one of the two copies of the covered_endpoint closure goes away. That is ~15 lines out and one class of divergence gone.
Also within can_retry_slabs: seven of its eight early returns are true, so the function reads as a 53-line "when may we skip" with the answer buried in the last line. Written as a predicate on the skip condition it is one expression:
fn can_retry_slabs(&self, cp: &PublishedCheckpoint) -> bool {
let Some((_, needed, short)) = self.slab_need(cp) else { return true };
let (writing, covered) = self.writing_spills();
!(writing < MAX_SPILLS && covered < short && !self.backoff_active() && !self.thinnable(short) && self.has_spillable_slots(short))
}
with thinnable the row block at :1432-1451 lifted out (it is self-contained and worth naming — short.div_ceil(row_slots) vs thinnable_rows is the least obvious predicate in the file).
7. selene/src/composite.rs:1378 — a full scan through the invariant checker to read one number
if self.writing_spills().0 < MAX_SPILLS {
writing_spills() (:752-771) iterates every jobs entry, and then runs debug_assert_eq! which iterates every parked entry again — in debug builds, on the hot rejection path, to answer "are 8 writes in flight?". writing_spills returns (usize, usize) but .0 alone is wanted at this call site (and at :888 the sum is only meaningful together with the parked-record check). Split it: fn writing_count(&self) -> usize (or drop it entirely at :1378 in favour of the cheap, always-correct self.outbound.values().filter(|o| o.write.is_some()).count()), and keep the (writing, covered) pair only where the covered sum is used (spill_parked, can_retry_slabs).
8. selene/src/composite.rs:656-720 + :1610-1613 — disk_stored returns a bool to bump a metric it already has &mut self for
if self.disk_stored(id, result, header) {
self.stats.progress += 1;
}
disk_stored takes &mut self, already writes self.stats.held[0] += 1 (:667), self.stats.stored += 1, self.stats.store_failed += 1 — and then hands back a bool so the caller can bump self.stats.progress in a different iteration of the same match. Two of its three return points (:658, :663) return values that only ever feed this if. Folding it in (self.stats.progress += 1; on the same lines, fn disk_stored(…) returning ()) removes a cross-function invari ant ("caller must not forget to bump progress"), and lets :660-663 — self.parked.remove(&key); return true; — read as the plain cleanup it is rather than as a signal.
9. selene/src/composite.rs:775-777 — unreachable guard
fn has_spillable_slots(&self, need: usize) -> bool {
if need == 0 {
return true;
}
Both production callers pass a value already proven > 0: :1334 if short > 0 && !self.has_spillable_slots(short) and :1452 (after :1429 if short == 0 { return true; }). Only the new test calls it unguarded (:6401). One line of defence against a caller that does not exist; either drop it or drop the short > 0 at :1334 and let this function be the single owner of the 0 case.
10. selene/src/composite.rs:2733-2736 — the relaxed assertion is a symptom worth subtracting rather than adding
if !store.parked[&child.key].writing {
store.spill(child.key).unwrap();
}
assert!(store.parked[&child.key].writing);
Before the PR this was store.spill(child.key).unwrap(); — the test relies on spill() returning Some for that key. The new guard at :819-821 if parked.writing { return None; } turns that into a silent no-op, so the test was wrapped to keep passing. But every other spill() call site already pre-checks the same condition (:1293 self.parked.get(&key).is_some_and(|p| !p.writing), :1339, :1824 filter(|p| !p.writing)) and waiting_spills filters !parked.writing at :874. So the guard duplicates four existing checks and its only observable effect in the tree is to make one existing caller's contract weaker. Either keep the guard and delete the four redundant pre-checks (net subtraction at the call sites), or drop the guard and keep spill() total — but not both, because today the code has two sources of truth for "may I start this write", which is exactly the kind of thing the new debug_assert! at :757-769 will start tripping on.
11. selene/src/composite.rs:1656-1671 — the wake edge is implemented by mutating a public counter twice, then re-reading it
let retry = self.retry_after.is_some_and(|at| self.retry_now() >= at);
if retry { self.retry_after = None; self.stats.progress += 1; }
let progress = self.stats().progress;
if !self.disk.preserve_committed && self.maintenance_progress != progress {
progress is read after the bump, so the maintenance branch fires because the metric moved, and the || retry disjunct that used to express this directly was deleted. The logic survives only because stats() is called one line below the increment. retry is right there and already computed:
if !self.disk.preserve_committed
&& (self.maintenance_progress != self.stats.progress_before_the_bump || retry)
i.e. keep the disjunct and the metric bump independent — one of them is a wake signal, the other is a number operators read (held_total{tier="dram"}, store_reasons_total), and coupling them means a future change to metric semantics silently changes when spill_parked()/disk.maintain() run. This is the one place I would not call the current shape merely verbose; it is fragile in a way a single extra || avoids.
Confirmed lean (no action)
selene/src/store.rs:324-330— default-truetrait method with a doc comment stating the exact contract ("Returnsfalseonly whenstore(checkpoint)would returnRetry(StoreReason::Slabs)again"). Out-of-tree implementors compile unchanged; nothing speculative.selene/src/pool/local.rs:45-49,selene/src/pool/store.rs:615-617— pure forwarding, four lines each, no logic to subtract.selene/src/composite.rs:221-240—retry_nowis#[inline]with the#[cfg(test)]override compiled out of release, andpoll_atis#[cfg(test)]. This is the cheap version of the seam; nothing to remove.has_spillable_slotsreplacing thesum()-everythingspillable_slots()is a real reduction (whole-map fold → early-exit scan) and the only remaining caller of the old shape is gone.- Tests: the 5 new selene tests hang off existing helpers (
parked_root,checkpoint,poll_until,composite_with_intake) rather than new fixtures; the 4 helios tests reuseFakeStorewith one added field (retry_slabs_ready,phase_tests.rs:2088, 2222-2226). No new test scaffolding to subtract.
One process note (not subtraction)
docs/prefix-cache-offload.md:293-297 still documents the pre-PR worker contract — "Retry accepts no copy. The worker retains only checkpoint IDs for retries after store progress" — while service_store now keeps IDs and a per-ID reason and a can_retry_slabs gate. Not changed by this PR, but it is the artifact a reader will use to decide whether the new bookkeeping is justified, so it argues for finding 1 and 2 to land as a smaller diff with the doc updated in the same place.