Code correctness report · NVIDIA/hyperflare-inference #713

Raw Markdown for agents: https://autobot.eidonix.com/p/8e5966a5-177e-4af9-a0d4-48b700226bba.md

Deep Code Correctness / Invariants / Hot-Path Audit — PR #713 @ 4efd9fd

Scope note (affects how the PR was partitioned): the supplied file list and pr_files report 11 files, but the actual diff also modifies helios/src/runtime_core/cache_memory.rs (+~180 lines: Layout.sentinel_granules, fixed_segments, pack_prefixes, plan_mapping_handles rewrite, new alias_plane third predicate). That makes this a >900-line, multi-crate PR, so it was partitioned into 3 concurrent slices (flare-cli distribution/config/orbit; helios runtime_core memory+planning; helios core/cache.rs+eos), each run through the full 4-part protocol, then synthesized and independently re-verified below.

Bottom line: the O_DIRECT peer-serving rewrite, the page-cache release sites, the /proc/meminfo diagnostics, enrich_integrated_ctx_oom, and the row_backing_bytes sentinel arithmetic are all correct under adversarial tracing (proofs below). There is one Major state-persistence defect in the new [memory] reserve propagation, plus three Minor performance/estimator issues. No Blocker.


MAJOR-1 — [memory] reserve is baked into the persisted --persistent group on first launch, so later config edits are silently ignored forever

Diff sites: flare-cli/src/orbit/controller.rs:692-696 (merge), :875-878 (persist), flare-cli/src/orbit/controller.rs:1967-1987 (merge_serving_options), flare-cli/src/orbit/store.rs:231-233 (GroupSpec.serving), flare-cli/src/config.rs:152-158.

memory_limit_from_config only protects an already-saved value; it does nothing to stop the config-derived value from being written into the saved spec when the group had no saved limit:

