Subtraction and simplicity report · NVIDIA/hyperflare-inference #646

Raw Markdown for agents: https://autobot.eidonix.com/p/9900dbbe-e3da-4ab4-a3f0-a3ded90742d8.md

Subtraction, Simplicity & Conventions review — PR #646

Key findings

The NVML consolidation in this PR is a genuine large deletion (helios/src/nvml.rs +378 replaces ~1,000 lines of duplicated FFI/init-shutdown across five files) and the selene/helios sizing changes are net simplifications. But four removable duplications and one speculative CLI surface survive, and one of them re-imports exactly the objection that left #147 blocked.

  1. Session authorizes twice per loop iteration — an identical 6-line pre-auth/slot-release block is executed twice with only read_header between; timeouts_cleared makes the first copy pure no-op (flare-cli/src/orbit/agent.rs:1148–1164).
  2. HELIOS_CACHE_DIRS is a hand-copied second list of Helios's managed directories, and after this PR no production caller can ever reach it — the only cache::evict call is on <agent cache>/bin (flare-cli/src/core_cache.rs:234–251, caller agent.rs:1443–1461). This is the exact "reserved names must come from owning modules" complaint that keeps #147 in CHANGES_REQUESTED.
  3. check(..).unwrap_err() + ?-then-unreachable!(): five map_err sites build a Result only to discard its Ok, and the PCI-error arm fabricates an infallible path (flare/src/hardware.rs:36–78, :215) — a non-Result error builder deletes the idiom and the helper's Result shape.
  4. Two parsers for one -rank<R> name format (parse_rank_directory is parse_rank_selector plus one length check) and a redundant HashSet clone-per-entry in Agent::cores (agent.rs:499–517, :1016–1019).
  5. The new --core-cache flag ships two speculative aliases, twice (--model-cache, --package-cache) for a field that did not exist before this PR (flare-cli/src/cli.rs:377–379, :406–408) — AGENTS.md rejects speculative compatibility.
  6. The metadata-only guard is implemented three times over one predicate; AuthorizedCore::is_loadable ANDs a flag against the field that flag was copied from (helios/src/runtime_core/protection.rs:223–246, :892, :2696, :2842).

Each is independently removable; none requires new code.


1. Subtraction

S1 (high). Session::session authorizes twice per iteration — delete the first copy

