Subtraction & Simplicity audit — PR #713 (head 4efd9fd)
Scope note: the tooling pr_diff for helios/src/runtime_core/memory.rs and flare-cli/src/main.rs includes unrelated merged work (e.g. row_backing_bytes, largest_count, registration_context), so I audited only the 11 files listed in pr_files and, inside them, only the hunks that belong to this PR's three stated changes. Verdict up front: the change is not lean. The I/O copy path itself is tight, but there are five concrete duplications the PR either creates or knowingly extends, and two of them have correctness consequences beyond style.
High signal — duplication with a behavioural cost
1. A second, divergent /proc/meminfo parser, reading the same file twice on the same path
helios/src/runtime_core/memory.rs:50–76 adds a strict parser:
let kib = fields.next()?.parse::<u64>().ok()?;if fields.next()? != "kB" || fields.next().is_some() { return None; }
But the tree already parses MemAvailable: in selene/src/offload.rs:959–971 (available_memory, looser: accepts any trailing junk after kB), MemTotal: at selene/src/offload.rs:983–993, and a third in ignition/planning.py:128–131 (not opened). The PR leaves shared_available delegating to the old parser —
memory.rs:31–33 pub(super) fn shared_available(meminfo: &str, total: usize) -> Result<usize> { Ok(flare_selene::offload::available_memory(meminfo, total)?) }
— and then reads /proc/meminfo again, with the new parser, inside the same planning call:
memory.rs:343–345(memory_snapshot):let info = std::fs::read_to_string("/proc/meminfo")…; shared_available(&info, usize::MAX)?memory.rs:1257–1259(LinuxMemInfo::read()→append_integrated_meminfo)
So one plan invocation reads /proc/meminfo twice and parses MemAvailable with two parsers that disagree on malformed input. The Plan cache line can therefore print a MemAvailable that differs from the number the plan was actually sized from — on the exact diagnostic path #630 asked for. Fix: extend flare_selene::offload with one meminfo_value(name)/LinuxMemInfo type (it owns the other two parsers) and delete LinuxMemInfo::parse (−27 lines), or at minimum have append_integrated_meminfo consume the already-read MemorySnapshot instead of re-reading the file.
2. verify_file is hash_file with one extra line, and the PR edited both
helios/src/core/cache.rs:4428–4447 and helios/src/core/cache.rs:4498–4514 are the same function:
verify_file: open,DigestContext::new(&SHA256),vec![0; 1 << 20], loop withInterruptedretry,crate::os::release_page_cache(&file); read?;thenif PayloadId::from_digest(context.finish()) != declared { … }hash_file: identical, minus the comparison.
verify_file(path, declared) collapses to if hash_file(path)? != declared { Err(...) } else { Ok(()) } — about 14 lines removed, and the release call (which the PR adds at both :4441 and :4511) exists in one place instead of two, so a future change cannot update one and miss the other.
3. enrich_integrated_ctx_oom has two arguments that encode one fact, and the OOM test is written twice
memory.rs:118–128:
pub(super) fn enrich_integrated_ctx_oom(mut error: crate::Error, integrated: bool, meminfo: Option<LinuxMemInfo>) -> crate::Errorif !integrated { return error; } let Some(info) = meminfo else { return error; };if let … && cuda.code == super::driver::CUDA_ERROR_OUT_OF_MEMORY
integrated == true && meminfo.is_some() is the only meaningful state; the (bool, Option<T>) pair is exactly the invalid-state-you-can-represent shape. It also forces the caller to compute integrated != 0 twice, helios/src/runtime_core/mod.rs:379–385:
memory::enrich_integrated_ctx_oom(error, integrated != 0,(integrated != 0 && status == driver::CUDA_ERROR_OUT_OF_MEMORY).then(memory::LinuxMemInfo::read).flatten(),
and the "is this an OOM" decision then lives in two places: the .then(… status == CUDA_ERROR_OUT_OF_MEMORY) in mod.rs:382 and the re-check at memory.rs:130. Collapse to one Option<LinuxMemInfo> parameter (caller passes None unless integrated-and-OOM) and drop the integrated parameter and one of the two OOM tests.
High signal — pure subtraction
4. AlignedBuffer is now the third copy of the same unsafe allocator wrapper
flare-cli/src/distribution.rs:1226–1253 (new, +28 lines) is byte-for-byte the shape of selene/src/disk.rs:2253–2294:
distribution.rs |
selene/src/disk.rs |
|---|---|
struct AlignedBuffer { address: usize, bytes: usize } |
struct AlignedBuffer { address: usize, length: usize } |
flare_helios::allocate_aligned(bytes)? + unsafe { std::ptr::write_bytes(address as *mut u8, 0, bytes) } |
flare_eos::allocate_aligned(length) + identical write_bytes |
impl Drop { unsafe { flare_helios::free_aligned(self.address, self.bytes) } } |
impl Drop { unsafe { flare_eos::free_aligned(self.address, self.length) } } |
helios/src/engram/reader.rs:90 (not opened)/:414 is a third raw alloc/free pair on the same two functions. flare_eos exports allocate_aligned/free_aligned (eos/src/lib.rs:48–64) but no owning type, so every caller re-derives the Drop invariant. Adding pub struct AlignedBuffer to flare_eos (where the allocator lives) deletes 28 lines here and ~40 in selene/src/disk.rs, and removes two hand-written // SAFETY:-correct blocks from review surface.
5. The --memory-limit precedence rule is argv string-matching, three times over
flare-cli/src/orbit/controller.rs:1967–1997:
fn has_memory_limit(args: &[String]) -> bool { args.iter().any(|arg| arg == "--memory-limit" || arg.starts_with("--memory-limit=")) }let skip_config_limit = memory_limit_from_config && has_memory_limit(saved);if arg == "--memory-limit" { skip_next = true; continue; } if arg.starts_with("--memory-limit=") { continue; }
The same arg == "--flag" / starts_with("--flag=") + skip_next pair-strip loop already exists twice in this crate: controller.rs:2004–2022 (deduplicate_tensor_parallel) and flare-cli/src/orbit/agent.rs:2232–2251 (grant argv strip for --tensor-parallel). This PR adds a third hand-rolled copy, and the copy is already fragile: a trailing --memory-limit with no value sets skip_next that is never consumed, and the predicate is duplicated between has_memory_limit (:1968–1969) and the strip body (:1986, :1990).
The structural version deletes the whole mechanism: RunOptions already distinguishes the two cases, so carry the config reserve as a value instead of as argv — pub memory_limit_from_config: bool (controller.rs:167–169) becomes config_memory_limit: Option<MemoryLimit>, the config layer stops injecting --memory-limit into options.serving at all (flare-cli/src/main.rs:538–540, flare-cli/src/cli.rs:672–682), and merge_serving_options shrinks to "use saved, else CLI, else config" with no string matching. That removes has_memory_limit, skip_config_limit, skip_next, the memory_limit_from_config bool field, the bool parameter at controller.rs:1975, and the duplicated predicate — roughly 20 lines and one new cross-module contract (the undocumented precedence rule) in exchange for one enum field.
6. The from_config predicate the test asserts is copied, not called
flare-cli/src/main.rs:538–540:
memory_limit_from_config: run.serving.memory_limit.is_some() && run_matches.value_source("memory_limit") != Some(clap::parser::ValueSource::CommandLine),
flare-cli/src/config.rs:917–918 (new test) re-implements it verbatim:
let from_config = run.serving.memory_limit.is_some() && run_matches.value_source("memory_limit") != Some(ValueSource::CommandLine);
Because the test reconstructs the expression instead of calling production code, it cannot fail if main.rs:538 changes — it only tests itself. Extract one fn memory_limit_from_config(run: &OrbitRun, matches: &ArgMatches) -> bool and call it from both (net −2 lines, but it makes ~30 lines of test assertions meaningful).
7. Duplicated release loop and a redundant empty guard
flare-cli/src/distribution.rs:1261–1263 and :1330–1332 are the same three lines:
for &(offset, size) in ranges { flare_helios::release_page_cache_range(file, offset, size); }
The direct path already has this loop; the buffered path needs it too. Since the buffered fallback inside copy_ranges_direct (:1309) routes through copy_ranges_buffered (which releases), the only reason for the outer copy at :1330–1332 is the success path of the direct copy. Hoisting the loop into copy_source_ranges after the branch (release always, then return the result) removes one copy and makes "every served range is released" true by construction in one place rather than two. Relatedly, :1324 if ranges.is_empty() || ranges.iter().all(|&(_, size)| size == 0) { return Ok(0); } overlaps release_page_cache_range's own if len == 0 { return; } (eos/src/unix.rs:75); the guard is only there to skip a 4 MiB allocation for an all-zero request — worth one comment, or drop the is_empty() half.
8. Two unexplained thresholds for one condition
helios/src/runtime_core/memory.rs:36–38:
pub(super) const PAGE_CACHE_WARN_THRESHOLD: u64 = 10 << 30;pub(super) const CTX_OOM_DROP_CACHES_THRESHOLD: u64 = 4 << 30;
Both answer "is reclaimable page cache large enough to be the cause?", 2 GiB into the same reclaimable gap, differing only in where they are checked. #630 asked for one number (">10 GiB divergence"). Either collapse to one constant or state why context creation is more sensitive than KV sizing — as written, a reviewer cannot tell whether 4 << 30 is measured or guessed, and the PR's own disclosure says it is unmeasured on target hardware.
9. The memory-line prints the same triple twice in one startup
memory.rs:105 appends meminfo.summary() to the summary that already became the Plan cache line, and :108–111 embeds {} = meminfo.summary() again inside the warning that is printed immediately after at memory.rs:1264–1267. On a polluted GB10 controller, one startup prints MemFree 1.00 GiB / MemAvailable 11.20 GiB / Cached 10.60 GiB twice. Drop the parenthetical from the warning string.
10. append_integrated_meminfo mixes a mutation with a returned warning
memory.rs:100–115 takes &mut String, appends, and returns Option<String> for the caller to eprintln!. That is why the call site needs the let meminfo_warning = …; finish(summary); if let Some(w) = … contortion at memory.rs:1256–1268. Returning Option<String> (the full line, or (line, Option<warning>)) makes the call site four straight lines and keeps formatting in one place.
Low signal
flare-cli/src/config.rs:77–80and:154–157are the same three-linememory.reserveinheritance block. Two occurrences do not yet justify a helper, but they must not be allowed to drift (one isCommand::Run, one isOrbitCommand::Run) — afn inherit_memory_limit(&mut ServingOptions, reserve: &Option<String>) -> Result<()>would cover both and theorbit pushpath if that ever needs it.helios/src/lib.rs:38–41widens helios's public surface with four passthrough re-exports (FileReadAt, allocate_aligned, direct_reopen, free_aligned) purely soflare-clineed not depend onflare-eos(flare-cli/Cargo.toml:22–37has noflare-eos). A direct dependency would delete the re-export and theflare_helios::indirection atdistribution.rs:1234, 1251, 1262, 1268, 1328; a judgement call, not a defect.helios/src/core/cache.rs:4773–4775:if let Ok(input) = File::open(source) { crate::os::release_page_cache(&input); }swallows the open error only tofadvisea path it does not otherwise use. Arelease_page_cache_path(&Path)ineos(used by this and any future path-only site) removes the best-effort open.
What is already lean — do not "simplify" these
copy_ranges_direct(distribution.rs:1268–1317): 50 lines for aligned chunking with unaligned head/tail,EINTRretry, short-read trimming and mid-streamEINVALfallback. There is no flag, no mode, no second entry point; theif let Ok(direct) = flare_helios::direct_reopen(file)at:1328is a clean capability test with no configuration knob. This is the correct shape and should stay.- The release-on-error property at
:1329–1333(no?oncopy_ranges_direct, result returned after the release loop) is deliberate and should be preserved if the loop is hoisted per item 7. - No new CLI flag, no new config key, no new crate dependency.
driver.rs:95(not opened) (CUDA_ERROR_OUT_OF_MEMORY = 2) is a one-line constant and belongs next to its siblings. LinuxMemInfoand the enrichment are correctly#[cfg(any(target_os = "linux", test))]/#[cfg(target_os = "linux")], so no dead Windows/macOS arms and noallow(dead_code)on the new code.main.rsrestructuring (bindingrun_matchesonce,:521) is a net simplification, not a regression.
Test volume vs. change
Of the +779 lines, roughly 300 are tests. The memory.rs parser tests (:2266–2409) are thorough and mostly worth keeping, but flare-cli/src/config.rs:896–992 is 97 lines of assertions for a 6-line production change, three of whose assertions test a predicate the test itself re-declares (item 6). If item 5's structural change lands, most of controller.rs:3793–3839's four merge_serving_options cases collapse to two (saved wins / CLI wins) because the flag-parsing edge cases no longer exist.