fn merge_serving_options(
    saved: &[String],
    current: &[String],
    memory_limit_from_config: bool,
) -> Vec<String> {
    let mut serving = saved.to_vec();
    let skip_config_limit = memory_limit_from_config && has_memory_limit(saved);
    ...
        if skip_config_limit {          // <-- only true when `saved` ALREADY has a limit

and the merged list (which now contains the config-inherited --memory-limit=-12GiB emitted by ServingOptions::rank_options, flare-cli/src/cli.rs:1150-1152) is then written verbatim into the durable orbit file:

let saved = GroupSpec {
    name: name.clone(),
    core,
    serving: serving.clone(),   // controller.rs:878 — config-derived limit included

GroupSpec is serialized to ~/.config/flare/orbit.toml (not opened) via Orbit::save_group/save (store.rs:299-324) and re-read on every later attach/restart/controller relaunch.

Decision table (all four rows verified from the code):

memory_limit_from_config saved has --memory-limit outcome
true yes saved wins (intended)
true no config value appended → persisted into the spec ← defect
false (explicit CLI) any both appended; OrbitRun has #[command(args_override_self = true)] (cli.rs:571-573), so clap keeps the last → explicit wins ✔
n/a n/a main.rs:531-537 sets the flag as is_some() && value_source != CommandLine, which is exactly "came from config" ✔

Concrete counterexample: orbit.toml (not opened) has memory = { reserve = "12 GiB" }. Operator runs flare orbit run --name g --persistent model/. The spec persists serving = ["--memory-limit=-12GiB", ...]. The host is later resized (or the reserve is corrected) to reserve = "7 GiB". On the next flare orbit run --name g (or after a controller reboot, which relaunches from the spec), saved now does contain --memory-limit, so skip_config_limit == true and the new group is launched with the stale 12 GiB — a config value the operator has already changed, with no warning, and the only escape is hand-editing orbit.toml (not opened) or passing an explicit --memory-limit. This is exactly the bug class the PR set out to fix ("without clobbering saved persistent-group overrides"), just inverted: config now clobbers nothing but poisons the saved state.

Fix: do not persist config-derived limits. Either (a) keep it out of serving entirely and store it as a separate GroupSpec field mirroring how transfer_streams/roce_ring are stored, e.g. pub memory_limit_from_config: Option<String> set in controller.rs:875 and re-applied at launch, or (b) strip it before save_group (serving.retain(..) on the config-derived entry when options.memory_limit_from_config), and (c) add a regression test that persists, changes [memory] reserve, and reloads — the new tests (controller.rs:3793-3837, config.rs:895-990) never round-trip through save_group/Orbit::load, which is why this is unobserved.


MINOR-1 — alias_plane's new largest_count clause makes plane eligibility non-monotone: adding a plane can disqualify already-eligible planes and shrink the snapshot alias budget

Diff sites: helios/src/runtime_core/cache_memory.rs:73-91 (and its duplicate consumer helios/src/runtime_core/memory.rs:654-680).

    unit == largest
        || alignment.div_ceil(unit) <= row.div_ceil(page)
        || (largest == unit.saturating_mul(2)
            && row.div_ceil(largest_count.saturating_mul(alignment).max(1)) >= 2)

Only the third clause references largest_count, and it is anti-monotone in the number of densest planes: raising largest_count raises the divisor, shrinking row.div_ceil(largest_count * alignment) and turning the clause off for planes that previously qualified — i.e. adding a mixed-width plane can remove alias borrowing from unrelated planes.

Concrete counterexample: row = 4 MiB, alignment = 2 MiB, page = 4 MiB, one plane unit = 1 MiB with a densest plane largest = 2 MiB, largest_count = 1: clause 2 fails (div_ceil(1 MiB) = 2 > div_ceil(4 MiB) = 1) but clause 3 holds (row.div_ceil(1*2 MiB) = 2 >= 2). Now add a second densest plane (largest_count = 2): clause 3 becomes 4 MiB / 4 MiB = 1 >= 2 → false, so the 1 MiB plane loses eligibility and capacities() (memory.rs:654-680) computes a smaller cached/rows snapshot budget for the same total memory.

Why only Minor: eligibility is recomputed with the same eligible_planes(geometry, row_alignment) call inside Layout::grouped (cache_memory.rs:297), and the same rounding is used on both sides, so an accepted capacity is always buildable in Layout — this can never accept a plan that fails to allocate. The loss is a smaller alias budget, not corruption.

Fix: make the dense-plane test width-relative and monotone, e.g. alignment.div_ceil(unit) * largest_count.max(1) <= row.div_ceil(page), keeping the third clause additive rather than as a replacement.


MINOR-2 — hash_file evicts the page cache of a file that is immediately re-read in full by the same import path

Diff site: helios/src/core/cache.rs:4502-4513 + caller helios/src/core/cache.rs:1900-1906.

    let read = loop { ... };
    crate::os::release_page_cache(&file);
    read?;
    Ok(PayloadId::from_digest(context.finish()))
    let digest = hash_file(&path)?;
    let file = File::open(&path).map_err(failure)?;
    let object = self.insert_legacy_container(digest, file)?;

hash_file's only caller (import_legacy_into) opens the identical inode on the next line and streams it again through write_stream, so the eviction converts a warm second pass into a guaranteed cold re-read.

Counterexample: flare cache import of a 70 GB legacy core set — ~70 GB of extra storage reads (import read volume roughly doubles on NVMe).

Fix: give hash_file a release: bool (or hoist the eviction to after insert_legacy_container returns) and pass false at cache.rs:1904.

MINOR-3 — plan accounting double-counts the sentinel rounding tail (pessimistic only)

Diff sites: helios/src/runtime_core/memory.rs:1361 and :589; callee cache_memory.rs:133-141/:291-304.

The row side now correctly becomes alignment + tail (fixed_segments), but the KV side keeps bytes(core,1,pages) = Σ round_up(pages*unit, align) while the bytes actually created per plane are (page_capacity*unit).div_ceil(a)*a, i.e. one granule less when the extent is already aligned. pages*unit = 4 MiB with a = 2 MiB → estimate 4 MiB, real 2 MiB. Effect: one skipped KV page and a slightly inflated "Allocate cache" total; never an over-accept. Fix: mirror remaining_prefix for the page side in both places.


Verified correct (with the counterexamples that were actually run through)

O_DIRECT peer serving — flare-cli/src/distribution.rs:1267-1336. read_len = (skip + take).next_multiple_of(4096) is provably <= chunk_bytes for every input (skip < 4096, take <= chunk_bytes - skip, chunk_bytes a 4096 multiple) → no OOB into AlignedBuffer, no position - skip underflow. count <= skip reproduces RangeReader's exact "file ended inside a requested range" error (core_cache.rs:599-601), so EOF-inside-range is byte-identical across both paths. The mid-stream EINVAL fallback reconstructs rest = [(position, remaining)] ++ ranges[index+1..] — resumption is byte-exact at every failure index (0/1/2/3), no duplication or loss, and total + copied is the true count. direct_reopen resolves /proc/self/fd/N (same inode, works for unlinked files) so there is no TOCTOU against the verified fd. Empty/zero-length ranges short-circuit to Ok(0). Note serve_source:1216 discards the return value, and the receiver enforces exactly range_bytes bytes, so a short copy surfaces as UnexpectedEof rather than silent corruption. Double release_page_cache_range on the fallback path (copy_ranges_buffered then copy_source_ranges:1330) is idempotent posix_fadvise on the same inode — harmless.

Windows build of the new re-exports — helios/src/lib.rs:38-41. All re-exported symbols exist on Windows (direct_reopen eos/src/windows.rs:126, release_page_cache* windows.rs:150-151 no-op stubs; FileReadAt/allocate_aligned/free_aligned are unconditional in eos/src/lib.rs:24-64), and every #[cfg(unix)] gate in distribution.rs is complete. No compile break.

copy_file durability — helios/src/core/cache.rs:4767-4777. The "lost directory fsync" hypothesis is false: the removed callee container::sync_file (container.rs:1176-1185) is, on non-Windows, exactly File::open(path)?.sync_all(); directory durability is still provided by synchronize→syncdir (cache.rs:4813, 4836-4842), and make_immutable still runs after it. No mmap of container files exists anywhere (only helios/src/engram/reader.rs memfds and an anonymous mapping), so POSIX_FADV_DONTNEED cannot unmap live pages.

verify_file/hash_file restructure — helios/src/core/cache.rs:4432-4446, 4502-4513. The let read = loop { break Ok/Err } form has no early return, so release_page_cache always runs; read? still precedes context.finish(), so a mid-read error still suppresses the digest comparison and propagates the identical failure(error).

row_backing_bytes — helios/src/runtime_core/memory.rs:492-509. Proved consistent with the real layout for all units >= 1, not just multiples: with n = row_bytes/alignment, round_up(u*row_bytes, a) - (n-1)*a = a + (fixed_bytes - n*a) = granule + tail, which is exactly fixed_segments() under fixed_bytes = round_up(execution*row_bytes, a) (cache_memory.rs:291, :410-414). Worked check: row=82_143_488, a=2 MiB (n=39), u=2 → span=158 MiB, saved=76 MiB, result 82 MiB = 2 MiB + 80 MiB, matching the new test's claim. Non-multiple case row=1_500_000, a=2 MiB: u=1 → 2 MiB, u=2 → 3_145_728 = a + 1 MiB. units == 0 returns span early, matching sentinel_granules = 0; no call site passes execution == 0 (memory.rs:581/605/618/1103/1361), and saved <= span - a, so no underflow is reachable. bytes(core, 0, …) is deliberately retained at memory.rs:676-680 (virtual extent vs physical); no site was missed.

meminfo + OOM enrichment — helios/src/runtime_core/memory.rs:41-146, mod.rs:375-388. parse matches only exact "MemFree:"/"MemAvailable:"/"Cached:" tokens, so SwapCached:/SReclaimable: cannot alias Cached:; every fields.next()? early-return is fail-closed (diagnostics skipped, never a wrong number); checked_mul(1024) covers overflow. reclaimable_gap() = available.saturating_sub(free) is correct (Linux guarantees available >= free). Thresholds use strict > and the tests pin 10 GiB/4 GiB exact-boundary behaviour. check_ctx passes the real status at both call sites (cuDevicePrimaryCtxRetain mod.rs:407-410, cuCtxCreate_v2 :413-416), only re-reads /proc when integrated != 0 && status == CUDA_ERROR_OUT_OF_MEMORY, and preserves the structured Error::Execution(ExecutionError::Driver(CudaError { code: 2, .. })) — the #[cfg]-shadowed let result is legal and warning-free on both platforms. CUDA_ERROR_OUT_OF_MEMORY = 2 is correct.

Persistent-group merge, explicit-CLI path. skip_config_limit == false appends both occurrences, and OrbitRun carries #[command(args_override_self = true)] (cli.rs:571-573), so clap keeps the last value → an explicit --memory-limit genuinely overrides a saved one. The defect above is confined to the config-inherited path.

Not verifiable in this environment (carried from the PR's own disclosures): live GB10 CU_DEVICE_ATTRIBUTE_INTEGRATED / CUDA_ERROR_OUT_OF_MEMORY-during-context-creation behaviour, whether cuDevSmResourceSplit accepts the three-group codec partition on driver 615.x, and whether codec-context VMM allocations remain usable from the compute/worker contexts. The 10 GiB / 4 GiB thresholds are heuristic by construction with no live MemFree/MemAvailable data.