flare-cli/src/orbit/agent.rs:1148–1164 (in fn session, :1136):

    loop {
        let authorized = agent.is_controller(&session.remote())?;
        if authorized && !timeouts_cleared {
            preauth_guard = None;
            session.clear_timeouts()?;
            timeouts_cleared = true;
        }
        let (tag, length) = match session.read_header() {
            Ok(header) => header,
            Err(_) => return Ok(()),
        };
        let authorized = agent.is_controller(&session.remote())?;
        if authorized && !timeouts_cleared {
            preauth_guard = None;
            session.clear_timeouts()?;
            timeouts_cleared = true;
        }

The two blocks are byte-identical and separated only by read_header; timeouts_cleared guarantees the second is a no-op once the first has run, so this is duplicated work plus an extra is_controller lookup per frame. Remove lines 1149–1154 (the first let authorized and its if). The copy at :1159–1164 still runs before every frame handler and still binds authorized for the _ if !authorized guard at :1184. ~6 lines and one lock acquisition per frame removed.

S2 (high). HELIOS_CACHE_DIRS duplicates Helios's directory list and is unreachable in production

flare-cli/src/core_cache.rs:234–251:

/// Managed `helios::core::cache::Root` top-level directories that flat cache eviction must never
/// remove even if a caller points `evict` at a shared cache root.
const HELIOS_CACHE_DIRS: &[&str] = &[
    "blobs", "models", "refs", "sources", "origins", "staging", "locks",
];
...
        let managed = name.is_some_and(|name| HELIOS_CACHE_DIRS.contains(&name));
        if !hidden && !managed && !pins.contains_key(&path) {

Three separate reasons to delete it rather than keep it:

Remove the const, the managed binding, the !managed conjunct, and that test. If #361's stated end state ("remove the directory scan and the skip list") is wanted, delete evict's directory scan itself instead of guarding it — either way the PR should not carry both a skip list and a claim to close the issue that asked for no skip list.

S3 (medium). Speculative CLI aliases added twice

flare-cli/src/cli.rs:377–379 and :406–408:

    /// Prepared-model cache root shared by staged and served cores.
    #[arg(long, alias = "model-cache", alias = "package-cache", value_name = "PATH")]
    pub core_cache: Option<PathBuf>,

core_cache is a new field on both AgentArgs and AgentCommand::Install; --model-cache/--package-cache never existed on flare agent, so nothing can depend on them. Every other command in the CLI spells it --core-cache, and this PR's own docs/orbit.md (not opened) rewrite only documents --core-cache. AGENTS.md rejects speculative compatibility and configuration switches without a concrete requirement. Drop both aliases in both places, which also removes the alias-precedence case the new config test has to cover.


2. Simplicity & duplication

S4 (high). check(..).unwrap_err() and ?-then-unreachable!() instead of an error helper

flare/src/hardware.rs:36–78:

        let device = if let Ok(index) = entry.parse::<u32>() {
            nvml.device_by_index(index)
                .map_err(|code| check("nvmlDeviceGetHandleByIndex_v2", code).unwrap_err())?
...
            Err(code) => {
                check("nvmlDeviceGetPciInfo_v3", code)?;
                unreachable!()
            }

with fn check(operation: &str, code: c_int) -> Result<()> at :215. Five sites (:38, :42, :46, :51, :54) construct a Result<()>, call ?-free unwrap_err() to pull the error back out, and hand it to map_err; :75–78 calls check with ? on a code that is known non-zero and then asserts unreachable!(). All of it is the same string-building code reached through a type it does not need.

Replace check with a non-Result builder:

fn nvml_failure(operation: &str, code: c_int) -> Box<dyn std::error::Error> { ... }

then write .map_err(|code| nvml_failure("nvmlDeviceGetHandleByIndex_v2", code))? at :38/:42/:46/:51/:54 and Err(code) => return Err(nvml_failure("nvmlDeviceGetPciInfo_v3", code)), at :75–78. That deletes the unwrap_err() idiom (5 sites), the ?-then-unreachable!() pair, and the Result wrapper on the helper — a straight line reduction in a file this PR already rewrote (−251 lines) but left this shape in.

S5 (medium). Two parsers for one name format, plus a redundant HashSet

flare-cli/src/orbit/agent.rs:499–517:

fn parse_rank_directory(directory: &str) -> Option<(&str, usize)> {
    let (prefix, rank_str) = directory.rsplit_once("-rank")?;
    let rank: usize = rank_str.parse().ok()?;
    let (export, len_str) = prefix.rsplit_once('-')?;
    if export.is_empty() || len_str.parse::<u64>().is_err() {
        return None;
    }
    Some((export, rank))
}

is parse_rank_selector (the very next function, :510–517, the format distribution::receive_rank writes) plus one length check. Collapse it to:

let (prefix, rank) = parse_rank_selector(directory)?;
let (export, len) = prefix.rsplit_once('-')?;
(!export.is_empty() && len.parse::<u64>().is_ok()).then_some((export, rank))

In the same area, Agent::cores agent.rs:1016–1019 / :1051 keeps a second copy of by_name's keys:

    let mut cores = Vec::with_capacity(by_name.len());
    let mut seen_names: std::collections::HashSet<String> = std::collections::HashSet::new();
    for (name, entry) in by_name {
        seen_names.insert(name.clone());

Iterate for (name, entry) in &by_name and test by_name.contains_key(&name) in the staged-directory loop at :1051; that removes the HashSet, one String clone per entry, and the Vec::with_capacity bookkeeping that only exists because seen_names does.

S6 (medium, verify-then-delete). The metadata-only guard is three copies of one predicate

helios/src/runtime_core/protection.rs:223–246:

pub struct AuthorizedCore {
    pub(super) kind: AuthorizedKind,
    pub(super) loadable: bool,
}
...
    pub fn is_loadable(&self) -> bool {
        self.loadable
            && match &self.kind {
                AuthorizedKind::Legacy { .. } => true,
                AuthorizedKind::Payload(core) => core.source.supporting_verified,
            }
    }

For the Payload arm the AND is x && x: :892 sets loadable: verify_payloads, and the same verify_payloads is what PayloadVerifiedCore::authorize_with_progress stores as supporting_verified (:2586). The Legacy arm is unconditionally true, so the match contributes nothing at all. The predicate then exists a third time at :2842 (if !self.source.supporting_verified { ... same error string ... }) and a fourth time at :2696.

Simplify to one definition: in the Payload arm at :885–893 compute let authorized = core.authorize_with_progress(...)?; let loadable = authorized.is_loadable();, then reduce is_loadable to self.loadable, and have PayloadAuthorizedCore::load (:2842) call self.is_loadable() instead of re-inlining the check. That keeps the Legacy metadata-only guard (which does need the flag, since AuthorizedKind::Legacy has nowhere else to record it), removes the redundant core.source.supporting_verified conjunct, and leaves one copy of the error string. authorize_metadata_is_not_loadable (:4480) still covers the behaviour. Worth confirming the equality at :892/:2586 before applying — if they can diverge, keep the flag and still delete the duplicated check at :2842.


3. Repo conventions


Checked and found lean (no action)

Open questions / could not confirm