Subtraction, Simplicity & Conventions review — PR #674
Key findings
For a +10,106 / −1,158 diff across 42 files, this change is leaner than its size suggests. Most of the volume is load-bearing and I say so explicitly below rather than padding the list. Six genuine simplifications remain, two of them high value:
- HIGH —
RowRestoreLatency(helios/src/server/runtime.rs:270-344) is a second copy ofselene::levels::Rate(selene/src/levels.rs:34-87): samesamples: [f64; 3]ring median, same 10 s recovery constant, same hold-while-in-flight rule. This duplication is the cause of round-2's sole Blocker, so the fix is subtraction (delete the copy), not another patch tostart(). - HIGH —
conditioned_window_ends(helios/src/scheduler.rs:2091-2123) re-implements the greedy window pack insideset_conditioned_inputs(:2162-2183), minus that function's geometry validation, and needssort_unstable/dedupto repair ordering the real loop already guarantees. One consumer (helios/src/scheduler/checkpoints.rs:462, :478). - MEDIUM —
worth_restore(runtime.rs:223-229) duplicatesflare_selene::worth_transfer(selene/src/store.rs:459-468), and this PR deleted the last production caller ofworth_fetching/worth_transfer, leaving them test-only exports. Delete one side. - MEDIUM — the new packed-write buffered fallback (
selene/src/disk.rs:1423-1437) is dead on Windows becauseis_direct_unsupported(:1774-1784) is hard-falseunder#[cfg(not(unix))]. Keep the fallback and delete the stub (matchingUnsupported | InvalidInput), or delete the fallback — not both. - MEDIUM —
write_record_direct's hand-staged aligned-prefix branch (selene/src/disk.rs:1278-1304) re-earnswrite_direct_slices(:1331-1376) to save one memcpy, reached only atspan.offset == 0. Delete it, or record the measurement that justifies it. - LOW (convention) — three parallel spellings of the pool-level order (
selene/src/levels.rs:119-128,helios/src/server/metrics.rs:1418-1423, plus a doc comment). One shared constant removes silent index drift; the author's claimedPOOL_LEVELSis not in the tree at head.
F1 (HIGH) — RowRestoreLatency duplicates selene::levels::Rate; deleting the copy fixes the Blocker
helios/src/server/runtime.rs:270-277:
#[derive(Default)]
struct RowRestoreBucket {
in_flight: usize,
samples: [f64; 3],
count: usize,
next: usize,
last_median: Option<(f64, std::time::Instant)>,
}
helios/src/server/runtime.rs:289-304 (the Blocker's site):
impl RowRestoreLatency {
const RECOVERY_SECONDS: f64 = 10.0;
fn start(&mut self, key: crate::cache::PrefixKey, source: RowRestoreSource) {
...
let bucket = self.buckets.entry(source).or_default();
bucket.in_flight += 1;
if let Some((_, last)) = &mut bucket.last_median {
*last = now;
}
}
The existing abstraction, selene/src/levels.rs:34-45 and :57-82:
const RECOVERY: Duration = Duration::from_secs(10);
/// Bytes per second, using the median of the last three completed transfers.
pub(crate) struct Rate {
seed: f64,
median: f64,
samples: [f64; 3],
count: usize,
next: usize,
last: Option<Instant>,
}
Rate::observe (levels.rs:65-67: values[..self.count].sort_by(f64::total_cmp); self.median = values[self.count / 2];) is byte-for-byte the same 3-sample ring median as RowRestoreLatency::observe (runtime.rs:324-329), and Rate::started (levels.rs:77-82) is the same hold-while-in-flight rule as estimate_seconds returning median when in_flight > 0 (runtime.rs:339-341) — except Rate::started is deliberately conditional (if self.median < self.seed), which is exactly the guard the copy lost at runtime.rs:301-303.
The only genuine differences are (a) decay direction — median * 0.5f64.powf(t/10) at runtime.rs:342 versus median * 2f64.powf(t/10) capped at seed at levels.rs:71-73 — and (b) per-RowRestoreSource bucketing. Both "drift toward the optimistic estimate"; Rate drifts by raising a throughput, RowRestoreLatency by lowering a latency, and they are inverses of each other.
Concrete simplification: keep RowRestoreLatency's in_flight: HashMap<PrefixKey, (RowRestoreSource, Instant)> and its buckets: HashMap<RowRestoreSource, Rate> (or an inverse-latency Rate with a seed, which needs no new accessor), and delete RowRestoreBucket plus observe/estimate_seconds/RECOVERY_SECONDS. If the inverse-latency framing reads poorly at the call site, add one pub(crate) fn decaying(&mut self) / get_decaying() to Rate for the pessimistic-versus-optimistic direction — one accessor in levels.rs instead of a 75-line duplicate type in runtime.rs. Either path removes the code that produced review finding 2 (and the round-2 Blocker), and neither requires patching start().
Caveat, stated plainly: because the decay directions differ, this is "collapse onto one estimator with one direction flag", not a literal drop-in. That is still less code than what is there now, and it makes the started() semantics (the contested behaviour) live in exactly one place.
F2 (HIGH) — conditioned_window_ends is a second copy of the window pack
New function, helios/src/scheduler.rs:2104-2121:
let mut ends = Vec::new();
let mut features = 0usize;
let mut in_window = false;
for input in inputs.iter().filter(|input| input.token_span.end > consumed) {
if !in_window || features + input.feature_range.len() > capacity {
if in_window {
ends.push(input.token_span.start);
}
in_window = true;
features = 0;
}
features += input.feature_range.len();
}
if in_window {
ends.push(prompt_tokens);
}
ends.sort_unstable();
ends.dedup();
The authoritative pack, helios/src/scheduler.rs:2164-2177:
for (index, input) in inputs.iter().enumerate() {
if windows.is_empty() || features + input.feature_range.len() > capacity {
if let Some(previous) = windows.back_mut() {
previous.prefill_end = input.token_span.start;
}
windows.push_back(ConditionedWindow {
inputs: index..index,
token_start: input.token_span.start,
Same boundary predicate (features + input.feature_range.len() > capacity), same boundary value (input.token_span.start), same accumulator. The copy also (i) omits the geometry validation the real loop relies on (scheduler.rs:2143-2158, which guarantees inputs are ordered and non-overlapping — hence the defensive sort_unstable(); dedup() at :2120-2121 repairing an ordering the invariant already provides), and (ii) drops the capacity == 0 / empty-input semantics into an early return at :2100-2103 that the real loop expresses implicitly.
Concrete simplification: extract one fn partition_conditioned(inputs: &[ConditionedInput], capacity: usize, consumed: usize, prompt_tokens: usize) -> Vec<(usize, usize)> returning (token_start, prefill_end) bounds, and have both conditioned_window_ends (map to ends) and set_conditioned_inputs (feed ConditionedWindow construction) call it. The new function has exactly one consumer — estimate_prefill_delta_ns (helios/src/scheduler/checkpoints.rs:462, :478, plus tests at :4402-4404) — which needs only the boundary list, so the shared helper is a single ~15-line function rather than 30 lines plus a parallel invariant.
F3 (MEDIUM) — worth_restore duplicates the shared policy, and the shared policy is now test-only
helios/src/server/runtime.rs:223-229:
/// A host restore is worthwhile when its transfer (plus any accumulated wait)
/// takes less than half the GPU prefill time it replaces.
fn worth_restore(transfer_seconds: f64, prefill_saved_seconds: f64) -> bool {
transfer_seconds.is_finite()
&& prefill_saved_seconds.is_finite()
&& transfer_seconds < 0.5 * prefill_saved_seconds
}
selene/src/store.rs:449-468:
/// A fetch is worthwhile when the transfer takes less than half the prefill it replaces.
pub fn worth_fetching(hit: &HostHit, prefill_tokens_per_second: f64) -> bool {
worth_transfer(
hit.consumed_tokens - hit.resident_tokens,
hit.estimated_seconds,
prefill_tokens_per_second,
)
}
/// The same rule for `gained_tokens` of prefill replaced by a transfer of `estimated_seconds`.
pub fn worth_transfer(
gained_tokens: u64,
estimated_seconds: f64,
prefill_tokens_per_second: f64,
) -> bool {
if !estimated_seconds.is_finite() || !prefill_tokens_per_second.is_finite() {
return false;
}
estimated_seconds < 0.5 * gained_tokens as f64 / prefill_tokens_per_second.max(1.0)
}
worth_transfer computes 0.5 * gained/rate, i.e. the same predicate with prefill_saved_seconds pre-divided. Worse for subtraction: this PR removed every production caller of the selene pair. A tree-wide search finds worth_fetching/worth_transfer used only in tests — selene/src/store.rs:498-504, selene/src/composite.rs:2920 (not opened), :2923, selene/src/disk_store/coalesce/tests.rs:1798 (not opened), :1967, :2142, :2258 — while both remain public exports at selene/src/lib.rs:53 (not opened) (StoreOutcome, StoreReason, StoreStats, worth_fetching, worth_transfer). worth_restore has two call sites (runtime.rs:246, :3354).
Concrete simplification: pick one side and delete the other. Preferred: one pub fn worth_restore(transfer_seconds: f64, prefill_saved_seconds: f64) -> bool in flare_selene (the doc comment above it is already the better contract), re-exported in place of the two-function pair, with the selene rule expressed as worth_restore(estimated_seconds, gained_tokens as f64 / prefill_tokens_per_second.max(1.0)) so selene's own tests keep working. That removes a public API surface that now has no production consumer, which is also a net reduction in the API the PR body lists as changed.
F4 (MEDIUM) — the packed-write buffered fallback is unreachable where it is needed
selene/src/disk.rs:1774-1784:
fn is_direct_unsupported(error: &io::Error) -> bool {
#[cfg(unix)]
{
error.raw_os_error() == Some(libc::EINVAL)
}
#[cfg(not(unix))]
{
let _ = error;
false
}
}
The #[cfg(not(unix))] arm exists only to keep the signature total; it makes every caller's fallback dead on Windows. The caller that matters is write_packed, which is not #[cfg(unix)]-gated (selene/src/disk.rs:1378), so it compiles on Windows and its only non-O_DIRECT path is selene/src/disk.rs:1423-1437:
Err(e) if is_direct_unsupported(&e) => {
let mut file = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(&temporary)
.map_err(|e| io_failure("create packed record file", e))?;
let mut total = 0u64;
for slice in &slices {
On Windows flare_eos::direct_file refuses via ErrorKind::Unsupported (eos/src/windows.rs:104-109), not EINVAL, so the guard never matches there. Compare selene/src/disk.rs:1311 — write_record_buffered really is #[cfg(unix)], and its caller arm at :859-861 sits inside a #[cfg(unix)] Job::WriteRecord (:830), so that pair is consistent and reachable.
Concrete simplification: delete the #[cfg(not(unix))] stub and match on the portable kind — matches!(error.kind(), io::ErrorKind::Unsupported | io::ErrorKind::InvalidInput) || (cfg!(unix) && error.raw_os_error() == Some(libc::EINVAL)) — keeping the fallback that Windows actually needs. The alternative (delete :1423-1437) is only correct if packed writes are declared Unix-only, which the current lack of a #[cfg] does not say. Per AGENTS.md:188-193 ("Do not add … fallback layers … without a concrete requirement"), one of the two must go; keeping both is the one option that is indefensible.
F5 (MEDIUM, conditional on a missing measurement) — hand-staged direct write re-earns write_direct_slices
selene/src/disk.rs:1277-1304:
let src = unsafe { raw_slice(span.address, span.length) };
if aligned(span.address as u64) && !src.is_empty() {
let block = BLOCK_BYTES as usize;
let aligned_prefix = src.len() - (src.len() % block);
let tail = src.len() - aligned_prefix;
debug_assert!(tail > 0 && tail < block);
// Copy only the unaligned tail into owned aligned scratch with
// zero-initialized padding so the direct write never reads past `src`.
self.scratch.as_mut_slice()[..tail].copy_from_slice(&src[aligned_prefix..]);
...
} else {
self.write_direct_slices(file, &[src])?;
}
This branch is reached only from whole_record — selene/src/disk.rs:848-852:
let whole_record = span.offset == 0
&& publish
.as_ref()
.is_some_and(|(_, size)| *size == span.length as u64);
let (file, bytes) = if span.aligned() || whole_record {
i.e. only at span.offset == 0, which is exactly the offset write_direct_slices (:1331-1376) writes from, and that function already stages arbitrary slices through the same self.scratch with zero-padded tails (:1362-1373).
Concrete simplification: replace the whole if aligned(span.address as u64) && !src.is_empty() block with self.write_direct_slices(file, &[src])?, reducing write_record_direct to the span.aligned() fast path plus one delegation. The trade is one extra memcpy of the aligned prefix through scratch; if that copy is measurably hot on the NVMe path this branch is worth keeping — but then the comment should say so with a number, because right now it reads as duplicated padding logic with no stated justification.
F6 (LOW, convention) — three parallel spellings of the pool-level order
selene/src/levels.rs:119-128:
/// Current transfer rates in bytes per second for pool restore levels:
/// `[NeighbourGpu, HostDram, HostNvme, RemoteNvme]`.
pub fn rates(&self) -> [f64; 4] {
[
self.rates[Level::NeighbourGpu.index()].get(),
self.rates[Level::HostDram.index()].get(),
self.rates[Level::HostNvme.index()].get(),
self.rates[Level::RemoteNvme.index()].get(),
]
}
helios/src/server/metrics.rs:1418-1423:
for (level, value) in [
("neighbour_gpu", &self.host_pool_inbound_rates[0]),
("host_dram", &self.host_pool_inbound_rates[1]),
("host_nvme", &self.host_pool_inbound_rates[2]),
("remote_nvme", &self.host_pool_inbound_rates[3]),
] {
The order is asserted by a doc comment on one side and by index literals on the other; nothing type-checks that the two lists agree, and the metric names are the only place the mapping is written down. Concrete simplification: one pub const POOL_LEVELS: [(Level, &'static str); 4] in selene/src/levels.rs, with rates() building from it and metrics.rs iterating POOL_LEVELS to index host_pool_inbound_rates[i]; the label strings then cannot drift from the rate vector. Note: the author's 18:08 comment claims exactly this fix, but POOL_LEVELS appears nowhere in the tree at head, so this is still open.
Deliberately not flagged (the lens was applied and rejected)
plan_mapping_handles'sevaluateclosure + lo/hi doubling + binary refinement (helios/src/runtime_core/cache_memory.rs:663-780) is more lines than the old ramp, but it replaces rank-order-dependent 2× stepping with a symmetric search — the extra code is the fix, not generality around it.PublishError+Reply::invalidatedthreading (selene/src/disk.rs:1657-1715) is the minimum needed to distinguish pre- from post-rename failure; do not collapse it back to an error enum.WindowReleaseSignal/writeback_wake_epoch/writeback_waiters/inflight_waiters(selene-manager/src/store.rs) is event-driven plumbing replacing timer polling. It reads as a lot of state, but each piece is load-bearing for the measuredselene_put_writeback_waits_totaldrop (87 → 6,293 → 11).PoolHandover+persisted_in_pool+refresh_ancestors/refresh_same_page_descendants+clean_slotsinvariants (selene/src/memory.rs:975-1010) encode the retention contract the PR exists to add; not speculative.- Test-only helpers
union_aliases(helios/src/runtime_core/cache_memory.rs:103-114),row_conflicts,verify_physical_invariantsare#[cfg(test)]and fine. Only note:handle_chargeandplan_mapping_handleswere widened topub(super)solely forhelios/src/runtime_core/memory/codec_layout_tests.rs(not opened) — acceptable, but it is visibility added for tests. - No config-switch or env-var violations: no new toggle reads a variable, so the
AGENTS.md:452-455rule is met. - Minor, one line:
TierStore::pending_pool_drain's default body returnsself.stats().memory_records(selene/src/store.rs:400-402), constructing a wholeStoreStatsper poll tick inMemoryStore. It is a default-method convenience, not a defect; worth an override only if the drain loop is hot.
Open questions / what I could not verify
- Whether
0ebee3d4(the author's claimed fix commit) exists and what it contains. At the recorded head19ce4a7b,POOL_LEVELS,HostAdmissionProbe, andflare_selene::worth_restoreare all absent from the tree (worth_fetching/worth_transferstill exported atselene/src/lib.rs:53(not opened);#[allow(clippy::too_many_arguments)]presumably still onadmit_with_host_store), andis_direct_unsupportedis still hard-falseoff-Unix. So F3, F4 and F6 are claimed fixed, not landed; if the next head contains them, F3/F6 shrink to "confirm the shape" and only F1, F2, F5 stand. - Whether the F5 aligned-prefix copy is measured. I found no comment or benchmark tying that branch to a number. A one-line measurement note would settle it; absent one, I would delete the branch.
- Whether packed writes are intended to work on Windows at all. F4's remedy forks on this: either the fallback is required (fix the predicate) or packed writes are Unix-only (add
#[cfg(unix)]towrite_packedand delete the fallback). The code currently says neither. - Merge-order effects on F2.
helios/src/scheduler/checkpoints.rsis also edited by open #655 (same author, Ready To Merge) and was just rewritten by #660 in main (4cc6f2fd); theconditioned_window_endsextraction should be coordinated with those before it is refactored, or the extraction will be re-conflicted.