Recommendation: Changes Requested
This PR tackles four real, high-impact operational defects (Orbit rank-cache collision and duplicate staging, GB10 page-cache/KV/offload memory sizing, flare-agent hardening, and NVML FFI/FD-leak consolidation), and the core fixes—including PayloadSource::release_page_cache, once-only input_window accounting, the OnceLock NVML consolidation, device.ordinal visibility matching, handshake magic/timeout hardening, and atomic_write_private—are clean and well-tested. However, verification surfaced one blocker (permanently leaked staged cores under <core-cache>/staging/orbit/ with no reclamation path) and several concrete correctness gaps, including a newly identified marker-ordering bug that defeats .flare-verified.json (not opened) fast-path reuse on multi-file cores after orbit push, an undersized pre-auth session cap for multi-host fabric bursts, a still-open PID-reuse race in agent::stop, and [paths].core_cache not being wired into flare agent install.
Merge Risk
Level: High
- Wide cross-crate blast radius in a single squashed commit: 29 files (+2,597/−1,217) spanning 5 crates (
helios,selene,flare,heliopause,flare-cli) and 4 independent subsystems (on-disk cache layout, unified-memory KV/offload sizing, process/network supervision, and process-wide NVML FFI). - Disk-exhaustion and cluster-launch risk: Abandoned
PUT/ interruptedTRANSFERfiles in<core-cache>/staging/orbit/have no GC path (Root::collectdoes not sweepstaging/orbit), andMAX_PREAUTH_SESSIONS = 256can silently drop legitimate multi-hostFETCH_FABRICstreams at 5+ direct peers × 64 streams. - Active branch overlap and unrun hardware paths: Touches the hot
selene/src/offload.rsbudget path (overlaps open#625and widens#497) andheliopause/src/export/capture.rs(overlaps open#647), while live GB10 KV capacity, live 4-Sparkorbit push/run, and Windowsnvml.dllbuilds are unrun.
Walkthrough
- Orbit rank-cache unification & CLI/Grant fixes (
flare-cli/src/{cli,config,core_cache,distribution,launch,main,trust}.rs,flare-cli/src/orbit/{agent,controller}.rs,helios/src/core/cache.rs,docs/orbit.md): Adds--core-cachetoflare agent/flare agent install, stagesPUT/TRANSFERunder<core-cache>/staging/orbit/, publishes verified transfers (including rank zero after controllerPUT) intohelios::core::cache::Rootwithorbit:<dir>,<export>-rank<R>, and<export>-completesource refs, passes--core-cache <agent.core_cache>and holdsflockentry leases on launched ranks, deduplicates--roce-ring/--roce-chainfromserving, resolvesmodel.safetensorsinside--hostscached dirs, and inferstensor_parallel = hosts.len() + 1. - GB10 page-cache reclamation, host sizing, & metadata-only guard (
helios/src/runtime_core/{protection,memory,mod,model}.rs,selene/src/offload.rs,selene/src/offload/tests.rs(not opened),docs/prefix-cache-offload.md(not opened)): ImplementsPayloadSource::release_page_cache()over deduplicatedArc<File>s before CUDA init/KV sizing, routesNativeModel::allocate_cachesthroughplanned_host_futuresoinput_windowis counted once, bounds all integrated-GPU local offload tiers tointake_slots(layout, 1), and rejects metadata-onlyAuthorizedCorevalues inNativeResources::load,NativeModel::load_agreeing, andPayloadAuthorizedCore::load. flare-agentsecurity, process lifecycle, & LAN probe resilience (flare-cli/src/orbit/{agent,controller,identity,session,store}.rs,flare-cli/src/{distribution,fabric_transport}.rs): Enforcesgrant.current(now())inAgent::grant(), bounds sessions (MAX_SESSIONS = 1024,MAX_PREAUTH_SESSIONS = 256), validates 8-byteFLAREFLTmagic before reading the remaining handshake and keeps timeouts armed until authorization, writes secret files viaatomic_write_private(O_CREAT|O_EXCL0600+fsync+rename), isolates ranks in process groups with LinuxPR_SET_PDEATHSIG(SIGTERM), bounds reaper stdio drain to2sandController::stop_grouprank-zero wait to120s, and tolerates stray probes on rendezvous and fabric relay listeners.- Consolidated NVML loader & visibility ordinal fix (
helios/src/{nvml,lib}.rs,helios/src/runtime_core/device_memory.rs,flare/src/hardware.rs,heliopause/src/export/capture.rs,flare-cli/src/{doctor.rs,orbit/gpu.rs}): Adds process-lifetimeflare_helios::nvml::Nvml(OnceLock, nonvmlShutdown) across all 7 call sites with zeroCargo.toml/Cargo.lockchanges, and fixesassign_visibility()to match numericCUDA_VISIBLE_DEVICESentries againstdevice.ordinal.
Pre-merge Checks
- [PASS] Security / malicious screen: Verified
atomic_write_private,grant.current(now()), magic-first handshake, async-signal-safepre_execsyscalls, and WindowsLOAD_LIBRARY_SEARCH_SYSTEM32; no malicious patterns. - [WARN] Charter & value fit: Solves real Orbit/GB10/NVML defects from a priority contributor and area owner, but bundles 4 unrelated changesets in one commit, overclaims
closes #630(missing the requested KV-budget warning andcuCtxCreateMemFree/MemAvailable/Cached diagnostics), and omits the#361-required migration rule for pre-existing flat~/.cache/flare/cores/data. - [WARN] Related / duplicate / conflict check: Supersedes open PR
#147(re-introducing a hardcoded directory skip list that#147's reviewer blocked) without notifying#147or#497authors; overlaps open#625(selene/src/offload.rs) and#647(heliopause/src/export/capture.rs). - [WARN] Tests & verification evidence: Strong CPU test coverage across all crates, but misses tests for staging reclamation, multi-file
.flare-verified.json(not opened) marker matching afterorbit push, and[paths].core_cacheonagent install; GB10 KV capacity, 4-Sparkorbit push/run, NVML FD count, and Windowsnvml.dllbuild remain unrun/unmeasured.
Blockers
- Abandoned
<core-cache>/staging/orbit/transfers leak whole cores permanently with no reclamation path (flare-cli/src/orbit/agent.rs:1443-1455,helios/src/core/cache.rs:3158-3214):put()stages controller-uploaded core files under<core-cache>/staging/orbit/cores/<dir>/and returns early atagent.rs:1454without ever running eviction.- Normal
TRANSFERcompletion (agent.rs:803) and verification failure (agent.rs:1623) removestaged_dir, but if aPUTis interrupted (controller Ctrl-C, network drop beforeTRANSFER, or agent restart), those tens/hundreds of GiB stay instaging/orbit/cores/forever. helios::core::cache::Root::collect()(helios/src/core/cache.rs:3158-3214) only sweepsstaging/trees,staging/incoming, andstaging/wrapped—staging/orbitis completely invisible toflare models gcand every agent cleanup path. (Additionally, if a fresh re-push stages and commits a second copy,stage_namedcreates a-2suffix atcache.rs:2088-2097whileRoot::collect()treats everymodels/*/*directory as live atcache.rs:3153-3156, leaving the superseded entry until manualflare models remove.)- Fix: Evict unpinned/unleased entries inside
cache::cores_directory(&agent.staging_root())onPUT(and/or agent startup) usingcore_cache::evict—which is safe there becausestaging/orbit/cores/contains only Orbit staging dirs, never Helios managed dirs—or teachRoot::collect()to reclaim unleased entries instaging/orbit/. Add a regression test verifying abandoned staged dirs are reclaimed.
Should Fix
-
publish_orbit_entrywrites.flare-verified.json(not opened) in unsortedfs::read_dirorder, breaking fast-path cache reuse on multi-file cores (flare-cli/src/orbit/agent.rs:546-590, 790-816,flare-cli/src/distribution.rs:643-671, 720-723):move_staged_tree()(agent.rs:560-588) pushes filenames intoentry_filesin filesystem-arbitraryfs::read_dirorder (despite its doc comment at:547saying "sorted") andpublish_orbit_entry()passes&entry_filesdirectly todistribution::write_verified_marker_for()(agent.rs:809-815), which recordsmarker.filesin that exact slice order (distribution.rs:652-670).- When
orbit runstarts peer ranks,distribution::verified_marker_matches()(distribution.rs:720-723) zipsplan.files(ordered byruntime_core::rank_ranges: primary first, then companions in manifest order) positionally againstmarker.filesand returnsfalseon the first name mismatch. - On multi-file (directory/payload) cores, this causes
.flare-verified.json(not opened) written byorbit pushto miss on the firstorbit run, forcing a full SHA-256 disk re-verification of the entire rank payload. - Fix: Match files by name (e.g., sort both sides by filename or index
marker.filesbyname) inwrite_verified_marker_for()/verified_marker_matches(), and sortentry_filesinmove_staged_tree()to match its doc comment. Add a multi-fileorbit push→receive_rankmarker-hit test.
-
MAX_PREAUTH_SESSIONS = 256can silently drop legitimate multi-hostFETCH_FABRICbursts (flare-cli/src/orbit/agent.rs:296-301, 1116-1120, 1749, 1775,flare-cli/src/orbit/controller.rs:1502):- Every incoming stream holds a
preauth_guardslot untilfetch_fabric()/fetch()verifies the grant (agent.rs:1749, 1775). Controllertriggers peerTRANSFERs concurrently (controller.rs:1502), and each peer may open up to64streams (agent.rs:1543). Withworldup to16(distribution.rs:141), a direct burst from 5+ peers × 64 streams (320–960 concurrent handshakes) exceedsMAX_PREAUTH_SESSIONS = 256—and even 4 peers × 64 = 256 has zero margin for a concurrent controller session or probe. Overflow connections are silently dropped (drop(stream); continue;atagent.rs:1118) with no log, aborting cluster transfers without diagnostics.- Fix: Raise
MAX_PREAUTH_SESSIONS(or release the pre-auth slot once the authenticated peer key/framing is checked, or split unauthenticated probe slots from authenticated-peer slots) and log when shedding connections at the cap.
- Every incoming stream holds a
-
PID-reuse signal window in
agent::stop()is narrowed, not closed (flare-cli/src/orbit/agent.rs:2135-2139, 2204-2221):- In the reaper (
agent.rs:2136-2138),child.wait()reaps the child (returninggroup.pidto the kernel pool) beforefinished.exited.store(true, Ordering::Release)runs, and without taking any lock shared withstop(). stop()(agent.rs:2207-2216) locksgroup.log(which the reaper does not hold aroundwait()orexited.store), checks!group.exited.load(Ordering::Acquire), and callslibc::kill(-group.pid, SIGTERM)(plus fallbacklibc::kill(group.pid, SIGTERM)onESRCH). Thusstop()can still race with reaping and signal a recycled PID, making theSAFETYcomment at:2212and the PR's claim that the window is closed inaccurate.- Fix: Do not hold a lock across blocking
child.wait()(that would deadlockstop()). Instead, on Linux wait without reaping first vialibc::waitid(P_PID, pid, &mut info, WEXITED | WNOWAIT)(keeping the zombie so the PID cannot be recycled), then acquire a dedicatedreap: Mutex<()>lock, setexited = true, and call now-nonblockingchild.wait()under that lock; havestop()hold the samereapmutex across itsexitedcheck andkill()calls.
- In the reaper (
-
[paths].core_cache(and top-level--core-cache) is not applied toflare agent install(flare-cli/src/config.rs:138-140,flare-cli/src/main.rs:147-157,flare-cli/src/orbit/agent.rs:2316-2324):Configuration::apply()(config.rs:138-140) only setsargs.core_cache.get_or_insert(cache)oncli::Command::Agent(args), leavingAgentCommand::Install { core_cache, .. }asNone.main.rs:147-157passes only the subcommand'score_cachetoorbit::agent::install(), ignoring both[paths].core_cacheandflare agent --core-cache PATH install.- This contradicts the PR description ("
Command::AgentandAgentCommand::Installaccept--core-cache… and apply[paths].core_cache"), and the new test inconfig.rs:762-786only coversflare agent. - Additionally,
agent.rs:2317interpolatespath.display()unquoted into systemdExecStart=, which breaks paths containing spaces or%. - Fix: Propagate
agent_args.core_cache/[paths].core_cacheintoAgentCommand::Install(or, ifinstallintentionally relies on runtime config loading when--core-cacheis omitted, update the PR description and still forwardagent_args.core_cache), shell/systemd-quote the path inExecStart, and add a config test forflare agent install.
-
Rendezvous loop ignores well-formed version-mismatch and duplicate-rank
Joins, turning misconfigurations into timeouts (flare-cli/src/distribution.rs:211-221):- Lines
200-210properly skip malformed/unparseable LAN probes. However, lines211-221alsocontinueon a valid, parsedJoinwithjoin.version != VERSION || join.rank == 0 || join.rank >= world || peers[join.rank].is_some(). - A genuine protocol-version mismatch or duplicate-rank cluster misconfiguration now loops until
deadlineand fails only with"timed out waiting for serving ranks"(:196) rather than failing fast with the root cause. This behavior change is not disclosed in the PR description. - Fix: Fail fast on valid
Joinframes withjoin.version != VERSIONor out-of-range/duplicate rank (keepingcontinueonly for malformed/unparseable connections), or explicitly justify and document the timeout semantics if stale-peer tolerance is required.
- Lines
-
Best-effort marker writes in
publish_orbit_entrycan silently publish entries reported as unverified (flare-cli/src/orbit/agent.rs:804-816):- Both
fs::write(entry.directory().join(VERIFIED), ...)(:804) anddistribution::write_verified_marker_for(...)(:809) discard errors vialet _ = .... - On ENOSPC or I/O error right after committing a multi-GiB entry,
publish_orbit_entrystill publishes source refs and reports"verified": true, whileAgent::cores()(:1024-1025) and placement (plan::Pool::holds,plan.rs:212-214) subsequently treat the entry as"verified": false. - Fix: Propagate errors from writing
.verifiedand (whenreal_coreis true).flare-verified.json(not opened) before publishing source refs.
- Both
Subtract / Simplify
- Delete hardcoded
HELIOS_CACHE_DIRSskip list (or source it fromhelios::core::cache) (flare-cli/src/core_cache.rs:234-251, 1936-1958):- After this PR, the only production caller of
core_cache::evict()isflare-cli/src/orbit/agent.rs:1461, which only runs for non-core/non-package uploads (<agent.cache>/bin) and can never touch a Helios cache root. - Hardcoding
["blobs", "models", "refs", "sources", "origins", "staging", "locks"]duplicateshelios/src/core/cache.rs:1589-1603and re-introduces the exact module-ownership concern that left#147inCHANGES_REQUESTED. Either removeHELIOS_CACHE_DIRS(and its test) outright, or exportpub const ROOT_DIRECTORIES: &[&str]fromhelios::core::cacheif defense-in-depth is desired.
- After this PR, the only production caller of
- Avoid double
controllers.toml(not opened) read/verify per frame insession()(flare-cli/src/orbit/agent.rs:1148-1164):agent.is_controller(&session.remote())?reads and verifiescontrollers.toml(not opened) from disk twice per frame even aftertimeouts_clearedistrue. Guard the pre-read_headerblock withif !timeouts_clearedso already-authorized controllers still clear timeouts and droppreauth_guardbefore blocking inread_header(), while steady-state frames only re-checkis_controlleronce afterread_header()(preserving mid-session controller revocation).
- Replace
check(..).unwrap_err()andcheck(..)?; unreachable!()with a direct NVML error builder (flare/src/hardware.rs:38-78, 215-223,helios/src/runtime_core/device_memory.rs:33-36,heliopause/src/export/capture.rs:2144-2152):- Converting
check(op, code) -> Result<()>into an error-formatting helper (matchingflare-cli/src/orbit/gpu.rs:149-152) removes 7unwrap_err()sites and 3unreachable!()branches.
- Converting
- Minor cleanups in
agent.rsandprotection.rs(flare-cli/src/orbit/agent.rs:499-517, 1016-1053,helios/src/runtime_core/protection.rs:229-236, 2842):parse_rank_directorycan delegate its-rank<R>split toparse_rank_selector;Agent::cores()can iterate&by_nameand checkby_name.contains_key(&name)at:1051instead of cloning keys into a separateseen_names: HashSet<String>; and becauseAuthorizedCore.loadableandPayloadSource.supporting_verifiedare always set to the sameverify_payloadsboolean (protection.rs:889-893, 2586,model.rs:274-278),AuthorizedCore::is_loadable()simplifies toself.loadableandPayloadAuthorizedCore::load(:2842) can callself.is_loadable().
Nits
- Honest issue scoping & migration rule: Change
closes #630toAddresses #630(the requested KV-budget warning andcuCtxCreateMemFree/MemAvailable/Cached diagnostics are not implemented here, and live GB10 measurements are not yet recorded). For#361, state the upgrade/cleanup rule indocs/orbit.mdfor pre-existing flat~/.cache/flare/cores/<export>...directories left by older agents. - Coordinate / consider splitting: If convenient for faster review and cleaner conflict resolution, consider splitting out the NVML consolidation and GB10/Selene sizing fixes from the Orbit changes, and drop a quick note on
#147(superseded) and coordinate merges with#625(selene/src/offload.rs) and#647(heliopause/src/export/capture.rs). intake_warningwording on integrated devices (selene/src/offload.rs:388-395, 606): Whenintegratedis true,sized_concurrencyis1, so the warning prints"full intake at max concurrency 1 needs ...", which can confuse operators who configured a higher--max-concurrency(pre-existing fordisk_only, now also shown whenmemory_bytes > 0). Rewording the integrated branch to clarify it is the two-window integrated-memory cap would help diagnostics.
Dropped on verification
- Speculative
--model-cache/--package-cachealiases onAgentArgsandAgentCommand::Install(Subtraction lens S3): Verified false—flare-cli/src/cli.rs:109, 243, 277, 1319-1342define those exact hidden aliases on every other--core-cacheflag in the CLI, so adding them onAgentis consistent rather than speculative. - "Remove lines 1149–1154" in
session()(Subtraction lens S1's proposed fix): Verified unsafe—removing the pre-read_headerauthorization check leavesHANDSHAKE_TIMEOUT(30s) armed and holdspreauth_guardwhile an already-authorized controller waits before sending its first frame, breaking idle authorized sessions. Replaced with the safeif !timeouts_clearedguard inSubtract / Simplify. - "Hold reaping mutex across
child.wait()" (Correctness lens #3's proposed fix): Verified unsafe—holding a lock shared withstop()across blockingchild.wait()would deadlockstop()forever. Replaced with thewaitid(..., WEXITED | WNOWAIT)+ lock-before-reap fix inShould Fix #3. - "
--hostssilently overrides--gpus; error whenhosts.len() + 1 != gpus.len()" (Correctness lens #10): Verified false—--gpusis a list of local GPU indices (e.g.--gpus 0haslen() == 1), not a count, and--hostsruns 1 rank per host (world = hosts.len() + 1). Erroring whenhosts.len() + 1 != gpus.len()would break valid launches likeflare run MODEL --hosts peer1 --gpus 0; explicit--tensor-parallelstill overrides inference intrust.rs:41. - "Fail
publish_orbit_entrywhenreal_core == false" (part of Correctness lens #8): Dropped—real_core == falseis the deliberate fallback exercised byAgent::with_fakesunit tests acrossagent.rsandcontroller.rsthat pass synthetic byte payloads and a fake verifier. Kept only the real ignored-error bug on.verified/.flare-verified.json(not opened) writes. - "
MAX_SESSIONS = 1024has zero headroom for control" (part of Correctness lens #2): Corrected—rank zero does not fetch from itself, so worst-case incoming fabric streams on a node is15 × 64 = 960, leaving 64 control slots within1024. OnlyMAX_PREAUTH_SESSIONS = 256is undersized. - "
TRANSFERreuse returnsverified: false" (Correctness lens metric check): Verified not a regression—flare-cli/src/orbit/controller.rs:2000-2004already defines the 3-way contract where(received == 0, verified == false)means"holds the verified core"(reused without re-verifying during this call) vs.(false, true)meaning"verified the cached core". - "
free_bytesnow measurescore_cacheinstead of~/.cache/flare, missingbin/mount" (Correctness lens #9): Low-signal—cores are tens/hundreds of GiB while optional executable overrides are ~tens of MiB, so measuringcore_cacheis strictly more accurate forcheck_spacewhen--core-cachesits on a separate volume. - "
assign_visibilityerrors ifCUDA_VISIBLE_DEVICESnames a filtered non-CUDA device" (Correctness lens #11): Low-signal / expected—explicitly selecting a non-CUDA device should error rather than silently misbinding another GPU by shifted slice index.