From ec1df8484e6209777abbcef7f1ede7afe109cf31 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Mon, 30 Nov 2026 10:21:08 -0800 Subject: [PATCH 1/2] Unify Orbit rank cache, fix GB10 page-cache KV sizing, consolidate NVML, and harden flare-agent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why this change is needed: Four classes of operational defects affect multi-host Orbit clusters and unified-memory GPUs (such as DGX Spark GB10): 1. Orbit rank-cache collision, eviction data loss, and duplicate staging (#119, #361, #629, #147): `flare agent` hardcoded its cache root to `~/.cache/flare` instead of honoring `--core-cache` / `[paths].core_cache`, stored flat core directories inside `~/.cache/flare/cores` (the default managed `helios::core::cache::Root` directory), and called `core_cache::evict` on that directory during `PUT` and `TRANSFER`. That eviction sweep deleted Helios's managed `blobs/`, `models/`, `refs/`, `sources/`, `origins/`, `staging/`, and `locks/` subdirectories without consulting Helios leases (#119). Meanwhile, `agent::run` passed `--core-cache ~/.cache/flare` to spawned `flare run` peers, so peer ranks opened a second model cache outside `~/.cache/flare/cores` and could not reuse peer rank shards staged by `orbit push` (#629). In addition, controller-local `PUT` uploads to `nodes[0]` skipped verification and left `.verified` absent; `OrbitRun::rank_options` and `launch::Peers::start` duplicated `--roce-ring` / `--roce-chain` into `spec.serving` and `Grant.serving` alongside `Grant`'s booleans (breaking overrides on saved persistent groups); and `flare run CORE --hosts` built `Grant.core` from the cached entry directory instead of `model.safetensors` while failing peer `core_cache::component_valid` on `+` in multi-deployment names and failing to infer `tensor_parallel = hosts.len() + 1`. 2. GB10 KV collapse and integrated-memory over-reservation (#630): `PayloadSource::release_page_cache()` was an empty no-op (unlike `Archive::release_page_cache()`), leaving tens of GiB of SHA-256-verified payload pages resident in Linux page cache through CUDA initialization and KV sizing. In `helios/src/runtime_core/memory.rs`, `NativeModel::allocate_caches` added `input_window` into both `offload_host` and `host_future`, charging it twice whenever prefix-cache offload was enabled. In `selene/src/offload.rs`, `target_intake_slots` bounded integrated-GPU intake to `intake_slots(layout, 1)` only when `memory_bytes == 0 && disk_enabled()`, allowing nonzero warm memory on unified-memory GPUs to reserve concurrency-scaled burst intake slots. Finally, `VerifiedCore::authorize_metadata` returned the same loadable `AuthorizedCore` type accepted by GPU loaders even though supporting payloads were not verified upfront. 3. `flare-agent` authentication, lifecycle, and LAN resilience gaps: `Agent::grant()` verified signatures without checking `grant.current(now())`, allowing expired grants to work indefinitely for `TRANSFER`, `FETCH`, and `FETCH_FABRIC`. `serve_on()` spawned unbounded pre-auth OS threads and `Session::accept` cleared read timeouts before `HELLO` or authorization while waiting for 44 bytes before checking the 8-byte `FLAREFLT` magic. `Key::load_or_create`, `AgentDir::private_write`, and `Orbit::save` wrote secret files with default umask before `chmod 0600`. The rank reaper joined stdout/stderr forwarders before calling `Group::finish()`, allowing a grandchild holding stdio open to lock GPUs and pins indefinitely and leaving a PID-reuse window in `agent::stop`; ranks were spawned without process-group isolation or `PR_SET_PDEATHSIG`; `Controller::stop_group` waited on rank zero without a timeout; and stray LAN probes on the rendezvous or wildcard fabric relay listeners aborted active launches. 4. Duplicated NVML loaders, FD leak, and ordinal visibility mismatch: Five files across `helios`, `flare`, `heliopause`, and `flare-cli` duplicated dynamic NVML loading, and six call sites invoked `nvmlInit_v2()` / `nvmlShutdown()` per query—causing `HardwareMonitor`'s 2-second polling loop to leak ~1,800 NVML event file descriptors per hour. In `flare/src/hardware.rs`, `assign_visibility()` matched numeric `CUDA_VISIBLE_DEVICES` entries against the filtered vector slice index instead of `device.ordinal`, misbinding GPUs whenever a non-CUDA device was skipped. What exactly changed: - Orbit rank cache unification and 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`): - Before: `flare agent` ignored `--core-cache` and `[paths].core_cache`, stored flat directories in `~/.cache/flare/cores`, evicted unpinned entries there, passed `--core-cache ~/.cache/flare` to ranks, left `nodes[0]` unverified after `PUT`, duplicated RoCE flags in `serving`, and wrote cached directory paths into `--hosts` `Grant.core`. - After: `Command::Agent` and `AgentCommand::Install` accept `--core-cache` and inherit `[paths].core_cache` (default `~/.cache/flare/cores`). In-flight `PUT`/`TRANSFER` files stage under `/staging/orbit`, never calling `core_cache::evict` on core caches (`evict` also skips Helios's seven managed directories as defense-in-depth). Verified transfers—including `nodes[0]` after controller `PUT`—commit into `helios::core::cache::Root` with `.verified` and `.flare-verified.json` markers and publish `orbit:`, `-rank`, and `-complete` source refs shared with `distribution::receive_rank`, `Agent::cores()`, and placement. `agent::run` passes `--core-cache `, holds `Entry` leases on active local cores, and skips `cache::entry` for remote-bootstrap peers. RoCE shape flags are stripped from `serving` and emitted once from `Grant`'s booleans. `--hosts` resolves `model.safetensors` inside cached entry directories and infers `tensor_parallel = hosts.len() + 1`. - GB10 page-cache release, memory sizing, Selene intake, and metadata-only guard (`helios/src/runtime_core/{protection,memory,mod,model}.rs`, `selene/src/offload.rs`, `docs/prefix-cache-offload.md`): - Before: `PayloadSource::release_page_cache()` was empty; `memory.rs` counted `input_window` in both `offload_host` and `host_future`; `selene::offload::target_intake_slots` only capped integrated GPUs when `disk_only`; and metadata-only `AuthorizedCore` could enter GPU loaders. - After: `PayloadSource::release_page_cache()` invokes `crate::os::release_page_cache` once per unique `Arc` across `primary` and all opened payload containers; `planned_host_future` counts `input_window` once; `target_intake_slots` and `sized_concurrency` bound all integrated-GPU local offload tiers to `intake_slots(layout, 1)`; and `AuthorizedCore` tracks `loadable` so `NativeResources::load`, `NativeModel::load_agreeing`, and `PayloadAuthorizedCore::load` reject metadata-only authorizations before touching CUDA. - `flare-agent` hardening and stray LAN probe handling (`flare-cli/src/orbit/{agent,controller,identity,session,store}.rs`, `flare-cli/src/{distribution,fabric_transport}.rs`): - Before: `Agent::grant()` ignored expiry; `serve_on()` had no session or pre-auth cap; `Session::accept` read 44 bytes before checking magic and cleared timeouts before authorization; secret files were written before `chmod 0600`; the reaper blocked `finish()` on forwarder joins with no process-group isolation or `PR_SET_PDEATHSIG`; `stop_group` looped unboundedly on rank zero; and stray TCP connections aborted rendezvous and fabric relay listeners. - After: `Agent::grant()` rejects expired grants across all RPCs; `serve_on()` bounds concurrent sessions (`1024`) and pre-auth sessions (`256`); `Session::accept` checks the 8-byte `FLAREFLT` magic first and keeps read/write handshake timeouts armed until peer authorization; `atomic_write_private` creates secrets with `O_CREAT | O_EXCL` mode `0600` + `fsync` + `rename`; rank processes run in isolated process groups (`setpgid(0, 0)`) with Linux `PR_SET_PDEATHSIG(SIGTERM)`, PID-reuse-guarded process-group `SIGTERM`, and a 2-second bounded forwarder drain before `finished.finish(code)`; `stop_group` bounds rank zero drain to 120s; and `distribution::root` and `fabric_transport::serve` drop stray LAN probes without aborting active transfers. - Consolidated NVML `OnceLock` loader and 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}`): - Before: five crates duplicated NVML FFI structs and per-call `nvmlInit_v2` / `nvmlShutdown`, leaking ~1,800 FDs/hr in `HardwareMonitor`, and `assign_visibility()` compared numeric `CUDA_VISIBLE_DEVICES` entries to slice index instead of `device.ordinal`. - After: added `flare_helios::nvml::Nvml` backed by a process-wide `OnceLock` (using `LOAD_LIBRARY_SEARCH_SYSTEM32` on Windows and never calling `nvmlShutdown`), migrated all seven Rust call sites across five files with zero `Cargo.toml`/`Cargo.lock` changes, and matched numeric `CUDA_VISIBLE_DEVICES` entries against `device.ordinal`. Claimed benefit or result: - Expected on multi-host Orbit clusters: eliminates silent deletion of managed Helios cache trees during `PUT`/`TRANSFER` (#119), eliminates duplicate peer rank staging between `orbit push` and `orbit run` (#361, #629), preserves `.verified` status on `nodes[0]`, fixes persistent-group RoCE shape overrides and `--hosts` cached/multi-deployment launches, and hardens `flare-agent` against expired-grant replay, pre-auth thread exhaustion, secret permission races, stuck reapers, and stray LAN probes. - Expected on GB10 and integrated-memory GPUs: reclaims verified weight page cache before CUDA init and KV sizing, stops double-charging `input_window`, and bounds local-tier offload intake when warm memory is nonzero (#630). - Expected on long-lived polling processes (`HardwareMonitor`, `flare agent`): eliminates the ~1,800 FDs/hr NVML event-descriptor leak and fixes numeric `CUDA_VISIBLE_DEVICES` matching when non-CUDA NVML devices are skipped. - These are CPU-verified behavioral guarantees; live GB10 KV token recovery and live 4-Spark transfer latency have not yet been measured on hardware. Supporting evidence and limitations: All Rust test suites ran with `--locked --release` in this worktree on Linux x86_64: - `eos`: 2 passed, 0 failed. - `selene` (`--features test-support`): 548 unit + 1 integration passed, 0 failed (updated integrated-GPU `memory_bytes > 0` intake assertions). - `selene-manager` (`--features test-support`): all passed, 0 failed. - `helios` (`--features runtime-core,server`, `core::`, `runtime_core::`, `nvml`): 504 passed, 0 failed, 12 ignored (GPU/checkpoint-gated), including `authorize_metadata_is_not_loadable`, `payload_source_release_page_cache_deduplicates_unique_files`, `planned_host_future_counts_input_window_once`, and `integrated_offload_host_budget_matches_small_soc_scaling_and_explicit_limits`. - `flare`: all unit and integration tests passed, 0 failed, including `gpu_inventory_visibility_matches_nvml_ordinal_when_non_cuda_devices_skipped`. - `flare-cli`: 208 unit tests passed (0 failed, 3 ignored) + 26 integration tests passed (`cache_commands` 9, `cli` 6, `inspect` 4, `unverified_payload` 7), including new tests for managed-cache eviction protection, shared `Root` rank refs, `nodes[0]` verification after `orbit push`, expired-grant rejection across all RPCs, RoCE deduplication, `Command::Agent` `--core-cache` precedence, atomic `0600` secret creation, immediate short-probe rejection, stray LAN probe tolerance on `fabric_transport`, and reaper completion with leaked grandchild stdio. (`actual_load_core_leases_managed_local_entries_and_releases_on_failure` exhibits a pre-existing parallel `fork`-vs-`flock` race in concurrent runs and passed standalone.) - `heliopause`: 216 passed, 0 failed, 6 ignored (CUDA). - Unrun checks: live GB10 KV capacity measurement, live multi-host 4-Spark `orbit push`/`orbit run`, Windows `nvml.dll` compilation, and `FLARE_TEST_TEMPLATE_DIR` chat-template tests. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b --- docs/orbit.md | 102 +- docs/prefix-cache-offload.md | 4 +- flare-cli/src/cli.rs | 13 +- flare-cli/src/config.rs | 57 + flare-cli/src/core_cache.rs | 39 +- flare-cli/src/distribution.rs | 52 +- flare-cli/src/doctor.rs | 382 +++---- flare-cli/src/fabric_transport.rs | 140 ++- flare-cli/src/launch.rs | 14 +- flare-cli/src/main.rs | 17 +- flare-cli/src/orbit/agent.rs | 1275 +++++++++++++++++++--- flare-cli/src/orbit/controller.rs | 125 ++- flare-cli/src/orbit/gpu.rs | 295 ++--- flare-cli/src/orbit/identity.rs | 10 +- flare-cli/src/orbit/session.rs | 50 +- flare-cli/src/orbit/store.rs | 61 +- flare-cli/src/trust.rs | 13 +- flare/src/hardware.rs | 388 +++---- heliopause/src/export/capture.rs | 67 +- helios/src/core/cache.rs | 19 + helios/src/lib.rs | 1 + helios/src/nvml.rs | 378 +++++++ helios/src/runtime_core/device_memory.rs | 67 +- helios/src/runtime_core/memory.rs | 45 +- helios/src/runtime_core/mod.rs | 1 + helios/src/runtime_core/model.rs | 3 + helios/src/runtime_core/protection.rs | 146 ++- selene/src/offload.rs | 20 +- selene/src/offload/tests.rs | 30 +- 29 files changed, 2597 insertions(+), 1217 deletions(-) create mode 100644 helios/src/nvml.rs diff --git a/docs/orbit.md b/docs/orbit.md index 2e34f630f..8a4aa4905 100644 --- a/docs/orbit.md +++ b/docs/orbit.md @@ -23,10 +23,10 @@ processes to hosts and authenticates control and file-transfer requests. | Command | Where | Effect | | --- | --- | --- | -| `flare agent install [--join-code CODE] [--accept-first] [--listen ADDR]` | Node | Installs the executable copy and user unit, restarts the service, requests linger, and prints pairing details | +| `flare agent install [--join-code CODE] [--accept-first] [--listen ADDR] [--core-cache PATH]` | Node | Installs the executable copy and user unit, restarts the service, requests linger, and prints pairing details | | `flare agent pair HOST... [--code CODE]` | Head or controller | Pairs the shared agent identities without a cluster definition | | `flare agent reset` | Node | Removes authorized controllers; the node becomes unpaired | -| `flare agent --listen ADDR` | Node | Runs the service (the unit's command) | +| `flare agent [--listen ADDR] [--core-cache PATH]` | Node | Runs the service (the unit's command) | | `flare orbit pair HOST... [--code CODE]` | Controller | Pairs and records nodes | | `flare orbit controllers add NAME PUBLIC_KEY` / `remove KEY` | Controller | Writes and distributes the next controller-set revision | | `flare orbit run [CORE] [--cluster NAME \| --nodes NODE,...] [--name GROUP] [--persistent] [--gpus N,...] [--dry-run] [--detach] ...` | Controller | Places a group on the candidate nodes' GPUs, starts it and attaches; `--persistent` saves its named definition; `--dry-run` prints the placement only | @@ -465,80 +465,64 @@ selected rank order. ## Core caching -An agent stores the files it receives through PUT and TRANSFER under -`~/.cache/flare` in its account: +An agent stores uploaded executables and publisher profiles under `~/.cache/flare` +and stores verified model cores in the host's managed Flare model cache +(`--core-cache`, then `[paths].core_cache`, then `~/.cache/flare/cores`): | Location | Contents | | --- | --- | -| `cores/-/` | Complete core for rank zero or single-host serving | -| `cores/--rank/` | Files and ranges of a peer rank staged by `orbit push` | -| `blobs/.safetensors` | Immutable payloads shared by core directories through hardlinks | -| `bin/flare-` | Uploaded executable overrides | -| `publishers/` | Public publisher profiles passed by controllers | - -An agent starts every rank with `--core-cache` set to that directory, which -makes it the root of the rank's Flare model cache. A peer rank that receives -its data during serving bootstrap publishes it as a model-cache entry, -`models///` with the primary named `model.safetensors`, -writes a `.flare-verified.json` marker there after verifying stored data, and -resolves that entry again on a later launch of the same export and rank. The -serving receiver does not read the agent's `cores/--rank/` -directory. A manually started peer uses `--core-cache`, then `paths.core_cache`, -then `~/.cache/flare/cores` as its model-cache root, so it shares entries with -an agent-started peer only when given the agent's directory. +| `/models///` | Published immutable complete cores and per-rank slices (`model.safetensors` plus companions) | +| `/sources/` | Lookup selectors shared between Orbit (`orbit:`, `-complete`) and serving bootstrap (`-rank`) | +| `/staging/orbit/` | In-flight PUT and TRANSFER files prior to verification and publication | +| `~/.cache/flare/bin/flare-` | Uploaded executable overrides | +| `~/.cache/flare/publishers/` | Public publisher profiles passed by controllers | + +An agent starts every rank with `--core-cache` set to that managed model-cache +root. Both `orbit push` and serving bootstrap publish verified rank slices into +`` under the shared `-rank` source reference with a +`.flare-verified.json` marker, so a peer rank started after `orbit push` or a +manual `flare run` reuses the cached entry without re-transferring payloads. A packed core is one `.safetensors` file. A directory core has a primary and companion files: payload-format companions have readable relative paths such as `weights/layer-000.safetensors`, and legacy companions are named by their SHA-256 beside the primary. No size threshold splits payloads. Peers receive -only the files and ranges their rank needs. An agent transfers a -digest-named companion whole, checks it against its filename hash, stores it -under `blobs/`, and hardlinks it into the core directory, so another core with -the same file reuses those bytes. Every other file receives its selected -ranges into a sparse file. Sparse logical lengths can greatly exceed allocated -disk space; use `du` to inspect allocation. +only the files and ranges their rank needs into sparse files; sparse logical +lengths can greatly exceed allocated disk space, so use `du` to inspect +allocation. The source of `NODE:PATH` is read in place. A source outside the agent cache is not copied merely to launch on that node. A repository core is acquired into the -downloading node's Flare model cache and read from that entry, while transfers -to other hosts populate each agent's own cache. -Keep source primaries, payloads, and symlink targets available while peers fetch -and ranks serve. - -An agent verifies data fetched by TRANSFER before writing a `.verified` marker -in that `cores/` directory. New writes -invalidate the marker; a repeated transfer requiring no bytes can reuse it. -Verification failure removes the core directory. Data sent directly by an -authorized controller is not given that marker by PUT. `--verify-weights` asks -each serving rank to digest its stored data during loading as well. - -Transfer sessions and running groups pin cache entries. Native receivers hold -file locks through serving, preventing agent eviction or concurrent replacement -of active rank cores. Receiving files can -evict unpinned executable overrides or core directories, but keeps reusable -blobs. Group-history pruning and `orbit rm` remove neither cores nor blobs. -The agent has no blob garbage-collection command; core-directory eviction -alone may reclaim little space when hardlinks still exist in the blob store. +downloading node's managed model cache and read from that entry, while transfers +to other hosts populate each agent's managed model cache. Keep source primaries, +payloads, and symlink targets available while peers fetch and ranks serve. + +An agent verifies staged core data during TRANSFER—including controller-uploaded +cores on rank zero—before committing the entry into `` and writing +its `.verified` and `.flare-verified.json` markers. Verification failure removes +the staged directory without publishing an entry. `--verify-weights` asks each +serving rank to digest its stored data during loading as well. + +Running groups and active controller sessions hold `flock` leases on published +model-cache entries. Receiving a core never sweeps or evicts directories inside +``; use `flare models remove` and `flare models gc` to reclaim +unleased entries and unreachable blobs. Receiving an executable override evicts +only unpinned files in `~/.cache/flare/bin/`. ## Prestaging `flare orbit push CORE --to NODE,... [--roce-ring | --roce-chain]` places a core on nodes ahead of any launch. It starts no ranks and sends no executable. With one node per multi-host rank, the first node receives the complete core and each peer -receives its rank's data, in the -listed order. With any other number of nodes, each receives the complete core. -Single-host cores are always staged complete. A node that holds the core -outside its cache is skipped. Node-to-node fetches are verified; a direct upload -from the controller follows PUT's verification rules. `flare orbit cores` lists -every node's cache directories with their file counts, bytes on disk and -verification state. A launch whose rank zero runs on a node holding the staged -complete core reuses it. Peer ranks receive their data again through serving -bootstrap unless their model cache already holds the entry, because the serving -receiver does not read a per-rank directory staged by `orbit push`; placement -still prefers a node whose STATUS lists that directory as verified. An explicit -executable override may still need uploading. Pre-staged core directories are -unpinned -after transfer and can be evicted when another core arrives. +receives its rank's data, in the listed order. With any other number of nodes, +each receives the complete core. Single-host cores are always staged complete. +A node that holds the core outside its cache is skipped. Both rank zero and +peer nodes verify staged data and publish entries into their managed model cache +with `.verified` and `.flare-verified.json` markers. `flare orbit cores` lists +every node's published and staged entries with their file counts, bytes on disk, +and verification state. Subsequent launches reuse both the verified complete core +on rank zero and the verified per-rank entries on peers without re-transferring +payloads. An explicit executable override may still need uploading. With `--roce-ring`, list exactly one node per multi-host rank in physical ring order. Core bytes follow the fabric TCP paths described below, without diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index f4294f83a..1dea285d0 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -164,14 +164,14 @@ holds every rank's bytes in one process. Each disk peer uses its host's intake. Automatic registered intake is additional to the warm budget whenever warm memory or local disk is enabled. It needs no setting: its slot count is `2 × max_active × row_slots + 2 × WINDOW_PAGES`, where `WINDOW_PAGES = 64`, -except for disk-only offload (`memory = 0` with local disk enabled) on an +except for local tiers (`memory > 0` or local disk enabled) on an integrated-memory device (`CU_DEVICE_ATTRIBUTE_INTEGRATED`), where intake targets two streaming windows and two continuation rows, `2 × (WINDOW_PAGES + row_slots)` (`intake_slots(layout, 1)`). The warm checkpoint budget rounds down to whole slots. If host headroom cannot hold the full intake, it shrinks toward two complete windows, `2 × (WINDOW_PAGES + row_slots)`, and one warning reports the memory needed for -full intake; on an integrated-memory disk-only host, the target already equals +full intake; on an integrated-memory host, the target already equals that two-window floor, so host headroom neither shrinks it nor emits a warning. Concurrent unique-prefix disk restores and concurrent outbound disk stores on an integrated-memory disk-only host share and serialize window allocations through diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 6016a2a03..5b11fcfde 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -373,6 +373,10 @@ pub struct AgentArgs { /// Address and port to listen on. #[arg(long, value_name = "IP:PORT", default_value = "0.0.0.0:29900")] pub listen: String, + + /// 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, } #[derive(Debug, Subcommand)] @@ -399,6 +403,9 @@ pub enum AgentCommand { /// Address and port the installed agent listens on. #[arg(long, value_name = "IP:PORT", default_value = "0.0.0.0:29900")] listen: String, + /// Prepared-model cache root passed to the installed agent service. + #[arg(long, alias = "model-cache", alias = "package-cache", value_name = "PATH")] + core_cache: Option, }, /// Remove this host's authorized controllers and pairing codes; keep its key and cache. Reset, @@ -655,11 +662,9 @@ pub struct OrbitRun { } impl OrbitRun { - /// Serving options every rank loads with. + /// Serving options every rank loads with. RoCE shape travels in Grant's dedicated fields. pub fn rank_options(&self, matches: &clap::ArgMatches) -> Vec { - let mut options = self - .serving - .rank_options(Shape::from_flags(self.roce_ring, self.roce_chain)); + let mut options = self.serving.rank_options(Shape::Mesh); // Explicit defaults must override saved values, while omitted defaults must not. if self.serving.kv_cache_limit == KvCacheLimit::Memory && matches.value_source("kv_cache_limit") diff --git a/flare-cli/src/config.rs b/flare-cli/src/config.rs index 40b0167da..f32f64681 100644 --- a/flare-cli/src/config.rs +++ b/flare-cli/src/config.rs @@ -135,6 +135,9 @@ impl Configuration { _ => {} } } + cli::Command::Agent(args) => { + args.core_cache.get_or_insert(cache); + } cli::Command::Orbit(args) => match &mut args.command { cli::OrbitCommand::Run(run) => { run.serving.hub.core_cache.get_or_insert(cache); @@ -755,4 +758,58 @@ namespace = "publisher" assert!(Configuration::parse(&format!("[prefix_cache]\nmax_age='{invalid}'")).is_err()); } } + + #[test] + fn agent_core_cache_uses_config_and_flag_override_and_orbit_omits_roce_from_serving() { + let home = Path::new("/home/test-user"); + let config = Configuration::parse("[paths]\ncore_cache = '/data/flare-cores'\n").unwrap(); + + let matches = cli::Cli::command() + .try_get_matches_from(["flare", "agent"]) + .unwrap(); + let mut parsed = cli::Cli::from_arg_matches(&matches).unwrap(); + config.apply(&mut parsed, &matches, home).unwrap(); + let cli::Command::Agent(agent) = parsed.command else { + panic!("expected agent command"); + }; + assert_eq!(agent.core_cache.as_deref(), Some(Path::new("/data/flare-cores"))); + + let matches = cli::Cli::command() + .try_get_matches_from(["flare", "agent", "--core-cache", "/override/cores"]) + .unwrap(); + let mut parsed = cli::Cli::from_arg_matches(&matches).unwrap(); + config.apply(&mut parsed, &matches, home).unwrap(); + let cli::Command::Agent(agent) = parsed.command else { + panic!("expected agent command"); + }; + assert_eq!(agent.core_cache.as_deref(), Some(Path::new("/override/cores"))); + + let matches = cli::Cli::command() + .try_get_matches_from([ + "flare", + "orbit", + "run", + "model.safetensors", + "--roce-ring", + "--max-concurrency", + "8", + ]) + .unwrap(); + let parsed = cli::Cli::from_arg_matches(&matches).unwrap(); + let cli::Command::Orbit(orbit) = parsed.command else { + panic!("expected orbit command"); + }; + let cli::OrbitCommand::Run(run) = orbit.command else { + panic!("expected orbit run"); + }; + let run_matches = matches + .subcommand_matches("orbit") + .unwrap() + .subcommand_matches("run") + .unwrap(); + let options = run.rank_options(run_matches); + assert!(run.roce_ring); + assert!(!options.iter().any(|arg| arg == "--roce-ring" || arg == "--roce-chain")); + assert!(options.iter().any(|arg| arg == "--max-concurrency")); + } } diff --git a/flare-cli/src/core_cache.rs b/flare-cli/src/core_cache.rs index ec5bb68b9..75546287d 100644 --- a/flare-cli/src/core_cache.rs +++ b/flare-cli/src/core_cache.rs @@ -231,16 +231,22 @@ impl Drop for Pinned { } } +/// 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", +]; + /// Remove a kind directory's units that nothing pins, leaving transfers in progress. pub fn evict(directory: &Path, pins: &Pins) -> Result, Failure> { let pins = pins.lock().unwrap(); let mut removed = Vec::new(); for entry in fs::read_dir(directory)? { let path = entry?.path(); - let hidden = path - .file_name() - .is_none_or(|name| name.to_string_lossy().starts_with('.')); - if !hidden && !pins.contains_key(&path) { + let name = path.file_name().and_then(|name| name.to_str()); + let hidden = name.is_none_or(|name| name.starts_with('.')); + let managed = name.is_some_and(|name| HELIOS_CACHE_DIRS.contains(&name)); + if !hidden && !managed && !pins.contains_key(&path) { let Some(_lease) = Lease::evict(&path)? else { continue; }; @@ -1925,4 +1931,29 @@ mod entry_path_tests { assert!(entry(cache, "bin", "nested/tool").is_err()); assert!(entry(cache, "bin", "tool").is_ok()); } + + #[test] + fn evict_never_removes_managed_helios_cache_subdirectories() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("cores"); + fs::create_dir_all(&root).unwrap(); + for managed in HELIOS_CACHE_DIRS { + let dir = root.join(managed); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join("sentinel"), b"keep").unwrap(); + } + let stale = root.join("old-export-123"); + fs::create_dir_all(&stale).unwrap(); + fs::write(stale.join("model.safetensors"), b"stale").unwrap(); + + let removed = evict(&root, &Pins::default()).unwrap(); + assert_eq!(removed, vec![stale.clone()]); + assert!(!stale.exists()); + for managed in HELIOS_CACHE_DIRS { + assert!( + root.join(managed).join("sentinel").is_file(), + "managed directory {managed} must survive evict" + ); + } + } } diff --git a/flare-cli/src/distribution.rs b/flare-cli/src/distribution.rs index a5f5cb95c..5c390420e 100644 --- a/flare-cli/src/distribution.rs +++ b/flare-cli/src/distribution.rs @@ -196,15 +196,28 @@ pub fn root( return Err("timed out waiting for serving ranks".into()); } match listener.accept() { - Ok((mut socket, _)) => { - configure(&socket, IO_TIMEOUT)?; - let join: Join = read(&mut socket)?; + Ok((mut socket, peer_addr)) => { + if let Err(error) = configure(&socket, IO_TIMEOUT) { + eprintln!("ignoring rendezvous probe from {peer_addr}: {error}"); + continue; + } + let join: Join = match read(&mut socket) { + Ok(join) => join, + Err(error) => { + eprintln!("ignoring stray rendezvous connection from {peer_addr}: {error}"); + continue; + } + }; if join.version != VERSION || join.rank == 0 || join.rank >= world || peers[join.rank].is_some() { - return Err("serving rank has an incompatible protocol, duplicate rank, or invalid rank".into()); + eprintln!( + "ignoring unexpected rendezvous join from {peer_addr} (version {}, rank {})", + join.version, join.rank + ); + continue; } endpoints[join.rank] = join.endpoint; configure(&socket, TIMEOUT)?; @@ -627,15 +640,20 @@ fn entry_file_name(plan: &Plan, file: &FileSpec) -> String { /// Record the state a successful full verification covered. The marker is written beside the /// immutable entry and binds the signed envelope, the primary digest, and every file's identity. -fn write_verified_marker(root: &Path, plan: &Plan, rank: usize) -> Result<(), Failure> { +pub(crate) fn write_verified_marker_for( + root: &Path, + envelope: [u8; 32], + export: &str, + rank: usize, + file_names: &[String], +) -> Result<(), Failure> { let primary_sha256 = hex_bytes(&sha256_file(&root.join("model.safetensors"))?); - let mut files = Vec::with_capacity(plan.files.len()); - for file in &plan.files { - let name = entry_file_name(plan, file); - let metadata = fs::metadata(root.join(&name)).map_err(|e| e.to_string())?; + let mut files = Vec::with_capacity(file_names.len()); + for name in file_names { + let metadata = fs::metadata(root.join(name)).map_err(|e| e.to_string())?; let (inode, device) = inode_device(&metadata); files.push(VerifiedFile { - name, + name: name.clone(), size: metadata.len(), modified_ns: modified_ns(&metadata), changed_ns: changed_ns(&metadata), @@ -645,8 +663,8 @@ fn write_verified_marker(root: &Path, plan: &Plan, rank: usize) -> Result<(), Fa } let marker = VerifiedMarker { version: 2, - envelope: hex_bytes(&plan.expected_envelope), - export: plan.export.clone(), + envelope: hex_bytes(&envelope), + export: export.to_owned(), rank, primary_sha256, files, @@ -672,6 +690,15 @@ fn write_verified_marker(root: &Path, plan: &Plan, rank: usize) -> Result<(), Fa Ok(()) } +fn write_verified_marker(root: &Path, plan: &Plan, rank: usize) -> Result<(), Failure> { + let names: Vec = plan + .files + .iter() + .map(|file| entry_file_name(plan, file)) + .collect(); + write_verified_marker_for(root, plan.expected_envelope, &plan.export, rank, &names) +} + /// True when the entry still matches the state its last full verification covered. fn verified_marker_matches(root: &Path, plan: &Plan, rank: usize) -> bool { let Ok(bytes) = fs::read(root.join(VERIFIED_MARKER)) else { @@ -828,6 +855,7 @@ fn receive_rank( fs::rename(&source, &destination).map_err(|e| e.to_string())?; } let _ = fs::remove_dir_all(staging_dir.join("cores")); + let _ = fs::remove_dir_all(staging_dir.join("blobs")); let path = staging_dir.join("model.safetensors"); let verify = progress.phase("Verify rank core", Some(plan_bytes(plan))); verify_plan(&path, plan, rank, Some(&verify))?; diff --git a/flare-cli/src/doctor.rs b/flare-cli/src/doctor.rs index fac6b6563..9cb313ba6 100644 --- a/flare-cli/src/doctor.rs +++ b/flare-cli/src/doctor.rs @@ -402,68 +402,28 @@ pub(crate) fn format_run_check_error(failed: &[Check]) -> String { /// the first non-NVLink pair. Returns `None` when NVML cannot be loaded or queried. #[cfg(target_os = "linux")] fn all_pairs_nvlink_by_pci_bdfs(gpu_bdfs: &[String]) -> Option { - use std::ffi::{CString, c_char, c_int, c_uint, c_void}; - - type Device = *mut c_void; - const NVML_P2P_CAPS_INDEX_NVLINK: c_uint = 2; - const NVML_P2P_STATUS_OK: c_uint = 0; + use flare_helios::nvml::{Nvml, P2P_CAPS_INDEX_NVLINK, P2P_STATUS_OK}; + use std::ffi::CString; if gpu_bdfs.len() <= 1 { return Some(false); } - // SAFETY: Only the system NVML library is loaded and kept alive for the duration of this call. - let library = unsafe { libloading::Library::new("libnvidia-ml.so.1") }.ok()?; - // SAFETY: Function signatures match nvml.h; shutdown balances init before library drop. - unsafe { - let init = library - .get:: c_int>(b"nvmlInit_v2\0") - .ok()?; - let shutdown = library - .get:: c_int>(b"nvmlShutdown\0") - .ok()?; - let get_by_pci = library - .get:: c_int>( - b"nvmlDeviceGetHandleByPciBusId_v2\0", - ) - .ok()?; - let get_p2p = library - .get:: c_int>( - b"nvmlDeviceGetP2PStatus\0", - ) - .ok()?; - if init() != 0 { - return None; - } - let result = (|| -> Option { - let mut handles = Vec::with_capacity(gpu_bdfs.len()); - for bdf in gpu_bdfs { - let c_bdf = CString::new(bdf.as_str()).ok()?; - let mut device: Device = std::ptr::null_mut(); - if get_by_pci(c_bdf.as_ptr(), &mut device) != 0 { - return None; - } - handles.push(device); - } - for i in 0..handles.len() { - for j in (i + 1)..handles.len() { - let mut status: c_uint = 0; - if get_p2p( - handles[i], - handles[j], - NVML_P2P_CAPS_INDEX_NVLINK, - &mut status, - ) != 0 - || status != NVML_P2P_STATUS_OK - { - return Some(false); - } - } + let nvml = Nvml::load().ok()?; + let mut handles = Vec::with_capacity(gpu_bdfs.len()); + for bdf in gpu_bdfs { + let c_bdf = CString::new(bdf.as_str()).ok()?; + let device = nvml.device_by_pci_bus_id(&c_bdf).ok()?; + handles.push(device); + } + for i in 0..handles.len() { + for j in (i + 1)..handles.len() { + let status = nvml.device_p2p_status(handles[i], handles[j], P2P_CAPS_INDEX_NVLINK)?; + if status != Ok(P2P_STATUS_OK) { + return Some(false); } - Some(true) - })(); - let _ = shutdown(); - result + } } + Some(true) } /// Render a human-readable `flare doctor` report into `canvas`. @@ -1236,23 +1196,8 @@ fn probe_linux_gpus(requested: &[i32], inherited: Option<&str>) -> Result) -> Result { - use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void}; - - type Device = *mut c_void; - - #[repr(C)] - struct PciInfo { - _bus_id_legacy: [c_char; 16], - _domain: c_uint, - _bus: c_uint, - _device: c_uint, - _device_id: c_uint, - _subsystem_id: c_uint, - bus_id: [c_char; 32], - } - - const NVML_P2P_CAPS_INDEX_NVLINK: c_uint = 2; - const NVML_P2P_STATUS_OK: c_uint = 0; + use flare_helios::nvml::{Device, Nvml, P2P_CAPS_INDEX_NVLINK, P2P_STATUS_OK}; + use std::ffi::CString; // Resolve explicit --gpus or inherited CUDA_VISIBLE_DEVICES before loading NVML. let explicit_selection: Option> = if !requested.is_empty() { @@ -1274,201 +1219,120 @@ fn probe_nvml_gpus(requested: &[i32], inherited: Option<&str>) -> Result c_int>(b"nvmlInit_v2\0")?; - let shutdown = library.get:: c_int>(b"nvmlShutdown\0")?; - let code = init(); - if code != 0 { - return Err(format!("nvmlInit_v2 failed with NVML error {code}").into()); - } - let result = (|| -> Result { - let get_count = library - .get:: c_int>(b"nvmlDeviceGetCount_v2\0")?; - let get_by_index = library.get:: c_int>( - b"nvmlDeviceGetHandleByIndex_v2\0", - )?; - let get_by_uuid = library - .get:: c_int>( - b"nvmlDeviceGetHandleByUUID\0", - )?; - let get_name = library - .get:: c_int>( - b"nvmlDeviceGetName\0", - )?; - let get_uuid = library - .get:: c_int>( - b"nvmlDeviceGetUUID\0", - )?; - let get_pci = library.get:: c_int>( - b"nvmlDeviceGetPciInfo_v3\0", - )?; - let get_p2p = library - .get:: c_int>( - b"nvmlDeviceGetP2PStatus\0", - ) - .ok(); - - let mut total: c_uint = 0; - let code = get_count(&mut total); - if code != 0 { - return Err(format!("nvmlDeviceGetCount_v2 failed with NVML error {code}").into()); - } - - let mut handles: Vec<(u32, Device)> = Vec::new(); - if let Some(entries) = explicit_selection { - // Build UUID lookup table only if a shortened UUID prefix is encountered. - let mut all_uuids: Option> = None; - for (visible_idx, entry) in entries.iter().enumerate() { - let mut device: Device = std::ptr::null_mut(); - let nvml_idx = if let Ok(index) = entry.parse::() { - let code = get_by_index(index, &mut device); - if code != 0 { - return Err(format!( - "GPU {index} is unavailable (nvmlDeviceGetHandleByIndex_v2 error {code})" - ) - .into()); - } - index - } else if entry.len() == 40 { - let c_uuid = CString::new(entry.as_str())?; - let code = get_by_uuid(c_uuid.as_ptr(), &mut device); - if code != 0 { - return Err(format!( - "GPU {entry} is unavailable (nvmlDeviceGetHandleByUUID error {code})" - ) - .into()); - } - visible_idx as u32 - } else { - let list = match all_uuids.as_ref() { - Some(list) => list, - None => { - let mut list = Vec::with_capacity(total as usize); - for idx in 0..total { - let mut candidate: Device = std::ptr::null_mut(); - if get_by_index(idx, &mut candidate) == 0 { - let mut buf = [0 as c_char; 96]; - if get_uuid(candidate, buf.as_mut_ptr(), 96) == 0 { - let uuid = CStr::from_ptr(buf.as_ptr()) - .to_string_lossy() - .into_owned(); - list.push((idx, uuid, candidate)); - } - } - } - all_uuids.insert(list) - } - }; - let matches: Vec<_> = list - .iter() - .filter(|(_, uuid, _)| uuid.starts_with(entry.as_str())) - .collect(); - let [matched] = matches.as_slice() else { - return Err(format!( - "CUDA_VISIBLE_DEVICES entry {entry:?} does not uniquely identify one GPU" - ) - .into()); - }; - device = matched.2; - matched.0 - }; - handles.push((nvml_idx, device)); - } + let nvml = Nvml::load()?; + let total = nvml + .device_count() + .map_err(|code| format!("nvmlDeviceGetCount_v2 failed with NVML error {code}"))?; + + let mut handles: Vec<(u32, Device)> = Vec::new(); + if let Some(entries) = explicit_selection { + // Build UUID lookup table only if a shortened UUID prefix is encountered. + let mut all_uuids: Option> = None; + for (visible_idx, entry) in entries.iter().enumerate() { + let (nvml_idx, device) = if let Ok(index) = entry.parse::() { + let device = nvml.device_by_index(index).map_err(|code| { + format!("GPU {index} is unavailable (nvmlDeviceGetHandleByIndex_v2 error {code})") + })?; + (index, device) + } else if entry.len() == 40 { + let c_uuid = CString::new(entry.as_str())?; + let device = nvml.device_by_uuid(&c_uuid).map_err(|code| { + format!("GPU {entry} is unavailable (nvmlDeviceGetHandleByUUID error {code})") + })?; + let nvml_idx = nvml + .device_index(device) + .and_then(|res| res.ok()) + .unwrap_or(visible_idx as u32); + (nvml_idx, device) } else { - for index in 0..total { - let mut device: Device = std::ptr::null_mut(); - let code = get_by_index(index, &mut device); - if code != 0 { - return Err(format!( - "nvmlDeviceGetHandleByIndex_v2({index}) failed with NVML error {code}" - ) - .into()); + let list = match all_uuids.as_ref() { + Some(list) => list, + None => { + let mut list = Vec::with_capacity(total as usize); + for idx in 0..total { + if let Ok(candidate) = nvml.device_by_index(idx) + && let Ok(uuid) = nvml.device_uuid(candidate) + { + list.push((idx, uuid, candidate)); + } + } + all_uuids.insert(list) } - handles.push((index, device)); - } - } - - let mut gpus = Vec::with_capacity(handles.len()); - for &(index, device) in &handles { - let mut name_buf = [0 as c_char; 256]; - let name = if get_name(device, name_buf.as_mut_ptr(), name_buf.len() as c_uint) == 0 - { - CStr::from_ptr(name_buf.as_ptr()) - .to_string_lossy() - .into_owned() - } else { - format!("NVIDIA GPU {index}") - }; - let mut uuid_buf = [0 as c_char; 96]; - let uuid = if get_uuid(device, uuid_buf.as_mut_ptr(), uuid_buf.len() as c_uint) == 0 - { - CStr::from_ptr(uuid_buf.as_ptr()) - .to_string_lossy() - .into_owned() - } else { - String::new() }; - let mut pci: PciInfo = std::mem::zeroed(); - let code = get_pci(device, &mut pci); - if code != 0 { + let matches: Vec<_> = list + .iter() + .filter(|(_, uuid, _)| uuid.starts_with(entry.as_str())) + .collect(); + let [matched] = matches.as_slice() else { return Err(format!( - "nvmlDeviceGetPciInfo_v3({index}) failed with NVML error {code}" + "CUDA_VISIBLE_DEVICES entry {entry:?} does not uniquely identify one GPU" ) .into()); - } - let raw_bus_id = CStr::from_ptr(pci.bus_id.as_ptr()).to_string_lossy(); - let pci_bus_id = normalize_pci_bdf(&raw_bus_id) - .unwrap_or_else(|| raw_bus_id.to_ascii_lowercase()); - gpus.push(InspectedGpu { - index, - name, - pci_bus_id, - uuid, - }); - } - - let interconnect = if handles.is_empty() { - Interconnect::NoGpus - } else if handles.len() == 1 { - Interconnect::SingleGpu - } else if let Some(get_p2p) = get_p2p { - let mut nvlink_pairs = 0usize; - let mut pcie_pairs = 0usize; - for i in 0..handles.len() { - for j in (i + 1)..handles.len() { - let mut status: c_uint = 0; - let code = - get_p2p(handles[i].1, handles[j].1, NVML_P2P_CAPS_INDEX_NVLINK, &mut status); - if code == 0 && status == NVML_P2P_STATUS_OK { - nvlink_pairs += 1; - } else { - pcie_pairs += 1; - } - } - } - match (nvlink_pairs > 0, pcie_pairs > 0) { - (true, false) => Interconnect::NvLink, - (true, true) => Interconnect::Mixed, - (false, _) => Interconnect::Pcie, - } - } else { - Interconnect::Pcie + }; + (matched.0, matched.2) }; + handles.push((nvml_idx, device)); + } + } else { + for index in 0..total { + let device = nvml.device_by_index(index).map_err(|code| { + format!("nvmlDeviceGetHandleByIndex_v2({index}) failed with NVML error {code}") + })?; + handles.push((index, device)); + } + } - Ok(GpuProbe { - gpus, - interconnect, - notes: Vec::new(), - }) - })(); - let _ = shutdown(); - result + let mut gpus = Vec::with_capacity(handles.len()); + for &(index, device) in &handles { + let name = nvml + .device_name(device) + .unwrap_or_else(|_| format!("NVIDIA GPU {index}")); + let uuid = nvml.device_uuid(device).unwrap_or_default(); + let pci = nvml.device_pci_info(device).map_err(|code| { + format!("nvmlDeviceGetPciInfo_v3({index}) failed with NVML error {code}") + })?; + let raw_bus_id = pci.bus_id_lossy(); + let pci_bus_id = + normalize_pci_bdf(&raw_bus_id).unwrap_or_else(|| raw_bus_id.to_ascii_lowercase()); + gpus.push(InspectedGpu { + index, + name, + pci_bus_id, + uuid, + }); } + + let interconnect = if handles.is_empty() { + Interconnect::NoGpus + } else if handles.len() == 1 { + Interconnect::SingleGpu + } else { + let mut nvlink_pairs = 0usize; + let mut pcie_pairs = 0usize; + for i in 0..handles.len() { + for j in (i + 1)..handles.len() { + let is_nvlink = nvml + .device_p2p_status(handles[i].1, handles[j].1, P2P_CAPS_INDEX_NVLINK) + .is_some_and(|status| status == Ok(P2P_STATUS_OK)); + if is_nvlink { + nvlink_pairs += 1; + } else { + pcie_pairs += 1; + } + } + } + match (nvlink_pairs > 0, pcie_pairs > 0) { + (true, false) => Interconnect::NvLink, + (true, true) => Interconnect::Mixed, + (false, _) => Interconnect::Pcie, + } + }; + + Ok(GpuProbe { + gpus, + interconnect, + notes: Vec::new(), + }) } #[cfg(target_os = "linux")] diff --git a/flare-cli/src/fabric_transport.rs b/flare-cli/src/fabric_transport.rs index cd95bfca5..9c091be00 100644 --- a/flare-cli/src/fabric_transport.rs +++ b/flare-cli/src/fabric_transport.rs @@ -235,24 +235,42 @@ fn relay( held: &Mutex, slots: &Mutex>, ) -> Result<(), Failure> { - socket.set_nodelay(true)?; - socket.set_read_timeout(Some(Duration::from_secs(30)))?; - let (destination, stream) = header(&mut socket, config)?; - let path = topology.path(0, destination)?; - let index = path - .iter() - .position(|&r| r == config.rank) - .ok_or("rank is outside the transfer path")?; - let downstream = *path - .get(index + 1) - .ok_or("destination cannot relay its own transfer")?; - let (from, to) = topology.hop(downstream, config.rank, stream)?; - if socket.local_addr()? != SocketAddr::V4(to) || socket.peer_addr()?.ip() != from { - return Err("preparation channel did not use its fabric endpoints".into()); + let Ok(()) = socket.set_nodelay(true) else { + return Ok(()); + }; + let Ok(()) = socket.set_read_timeout(Some(Duration::from_secs(5))) else { + return Ok(()); + }; + // Stray LAN probes on the wildcard listener fail header or fabric-endpoint validation; + // drop them quietly without aborting active transfers. + let Ok((destination, stream)) = header(&mut socket, config) else { + return Ok(()); + }; + let Ok(path) = topology.path(0, destination) else { + return Ok(()); + }; + let Some(index) = path.iter().position(|&r| r == config.rank) else { + return Ok(()); + }; + let Some(&downstream) = path.get(index + 1) else { + return Ok(()); + }; + let Ok((from, to)) = topology.hop(downstream, config.rank, stream) else { + return Ok(()); + }; + let Ok(local_addr) = socket.local_addr() else { + return Ok(()); + }; + let Ok(peer_addr) = socket.peer_addr() else { + return Ok(()); + }; + if local_addr != SocketAddr::V4(to) || peer_addr.ip() != from { + return Ok(()); } if !slots.lock().unwrap().insert((destination, stream)) { - return Err("duplicate preparation channel".into()); + return Ok(()); } + held.lock().unwrap().tcp(&socket)?; socket.set_read_timeout(None)?; let upstream = upstream(config, topology, destination, stream, held)?; bridge(&socket, &upstream, &socket, &upstream, || { @@ -330,30 +348,40 @@ fn serve( let slots = Mutex::new(HashSet::new()); thread::scope(|scope| -> Result<(), Failure> { let (sender, receiver) = mpsc::channel(); - let mut workers = Vec::new(); + let mut workers: Vec> = Vec::new(); let mut error = None; + let max_workers = config.world * config.streams + 16; while !stopping.load(Ordering::Acquire) { if let Ok(Err(failure)) = receiver.try_recv() { error = Some(failure); break; } - // At most one local or relayed channel per destination and stream, plus one - // pending handshake. Retained shutdown handles have the same finite bound. - if workers.len() >= config.world * config.streams + 1 { - error = Some("preparation channel capacity exceeded".into()); + let mut idx = 0; + while idx < workers.len() { + if workers[idx].is_finished() { + let worker = workers.swap_remove(idx); + if worker.join().is_err() { + error = Some("preparation relay panicked".into()); + break; + } + } else { + idx += 1; + } + } + if error.is_some() { break; } match network.accept() { Ok((socket, _)) => { - if let Err(e) = held.lock().unwrap().tcp(&socket) { - error = Some(e.into()); - break; + if workers.len() >= max_workers { + drop(socket); + } else { + let (config, topology, held, slots, sender) = + (&config, &topology, &held, &slots, sender.clone()); + workers.push(scope.spawn(move || { + let _ = sender.send(relay(socket, config, topology, held, slots)); + })); } - let (config, topology, held, slots, sender) = - (&config, &topology, &held, &slots, sender.clone()); - workers.push(scope.spawn(move || { - let _ = sender.send(relay(socket, config, topology, held, slots)); - })); } Err(e) if e.kind() == io::ErrorKind::WouldBlock => {} Err(e) => { @@ -364,6 +392,10 @@ fn serve( if let Some(local_listener) = &local_listener { match local_listener.accept() { Ok((socket, _)) => { + if workers.len() >= max_workers { + error = Some("preparation channel capacity exceeded".into()); + break; + } match socket.try_clone() { Ok(copy) => held.lock().unwrap().local.push(copy), Err(e) => { @@ -602,4 +634,56 @@ mod tests { .contains("rank and stream slots") ); } + + #[test] + fn stray_lan_probes_do_not_abort_active_relay() { + let source = TcpListener::bind("127.0.0.1:0").unwrap(); + let network = TcpListener::bind("127.0.0.1:0").unwrap(); + let network_addr = network.local_addr().unwrap(); + let peer = TcpListener::bind("127.0.0.1:0").unwrap(); + network.set_nonblocking(true).unwrap(); + let topology = Topology::plan( + &vec![b"a 127.0.0.1/8 -\n".to_vec(); 2], + &[network_addr.port(), peer.local_addr().unwrap().port()], + false, + ) + .unwrap(); + let stopping = Arc::new(AtomicBool::new(false)); + let stop_worker = stopping.clone(); + let config = Config { + rank: 0, + world: 2, + ring: false, + chain: false, + streams: 1, + source_port: source.local_addr().unwrap().port(), + }; + let worker = thread::spawn(move || serve(&config, &topology, network, None, &stop_worker)); + + // Send several stray LAN probes (invalid header, immediate EOF) before the real peer. + for payload in [&b"GET / HTTP/1.1\r\n"[..], &b""[..], &[0xff; 8][..]] { + let mut probe = TcpStream::connect(network_addr).unwrap(); + let _ = probe.write_all(payload); + let _ = probe.shutdown(Shutdown::Both); + } + // Real peer must still connect and transfer cleanly. + let mut client = TcpStream::connect(network_addr).unwrap(); + client + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + client.write_all(&1u32.to_le_bytes()).unwrap(); + client.write_all(&0u32.to_le_bytes()).unwrap(); + let (mut upstream, _) = source.accept().unwrap(); + upstream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + upstream.read_exact(&mut [0; 8]).unwrap(); + upstream.write_all(&[1, 2, 3, 4]).unwrap(); + let mut response = [0; 4]; + client.read_exact(&mut response).unwrap(); + assert_eq!(response, [1, 2, 3, 4]); + client.shutdown(Shutdown::Both).unwrap(); + stopping.store(true, Ordering::Release); + worker.join().unwrap().unwrap(); + } } diff --git a/flare-cli/src/launch.rs b/flare-cli/src/launch.rs index 4f888a676..99950993d 100644 --- a/flare-cli/src/launch.rs +++ b/flare-cli/src/launch.rs @@ -115,23 +115,27 @@ impl Peers { args.rank = Some(0); let issued = orbit::now(); let group = format!("manual-{}-{}", issued, orbit::hex(&orbit::random(4)?)); - let mut serving = args - .serving - .rank_options(Shape::from_flags(args.roce_ring, args.roce_chain)); + let mut serving = args.serving.rank_options(Shape::Mesh); if args.hub.offline { serving.push("--offline".into()); } if args.stage_only { serving.push("--stage-only".into()); } + let primary = if path.is_dir() { + path.join("model.safetensors") + } else { + path.to_path_buf() + }; let grant = Grant { group: group.clone(), name: String::new(), core: Core { export, - length: File::open(path)?.metadata()?.len(), + length: File::open(&primary)?.metadata()?.len(), files: vec![ - path.file_name() + primary + .file_name() .and_then(|s| s.to_str()) .ok_or("core filename must be UTF-8")? .to_owned(), diff --git a/flare-cli/src/main.rs b/flare-cli/src/main.rs index c66489c99..a81da4431 100644 --- a/flare-cli/src/main.rs +++ b/flare-cli/src/main.rs @@ -137,6 +137,9 @@ fn run() -> Result> { &agent_args.listen, orbit::store::AgentDir::new(orbit::store::AgentDir::default_root()), orbit::cache::default_root(), + agent_args + .core_cache + .unwrap_or_else(|| cache_support::default_core_root(&home)), configuration .hub_cache(&home) .unwrap_or_else(|| cache_support::hub_cache_default(&home)), @@ -145,7 +148,13 @@ fn run() -> Result> { join_code, accept_first, listen, - }) => orbit::agent::install(&listen, join_code.as_deref(), accept_first), + core_cache, + }) => orbit::agent::install( + &listen, + join_code.as_deref(), + accept_first, + core_cache.as_deref(), + ), Some(cli::AgentCommand::Pair { hosts, code, @@ -439,7 +448,11 @@ fn load_core( let entry = hub::download( text, &hub_options, - args.gpus.len(), + if !args.hosts.is_empty() { + args.hosts.len() + 1 + } else { + args.gpus.len() + }, &args.publisher_keys, args.trust_store.as_deref(), &[], diff --git a/flare-cli/src/orbit/agent.rs b/flare-cli/src/orbit/agent.rs index 642c08fc4..ce1f66bc7 100644 --- a/flare-cli/src/orbit/agent.rs +++ b/flare-cli/src/orbit/agent.rs @@ -16,17 +16,20 @@ //! Request bodies are JSON except PUT, whose body is a little-endian `u32` header length, the //! JSON header, and the transferred bytes in range order. -use std::collections::VecDeque; +use std::collections::{BTreeMap, VecDeque}; use std::fs::{self, File}; use std::io::{BufRead, BufReader, Read}; use std::net::{TcpListener, TcpStream}; use std::os::unix::fs::PermissionsExt; +use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use std::sync::{Arc, Mutex, mpsc}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, mpsc}; use std::thread; use std::time::{Duration, Instant}; +use flare_helios::core::cache::{self as helios_cache, Entry as CacheEntry, Root as CacheRoot}; use flare_helios::runtime_core::{Publisher, VerifiedCore}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -91,13 +94,15 @@ struct StorageEstimate { core_cache_free: Option, } -/// Replace any controller-supplied value with this node's configured hub cache. -/// The field is host-local and serde-skipped on the wire. +/// Replace any controller-supplied cache values with this node's configured caches. +/// Both fields are host-local and never controlled by a remote caller. fn node_download_options( hub_cache: Option<&Path>, + core_cache: &Path, mut options: crate::cli::HubOptions, ) -> crate::cli::HubOptions { options.hub_cache = hub_cache.map(Path::to_owned); + options.core_cache = Some(core_cache.to_owned()); options } @@ -283,9 +288,49 @@ struct Log { subscribers: Vec>, /// Cache pins held while the rank runs. pins: Option, + /// Managed `helios::core::cache::Root` lease held while the rank runs. + core_lease: Option, } const RETAINED_BYTES: usize = 64 << 10; +/// Maximum concurrent unauthenticated sessions awaiting handshake or authorization. +/// Sized above a multi-host burst of parallel fabric transfers (e.g. 64 streams per peer) while +/// still bounding pre-auth OS threads against connection floods. +const MAX_PREAUTH_SESSIONS: usize = 256; +/// Maximum total concurrent agent session threads (up to 16 ranks x 64 fabric streams plus control). +const MAX_SESSIONS: usize = 1024; +/// Maximum time the rank reaper waits for stdout/stderr forwarders to reach EOF after the child +/// exits before releasing GPUs, pins, leases, and notifying attached subscribers. +const FORWARDER_DRAIN_TIMEOUT: Duration = Duration::from_secs(2); + +/// Bounded slot counter released on drop. +struct SlotGuard(Arc); + +impl SlotGuard { + fn try_acquire(counter: &Arc, limit: usize) -> Option { + let mut current = counter.load(Ordering::Acquire); + loop { + if current >= limit { + return None; + } + match counter.compare_exchange_weak( + current, + current + 1, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return Some(Self(counter.clone())), + Err(actual) => current = actual, + } + } + } +} + +impl Drop for SlotGuard { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::AcqRel); + } +} /// A rank process this agent started and supervises. pub struct Group { @@ -296,6 +341,8 @@ pub struct Group { /// UUIDs of the GPUs the rank holds while it runs. pub gpus: Vec, pub pid: i32, + /// Set immediately after `child.wait()` reaps the process so STOP cannot signal a reused PID. + exited: AtomicBool, /// Rank zero's metrics URL, derived from its HTTP bind options; None for a peer rank. pub metrics_url: Option, started: Instant, @@ -324,6 +371,7 @@ impl Group { .retain(|s| s.send(Event::Exit(code)).is_ok()); log.subscribers.clear(); log.pins = None; + log.core_lease = None; } pub fn running(&self) -> bool { @@ -423,7 +471,11 @@ fn verify_core(primary: &Path, rank: Option, publisher: &Publisher) -> Re pub struct Agent { pub dir: AgentDir, pub key: Key, + /// Agent auxiliary cache (`bin/` executable overrides, `publishers/` profiles). pub cache: PathBuf, + /// Managed `helios::core::cache::Root` shared with `flare run`, `flare download`, and + /// `flare models`. + pub core_cache: PathBuf, pub name: String, /// Host-local Hugging Face cache from this agent's configuration; never from a controller. hub_cache: Option, @@ -443,6 +495,156 @@ pub struct Agent { /// How often the sampler reads GPUs and scrapes running rank-zero groups. const SAMPLE_PERIOD: Duration = Duration::from_secs(1); +/// Parse `--rank` into `(, R)` when a directory name follows that form. +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::().is_err() { + return None; + } + Some((export, rank)) +} + +/// Parse `-rank` selector (written by `distribution::receive_rank`) into `(, R)`. +fn parse_rank_selector(selector: &str) -> Option<(&str, usize)> { + let (export, rank_str) = selector.rsplit_once("-rank")?; + if export.is_empty() { + return None; + } + let rank: usize = rank_str.parse().ok()?; + Some((export, rank)) +} + +/// Build a valid `helios::core::cache` entry ID (`1..=128` chars in `[A-Za-z0-9._+-]`). +fn orbit_entry_id(platform: &str, tensor_parallel: u32, directory: &str) -> String { + let sanitized: String = directory + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-') { + c + } else { + '-' + } + }) + .collect(); + let trimmed = sanitized.trim_start_matches('.'); + let raw = if !platform.is_empty() && tensor_parallel > 0 { + format!("{platform}-tp{tensor_parallel}-{trimmed}") + } else if !trimmed.is_empty() { + format!("orbit-{trimmed}") + } else { + "orbit-core".to_owned() + }; + let mut id: String = raw.chars().take(112).collect(); + if id.is_empty() || id.starts_with('.') { + id = "orbit-core".to_owned(); + } + id +} + +/// Move all non-hidden files from `source_root` into `dest_root`, renaming `primary_name` at the +/// root to `model.safetensors`, and return the sorted entry-relative filenames. +fn move_staged_tree( + source_root: &Path, + relative: &Path, + dest_root: &Path, + primary_name: &str, + files: &mut Vec, +) -> Result<(), Failure> { + let current = if relative.as_os_str().is_empty() { + source_root.to_path_buf() + } else { + source_root.join(relative) + }; + for item in fs::read_dir(¤t)? { + let item = item?; + let name = item.file_name(); + let name_str = name.to_string_lossy(); + if name_str.starts_with('.') { + continue; + } + let rel = if relative.as_os_str().is_empty() { + PathBuf::from(&name) + } else { + relative.join(&name) + }; + let src = item.path(); + if src.is_dir() { + move_staged_tree(source_root, &rel, dest_root, primary_name, files)?; + } else if src.is_file() { + let dest_rel = if relative.as_os_str().is_empty() && name_str == primary_name { + PathBuf::from("model.safetensors") + } else { + rel + }; + let dst = dest_root.join(&dest_rel); + if let Some(parent) = dst.parent() { + fs::create_dir_all(parent)?; + } + fs::rename(&src, &dst)?; + files.push(dest_rel.to_string_lossy().into_owned()); + } + } + Ok(()) +} + +/// Collect regular non-hidden file entries and total allocated disk bytes under `root`. +fn entry_inventory( + root: &Path, + relative: &Path, + files: &mut Vec, + bytes: &mut u64, +) { + use std::os::unix::fs::MetadataExt; + let current = if relative.as_os_str().is_empty() { + root.to_path_buf() + } else { + root.join(relative) + }; + let Ok(entries) = fs::read_dir(¤t) else { + return; + }; + let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); + paths.sort(); + for path in paths { + let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned()) else { + continue; + }; + let Ok(metadata) = fs::metadata(&path) else { + continue; + }; + if metadata.is_dir() { + if !name.starts_with('.') { + let rel = if relative.as_os_str().is_empty() { + PathBuf::from(&name) + } else { + relative.join(&name) + }; + entry_inventory(root, &rel, files, bytes); + } + continue; + } + *bytes += metadata.blocks() * 512; + if !name.starts_with('.') { + let display = if relative.as_os_str().is_empty() { + name + } else { + relative.join(&name).to_string_lossy().into_owned() + }; + files.push(json!({"name": display, "size": metadata.len()})); + } + } +} + +fn entry_file_path(entry: &CacheEntry, primary: &str, name: &str) -> PathBuf { + if name == primary { + entry.directory().join("model.safetensors") + } else { + entry.directory().join(name) + } +} + impl Agent { pub fn new(dir: AgentDir, cache: PathBuf) -> Result { Self::with_fakes(dir, cache, Box::new(verify_core), Box::new(gpu::enumerate)) @@ -460,11 +662,12 @@ impl Agent { for directory in ["bin", "publishers"] { fs::create_dir_all(cache.join(directory))?; } - fs::create_dir_all(cache::cores_directory(&cache))?; - Ok(Self { + let core_cache = cache::cores_directory(&cache); + let agent = Self { dir, key, cache, + core_cache, name: super::hostname(), hub_cache: None, executable: std::env::current_exe()?, @@ -475,7 +678,167 @@ impl Agent { sampled_gpus: Mutex::new(None), #[cfg(test)] fabric_endpoints: None, - }) + }; + agent.init_core_cache()?; + Ok(agent) + } + + /// Override the managed `helios::core::cache::Root` from `--core-cache` or `[paths].core_cache`. + pub fn with_core_cache(mut self, core_cache: PathBuf) -> Result { + self.core_cache = core_cache; + self.init_core_cache()?; + Ok(self) + } + + fn init_core_cache(&self) -> Result<(), Failure> { + let _ = self.core_root()?; + fs::create_dir_all(cache::cores_directory(&self.staging_root()))?; + Ok(()) + } + + /// Isolated staging area on the same filesystem as `core_cache` for in-flight `PUT` and + /// `TRANSFER` assembly before verification and publication into `helios::core::cache::Root`. + pub(crate) fn staging_root(&self) -> PathBuf { + self.core_cache.join("staging").join("orbit") + } + + pub(crate) fn core_root(&self) -> Result { + CacheRoot::open(&self.core_cache).map_err(|e| Failure::from(e.to_string())) + } + + /// Resolve a published verified Orbit or serving-bootstrap entry in `core_cache`. + pub(crate) fn resolve_orbit_entry(&self, directory: &str) -> Result, Failure> { + let root = self.core_root()?; + if let Some((_, entry)) = root + .resolve_source_ref(&format!("orbit:{directory}")) + .map_err(|e| Failure::from(e.to_string()))? + { + return Ok(Some(entry)); + } + if let Some((export, rank)) = parse_rank_directory(directory) + && let Some((_, entry)) = root + .resolve_source_ref(&format!("{export}-rank{rank}")) + .map_err(|e| Failure::from(e.to_string()))? + { + return Ok(Some(entry)); + } + Ok(None) + } + + /// Commit a verified staged directory into `helios::core::cache::Root` and publish lookup + /// selectors shared with `distribution::receive_rank`, `orbit cores`, and placement. + fn publish_orbit_entry( + &self, + staged_dir: &Path, + grant: &Grant, + rank: usize, + directory: &str, + publisher: &Publisher, + ) -> Result { + let root = self.core_root()?; + let staged_primary = staged_dir.join(grant.primary()); + let complete = rank == 0; + let verified_meta = VerifiedCore::open( + &staged_primary, + std::slice::from_ref(publisher), + (!complete).then_some(rank), + ) + .ok(); + let (model_key, platform, tensor_parallel, envelope, real_core) = + if let Some(verified) = verified_meta { + let envelope = verified.envelope_digest(); + let (model_id, hardware, tp) = verified + .authorize_metadata(&publisher.namespace, false) + .ok() + .and_then(|auth| auth.identity().ok()) + .map(|id| (id.model, id.hardware, id.tensor_parallel)) + .unwrap_or_else(|| { + ( + if grant.name.is_empty() { + grant.core.export.clone() + } else { + grant.name.clone() + }, + String::new(), + grant.members.len() as u32, + ) + }); + let key = helios_cache::model_key(&model_id) + .unwrap_or_else(|_| "orbit".to_owned()); + (key, hardware, tp, envelope, true) + } else { + let fallback_model = if grant.name.is_empty() { + grant.core.export.as_str() + } else { + grant.name.as_str() + }; + let key = helios_cache::model_key(fallback_model) + .unwrap_or_else(|_| "orbit".to_owned()); + (key, String::new(), grant.members.len() as u32, [0u8; 32], false) + }; + + let base_id = orbit_entry_id(&platform, tensor_parallel, directory); + let staging = match root.stage_named(&model_key, &base_id) { + Ok(staging) => staging, + Err(_) => { + let suffix = hex(&super::random(4)?); + let unique = format!("{base_id}-{suffix}"); + root.stage_named(&model_key, &unique) + .map_err(|e| Failure::from(e.to_string()))? + } + }; + let mut entry_files = Vec::new(); + let move_result = move_staged_tree( + staged_dir, + Path::new(""), + staging.directory(), + grant.primary(), + &mut entry_files, + ); + if let Err(error) = move_result { + staging.abort(); + return Err(error); + } + let entry = staging.commit().map_err(|e| Failure::from(e.to_string()))?; + let _ = fs::remove_dir_all(staged_dir); + let _ = fs::write( + entry.directory().join(VERIFIED), + format!("{} {}\n", grant.primary(), grant.core.length), + ); + if real_core { + let _ = crate::distribution::write_verified_marker_for( + entry.directory(), + envelope, + &grant.core.export, + rank, + &entry_files, + ); + } + root.publish_source_ref( + &format!("orbit:{directory}"), + &grant.core.export, + &entry, + envelope, + ) + .map_err(|e| Failure::from(e.to_string()))?; + if rank > 0 { + root.publish_source_ref( + &format!("{}-rank{rank}", grant.core.export), + &grant.core.export, + &entry, + envelope, + ) + .map_err(|e| Failure::from(e.to_string()))?; + } else { + root.publish_source_ref( + &format!("{}-complete", grant.core.export), + &grant.core.export, + &entry, + envelope, + ) + .map_err(|e| Failure::from(e.to_string()))?; + } + Ok(entry) } /// Select the host-local Hugging Face cache from the agent process's own configuration. @@ -551,7 +914,7 @@ impl Agent { name: self.name.clone(), public_key: self.key.public().to_hex(), controllers_revision: self.dir.controllers()?.map_or(0, |(_, set)| set.revision), - free_bytes: free_bytes(&self.cache), + free_bytes: free_bytes(&self.core_cache), executable: Some(self.executable.clone()), download_progress: true, }) @@ -564,7 +927,7 @@ impl Agent { .is_some_and(|(_, set)| set.contains(key))) } - /// Verify a grant against this node's controllers. + /// Verify a grant against this node's controllers and reject expired grants. fn grant(&self, signed: &Value) -> Result { let signed: Signed = serde_json::from_value(signed.clone())?; let Some((_, set)) = self.dir.controllers()? else { @@ -574,6 +937,9 @@ impl Agent { if grant.members.is_empty() || grant.core.files.is_empty() { return Err("grant names no members or files".into()); } + if !grant.current(now()) { + return Err("the grant has expired".into()); + } Ok(grant) } @@ -609,48 +975,93 @@ impl Agent { } } - /// Core cache directories with their files and verification state. + /// Verified Orbit and serving-bootstrap core entries in `core_cache`. fn cores(&self) -> Vec { - use std::os::unix::fs::MetadataExt; - let mut cores = Vec::new(); - let Ok(entries) = fs::read_dir(cache::cores_directory(&self.cache)) else { - return cores; + let Ok(root) = self.core_root() else { + return Vec::new(); }; - let mut directories: Vec = entries - .filter_map(|e| e.ok().map(|e| e.path())) - .filter(|p| { - p.is_dir() - && !p - .file_name() - .is_none_or(|n| n.to_string_lossy().starts_with('.')) - }) - .collect(); - directories.sort(); - for directory in directories { - let mut files = Vec::new(); - let mut bytes = 0u64; - if let Ok(entries) = fs::read_dir(&directory) { - let mut names: Vec = - entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - names.sort(); - for path in names { - let name = path.file_name().unwrap().to_string_lossy().into_owned(); - let Ok(metadata) = fs::metadata(&path) else { - continue; - }; - bytes += metadata.blocks() * 512; - if !name.starts_with('.') { - files.push(json!({"name": name, "size": metadata.len()})); - } + let Ok(refs) = root.source_refs() else { + return Vec::new(); + }; + let mut by_name: BTreeMap = BTreeMap::new(); + let mut orbit_entries: std::collections::HashSet<(String, String)> = + std::collections::HashSet::new(); + for reference in &refs { + let Some(name) = reference.selector().strip_prefix("orbit:") else { + continue; + }; + if let Ok(Some((_, entry))) = root.resolve_source_ref_record(reference.selector()) { + orbit_entries.insert((entry.model().to_owned(), entry.id().to_owned())); + by_name.entry(name.to_owned()).or_insert(entry); + } + } + for reference in &refs { + if reference.selector().starts_with("orbit:") { + continue; + } + let Some((export, rank)) = parse_rank_selector(reference.selector()) else { + continue; + }; + if let Ok(Some((_, entry))) = root.resolve_source_ref_record(reference.selector()) { + if orbit_entries.contains(&(entry.model().to_owned(), entry.id().to_owned())) { + continue; } + let Ok(meta) = fs::metadata(entry.directory().join("model.safetensors")) else { + continue; + }; + let name = format!("{export}-{}-rank{rank}", meta.len()); + by_name.entry(name).or_insert(entry); } + } + let mut cores = Vec::with_capacity(by_name.len()); + let mut seen_names: std::collections::HashSet = std::collections::HashSet::new(); + for (name, entry) in by_name { + seen_names.insert(name.clone()); + let directory = entry.directory(); + let mut files = Vec::new(); + let mut bytes = 0u64; + entry_inventory(directory, Path::new(""), &mut files, &mut bytes); + let verified = directory.join(VERIFIED).is_file() + || directory.join(".flare-verified.json").is_file(); cores.push(json!({ - "name": directory.file_name().unwrap().to_string_lossy(), + "name": name, "files": files, - "verified": directory.join(VERIFIED).is_file(), + "verified": verified, "bytes": bytes, })); } + // Also report unverified staged directories (e.g. after PUT, before TRANSFER verification). + if let Ok(entries) = fs::read_dir(cache::cores_directory(&self.staging_root())) { + let mut staged: Vec = entries + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| { + p.is_dir() + && !p + .file_name() + .is_none_or(|n| n.to_string_lossy().starts_with('.')) + }) + .collect(); + staged.sort(); + for directory in staged { + let name = directory + .file_name() + .unwrap() + .to_string_lossy() + .into_owned(); + if seen_names.contains(&name) { + continue; + } + let mut files = Vec::new(); + let mut bytes = 0u64; + entry_inventory(&directory, Path::new(""), &mut files, &mut bytes); + cores.push(json!({ + "name": name, + "files": files, + "verified": false, + "bytes": bytes, + })); + } + } cores } } @@ -660,17 +1071,22 @@ pub fn serve( listen: &str, dir: AgentDir, cache: PathBuf, + core_cache: PathBuf, hub_cache: PathBuf, ) -> Result<(), Failure> { let listener = TcpListener::bind(listen).map_err(|e| format!("cannot listen on {listen}: {e}"))?; - let agent = Arc::new(Agent::new(dir, cache)?.with_hub_cache(Some(hub_cache))); + let agent = Arc::new( + Agent::new(dir, cache)? + .with_core_cache(core_cache)? + .with_hub_cache(Some(hub_cache)), + ); eprintln!( - "flare agent {} ({}) listening on {}; cache {}; {}", + "flare agent {} ({}) listening on {}; core cache {}; {}", agent.name, agent.key.public().fingerprint(), listener.local_addr()?, - agent.cache.display(), + agent.core_cache.display(), match agent.dir.controllers()? { Some((_, set)) => format!("controller set revision {}", set.revision), None => "unpaired".to_owned(), @@ -689,15 +1105,27 @@ pub fn serve_on(listener: TcpListener, agent: Arc) -> Result<(), Failure> } }); } + let active_sessions = Arc::new(AtomicUsize::new(0)); + let preauth_sessions = Arc::new(AtomicUsize::new(0)); for connection in listener.incoming() { let Ok(stream) = connection else { continue }; + let Some(session_guard) = SlotGuard::try_acquire(&active_sessions, MAX_SESSIONS) else { + drop(stream); + continue; + }; + let Some(preauth_guard) = SlotGuard::try_acquire(&preauth_sessions, MAX_PREAUTH_SESSIONS) + else { + drop(stream); + continue; + }; let agent = agent.clone(); thread::spawn(move || { + let _session_guard = session_guard; let peer = stream .peer_addr() .map(|a| a.to_string()) .unwrap_or_default(); - if let Err(error) = session(&agent, stream) { + if let Err(error) = session(&agent, stream, Some(preauth_guard)) { eprintln!("{peer}: {error}"); } }); @@ -705,19 +1133,35 @@ pub fn serve_on(listener: TcpListener, agent: Arc) -> Result<(), Failure> Ok(()) } -fn session(agent: &Arc, stream: TcpStream) -> Result<(), Failure> { +fn session( + agent: &Arc, + stream: TcpStream, + mut preauth_guard: Option, +) -> Result<(), Failure> { let mut session = Session::accept(stream, &agent.key)?; let hello = exchange_hello(&mut session, &agent.hello()?)?; let mut pinned = Pinned::new(&agent.pins); - // Downloads stay leased for this controller session, which is the window in + // Downloads and staged entries stay leased for this controller session, which is the window in // which its transfers read those entries, and drop when the session ends. - let mut downloads: Vec = Vec::new(); + let mut downloads: Vec = Vec::new(); + let mut timeouts_cleared = false; 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; + } let result = match tag { frame::PAIR => { let request = json_body(&mut session, length)?; @@ -725,14 +1169,14 @@ fn session(agent: &Arc, stream: TcpStream) -> Result<(), Failure> { } frame::FETCH => { let request = json_body(&mut session, length)?; - match fetch(agent, &mut session, &mut pinned, &request) { + match fetch(agent, &mut session, &mut pinned, &mut preauth_guard, &request) { Ok(()) => continue, Err(error) => Err(error), } } frame::FETCH_FABRIC => { let request = json_body(&mut session, length)?; - match fetch_fabric(agent, &mut session, &mut pinned, &request) { + match fetch_fabric(agent, &mut session, &mut pinned, &mut preauth_guard, &request) { Ok(()) => continue, Err(error) => Err(error), } @@ -751,12 +1195,12 @@ fn session(agent: &Arc, stream: TcpStream) -> Result<(), Failure> { } frame::HAVE => { let request = json_body(&mut session, length)?; - have(agent, &mut pinned, &request) + have(agent, &mut pinned, &mut downloads, &request) } frame::PUT => put(agent, &mut session, &mut pinned, length), frame::TRANSFER => { let request = json_body(&mut session, length)?; - transfer(agent, &mut pinned, &request) + transfer(agent, &mut pinned, &mut downloads, &request) } frame::RUN | frame::ATTACH => { let request = json_body(&mut session, length)?; @@ -814,8 +1258,11 @@ fn session(agent: &Arc, stream: TcpStream) -> Result<(), Failure> { frame::DOWNLOAD => { let mut request: DownloadRequest = serde_json::from_value(json_body(&mut session, length)?)?; - request.options = - node_download_options(agent.hub_cache.as_deref(), request.options); + request.options = node_download_options( + agent.hub_cache.as_deref(), + &agent.core_cache, + request.options, + ); if hello.download_progress { let storage = storage_estimate(&request.options); let counters = flare_helios::core::progress::AcquisitionProgress::new(); @@ -931,14 +1378,39 @@ fn pair( Ok(reply.to_string().into_bytes()) } -fn have(agent: &Agent, pinned: &mut Pinned, request: &Value) -> Result, Failure> { +fn have( + agent: &Agent, + pinned: &mut Pinned, + downloads: &mut Vec, + request: &Value, +) -> Result, Failure> { let size = request["size"].as_u64().ok_or("request lacks size")?; - let held = cache::have( - &agent.cache, - field(request, "kind")?, - field(request, "name")?, - size, - )?; + let kind = field(request, "kind")?; + let name = field(request, "name")?; + if matches!(kind, "core" | "package") { + if let Some((directory, file)) = name.split_once('/') + && let Some(entry) = agent.resolve_orbit_entry(directory)? + { + let direct = entry.directory().join(file); + let primary_alias = (!file.contains('/')).then(|| entry.directory().join("model.safetensors")); + let matched = fs::metadata(&direct) + .is_ok_and(|m| m.is_file() && m.len() == size) + || primary_alias.as_ref().is_some_and(|path| { + fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() == size) + }); + if matched { + downloads.push(entry); + return Ok(vec![1]); + } + } + let staging = agent.staging_root(); + let held = cache::have(&staging, kind, name, size)?; + if let Some(path) = &held { + pinned.pin(cache::unit(&staging, path)); + } + return Ok(vec![held.is_some() as u8]); + } + let held = cache::have(&agent.cache, kind, name, size)?; if let Some(path) = &held { pinned.pin(cache::unit(&agent.cache, path)); } @@ -968,13 +1440,23 @@ fn put( if cache::range_bytes(&ranges) + 4 + header_length as u64 != length { return Err("PUT length does not match its ranges".into()); } + if matches!(kind, "core" | "package") { + // Stage controller-uploaded core files in `core_cache/staging/orbit` until TRANSFER + // verifies and publishes them into `helios::core::cache::Root`. Never run flat + // `core_cache::evict` on `core_cache` or managed Helios directories. + let staging = agent.staging_root(); + let entry = cache::entry(&staging, cache::kind_directory(kind)?, name)?; + let _lease = cache::Lease::write(&cache::unit(&staging, &entry))?; + let path = cache::store(&staging, kind, name, size, &ranges, &mut body)?; + let unit = cache::unit(&staging, &path); + let _ = fs::remove_file(unit.join(VERIFIED)); + pinned.pin(unit); + return Ok(Vec::new()); + } let entry = cache::entry(&agent.cache, cache::kind_directory(kind)?, name)?; let _lease = cache::Lease::write(&cache::unit(&agent.cache, &entry))?; let path = cache::store(&agent.cache, kind, name, size, &ranges, &mut body)?; let unit = cache::unit(&agent.cache, &path); - if matches!(kind, "core" | "package") { - let _ = fs::remove_file(unit.join(VERIFIED)); - } pinned.pin(unit.clone()); for removed in cache::evict(unit.parent().unwrap(), &agent.pins)? { eprintln!("removed superseded {}", removed.display()); @@ -982,8 +1464,14 @@ fn put( Ok(Vec::new()) } -/// Fetch the files of a core from another node under a grant into the cache. -fn transfer(agent: &Agent, pinned: &mut Pinned, request: &Value) -> Result, Failure> { +/// Fetch the files of a core from another node under a grant, verify them, and publish the +/// verified entry into `helios::core::cache::Root`. +fn transfer( + agent: &Agent, + pinned: &mut Pinned, + downloads: &mut Vec, + request: &Value, +) -> Result, Failure> { let grant = agent.grant(&request["grant"])?; let rank = grant .member(&agent.key.public()) @@ -996,13 +1484,37 @@ fn transfer(agent: &Agent, pinned: &mut Pinned, request: &Value) -> Result Result Result ") ); cache::store_parallel( - &agent.cache, + &staging, &entry, size, &ranges, @@ -1088,7 +1601,7 @@ fn transfer(agent: &Agent, pinned: &mut Pinned, request: &Value) -> Result Result Result, request: &Value, ) -> Result<(), Failure> { let grant = agent.grant(&request["grant"])?; @@ -1242,9 +1746,10 @@ fn fetch_fabric( if local != std::net::SocketAddr::V4(to) || remote.ip() != std::net::IpAddr::V4(from) { return Err("fabric FETCH did not use the signed fabric interfaces".into()); } + *preauth_guard = None; session.transfer_timeout()?; if index == 0 { - return fetch(agent, session, pinned, request); + return fetch(agent, session, pinned, preauth_guard, request); } let mut upstream = fabric_upstream(agent, &grant, request, rank)?; // One encrypted record at a time; TCP backpressure bounds memory at every hop. @@ -1256,6 +1761,7 @@ fn fetch( agent: &Agent, session: &mut Session, pinned: &mut Pinned, + preauth_guard: &mut Option, request: &Value, ) -> Result<(), Failure> { let grant = agent.grant(&request["grant"])?; @@ -1266,39 +1772,60 @@ fn fetch( ) .into()); } + *preauth_guard = None; + session.transfer_timeout()?; let name = field(request, "name")?; if !grant.core.files.iter().any(|f| f == name) { return Err(format!("{name} is not a file of the grant's core").into()); } let mine = agent.key.public().to_hex(); + let mut _lease: Option = None; + let staging = agent.staging_root(); let path = match &grant.core.source { Some(source) if source.public_key == mine => Path::new(&source.path) .parent() .ok_or("source path has no directory")? .join(name), _ => { - let complete = cache::entry( - &agent.cache, - "cores", - &format!("{}/{name}", grant.complete_directory()), - )?; - if complete.is_file() { - complete + if let Some(entry) = agent.resolve_orbit_entry(&grant.complete_directory())? + && entry_file_path(&entry, grant.primary(), name).is_file() + { + let file_path = entry_file_path(&entry, grant.primary(), name); + _lease = Some(entry); + file_path + } else if let Some(rank) = grant.member(&agent.key.public()).map(|m| m.rank) + && let Some(entry) = agent.resolve_orbit_entry(&grant.cache_directory(rank))? + && entry_file_path(&entry, grant.primary(), name).is_file() + { + let file_path = entry_file_path(&entry, grant.primary(), name); + _lease = Some(entry); + file_path } else { - let rank = grant - .member(&agent.key.public()) - .map(|m| m.rank) - .ok_or("this node holds no copy of the core")?; - cache::entry( - &agent.cache, + let complete = cache::entry( + &staging, "cores", - &format!("{}/{name}", grant.cache_directory(rank)), - )? + &format!("{}/{name}", grant.complete_directory()), + )?; + if complete.is_file() { + complete + } else { + let rank = grant + .member(&agent.key.public()) + .map(|m| m.rank) + .ok_or("this node holds no copy of the core")?; + cache::entry( + &staging, + "cores", + &format!("{}/{name}", grant.cache_directory(rank)), + )? + } } } }; let file = File::open(&path).map_err(|e| format!("cannot open {}: {e}", path.display()))?; - pinned.pin(cache::unit(&agent.cache, &path)); + if _lease.is_none() { + pinned.pin(cache::unit(&staging, &path)); + } let size = file.metadata()?.len(); let ranges = cache::ranges_from_json(size, request.get("ranges"))?; let mut reader = cache::RangeReader::new(&file, &ranges); @@ -1368,9 +1895,6 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { if member.public_key != mine.to_hex() { return Err(format!("the grant names another node at rank {rank}").into()); } - if !grant.current(now()) { - return Err("the grant has expired".into()); - } let mut pins = Pinned::new(&agent.pins); let binary = if request["binary"].is_null() { agent.executable.clone() @@ -1385,20 +1909,6 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { }; let publisher: Publisher = serde_json::from_value(request["publisher"].clone())?; publisher.validate().map_err(|e| e.to_string())?; - let primary = grant.primary(); - let core = match &grant.core.source { - Some(source) if source.public_key == mine.to_hex() => PathBuf::from(&source.path), - _ => { - let directory = if rank == 0 { - grant.complete_directory() - } else { - grant.cache_directory(rank) - }; - let path = cache::entry(&agent.cache, "cores", &format!("{directory}/{primary}"))?; - pins.pin(cache::unit(&agent.cache, &path)); - path - } - }; let local_core = rank == 0 || grant.single_host || grant @@ -1406,9 +1916,46 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { .source .as_ref() .is_some_and(|source| source.public_key == mine.to_hex()); - if local_core && !core.is_file() { - return Err(format!("core {} is not on this node", core.display()).into()); - } + let mut core_lease: Option = None; + let core = if local_core { + let path = match &grant.core.source { + Some(source) if source.public_key == mine.to_hex() => { + let path = PathBuf::from(&source.path); + core_lease = agent + .core_root() + .ok() + .and_then(|root| root.entry_for_path(&path).ok().flatten()); + path + } + _ => { + let directory = if rank == 0 { + grant.complete_directory() + } else { + grant.cache_directory(rank) + }; + if let Some(entry) = agent.resolve_orbit_entry(&directory)? { + let path = entry.directory().join("model.safetensors"); + core_lease = Some(entry); + path + } else { + let staging = agent.staging_root(); + let path = cache::entry( + &staging, + "cores", + &format!("{directory}/{}", grant.primary()), + )?; + pins.pin(cache::unit(&staging, &path)); + path + } + } + }; + if !path.is_file() { + return Err(format!("core {} is not on this node", path.display()).into()); + } + Some(path) + } else { + None + }; let profile = agent .cache .join("publishers") @@ -1416,10 +1963,10 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { fs::write(&profile, serde_json::to_vec(&vec![&publisher])?)?; let mut command = Command::new(&binary); command.arg("run"); - if local_core { - command.arg(&core); + if let Some(core_path) = &core { + command.arg(core_path); } - command.arg("--core-cache").arg(&agent.cache); + command.arg("--core-cache").arg(&agent.core_cache); if !grant.single_host { let port = grant .rendezvous @@ -1436,13 +1983,18 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { grant.rendezvous.clone() }); } - command.args(&grant.serving); - if rank == 0 { - command.args(&grant.rank_zero); - } if grant.roce_ring && grant.roce_chain { return Err("grant selects both a ring and a chain".into()); } + command.args( + grant + .serving + .iter() + .filter(|arg| arg.as_str() != "--roce-ring" && arg.as_str() != "--roce-chain"), + ); + if rank == 0 { + command.args(&grant.rank_zero); + } if grant.roce_ring { command.arg("--roce-ring"); } @@ -1499,16 +2051,40 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { .into()); } } + let parent_pid = unsafe { libc::getpid() }; + // SAFETY: `pre_exec` calls only async-signal-safe syscalls (`setpgid`, `prctl`, `getppid`, + // `_exit`) to isolate the rank in its own process group and deliver `SIGTERM` if the agent + // dies unexpectedly. + unsafe { + command.pre_exec(move || { + let _ = libc::setpgid(0, 0); + #[cfg(target_os = "linux")] + { + let _ = libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM); + if libc::getppid() != parent_pid { + libc::_exit(1); + } + } + #[cfg(not(target_os = "linux"))] + let _ = parent_pid; + Ok(()) + }); + } let mut child = command .spawn() .map_err(|e| format!("cannot start {}: {e}", binary.display()))?; + let core_display = core + .as_ref() + .map(|path| path.display().to_string()) + .unwrap_or_else(|| grant.primary().to_owned()); let group = Arc::new(Group { id: grant.group.clone(), name: grant.name.clone(), rank, - core: core.display().to_string(), + core: core_display, gpus, pid: child.id() as i32, + exited: AtomicBool::new(false), metrics_url: (rank == 0).then(|| metrics_url(&grant.rank_zero)), started: Instant::now(), metrics: Mutex::new(None), @@ -1518,6 +2094,7 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { exit: None, subscribers: Vec::new(), pins: Some(pins), + core_lease, }), }); groups.push(group.clone()); @@ -1534,30 +2111,59 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { group.gpus.join(",") } ); + let forwarder_state = Arc::new((Mutex::new(2usize), Condvar::new())); let mut forwarders = Vec::new(); for output in [ Box::new(child.stdout.take().unwrap()) as Box, Box::new(child.stderr.take().unwrap()), ] { let group = group.clone(); + let state = forwarder_state.clone(); forwarders.push(thread::spawn(move || { for line in BufReader::new(output).lines().map_while(Result::ok) { group.push(line); } + let (lock, cvar) = &*state; + let mut remaining = lock.lock().unwrap(); + *remaining -= 1; + if *remaining == 0 { + cvar.notify_all(); + } })); } let finished = group.clone(); thread::spawn(move || { let status = child.wait(); - for forwarder in forwarders { - let _ = forwarder.join(); - } + // Record process reaping before draining pipes so STOP can never signal a reused PID. + finished.exited.store(true, Ordering::Release); let code = status.ok().and_then(|s| s.code()).unwrap_or(-1); + let (lock, cvar) = &*forwarder_state; + let deadline = Instant::now() + FORWARDER_DRAIN_TIMEOUT; + let mut remaining = lock.lock().unwrap(); + while *remaining > 0 { + let Some(wait) = deadline.checked_duration_since(Instant::now()) else { + break; + }; + let (guard, result) = cvar.wait_timeout(remaining, wait).unwrap(); + remaining = guard; + if result.timed_out() { + break; + } + } + let drained = *remaining == 0; + drop(remaining); eprintln!( "group {} rank {}: exited with status {code}", finished.id, finished.rank ); + // Always finish the group so GPUs, pins, and cache leases release even if an orphaned + // grandchild kept stdout/stderr open past `FORWARDER_DRAIN_TIMEOUT`. finished.finish(code); + if drained { + for forwarder in forwarders { + let _ = forwarder.join(); + } + } }); Ok(group) } @@ -1597,12 +2203,21 @@ fn stream_group(session: &mut Session, group: &Group) -> Result<(), Failure> { fn stop(agent: &Agent, request: &Value) -> Result, Failure> { let group = named_group(agent, request)?; - let running = group.running(); - if running { - // SAFETY: pid is this agent's child. - unsafe { libc::kill(group.pid, libc::SIGTERM) }; - eprintln!("group {} rank {}: stop requested", group.id, group.rank); - } + let running = { + let log = group.log.lock().unwrap(); + let active = log.exit.is_none() && !group.exited.load(Ordering::Acquire); + if active { + // Signal the child's process group (created via `setpgid(0, 0)`); fall back to the + // child PID if the group leader already changed groups. + // SAFETY: `group.pid` is an un-reaped child process of this agent while `exited` is false. + let rc = unsafe { libc::kill(-group.pid, libc::SIGTERM) }; + if rc != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) { + unsafe { libc::kill(group.pid, libc::SIGTERM) }; + } + eprintln!("group {} rank {}: stop requested", group.id, group.rank); + } + active + }; Ok(json!({"stopped": running}).to_string().into_bytes()) } @@ -1663,7 +2278,7 @@ fn status(agent: &Agent, request: &Value) -> Result, Failure> { "public_key": agent.key.public().to_hex(), "fingerprint": agent.key.public().fingerprint(), "version": PROTOCOL_VERSION, - "free_bytes": free_bytes(&agent.cache), + "free_bytes": free_bytes(&agent.core_cache), "controllers_revision": agent.dir.controllers()?.map_or(0, |(_, s)| s.revision), "group": groups.last().map(|g| describe(g)), "groups": groups.iter().map(|g| describe(g)).collect::>(), @@ -1680,7 +2295,12 @@ fn status(agent: &Agent, request: &Value) -> Result, Failure> { // ---- install ----------------------------------------------------------------------------------- /// Install this executable as the host's agent service and prepare pairing. -pub fn install(listen: &str, join_code: Option<&str>, accept_first: bool) -> Result<(), Failure> { +pub fn install( + listen: &str, + join_code: Option<&str>, + accept_first: bool, + core_cache: Option<&Path>, +) -> Result<(), Failure> { let dir = AgentDir::new(AgentDir::default_root()); let key = dir.key()?; let home = super::home(); @@ -1693,10 +2313,13 @@ pub fn install(listen: &str, join_code: Option<&str>, accept_first: bool) -> Res fs::rename(&temporary, &destination)?; let unit_dir = home.join(".config/systemd/user"); fs::create_dir_all(&unit_dir)?; + let cache_flag = core_cache + .map(|path| format!(" --core-cache {}", path.display())) + .unwrap_or_default(); fs::write( unit_dir.join("flare-agent.service"), format!( - "[Unit]\nDescription=Flare agent: runs this host's rank of a orbit's serving group\nAfter=network-online.target\n\n[Service]\nExecStart=%h/.local/lib/flare-agent/flare agent --listen {listen}\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n" + "[Unit]\nDescription=Flare agent: runs this host's rank of a orbit's serving group\nAfter=network-online.target\n\n[Service]\nExecStart=%h/.local/lib/flare-agent/flare agent --listen {listen}{cache_flag}\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n" ), )?; let code = if accept_first { @@ -1835,7 +2458,7 @@ pub mod tests { let harness = harness(74); let (core, _profile_path, publisher, commit) = crate::hub::tests::signed_payload_fixture(harness.temp.path()); - let model_root = harness.temp.path().join("flare"); + let model_root = harness.agent.core_cache.clone(); let root = Root::open(&model_root).unwrap(); let metadata = flare_helios::core::reader::Metadata::open(&core).unwrap(); let selections = crate::core_cache::select_deployments( @@ -2215,12 +2838,14 @@ pub mod tests { fn download_options_use_the_nodes_hub_cache_without_wire_paths() { let controller = Path::new("/controller/hf"); let node = Path::new("/node/hf"); + let node_cores = Path::new("/node/cores"); let options = crate::cli::HubOptions { hub_cache: Some(controller.to_owned()), ..Default::default() }; - let options = node_download_options(Some(node), options); + let options = node_download_options(Some(node), node_cores, options); assert_eq!(options.hub_cache.as_deref(), Some(node)); + assert_eq!(options.core_cache.as_deref(), Some(node_cores)); let wire = serde_json::to_value(&options).unwrap(); assert!(wire.get("hub_cache").is_none(), "{wire}"); assert!(!wire.to_string().contains("/node/hf"), "{wire}"); @@ -2228,12 +2853,14 @@ pub mod tests { let cleared = node_download_options( None, + node_cores, crate::cli::HubOptions { hub_cache: Some(controller.to_owned()), ..Default::default() }, ); assert!(cleared.hub_cache.is_none()); + assert_eq!(cleared.core_cache.as_deref(), Some(node_cores)); } #[test] @@ -2846,6 +3473,7 @@ pub mod tests { core: "model.safetensors".into(), gpus: Vec::new(), pid: 0, + exited: AtomicBool::new(false), metrics_url: None, started, log: Mutex::new(Log { @@ -2854,6 +3482,7 @@ pub mod tests { exit: None, subscribers: Vec::new(), pins: None, + core_lease: None, }), metrics: Mutex::new(None), }) @@ -3295,10 +3924,13 @@ pub mod tests { } }); for rank in 1..hosts.len() { - let directory = hosts[rank] + let dir_name = format!("ring-{}-rank{rank}", bytes.len()); + let entry = hosts[rank] .agent - .cache - .join(format!("cores/ring-{}-rank{rank}", bytes.len())); + .resolve_orbit_entry(&dir_name) + .unwrap() + .expect("published entry in helios::core::cache::Root"); + let directory = entry.directory(); let copy = fs::read(directory.join("model.safetensors")).unwrap(); assert_eq!(copy.len(), bytes.len()); for (offset, count) in ranges { @@ -3308,13 +3940,20 @@ pub mod tests { assert!(copy[100_001..1_000_000].iter().all(|&b| b == 0)); assert!(directory.join(VERIFIED).exists()); assert_eq!(hosts[rank].verified.lock().unwrap().len(), 1); + // Verify the same entry is directly discoverable via `distribution::receive_rank`'s selector. + let root = hosts[rank].agent.core_root().unwrap(); + let (_, via_rank_ref) = root + .resolve_source_ref(&format!("ring-rank{rank}")) + .unwrap() + .expect("rank source ref shared with distribution::receive_rank"); + assert_eq!(via_rank_ref.directory(), directory); } assert!( - !hosts[1] + hosts[1] .agent - .cache - .join(format!("cores/ring-{}-rank2", bytes.len())) - .exists() + .resolve_orbit_entry(&format!("ring-{}-rank2", bytes.len())) + .unwrap() + .is_none() ); if !ring { @@ -3465,11 +4104,20 @@ pub mod tests { .unwrap(); assert_eq!(reply["received"], 14096); assert_eq!(reply["verified"], true); - let marker = peer.agent.cache.join("cores/export-100000-rank1/.verified"); + let entry = peer + .agent + .resolve_orbit_entry("export-100000-rank1") + .unwrap() + .expect("published entry in helios::core::cache::Root"); + let marker = entry.directory().join(VERIFIED); assert!(marker.is_file()); + let expected_staged = peer + .agent + .staging_root() + .join("cores/export-100000-rank1/model.safetensors"); assert_eq!( peer.verified.lock().unwrap().as_slice(), - [(marker.with_file_name("model.safetensors"), Some(1))] + [(expected_staged, Some(1))] ); // A repeated transfer of held files neither fetches nor verifies again. let request = json!({ @@ -3504,13 +4152,20 @@ pub mod tests { error.contains("failed verification and was removed"), "{error}" ); - assert!(!peer.agent.cache.join("cores/export-100000-rank2").exists()); - let copy = fs::read( + assert!( peer.agent - .cache - .join("cores/export-100000-rank1/model.safetensors"), - ) - .unwrap(); + .resolve_orbit_entry("export-100000-rank2") + .unwrap() + .is_none() + ); + assert!( + !peer + .agent + .staging_root() + .join("cores/export-100000-rank2") + .exists() + ); + let copy = fs::read(entry.directory().join("model.safetensors")).unwrap(); assert_eq!(copy.len(), bytes.len()); for &(offset, nbytes) in &ranges { let span = offset as usize..(offset + nbytes) as usize; @@ -3567,4 +4222,280 @@ pub mod tests { .is_err() ); } + + #[test] + fn put_and_transfer_preserve_managed_cache_and_enforce_grant_expiry() { + let source = harness(31); + let peer = Harness { + controller: Key::from_seed(&[31; 32]).unwrap(), + ..harness(32) + }; + let _source_session = pair_accept_first(&source); + let mut peer_session = pair_accept_first(&peer); + // Seed a sentinel inside managed Helios cache directories in `peer.agent.core_cache`. + let root = peer.agent.core_root().unwrap(); + let sentinel = peer.agent.core_cache.join("models/keep-sentinel"); + fs::create_dir_all(&sentinel).unwrap(); + fs::write(sentinel.join("data"), b"490gib-safe").unwrap(); + drop(root); + + let bytes = b"fixture core payload".to_vec(); + let core = source.temp.path().join("model.safetensors"); + fs::write(&core, &bytes).unwrap(); + // Controller PUT into peer must never evict managed Helios cache subdirs. + put( + &mut peer_session, + "core", + "put-check-20/model.safetensors", + &bytes, + None, + ); + assert!(sentinel.join("data").is_file()); + + // Expired grants must be rejected on TRANSFER, FETCH, FETCH_FABRIC, and RUN. + let expired_grant = Signed::sign( + &source.controller, + &Grant { + group: "expired".into(), + name: "expired".into(), + core: Core { + export: "exp".into(), + length: bytes.len() as u64, + files: vec!["model.safetensors".into()], + source: Some(Source { + public_key: source.agent.key.public().to_hex(), + path: core.display().to_string(), + }), + }, + members: vec![ + Member { + rank: 0, + name: "source".into(), + public_key: source.agent.key.public().to_hex(), + address: source.address.clone(), + gpus: vec![], + }, + Member { + rank: 1, + name: "peer".into(), + public_key: peer.agent.key.public().to_hex(), + address: peer.address.clone(), + gpus: vec![], + }, + ], + rendezvous: "127.0.0.1:29800".into(), + serving: vec![], + rank_zero: vec![], + roce_ring: false, + transfer_fabric: None, + roce_chain: false, + single_host: false, + issued: now().saturating_sub(120), + expires: now().saturating_sub(1), + }, + ) + .unwrap(); + let err = connect(&peer, &peer.controller) + .request( + frame::TRANSFER, + &json!({ + "grant": expired_grant, + "publisher": publisher(), + "source": {"public_key": source.agent.key.public().to_hex(), "address": source.address}, + "directory": "exp-20-rank1", + "files": [{"name": "model.safetensors", "size": bytes.len(), "ranges": [[0, bytes.len()]]}], + }), + ) + .unwrap_err() + .to_string(); + assert!(err.contains("expired"), "{err}"); + + let mut fetch_session = Session::connect(&source.address, &peer.agent.key).unwrap(); + exchange_hello(&mut fetch_session, &peer.agent.hello().unwrap()).unwrap(); + fetch_session + .write_frame( + frame::FETCH, + &json!({"grant": expired_grant, "name": "model.safetensors", "ranges": [[0, 10]]}) + .to_string() + .into_bytes(), + ) + .unwrap(); + let err = fetch_session.expect(frame::OK).unwrap_err().to_string(); + assert!(err.contains("expired"), "{err}"); + + let mut fabric_session = Session::connect(&source.address, &peer.agent.key).unwrap(); + exchange_hello(&mut fabric_session, &peer.agent.hello().unwrap()).unwrap(); + fabric_session + .write_frame( + frame::FETCH_FABRIC, + &json!({ + "grant": expired_grant, + "source_rank": 0, + "destination_rank": 1, + "rail": 0, + "name": "model.safetensors", + "size": bytes.len(), + "ranges": [[0, 10]], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + let err = fabric_session.expect(frame::OK).unwrap_err().to_string(); + assert!(err.contains("expired"), "{err}"); + + let err = connect(&source, &source.controller) + .request(frame::RUN, &run_request(&expired_grant, 0, "unused")) + .unwrap_err() + .to_string(); + assert!(err.contains("expired"), "{err}"); + + // Peer RUN (`local_core == false`) must accept `+` in Grant.core.files (multi-deployment + // cache names), pass `--core-cache `, and strip duplicate RoCE flags. + let script = "#!/bin/sh\necho \"$*\"\n"; + let bin_name = cache::binary_name(script.as_bytes()); + put(&mut peer_session, "binary", &bin_name, script.as_bytes(), None); + let peer_grant = Signed::sign( + &peer.controller, + &Grant { + group: "peer-plus".into(), + name: "peer-plus".into(), + core: Core { + export: "exp".into(), + length: 4096, + files: vec!["gb10-tp1+tp2-20261130".into()], + source: None, + }, + members: vec![ + Member { + rank: 0, + name: "source".into(), + public_key: source.agent.key.public().to_hex(), + address: source.address.clone(), + gpus: vec![], + }, + Member { + rank: 1, + name: "peer".into(), + public_key: peer.agent.key.public().to_hex(), + address: peer.address.clone(), + gpus: vec![], + }, + ], + rendezvous: "127.0.0.1:29800".into(), + serving: vec!["--roce-ring".into(), "--max-concurrency".into(), "4".into()], + rank_zero: vec![], + roce_ring: false, + roce_chain: true, + transfer_fabric: None, + single_host: false, + issued: now(), + expires: now() + 60, + }, + ) + .unwrap(); + let mut run_sess = connect(&peer, &peer.controller); + run_sess + .request(frame::RUN, &run_request(&peer_grant, 1, &bin_name)) + .unwrap(); + let (lines, exit) = collect(&mut run_sess); + assert_eq!(exit, 0); + let joined = lines.join(" "); + assert!( + joined.contains(&format!("--core-cache {}", peer.agent.core_cache.display())), + "{joined}" + ); + assert!(!joined.contains("--roce-ring"), "{joined}"); + assert_eq!(joined.matches("--roce-chain").count(), 1, "{joined}"); + } + + #[test] + fn reaper_finishes_group_even_when_grandchild_holds_stdio_open() { + let harness = harness(33); + let mut session = pair_accept_first(&harness); + let pid_file = harness.temp.path().join("grandchild.pid"); + // Spawn a background grandchild inheriting stdout/stderr, then exit immediately. + let script = format!( + "#!/bin/sh\necho started\nsleep 30 &\necho $! > {}\nexit 0\n", + pid_file.display() + ); + let bin_name = cache::binary_name(script.as_bytes()); + put(&mut session, "binary", &bin_name, script.as_bytes(), None); + put( + &mut session, + "core", + "export-13/model.safetensors", + b"fixture bytes", + None, + ); + let grant = grant_on_gpus( + &harness, + "leaked-fd", + &["GPU-aaaaaaaa-0000-0000-0000-000000000000"], + ); + let started = Instant::now(); + let mut run_sess = connect(&harness, &harness.controller); + run_sess + .request(frame::RUN, &run_request(&grant, 0, &bin_name)) + .unwrap(); + let (lines, exit) = collect(&mut run_sess); + assert_eq!(exit, 0); + assert!(lines.iter().any(|l| l == "started"), "{lines:?}"); + assert!( + started.elapsed() < Duration::from_secs(10), + "reaper blocked on grandchild stdio for {:?}", + started.elapsed() + ); + // GPU must be free immediately after finish. + let status: Value = serde_json::from_slice( + &connect(&harness, &harness.controller) + .request(frame::STATUS, &json!({})) + .unwrap(), + ) + .unwrap(); + assert!( + status["gpus"] + .as_array() + .unwrap() + .iter() + .all(|g| g["group"].is_null()) + ); + if let Ok(pid_text) = fs::read_to_string(&pid_file) + && let Ok(pid) = pid_text.trim().parse::() + { + unsafe { libc::kill(pid, libc::SIGKILL) }; + } + } + + #[test] + fn atomic_private_writes_create_owner_only_secrets() { + let temp = tempfile::tempdir().unwrap(); + let key_path = temp.path().join("agent/node.key"); + let _ = Key::load_or_create(&key_path).unwrap(); + assert_eq!(fs::metadata(&key_path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!( + fs::metadata(key_path.parent().unwrap()) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o700 + ); + let dir = AgentDir::new(temp.path().join("agent2")); + dir.set_join_code("ABCD-EFGH-IJKL-MNOP", 60).unwrap(); + assert_eq!( + fs::metadata(temp.path().join("agent2/join-code")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + let orbit_path = temp.path().join("orbit.toml"); + crate::orbit::store::Orbit::default().save(&orbit_path).unwrap(); + assert_eq!( + fs::metadata(&orbit_path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } } diff --git a/flare-cli/src/orbit/controller.rs b/flare-cli/src/orbit/controller.rs index 682ac2196..3bdf3d8fe 100644 --- a/flare-cli/src/orbit/controller.rs +++ b/flare-cli/src/orbit/controller.rs @@ -50,6 +50,8 @@ pub const RENDEZVOUS_PORT: u16 = 29800; pub const GRANT_SECONDS: u64 = 600; /// How long peers may keep running after rank zero exits before they receive STOP. const PEER_GRACE: Duration = Duration::from_secs(30); +/// Maximum time `stop_group` waits for rank zero to drain before forcing peer shutdown. +const RANK_ZERO_STOP_TIMEOUT: Duration = Duration::from_secs(120); /// An agent sends an empty LOG frame after 20 silent seconds, so an attachment silent for longer /// has lost its node. const ATTACH_TIMEOUT: Duration = Duration::from_secs(90); @@ -682,6 +684,9 @@ impl Controller { }); let mut serving = spec.as_ref().map_or_else(Vec::new, |s| s.serving.clone()); serving.extend(options.serving.iter().cloned()); + // RoCE shape lives in Grant's dedicated booleans; strip any legacy flags saved in + // `spec.serving` so overriding `--roce-ring` <-> `--roce-chain` never conflicts. + serving.retain(|arg| arg != "--roce-ring" && arg != "--roce-chain"); let verify_weights = options.verify_weights || options.run_args.serving.verify_weights || serving.iter().any(|arg| arg == "--verify-weights"); @@ -1435,6 +1440,31 @@ impl Controller { .map_err(|e| at(&nodes[rank].name, e)) }))?; + // Controller-uploaded files on rank zero still need agent-side verification and + // publication into the managed model cache before peers fetch or ranks launch. + if matches!(&core.holder, Holder::Controller { .. }) { + let files: Vec = core + .files + .iter() + .map(|f| RankFile { + name: f.name.clone(), + size: f.size, + ranges: vec![(0, f.size)], + }) + .collect(); + transfer( + &mut sessions[0], + &nodes[0], + &statuses[0], + &transfer_grant, + &core.publisher, + &nodes[0], + &complete, + &files, + 1, + ) + .map_err(|e| at(&nodes[0].name, e))?; + } // Launch needs the complete source on rank zero. Prestaging also fetches peer ranges; // serving launches leave those ranges to the rank processes. let mut source = match &core.holder { @@ -1779,10 +1809,12 @@ impl Controller { }); if stopping { eprintln!( - "stopping rank 0 on {}; waiting for it to drain (Ctrl-C stops every rank now)", - zero.name + "stopping rank 0 on {}; waiting up to {}s for it to drain (Ctrl-C stops every rank now)", + zero.name, + RANK_ZERO_STOP_TIMEOUT.as_secs() ); grace = PEER_GRACE; + let deadline = Instant::now() + RANK_ZERO_STOP_TIMEOUT; loop { match self.group_running(zero, group) { Ok(true) => {} @@ -1799,6 +1831,15 @@ impl Controller { grace = Duration::ZERO; break; } + if Instant::now() >= deadline { + eprintln!( + "rank 0 on {} did not exit within {}s; stopping peers now", + zero.name, + RANK_ZERO_STOP_TIMEOUT.as_secs() + ); + grace = Duration::ZERO; + break; + } thread::sleep(Duration::from_secs(1)); } } @@ -2974,18 +3015,23 @@ mod tests { } assert_eq!(exits, BTreeMap::from([(0, 0), (1, 0)])); - // Rank zero holds the complete core. Peer processes fetch their own shards during - // serving bootstrap; the controller starts them without a local core. - let complete = zero.agent.cache.join(format!( - "cores/{}/model.safetensors", - launch.grant.complete_directory() - )); + // Rank zero holds the complete core in its unified `helios::core::cache::Root`. Peer + // processes fetch their own shards during serving bootstrap; the controller starts them + // without a local core. + let complete_entry = zero + .agent + .resolve_orbit_entry(&launch.grant.complete_directory()) + .unwrap() + .expect("complete core published in rank zero Root"); + let complete = complete_entry.directory().join("model.safetensors"); assert_eq!(fs::read(&complete).unwrap(), bytes); - let partial = one.agent.cache.join(format!( - "cores/{}/model.safetensors", - launch.grant.cache_directory(1) - )); - assert!(!partial.exists()); + assert!(complete.with_file_name(".verified").is_file()); + assert!( + one.agent + .resolve_orbit_entry(&launch.grant.cache_directory(1)) + .unwrap() + .is_none() + ); for harness in [&zero, &one] { let selected = match executable { Some(bytes) => { @@ -3053,9 +3099,14 @@ mod tests { .is_empty() ); assert!(complete.is_file()); - assert!(!partial.exists()); + assert!( + one.agent + .resolve_orbit_entry(&launch.grant.cache_directory(1)) + .unwrap() + .is_none() + ); - // Staging places and verifies the core without executables or ranks. + // Staging places and verifies the core on BOTH rank zero and peers without executables or ranks. let staged = ResolvedCore { export: "export2".into(), ..core.clone() @@ -3076,18 +3127,22 @@ mod tests { .unwrap(); assert!(launch.ranks.is_empty()); assert_eq!(launch.grant.name, "push-model"); + let zero_staged = zero + .agent + .resolve_orbit_entry(&launch.grant.complete_directory()) + .unwrap() + .expect("nodes[0] verified and published after orbit push"); assert_eq!( - fs::read(zero.agent.cache.join(format!( - "cores/{}/model.safetensors", - launch.grant.complete_directory() - ))) - .unwrap(), + fs::read(zero_staged.directory().join("model.safetensors")).unwrap(), bytes ); - let staged_rank = one.agent.cache.join(format!( - "cores/{}/model.safetensors", - launch.grant.cache_directory(1) - )); + assert!(zero_staged.directory().join(".verified").is_file()); + let staged_rank_entry = one + .agent + .resolve_orbit_entry(&launch.grant.cache_directory(1)) + .unwrap() + .expect("peer rank published in helios::core::cache::Root"); + let staged_rank = staged_rank_entry.directory().join("model.safetensors"); assert_eq!( fs::read(&staged_rank).unwrap()[40_000..48_000], bytes[40_000..48_000] @@ -3124,16 +3179,22 @@ mod tests { }, ) .unwrap(); - let complete = zero.agent.cache.join(format!( - "cores/{}/model.safetensors", - staged.grant.complete_directory() - )); + let complete = zero + .agent + .resolve_orbit_entry(&staged.grant.complete_directory()) + .unwrap() + .expect("external complete core published on rank zero") + .directory() + .join("model.safetensors"); assert_eq!(fs::read(&complete).unwrap(), bytes); assert!(complete.with_file_name(".verified").is_file()); - let partial = one.agent.cache.join(format!( - "cores/{}/model.safetensors", - staged.grant.cache_directory(1) - )); + let partial = one + .agent + .resolve_orbit_entry(&staged.grant.cache_directory(1)) + .unwrap() + .expect("external peer rank published on rank one") + .directory() + .join("model.safetensors"); assert_eq!( fs::read(&partial).unwrap()[40_000..48_000], bytes[40_000..48_000] diff --git a/flare-cli/src/orbit/gpu.rs b/flare-cli/src/orbit/gpu.rs index 64bf76415..c45f12830 100644 --- a/flare-cli/src/orbit/gpu.rs +++ b/flare-cli/src/orbit/gpu.rs @@ -3,28 +3,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -//! GPU inventory read through NVML (`libnvidia-ml.so.1`). NVML queries the driver without -//! creating a CUDA context, so the agent can report every GPU on its host, including GPUs that -//! running ranks own. -//! -//! The library is loaded and initialized once per process and stays initialized until exit: -//! every `nvmlInit_v2` and `nvmlShutdown` cycle leaves an event descriptor open, so an agent -//! sampling once a second would exhaust its descriptor limit within minutes. +//! GPU inventory read through the shared NVML loader (`flare_helios::nvml`). NVML queries the +//! driver without creating a CUDA context, so the agent can report every GPU on its host, +//! including GPUs that running ranks own. -use std::ffi::{CStr, c_char, c_int, c_uint, c_void}; -use std::sync::OnceLock; +use std::ffi::c_int; -use libloading::{Library, Symbol}; +use flare_helios::nvml::{CLOCK_SM, NOT_SUPPORTED, Nvml, TEMPERATURE_GPU}; use serde::{Deserialize, Serialize}; use super::Failure; -const LIBRARY: &str = "libnvidia-ml.so.1"; -/// NVML_DEVICE_UUID_V2_BUFFER_SIZE and NVML_DEVICE_NAME_V2_BUFFER_SIZE. -const TEXT_BUFFER: usize = 96; -/// NVML_ERROR_NOT_SUPPORTED. -const NOT_SUPPORTED: c_int = 3; - /// One GPU as the agent reports it. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Gpu { @@ -58,164 +47,70 @@ pub struct Gpu { pub clock_mhz: Option, } -static NVML: OnceLock> = OnceLock::new(); - -/// The NVML library, loaded and initialized on first use for the rest of the process. -fn nvml() -> Result<&'static Library, Failure> { - NVML.get_or_init(|| { - // SAFETY: Only the system NVML library is loaded, and it is never unloaded. - let library = unsafe { Library::new(LIBRARY) } - .map_err(|error| format!("cannot load {LIBRARY}: {error}"))?; - let library: &'static Library = Box::leak(Box::new(library)); - // SAFETY: The signatures match the NVML ABI in nvml.h. - unsafe { - let describe = library - .get::(b"nvmlErrorString\0") - .map_err(|e| e.to_string())?; - let init = library - .get:: c_int>(b"nvmlInit_v2\0") - .map_err(|e| e.to_string())?; - check(&describe, "nvmlInit_v2", init()).map_err(|e| e.to_string())?; - } - Ok(library) - }) - .clone() - .map_err(Failure::from) -} - /// Every GPU NVML reports, in NVML index order. Fails with an error naming `libnvidia-ml.so.1` /// when that library cannot be loaded. pub fn enumerate() -> Result, Failure> { - let library = nvml()?; - // SAFETY: These signatures match the NVML ABI in nvml.h, the structures below match its - // layouts, and every output pointer is valid for the duration of its call. - unsafe { - let describe = library.get::(b"nvmlErrorString\0")?; - let get_count = library - .get:: c_int>(b"nvmlDeviceGetCount_v2\0")?; - let get_handle = library.get:: c_int>( - b"nvmlDeviceGetHandleByIndex_v2\0", - )?; - let get_uuid = library.get:: c_int>( - b"nvmlDeviceGetUUID\0", - )?; - let get_name = library.get:: c_int>( - b"nvmlDeviceGetName\0", - )?; - let get_memory = library.get:: c_int>( - b"nvmlDeviceGetMemoryInfo\0", - )?; - let get_pci = library.get:: c_int>( - b"nvmlDeviceGetPciInfo_v3\0", - )?; - let get_capability = - library.get:: c_int>( - b"nvmlDeviceGetCudaComputeCapability\0", - )?; - let get_utilization = library - .get:: c_int>( - b"nvmlDeviceGetUtilizationRates\0", - )?; - let get_temperature = library - .get:: c_int>( - b"nvmlDeviceGetTemperature\0", - )?; - let get_clock = library.get:: c_int>( - b"nvmlDeviceGetClockInfo\0", - )?; - - let mut count: c_uint = 0; - check(&describe, "nvmlDeviceGetCount_v2", get_count(&mut count))?; - let mut gpus = Vec::with_capacity(count as usize); - for index in 0..count { - let mut device: Device = std::ptr::null_mut(); - check( - &describe, - "nvmlDeviceGetHandleByIndex_v2", - get_handle(index, &mut device), - )?; - - let mut uuid = [0u8; TEXT_BUFFER]; - check( - &describe, - "nvmlDeviceGetUUID", - get_uuid(device, uuid.as_mut_ptr().cast(), TEXT_BUFFER as c_uint), - )?; - let mut name = [0u8; TEXT_BUFFER]; - check( - &describe, - "nvmlDeviceGetName", - get_name(device, name.as_mut_ptr().cast(), TEXT_BUFFER as c_uint), - )?; - - let mut pci = PciInfo { - _bus_id_legacy: [0; 16], - _domain: 0, - _bus: 0, - _device: 0, - pci_device_id: 0, - _pci_subsystem_id: 0, - _bus_id: [0; 32], - }; - let pci_code = get_pci(device, &mut pci); - if pci_code != NOT_SUPPORTED { - check(&describe, "nvmlDeviceGetPciInfo_v3", pci_code)?; - } - let (mut major, mut minor) = (0, 0); - check( - &describe, - "nvmlDeviceGetCudaComputeCapability", - get_capability(device, &mut major, &mut minor), - )?; - - let mut memory = Memory { - total: 0, - free: 0, - _used: 0, - }; - let code = get_memory(device, &mut memory); - let (memory_total, memory_free) = if code == NOT_SUPPORTED { - host_memory()? - } else { - check(&describe, "nvmlDeviceGetMemoryInfo", code)?; - (memory.total, memory.free) - }; - - // Readings a GPU does not support are absent rather than failing the inventory. - let optional = |code: c_int, value: u32| -> Result, Failure> { - if code == NOT_SUPPORTED { - Ok(None) - } else { - check(&describe, "nvml reading", code)?; - Ok(Some(value)) - } - }; - let mut rates = Utilization { gpu: 0, memory: 0 }; - let code = get_utilization(device, &mut rates); - let utilization = optional(code, rates.gpu)?; - let memory_utilization = optional(code, rates.memory)?; - let mut temperature: c_uint = 0; - // NVML_TEMPERATURE_GPU is sensor 0. - let temperature = optional(get_temperature(device, 0, &mut temperature), temperature)?; - let mut clock: c_uint = 0; - // NVML_CLOCK_SM is clock type 1. - let clock_mhz = optional(get_clock(device, 1, &mut clock), clock)?; - - gpus.push(Gpu { - index, - uuid: text(&uuid), - name: text(&name), - revision: revision(pci.pci_device_id, major, minor), - memory_total, - memory_free, - utilization, - memory_utilization, - temperature, - clock_mhz, - }); - } - Ok(gpus) + let nvml = Nvml::load().map_err(Failure::from)?; + let count = nvml + .device_count() + .map_err(|code| check(nvml, "nvmlDeviceGetCount_v2", code))?; + let mut gpus = Vec::with_capacity(count as usize); + for index in 0..count { + let device = nvml + .device_by_index(index) + .map_err(|code| check(nvml, "nvmlDeviceGetHandleByIndex_v2", code))?; + let uuid = nvml + .device_uuid(device) + .map_err(|code| check(nvml, "nvmlDeviceGetUUID", code))?; + let name = nvml + .device_name(device) + .map_err(|code| check(nvml, "nvmlDeviceGetName", code))?; + let pci_device_id = match nvml.device_pci_info(device) { + Ok(pci) => pci.device_id, + Err(NOT_SUPPORTED) => 0, + Err(code) => return Err(check(nvml, "nvmlDeviceGetPciInfo_v3", code)), + }; + let (major, minor) = nvml + .device_cuda_compute_capability(device) + .ok_or_else(|| Failure::from("NVML missing nvmlDeviceGetCudaComputeCapability"))? + .map_err(|code| check(nvml, "nvmlDeviceGetCudaComputeCapability", code))?; + let (memory_total, memory_free) = match nvml.device_memory_info(device) { + Ok(memory) => (memory.total, memory.free), + Err(NOT_SUPPORTED) => host_memory()?, + Err(code) => return Err(check(nvml, "nvmlDeviceGetMemoryInfo", code)), + }; + + // Readings a GPU does not support are absent rather than failing the inventory. + let (utilization, memory_utilization) = match nvml.device_utilization_rates(device) { + Ok(rates) => (Some(rates.gpu), Some(rates.memory)), + Err(NOT_SUPPORTED) => (None, None), + Err(code) => return Err(check(nvml, "nvml reading", code)), + }; + let temperature = match nvml.device_temperature(device, TEMPERATURE_GPU) { + Ok(value) => Some(value), + Err(NOT_SUPPORTED) => None, + Err(code) => return Err(check(nvml, "nvml reading", code)), + }; + let clock_mhz = match nvml.device_clock_info(device, CLOCK_SM) { + Ok(value) => Some(value), + Err(NOT_SUPPORTED) => None, + Err(code) => return Err(check(nvml, "nvml reading", code)), + }; + + gpus.push(Gpu { + index, + uuid, + name, + revision: revision(pci_device_id, major, minor), + memory_total, + memory_free, + utilization, + memory_utilization, + temperature, + clock_mhz, + }); } + Ok(gpus) } /// The Flare hardware revision of a compute capability, for devices the PCI table does not list @@ -251,63 +146,9 @@ pub fn visible_devices(uuids: &[String]) -> String { uuids.join(",") } -/// nvmlDevice_t, an opaque handle owned by NVML. -type Device = *mut c_void; -type ErrorString = unsafe extern "C" fn(c_int) -> *const c_char; - -/// nvmlUtilization_t: percent of the last sample period with a kernel running, and with memory -/// traffic. -#[repr(C)] -struct Utilization { - gpu: c_uint, - memory: c_uint, -} - -/// nvmlMemory_t, the version 1 layout that nvmlDeviceGetMemoryInfo fills. -#[repr(C)] -struct Memory { - total: u64, - free: u64, - _used: u64, -} - -/// nvmlPciInfo_t as nvmlDeviceGetPciInfo_v3 fills it. -#[repr(C)] -struct PciInfo { - _bus_id_legacy: [c_char; 16], - _domain: c_uint, - _bus: c_uint, - _device: c_uint, - /// Device ID in the high 16 bits and vendor ID in the low 16 bits, the layout of CUDA's - /// GPU_PCI_DEVICE_ID attribute. - pci_device_id: c_uint, - _pci_subsystem_id: c_uint, - _bus_id: [c_char; 32], -} - -fn check(describe: &Symbol<'_, ErrorString>, call: &str, code: c_int) -> Result<(), Failure> { - if code == 0 { - return Ok(()); - } - // SAFETY: nvmlErrorString accepts any return code and returns a static NUL-terminated string. - let message = unsafe { - let message = describe(code); - if message.is_null() { - String::new() - } else { - CStr::from_ptr(message).to_string_lossy().into_owned() - } - }; - Err(format!("NVML {call} failed with {code} ({message})").into()) -} - -/// The NUL-terminated text NVML wrote into `buffer`. -fn text(buffer: &[u8]) -> String { - let end = buffer - .iter() - .position(|&byte| byte == 0) - .unwrap_or(buffer.len()); - String::from_utf8_lossy(&buffer[..end]).into_owned() +fn check(nvml: &Nvml, call: &str, code: c_int) -> Failure { + let message = nvml.error_string(code); + format!("NVML {call} failed with {code} ({message})").into() } fn revision(pci_device_id: u32, major: c_int, minor: c_int) -> String { diff --git a/flare-cli/src/orbit/identity.rs b/flare-cli/src/orbit/identity.rs index 2701b01dc..572f8aff3 100644 --- a/flare-cli/src/orbit/identity.rs +++ b/flare-cli/src/orbit/identity.rs @@ -47,14 +47,8 @@ impl Key { } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { let key = Self::generate()?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?; - } - let temporary = path.with_extension("tmp"); - fs::write(&temporary, format!("{}\n", hex(&key.seed)))?; - fs::set_permissions(&temporary, fs::Permissions::from_mode(0o600))?; - fs::rename(&temporary, path)?; + let content = format!("{}\n", hex(&key.seed)); + super::store::atomic_write_private(path, content.as_bytes(), true)?; Ok(key) } Err(error) => Err(format!("cannot read key {}: {error}", path.display()).into()), diff --git a/flare-cli/src/orbit/session.rs b/flare-cli/src/orbit/session.rs index 490f24b12..ec37a13b9 100644 --- a/flare-cli/src/orbit/session.rs +++ b/flare-cli/src/orbit/session.rs @@ -251,6 +251,7 @@ impl Session { pub fn initiate(mut stream: TcpStream, key: &Key) -> Result { stream.set_nodelay(true)?; stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT))?; + stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT))?; let rng = ring::rand::SystemRandom::new(); let ephemeral = EphemeralPrivateKey::generate(&X25519, &rng).map_err(|_| "no entropy")?; let mine = ephemeral @@ -282,6 +283,7 @@ impl Session { let record3 = send.seal(&proof(key, &transcript, b"initiator"))?; write_record(&mut stream, &record3)?; stream.set_read_timeout(None)?; + stream.set_write_timeout(None)?; Ok(Self { stream, send, @@ -296,13 +298,24 @@ impl Session { } /// Complete the handshake on an accepted connection as the responder. + /// + /// Leaves the handshake read/write timeouts armed until the caller authorizes the peer and + /// calls [`Session::clear_timeouts`], so unauthenticated clients cannot hold agent threads + /// open indefinitely before `HELLO` or authorization. pub fn accept(mut stream: TcpStream, key: &Key) -> Result { stream.set_nodelay(true)?; stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT))?; - let message1 = read_exact(&mut stream, 8 + 4 + 32)?; - if &message1[..8] != MAGIC { + stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT))?; + // Read the 8-byte magic first so short non-Orbit LAN probes fail immediately instead of + // waiting for the full 44-byte ClientHello. + let magic = read_exact(&mut stream, MAGIC.len())?; + if magic.as_slice() != MAGIC { return Err("not a flare orbit connection".into()); } + let rest = read_exact(&mut stream, 4 + 32)?; + let mut message1 = Vec::with_capacity(MAGIC.len() + rest.len()); + message1.extend_from_slice(&magic); + message1.extend_from_slice(&rest); let version = u32::from_le_bytes(message1[8..12].try_into().unwrap()); if version != PROTOCOL_VERSION { return Err(format!( @@ -333,7 +346,6 @@ impl Session { let transcript = transcript_hash(&[&message1, mine.as_ref(), &record2]); let record3 = read_record(&mut stream)?; let remote = verify_proof(&receive.open(record3.clone())?, &transcript, b"initiator")?; - stream.set_read_timeout(None)?; Ok(Self { stream, send, @@ -347,6 +359,13 @@ impl Session { }) } + /// Clear handshake read/write timeouts after the peer has been authorized. + pub fn clear_timeouts(&self) -> Result<(), Failure> { + self.stream.set_read_timeout(None)?; + self.stream.set_write_timeout(None)?; + Ok(()) + } + /// The authenticated identity on the other side. pub fn remote(&self) -> PublicKey { self.remote @@ -705,4 +724,29 @@ mod tests { write_record(&mut raw, &corrupted).unwrap(); assert!(server.read_frame().is_err()); } + + #[test] + fn short_non_orbit_probe_fails_immediately_without_waiting_handshake_timeout() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let started = std::time::Instant::now(); + let server = thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + Session::accept(stream, &Key::from_seed(&[2; 32]).unwrap()) + .err() + .unwrap() + .to_string() + }); + let mut probe = TcpStream::connect(address).unwrap(); + // Send only 8 non-magic bytes and hold the socket open; accept must reject immediately. + probe.write_all(b"GET / HT").unwrap(); + let error = server.join().unwrap(); + assert!(error.contains("not a flare orbit connection"), "{error}"); + assert!( + started.elapsed() < Duration::from_secs(5), + "probe rejection stalled for {:?}", + started.elapsed() + ); + drop(probe); + } } diff --git a/flare-cli/src/orbit/store.rs b/flare-cli/src/orbit/store.rs index 785e155ac..4fc73a608 100644 --- a/flare-cli/src/orbit/store.rs +++ b/flare-cli/src/orbit/store.rs @@ -37,6 +37,50 @@ pub struct JoinCode { pub expires: u64, } +/// Atomically create a secret file with mode `0600` before writing any bytes, eliminating any +/// window where another local user could open the temporary file before `chmod`. +pub(crate) fn atomic_write_private( + path: &Path, + contents: &[u8], + protect_parent: bool, +) -> Result<(), Failure> { + use std::io::Write as _; + use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; + + let parent = path.parent().ok_or("secret path has no parent directory")?; + if protect_parent { + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(parent)?; + fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?; + } else { + fs::create_dir_all(parent)?; + } + let name = path + .file_name() + .and_then(|s| s.to_str()) + .ok_or("secret path has no filename")?; + let nonce = hex(&super::random(8)?); + let temporary = parent.join(format!(".{name}.tmp.{}.{nonce}", std::process::id())); + let write_result = (|| -> Result<(), Failure> { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary)?; + file.write_all(contents)?; + file.sync_all()?; + drop(file); + fs::rename(&temporary, path)?; + Ok(()) + })(); + if write_result.is_err() { + let _ = fs::remove_file(&temporary); + } + write_result +} + impl AgentDir { pub fn default_root() -> PathBuf { home().join(".config/flare/agent") @@ -51,13 +95,7 @@ impl AgentDir { } fn private_write(&self, path: &Path, text: &str) -> Result<(), Failure> { - fs::create_dir_all(&self.root)?; - fs::set_permissions(&self.root, fs::Permissions::from_mode(0o700))?; - let temporary = path.with_extension("tmp"); - fs::write(&temporary, text)?; - fs::set_permissions(&temporary, fs::Permissions::from_mode(0o600))?; - fs::rename(&temporary, path)?; - Ok(()) + atomic_write_private(path, text.as_bytes(), true) } /// The stored controller-set record and its verified set, or None on an unpaired node. @@ -259,14 +297,7 @@ impl Orbit { } pub fn save(&self, path: &Path) -> Result<(), Failure> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - let temporary = path.with_extension("tmp"); - fs::write(&temporary, toml::to_string(self)?)?; - fs::set_permissions(&temporary, fs::Permissions::from_mode(0o600))?; - fs::rename(&temporary, path)?; - Ok(()) + atomic_write_private(path, toml::to_string(self)?.as_bytes(), false) } pub fn controller_set(&self) -> Result, Failure> { diff --git a/flare-cli/src/trust.rs b/flare-cli/src/trust.rs index 8ed8fb0fd..820e498f7 100644 --- a/flare-cli/src/trust.rs +++ b/flare-cli/src/trust.rs @@ -38,10 +38,15 @@ fn load_with( .into(), ); } - let tensor_parallel = - args.hub.tensor_parallel.first().copied().or_else(|| { - (args.rank.is_none() && !args.gpus.is_empty()).then(|| args.gpus.len() as u32) - }); + let tensor_parallel = args.hub.tensor_parallel.first().copied().or_else(|| { + if !args.hosts.is_empty() { + Some((args.hosts.len() + 1) as u32) + } else if args.rank.is_none() && !args.gpus.is_empty() { + Some(args.gpus.len() as u32) + } else { + None + } + }); let phase = progress.phase("Verify core", None); let review = flare::trust::review( root, diff --git a/flare/src/hardware.rs b/flare/src/hardware.rs index 6a017a20f..c909119cd 100644 --- a/flare/src/hardware.rs +++ b/flare/src/hardware.rs @@ -9,9 +9,9 @@ mod monitor; pub use monitor::{HardwareMonitor, HardwareSnapshot}; -use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void}; +use std::ffi::{CString, c_int}; -use libloading::Library; +use flare_helios::nvml::{NOT_SUPPORTED as NVML_ERROR_NOT_SUPPORTED, Nvml}; type Result = std::result::Result>; @@ -24,120 +24,74 @@ fn platform_from_capability(major: u32, minor: u32) -> Option<&'static str> { flare_helios::core::naming::platform_from_capability(major, minor) } -const NVML_ERROR_NOT_SUPPORTED: c_int = 3; - pub fn detect(count: usize) -> Result<&'static str> { let inherited = std::env::var("CUDA_VISIBLE_DEVICES").ok(); let indices: Vec<_> = (0..count as i32).collect(); let visible = crate::environment::visibility(&indices, inherited.as_deref())?; - // SAFETY: Only the system driver is loaded, and the library remains live through all calls. - #[cfg(unix)] - let library = unsafe { Library::new("libnvidia-ml.so.1") }; - #[cfg(windows)] - let library = unsafe { - libloading::os::windows::Library::load_with_flags( - "nvml.dll", - windows_sys::Win32::System::LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32, - ) - .map(Library::from) - }; - let library = library.map_err(|error| { + let nvml = Nvml::load().map_err(|error| { format!("cannot detect hardware without NVIDIA NVML: {error}; specify --revision") })?; - // SAFETY: These signatures and PciInfo match nvml.h; output pointers are valid. - unsafe { - let init = library.get:: c_int>(b"nvmlInit_v2\0")?; - let shutdown = library.get:: c_int>(b"nvmlShutdown\0")?; - check("nvmlInit_v2", init())?; - let result = (|| { - let get = library.get:: c_int>( - b"nvmlDeviceGetHandleByIndex_v2\0", - )?; - let get_by_uuid = library - .get:: c_int>( - b"nvmlDeviceGetHandleByUUID\0", - )?; - let get_count = library - .get:: c_int>(b"nvmlDeviceGetCount_v2\0")?; - let get_uuid = library - .get:: c_int>( - b"nvmlDeviceGetUUID\0", - )?; - let get_pci = library.get:: c_int>( - b"nvmlDeviceGetPciInfo_v3\0", - )?; - let get_capability = library - .get:: c_int>( - b"nvmlDeviceGetCudaComputeCapability\0", - ) - .ok(); - let mut selected = None; - for entry in visible.split(',') { - let mut device = std::ptr::null_mut(); - if let Ok(index) = entry.parse::() { - check("nvmlDeviceGetHandleByIndex_v2", get(index, &mut device))?; - } else if entry.len() == 40 { - let uuid = CString::new(entry)?; - check( - "nvmlDeviceGetHandleByUUID", - get_by_uuid(uuid.as_ptr(), &mut device), - )?; - } else { - let mut total = 0; - check("nvmlDeviceGetCount_v2", get_count(&mut total))?; - let mut candidates = Vec::new(); - for index in 0..total { - let mut candidate = std::ptr::null_mut(); - check("nvmlDeviceGetHandleByIndex_v2", get(index, &mut candidate))?; - let mut uuid = [0; 96]; - check( - "nvmlDeviceGetUUID", - get_uuid(candidate, uuid.as_mut_ptr(), 96), - )?; - candidates.push(( - CStr::from_ptr(uuid.as_ptr()).to_str()?.to_owned(), - candidate, - )); - } - device = candidates[unique_uuid(entry, &candidates)?].1; - } - let mut pci: PciInfo = std::mem::zeroed(); - let pci_status = get_pci(device, &mut pci); - let detected = if pci_status == NVML_ERROR_NOT_SUPPORTED { - let (mut major, mut minor) = (0, 0); - let capability = get_capability.as_ref().and_then(|query| { - (query(device, &mut major, &mut minor) == 0 && major > 0 && minor >= 0) - .then_some((major as u32, minor as u32)) + let mut selected = None; + for entry in visible.split(',') { + let device = if let Ok(index) = entry.parse::() { + nvml.device_by_index(index) + .map_err(|code| check("nvmlDeviceGetHandleByIndex_v2", code).unwrap_err())? + } else if entry.len() == 40 { + let uuid = CString::new(entry)?; + nvml.device_by_uuid(&uuid) + .map_err(|code| check("nvmlDeviceGetHandleByUUID", code).unwrap_err())? + } else { + let total = nvml + .device_count() + .map_err(|code| check("nvmlDeviceGetCount_v2", code).unwrap_err())?; + let mut candidates = Vec::new(); + for index in 0..total { + let candidate = nvml + .device_by_index(index) + .map_err(|code| check("nvmlDeviceGetHandleByIndex_v2", code).unwrap_err())?; + let uuid = nvml + .device_uuid(candidate) + .map_err(|code| check("nvmlDeviceGetUUID", code).unwrap_err())?; + candidates.push((uuid, candidate)); + } + candidates[unique_uuid(entry, &candidates)?].1 + }; + let detected = match nvml.device_pci_info(device) { + Err(NVML_ERROR_NOT_SUPPORTED) => { + let capability = nvml + .device_cuda_compute_capability(device) + .and_then(|res| res.ok()) + .and_then(|(major, minor)| { + (major > 0 && minor >= 0).then_some((major as u32, minor as u32)) }); - capability - .and_then(|(major, minor)| platform_from_capability(major, minor)) - .ok_or_else(|| { - format!( - "GPU {entry} does not report a PCI ID and has unsupported compute capability; specify --revision" - ) - })? - } else { - check("nvmlDeviceGetPciInfo_v3", pci_status)?; - platform(pci.device_id).ok_or_else(|| { + capability + .and_then(|(major, minor)| platform_from_capability(major, minor)) + .ok_or_else(|| { format!( - "GPU {entry} has unsupported PCI ID {:#010x}; specify --revision", - pci.device_id + "GPU {entry} does not report a PCI ID and has unsupported compute capability; specify --revision" ) })? - }; - if selected.is_some_and(|value| value != detected) { - return Err( - "selected GPUs span multiple platforms; select one platform or specify --revision" - .into(), - ); - } - selected = Some(detected); } - selected.ok_or_else(|| "select at least one GPU or specify --revision".into()) - })(); - let closed = check("nvmlShutdown", shutdown()); - result.and_then(|revision| closed.map(|()| revision)) + Err(code) => { + check("nvmlDeviceGetPciInfo_v3", code)?; + unreachable!() + } + Ok(pci) => platform(pci.device_id).ok_or_else(|| { + format!( + "GPU {entry} has unsupported PCI ID {:#010x}; specify --revision", + pci.device_id + ) + })?, + }; + if selected.is_some_and(|value| value != detected) { + return Err( + "selected GPUs span multiple platforms; select one platform or specify --revision" + .into(), + ); + } + selected = Some(detected); } + selected.ok_or_else(|| "select at least one GPU or specify --revision".into()) } /// Driver-reported GPU metadata; querying NVML creates no CUDA context. @@ -153,138 +107,61 @@ pub struct GpuInfo { pub platform: Option, } -#[repr(C)] -struct NvmlMemory { - total: u64, - free: u64, - used: u64, -} - /// Enumerate actual NVIDIA devices and their inherited visibility without changing process policy. pub fn inventory() -> Result> { - #[cfg(unix)] - let library = unsafe { Library::new("libnvidia-ml.so.1") }; - #[cfg(windows)] - let library = unsafe { - libloading::os::windows::Library::load_with_flags( - "nvml.dll", - windows_sys::Win32::System::LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32, - ) - .map(Library::from) - }; - let library = - library.map_err(|error| format!("NVIDIA device information is unavailable: {error}"))?; - // SAFETY: These NVML signatures match the system driver. Every output buffer is live and - // the library remains loaded until the initialized NVML reference has been released. - unsafe { - let init = library.get:: c_int>(b"nvmlInit_v2\0")?; - let shutdown = library.get:: c_int>(b"nvmlShutdown\0")?; - let initialized = init(); - if initialized != 0 { - return Err(format!("NVIDIA device query failed with NVML error {initialized}").into()); - } - let result = (|| -> Result> { - let count_fn = library - .get:: c_int>(b"nvmlDeviceGetCount_v2\0")?; - let get = library.get:: c_int>( - b"nvmlDeviceGetHandleByIndex_v2\0", - )?; - let name_fn = library - .get:: c_int>( - b"nvmlDeviceGetName\0", - )?; - let uuid_fn = library - .get:: c_int>( - b"nvmlDeviceGetUUID\0", - )?; - let memory_fn = library.get:: c_int>( - b"nvmlDeviceGetMemoryInfo\0", - )?; - let architecture_fn = library - .get:: c_int>( - b"nvmlDeviceGetCudaComputeCapability\0", - ) - .ok(); - let pci_fn = library.get:: c_int>( - b"nvmlDeviceGetPciInfo_v3\0", - )?; - let mut count = 0; - let code = count_fn(&mut count); - if code != 0 { - return Err( - format!("NVIDIA device enumeration failed with NVML error {code}").into(), - ); - } - let mut devices = Vec::new(); - for ordinal in 0..count { - let mut device = std::ptr::null_mut(); - let code = get(ordinal, &mut device); - if code != 0 { - return Err( - format!("Cannot query NVIDIA GPU {ordinal}: NVML error {code}").into(), - ); - } - let mut name = [0 as c_char; 256]; - let mut uuid = [0 as c_char; 96]; - let name = if name_fn(device, name.as_mut_ptr(), name.len() as u32) == 0 { - CStr::from_ptr(name.as_ptr()).to_string_lossy().into_owned() - } else { - format!("NVIDIA GPU {ordinal}") - }; - let uuid = if uuid_fn(device, uuid.as_mut_ptr(), uuid.len() as u32) == 0 { - CStr::from_ptr(uuid.as_ptr()).to_string_lossy().into_owned() - } else { - String::new() - }; - let mut memory: NvmlMemory = std::mem::zeroed(); - let memory_known = memory_fn(device, &mut memory) == 0 - && memory.total > 0 - && memory.total != u64::MAX; - let mut major = 0; - let mut minor = 0; - let architecture = architecture_fn.as_ref().and_then(|query| { - (query(device, &mut major, &mut minor) == 0 && major > 0 && minor >= 0) - .then_some([major as u32, minor as u32]) - }); - let mut pci: PciInfo = std::mem::zeroed(); - let platform = (pci_fn(device, &mut pci) == 0) - .then(|| platform(pci.device_id)) - .flatten() - .or_else(|| { - architecture - .and_then(|[major, minor]| platform_from_capability(major, minor)) - }) - .map(str::to_owned); - // NVML also enumerates accelerators without CUDA capability or a supported GPU identity. - if architecture.is_none() && platform.is_none() { - continue; - } - devices.push(GpuInfo { - ordinal, - visible_ordinal: None, - name, - uuid, - total_memory_bytes: memory_known.then_some(memory.total), - free_memory_bytes: (memory_known && memory.free <= memory.total) - .then_some(memory.free), - architecture, - platform, - }); - } - assign_visibility( - &mut devices, - std::env::var("CUDA_VISIBLE_DEVICES").ok().as_deref(), - )?; - Ok(devices) - })(); - let released = shutdown(); - if released != 0 { - return Err( - format!("NVIDIA device query shutdown failed with NVML error {released}").into(), - ); + let nvml = + Nvml::load().map_err(|error| format!("NVIDIA device information is unavailable: {error}"))?; + let count = nvml + .device_count() + .map_err(|code| format!("NVIDIA device enumeration failed with NVML error {code}"))?; + let mut devices = Vec::new(); + for ordinal in 0..count { + let device = nvml + .device_by_index(ordinal) + .map_err(|code| format!("Cannot query NVIDIA GPU {ordinal}: NVML error {code}"))?; + let name = nvml + .device_name(device) + .unwrap_or_else(|_| format!("NVIDIA GPU {ordinal}")); + let uuid = nvml.device_uuid(device).unwrap_or_default(); + let memory = nvml.device_memory_info(device).ok(); + let memory_known = + memory.is_some_and(|info| info.total > 0 && info.total != u64::MAX); + let architecture = nvml + .device_cuda_compute_capability(device) + .and_then(|res| res.ok()) + .and_then(|(major, minor)| { + (major > 0 && minor >= 0).then_some([major as u32, minor as u32]) + }); + let platform = nvml + .device_pci_info(device) + .ok() + .and_then(|pci| platform(pci.device_id)) + .or_else(|| { + architecture.and_then(|[major, minor]| platform_from_capability(major, minor)) + }) + .map(str::to_owned); + // NVML also enumerates accelerators without CUDA capability or a supported GPU identity. + if architecture.is_none() && platform.is_none() { + continue; } - result + devices.push(GpuInfo { + ordinal, + visible_ordinal: None, + name, + uuid, + total_memory_bytes: memory.filter(|_| memory_known).map(|info| info.total), + free_memory_bytes: memory + .filter(|info| memory_known && info.free <= info.total) + .map(|info| info.free), + architecture, + platform, + }); } + assign_visibility( + &mut devices, + std::env::var("CUDA_VISIBLE_DEVICES").ok().as_deref(), + )?; + Ok(devices) } fn assign_visibility(devices: &mut [GpuInfo], inherited: Option<&str>) -> Result<()> { @@ -306,7 +183,7 @@ fn assign_visibility(devices: &mut [GpuInfo], inherited: Option<&str>) -> Result .filter_map(|(index, device)| { let matches = identifier.parse::().map_or_else( |_| !device.uuid.is_empty() && device.uuid.starts_with(identifier), - |ordinal| index == ordinal as usize, + |ordinal| device.ordinal == ordinal, ); matches.then_some(index) }) @@ -322,21 +199,7 @@ fn assign_visibility(devices: &mut [GpuInfo], inherited: Option<&str>) -> Result Ok(()) } -type Device = *mut c_void; - -/// nvmlPciInfo_t as filled by nvmlDeviceGetPciInfo_v3. -#[repr(C)] -struct PciInfo { - _bus_id_legacy: [c_char; 16], - _domain: c_uint, - _bus: c_uint, - _device: c_uint, - device_id: c_uint, - _subsystem_id: c_uint, - _bus_id: [c_char; 32], -} - -fn unique_uuid(prefix: &str, candidates: &[(String, Device)]) -> Result { +fn unique_uuid(prefix: &str, candidates: &[(String, T)]) -> Result { let mut matches = candidates .iter() .enumerate() @@ -404,12 +267,35 @@ mod tests { ); } + #[test] + fn gpu_inventory_visibility_matches_nvml_ordinal_when_non_cuda_devices_skipped() { + let mut devices = vec![ + GpuInfo { + ordinal: 1, + uuid: "GPU-bbbb".into(), + ..Default::default() + }, + GpuInfo { + ordinal: 3, + uuid: "GPU-dddd".into(), + ..Default::default() + }, + ]; + assign_visibility(&mut devices, Some("3,1")).unwrap(); + assert_eq!(devices[0].visible_ordinal, Some(1)); + assert_eq!(devices[1].visible_ordinal, Some(0)); + for device in &mut devices { + device.visible_ordinal = None; + } + assert!(assign_visibility(&mut devices, Some("0")).is_err()); + } + #[test] fn uuid_selection_requires_an_unambiguous_prefix() { let candidates = vec![ - ("GPU-abcdef01".into(), std::ptr::null_mut()), - ("GPU-abcdef02".into(), std::ptr::null_mut()), - ("GPU-12345678".into(), std::ptr::null_mut()), + ("GPU-abcdef01".into(), 0usize), + ("GPU-abcdef02".into(), 1usize), + ("GPU-12345678".into(), 2usize), ]; assert_eq!(unique_uuid("GPU-abcdef01", &candidates).unwrap(), 0); assert_eq!(unique_uuid("GPU-123", &candidates).unwrap(), 2); diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index 05b39bdce..5136c5289 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -2136,53 +2136,28 @@ fn current_platform(cuda: &Cuda) -> ExportResult> { let slot = attribute("cuDeviceGetAttribute", 34, b"cuDeviceGetAttribute\0")?; let domain = attribute("cuDeviceGetAttribute", 50, b"cuDeviceGetAttribute\0")?; let bus_id = std::ffi::CString::new(format!("{domain:04x}:{bus:02x}:{slot:02x}.0"))?; - let soname = if cfg!(windows) { - "nvml.dll" - } else { - "libnvidia-ml.so.1" - }; - let library = unsafe { Library::new(soname) } + let nvml = helios_core::nvml::Nvml::load() .map_err(|error| invalid(format!("NVML is required to name an export: {error}")))?; - #[repr(C)] - struct PciInfo { - _bus_id_legacy: [c_char; 16], - _domain: c_uint, - _bus: c_uint, - _device: c_uint, - device_id: c_uint, - _subsystem_id: c_uint, - _bus_id: [c_char; 32], - } - unsafe { - let init = library.get:: c_int>(b"nvmlInit_v2\0")?; - let shutdown = library.get:: c_int>(b"nvmlShutdown\0")?; - cuda.check("nvmlInit_v2", init())?; - let result = (|| -> ExportResult> { - let mut handle: *mut c_void = std::ptr::null_mut(); - let get = library - .get:: c_int>( - b"nvmlDeviceGetHandleByPciBusId_v2\0", - )?; - cuda.check( - "nvmlDeviceGetHandleByPciBusId_v2", - get(bus_id.as_ptr(), &mut handle), - )?; - let mut pci = std::mem::zeroed::(); - let get_pci = library - .get:: c_int>( - b"nvmlDeviceGetPciInfo_v3\0", - )?; - cuda.check("nvmlDeviceGetPciInfo_v3", get_pci(handle, &mut pci))?; - match helios_core::core::naming::platform_from_pci(pci.device_id) { - Some(platform) => Ok(Some(platform.to_string())), - None => Err(invalid(format!( - "NVML reports unsupported GPU PCI id {:#010x}", - pci.device_id - ))), - } - })(); - let _ = shutdown(); - result + let handle = match nvml.device_by_pci_bus_id(&bus_id) { + Ok(handle) => handle, + Err(code) => { + cuda.check("nvmlDeviceGetHandleByPciBusId_v2", code)?; + unreachable!() + } + }; + let pci = match nvml.device_pci_info(handle) { + Ok(pci) => pci, + Err(code) => { + cuda.check("nvmlDeviceGetPciInfo_v3", code)?; + unreachable!() + } + }; + match helios_core::core::naming::platform_from_pci(pci.device_id) { + Some(platform) => Ok(Some(platform.to_string())), + None => Err(invalid(format!( + "NVML reports unsupported GPU PCI id {:#010x}", + pci.device_id + ))), } } diff --git a/helios/src/core/cache.rs b/helios/src/core/cache.rs index 666ebfeb7..39809a427 100644 --- a/helios/src/core/cache.rs +++ b/helios/src/core/cache.rs @@ -2589,6 +2589,25 @@ impl Root { Ok(reference) } + /// List every valid source reference stored in this cache root. + pub fn source_refs(&self) -> Result> { + let mut references = Vec::new(); + for path in read_dir(&self.root.join("sources"))? { + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if PayloadId::parse(name).is_err() { + continue; + } + if let Ok(Some(reference)) = Self::read_source_file(&path) + && PayloadId::of(reference.selector().as_bytes()).to_string() == name + { + references.push(reference); + } + } + Ok(references) + } + /// Acquisition references retained by caches without a per-version origin record. pub fn entry_source_refs(&self, entry: &Entry) -> Result> { let mut references = Vec::new(); diff --git a/helios/src/lib.rs b/helios/src/lib.rs index a893143fa..ab331ff2f 100644 --- a/helios/src/lib.rs +++ b/helios/src/lib.rs @@ -15,6 +15,7 @@ pub mod execution; #[cfg(feature = "grammar")] pub mod grammar; pub mod model; +pub mod nvml; pub mod offload; mod os; #[cfg(any(feature = "server", all(kani, feature = "runtime-core")))] diff --git a/helios/src/nvml.rs b/helios/src/nvml.rs new file mode 100644 index 000000000..5b54b1526 --- /dev/null +++ b/helios/src/nvml.rs @@ -0,0 +1,378 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Process-wide dynamic NVML loader shared across Helios, Flare, Flare CLI, and Heliopause. +//! +//! NVML is loaded and initialized once per process through a `OnceLock` and remains initialized +//! until process exit. Repeated `nvmlInit_v2` / `nvmlShutdown` cycles leak an NVML event file +//! descriptor per call, so long-lived polling processes (`HardwareMonitor`, `flare agent`) must +//! never shut down and reinitialize NVML. + +use std::ffi::{CStr, c_char, c_int, c_uint, c_void}; +use std::sync::OnceLock; + +use libloading::Library; + +/// `NVML_ERROR_NOT_SUPPORTED`. +pub const NOT_SUPPORTED: c_int = 3; +/// `NVML_P2P_CAPS_INDEX_NVLINK`. +pub const P2P_CAPS_INDEX_NVLINK: c_uint = 2; +/// `NVML_P2P_STATUS_OK`. +pub const P2P_STATUS_OK: c_uint = 0; +/// `NVML_TEMPERATURE_GPU`. +pub const TEMPERATURE_GPU: c_uint = 0; +/// `NVML_CLOCK_SM`. +pub const CLOCK_SM: c_uint = 1; + +/// Opaque `nvmlDevice_t` handle owned by the loaded NVML library. +#[derive(Clone, Copy, Debug)] +pub struct Device(*mut c_void); + +// SAFETY: NVML device handles are process-wide opaque pointers safe to share across threads. +unsafe impl Send for Device {} +unsafe impl Sync for Device {} + +/// `nvmlMemory_t` (version 1) filled by `nvmlDeviceGetMemoryInfo`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct Memory { + pub total: u64, + pub free: u64, + pub used: u64, +} + +/// `nvmlUtilization_t` filled by `nvmlDeviceGetUtilizationRates`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct Utilization { + pub gpu: c_uint, + pub memory: c_uint, +} + +/// `nvmlPciInfo_t` filled by `nvmlDeviceGetPciInfo_v3`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct PciInfo { + _bus_id_legacy: [c_char; 16], + _domain: c_uint, + _bus: c_uint, + _device: c_uint, + /// PCI device ID in the high 16 bits and vendor ID in the low 16 bits. + pub device_id: c_uint, + _subsystem_id: c_uint, + pub bus_id: [c_char; 32], +} + +impl PciInfo { + /// NUL-terminated PCI bus ID string reported in `bus_id`. + pub fn bus_id_lossy(&self) -> String { + // SAFETY: NVML guarantees NUL termination within `bus_id`; fall back to full slice length. + let bytes: &[u8] = unsafe { + std::slice::from_raw_parts(self.bus_id.as_ptr().cast::(), self.bus_id.len()) + }; + let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); + String::from_utf8_lossy(&bytes[..end]).into_owned() + } +} + +type ErrorStringFn = unsafe extern "C" fn(c_int) -> *const c_char; +type InitFn = unsafe extern "C" fn() -> c_int; +type CountFn = unsafe extern "C" fn(*mut c_uint) -> c_int; +type HandleByIndexFn = unsafe extern "C" fn(c_uint, *mut *mut c_void) -> c_int; +type HandleByStrFn = unsafe extern "C" fn(*const c_char, *mut *mut c_void) -> c_int; +type GetIndexFn = unsafe extern "C" fn(*mut c_void, *mut c_uint) -> c_int; +type GetTextFn = unsafe extern "C" fn(*mut c_void, *mut c_char, c_uint) -> c_int; +type GetMemoryFn = unsafe extern "C" fn(*mut c_void, *mut Memory) -> c_int; +type GetPciFn = unsafe extern "C" fn(*mut c_void, *mut PciInfo) -> c_int; +type GetCapabilityFn = unsafe extern "C" fn(*mut c_void, *mut c_int, *mut c_int) -> c_int; +type GetUtilizationFn = unsafe extern "C" fn(*mut c_void, *mut Utilization) -> c_int; +type GetSensorFn = unsafe extern "C" fn(*mut c_void, c_uint, *mut c_uint) -> c_int; +type GetP2pFn = unsafe extern "C" fn(*mut c_void, *mut c_void, c_uint, *mut c_uint) -> c_int; + +/// Initialized process-wide NVML function table backed by a permanently loaded system library. +pub struct Nvml { + _library: &'static Library, + error_string: Option, + get_count: CountFn, + get_by_index: HandleByIndexFn, + get_by_uuid: HandleByStrFn, + get_by_pci: HandleByStrFn, + get_index: Option, + get_name: GetTextFn, + get_uuid: GetTextFn, + get_memory: GetMemoryFn, + get_pci: GetPciFn, + get_capability: Option, + get_utilization: Option, + get_temperature: Option, + get_clock: Option, + get_p2p: Option, +} + +// SAFETY: All stored symbols point into a leaked process-lifetime dynamic library and NVML APIs +// are thread-safe after `nvmlInit_v2`. +unsafe impl Send for Nvml {} +unsafe impl Sync for Nvml {} + +static NVML: OnceLock> = OnceLock::new(); + +#[cfg(unix)] +const LIBRARY_NAME: &str = "libnvidia-ml.so.1"; +#[cfg(windows)] +const LIBRARY_NAME: &str = "nvml.dll"; + +fn open_system_library() -> std::result::Result { + #[cfg(unix)] + // SAFETY: Loading the system NVIDIA NVML shared library once for the lifetime of the process. + unsafe { + Library::new(LIBRARY_NAME) + } + #[cfg(windows)] + // SAFETY: Restricting lookup to System32 prevents DLL search-order hijacking. + unsafe { + libloading::os::windows::Library::load_with_flags( + LIBRARY_NAME, + windows_sys::Win32::System::LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + .map(Library::from) + } +} + +fn load_symbol(library: &'static Library, name: &[u8]) -> std::result::Result { + // SAFETY: Caller passes the exact C symbol name and matching ABI function pointer type. + unsafe { library.get::(name) } + .map(|symbol| *symbol) + .map_err(|error| error.to_string()) +} + +fn load_optional(library: &'static Library, name: &[u8]) -> Option { + // SAFETY: Caller passes the exact C symbol name and matching ABI function pointer type. + unsafe { library.get::(name) }.ok().map(|symbol| *symbol) +} + +fn describe_code(error_string: Option, code: c_int) -> String { + if let Some(describe) = error_string { + // SAFETY: `nvmlErrorString` accepts any return code and returns a static NUL string. + let ptr = unsafe { describe(code) }; + if !ptr.is_null() { + // SAFETY: Non-null pointer returned by `nvmlErrorString` is valid static NUL text. + return unsafe { CStr::from_ptr(ptr) } + .to_string_lossy() + .into_owned(); + } + } + String::new() +} + +impl Nvml { + /// Load and initialize the system NVML library once for the lifetime of the process. + pub fn load() -> std::result::Result<&'static Self, String> { + NVML.get_or_init(|| { + let library = open_system_library() + .map_err(|error| format!("cannot load {LIBRARY_NAME}: {error}"))?; + // Keep the library mapped permanently; calling `nvmlShutdown` leaks an event FD. + let library: &'static Library = Box::leak(Box::new(library)); + let error_string = load_optional::(library, b"nvmlErrorString\0"); + let init = load_symbol::(library, b"nvmlInit_v2\0")?; + // SAFETY: `nvmlInit_v2` takes no arguments and initializes process-wide NVML state. + let code = unsafe { init() }; + if code != 0 { + let message = describe_code(error_string, code); + return Err(if message.is_empty() { + format!("nvmlInit_v2 failed with NVML error {code}") + } else { + format!("nvmlInit_v2 failed with NVML error {code} ({message})") + }); + } + Ok(Self { + _library: library, + error_string, + get_count: load_symbol(library, b"nvmlDeviceGetCount_v2\0")?, + get_by_index: load_symbol(library, b"nvmlDeviceGetHandleByIndex_v2\0")?, + get_by_uuid: load_symbol(library, b"nvmlDeviceGetHandleByUUID\0")?, + get_by_pci: load_symbol(library, b"nvmlDeviceGetHandleByPciBusId_v2\0")?, + get_index: load_optional(library, b"nvmlDeviceGetIndex\0"), + get_name: load_symbol(library, b"nvmlDeviceGetName\0")?, + get_uuid: load_symbol(library, b"nvmlDeviceGetUUID\0")?, + get_memory: load_symbol(library, b"nvmlDeviceGetMemoryInfo\0")?, + get_pci: load_symbol(library, b"nvmlDeviceGetPciInfo_v3\0")?, + get_capability: load_optional(library, b"nvmlDeviceGetCudaComputeCapability\0"), + get_utilization: load_optional(library, b"nvmlDeviceGetUtilizationRates\0"), + get_temperature: load_optional(library, b"nvmlDeviceGetTemperature\0"), + get_clock: load_optional(library, b"nvmlDeviceGetClockInfo\0"), + get_p2p: load_optional(library, b"nvmlDeviceGetP2PStatus\0"), + }) + }) + .as_ref() + .map_err(Clone::clone) + } + + /// Human-readable NVML error description when `nvmlErrorString` is present. + pub fn error_string(&self, code: c_int) -> String { + describe_code(self.error_string, code) + } + + pub fn device_count(&self) -> std::result::Result { + let mut count: c_uint = 0; + // SAFETY: Output pointer is valid for the duration of the call. + let code = unsafe { (self.get_count)(&mut count) }; + if code == 0 { Ok(count) } else { Err(code) } + } + + pub fn device_by_index(&self, index: u32) -> std::result::Result { + let mut handle: *mut c_void = std::ptr::null_mut(); + // SAFETY: Output pointer is valid for the duration of the call. + let code = unsafe { (self.get_by_index)(index, &mut handle) }; + if code == 0 { + Ok(Device(handle)) + } else { + Err(code) + } + } + + pub fn device_by_uuid(&self, uuid: &CStr) -> std::result::Result { + let mut handle: *mut c_void = std::ptr::null_mut(); + // SAFETY: `uuid` is NUL-terminated and `handle` is a valid output pointer. + let code = unsafe { (self.get_by_uuid)(uuid.as_ptr(), &mut handle) }; + if code == 0 { + Ok(Device(handle)) + } else { + Err(code) + } + } + + pub fn device_by_pci_bus_id(&self, bus_id: &CStr) -> std::result::Result { + let mut handle: *mut c_void = std::ptr::null_mut(); + // SAFETY: `bus_id` is NUL-terminated and `handle` is a valid output pointer. + let code = unsafe { (self.get_by_pci)(bus_id.as_ptr(), &mut handle) }; + if code == 0 { + Ok(Device(handle)) + } else { + Err(code) + } + } + + pub fn device_index(&self, device: Device) -> Option> { + let query = self.get_index?; + let mut index: c_uint = 0; + // SAFETY: `device` is an active NVML handle and `index` is valid. + let code = unsafe { query(device.0, &mut index) }; + Some(if code == 0 { Ok(index) } else { Err(code) }) + } + + pub fn device_name(&self, device: Device) -> std::result::Result { + let mut buffer = [0 as c_char; 256]; + // SAFETY: `buffer` has length 256 and NVML writes a NUL-terminated name. + let code = unsafe { (self.get_name)(device.0, buffer.as_mut_ptr(), buffer.len() as c_uint) }; + if code == 0 { + Ok(text_from_c_chars(&buffer)) + } else { + Err(code) + } + } + + pub fn device_uuid(&self, device: Device) -> std::result::Result { + let mut buffer = [0 as c_char; 96]; + // SAFETY: `buffer` has length 96 and NVML writes a NUL-terminated UUID. + let code = unsafe { (self.get_uuid)(device.0, buffer.as_mut_ptr(), buffer.len() as c_uint) }; + if code == 0 { + Ok(text_from_c_chars(&buffer)) + } else { + Err(code) + } + } + + pub fn device_memory_info(&self, device: Device) -> std::result::Result { + let mut memory = Memory::default(); + // SAFETY: `Memory` matches `nvmlMemory_t` layout and is valid for writing. + let code = unsafe { (self.get_memory)(device.0, &mut memory) }; + if code == 0 { Ok(memory) } else { Err(code) } + } + + pub fn device_pci_info(&self, device: Device) -> std::result::Result { + // SAFETY: `PciInfo` is a `#[repr(C)]` POD struct; zeroed bytes are valid. + let mut pci: PciInfo = unsafe { std::mem::zeroed() }; + // SAFETY: `PciInfo` matches `nvmlPciInfo_t` layout for `nvmlDeviceGetPciInfo_v3`. + let code = unsafe { (self.get_pci)(device.0, &mut pci) }; + if code == 0 { Ok(pci) } else { Err(code) } + } + + pub fn device_cuda_compute_capability( + &self, + device: Device, + ) -> Option> { + let query = self.get_capability?; + let (mut major, mut minor) = (0 as c_int, 0 as c_int); + // SAFETY: Output pointers are valid for the duration of the call. + let code = unsafe { query(device.0, &mut major, &mut minor) }; + Some(if code == 0 { + Ok((major, minor)) + } else { + Err(code) + }) + } + + pub fn device_utilization_rates( + &self, + device: Device, + ) -> std::result::Result { + let Some(query) = self.get_utilization else { + return Err(NOT_SUPPORTED); + }; + let mut rates = Utilization::default(); + // SAFETY: `Utilization` matches `nvmlUtilization_t` layout. + let code = unsafe { query(device.0, &mut rates) }; + if code == 0 { Ok(rates) } else { Err(code) } + } + + pub fn device_temperature( + &self, + device: Device, + sensor: c_uint, + ) -> std::result::Result { + let Some(query) = self.get_temperature else { + return Err(NOT_SUPPORTED); + }; + let mut value: c_uint = 0; + // SAFETY: Output pointer is valid for the duration of the call. + let code = unsafe { query(device.0, sensor, &mut value) }; + if code == 0 { Ok(value) } else { Err(code) } + } + + pub fn device_clock_info( + &self, + device: Device, + clock_type: c_uint, + ) -> std::result::Result { + let Some(query) = self.get_clock else { + return Err(NOT_SUPPORTED); + }; + let mut value: c_uint = 0; + // SAFETY: Output pointer is valid for the duration of the call. + let code = unsafe { query(device.0, clock_type, &mut value) }; + if code == 0 { Ok(value) } else { Err(code) } + } + + pub fn device_p2p_status( + &self, + device1: Device, + device2: Device, + p2p_index: c_uint, + ) -> Option> { + let query = self.get_p2p?; + let mut status: c_uint = 0; + // SAFETY: Output pointer is valid for the duration of the call. + let code = unsafe { query(device1.0, device2.0, p2p_index, &mut status) }; + Some(if code == 0 { Ok(status) } else { Err(code) }) + } +} + +fn text_from_c_chars(buffer: &[c_char]) -> String { + // SAFETY: Reinterpreting `c_char` bytes as `u8` for bounded NUL search. + let bytes: &[u8] = + unsafe { std::slice::from_raw_parts(buffer.as_ptr().cast::(), buffer.len()) }; + let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); + String::from_utf8_lossy(&bytes[..end]).into_owned() +} diff --git a/helios/src/runtime_core/device_memory.rs b/helios/src/runtime_core/device_memory.rs index 8adcaaf04..194cd52d9 100644 --- a/helios/src/runtime_core/device_memory.rs +++ b/helios/src/runtime_core/device_memory.rs @@ -5,18 +5,11 @@ //! Observe memory before creating CUDA contexts, so occupied limits include driver setup. -use std::ffi::{c_char, c_int, c_void}; +use std::ffi::{CStr, c_char, c_int}; use super::{NativeResources, driver::Driver, format::invalid, memory::MemorySnapshot}; use crate::Result; - -#[repr(C)] -#[derive(Default)] -struct NvmlMemory { - total: u64, - free: u64, - used: u64, -} +use crate::nvml::Nvml; fn check(operation: &str, status: c_int) -> Result<()> { if status == 0 { @@ -31,51 +24,17 @@ fn check(operation: &str, status: c_int) -> Result<()> { /// CUDA's cuMemGetInfo requires a context. NVML can observe discrete memory without one. /// Its device is resolved by PCI address so CUDA visibility and NVML ordinals cannot disagree. unsafe fn discrete_free(pci: &[c_char]) -> Result { - #[cfg(unix)] - let library = unsafe { libloading::Library::new("libnvidia-ml.so.1") }; - #[cfg(windows)] - let library = unsafe { - libloading::os::windows::Library::load_with_flags( - "nvml.dll", - windows_sys::Win32::System::LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32, - ) - .map(libloading::Library::from) - }; - let library = - library.map_err(|e| invalid(format!("occupied memory limits require NVIDIA NVML: {e}")))?; - // SAFETY: Signatures and NvmlMemory match NVIDIA's NVML ABI. The library remains live, - // and shutdown balances initialization even if a subsequent query fails. - unsafe { - let init = library - .get:: c_int>(b"nvmlInit_v2\0") - .map_err(|e| e.to_string())?; - let shutdown = library - .get:: c_int>(b"nvmlShutdown\0") - .map_err(|e| e.to_string())?; - let device = library - .get:: c_int>( - b"nvmlDeviceGetHandleByPciBusId_v2\0", - ) - .map_err(|e| e.to_string())?; - let info = library - .get:: c_int>( - b"nvmlDeviceGetMemoryInfo\0", - ) - .map_err(|e| e.to_string())?; - check("nvmlInit_v2", init())?; - let result = (|| { - let mut handle = std::ptr::null_mut(); - check( - "nvmlDeviceGetHandleByPciBusId_v2", - device(pci.as_ptr(), &mut handle), - )?; - let mut memory = NvmlMemory::default(); - check("nvmlDeviceGetMemoryInfo", info(handle, &mut memory))?; - Ok(memory.free) - })(); - shutdown(); - result - } + let nvml = Nvml::load() + .map_err(|e| invalid(format!("occupied memory limits require NVIDIA NVML: {e}")))?; + // SAFETY: `pci` is NUL-terminated by `cuDeviceGetPCIBusId`. + let bus_id = unsafe { CStr::from_ptr(pci.as_ptr()) }; + let handle = nvml + .device_by_pci_bus_id(bus_id) + .map_err(|code| check("nvmlDeviceGetHandleByPciBusId_v2", code).unwrap_err())?; + let memory = nvml + .device_memory_info(handle) + .map_err(|code| check("nvmlDeviceGetMemoryInfo", code).unwrap_err())?; + Ok(memory.free) } impl NativeResources { diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index 16f5fce80..85a44ac29 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -380,6 +380,15 @@ fn bytes(core: &Core, capacity: i32, units: u64) -> Result { }) } +/// Host memory reserved for post-KV-sizing allocations: offload tiers/index/restore staging plus +/// one prepared-input staging window and one decoded-source retention window. +fn planned_host_future(offload_host: u64, input_window: u64, source_window: u64) -> Result { + offload_host + .checked_add(input_window) + .and_then(|bytes| bytes.checked_add(source_window)) + .ok_or_else(|| invalid("CPU image input windows overflow host memory")) +} + /// Additional per-GPU cost above the capture buffer reserved before pool registration. fn capture_growth( layout: &flare_selene::Layout, @@ -851,8 +860,7 @@ impl NativeModel { flare_selene::input::INDEX_HEADROOM_BYTES }; let host = tier_host - .checked_add(staging) - .and_then(|n| n.checked_add(index)) + .checked_add(index) .and_then(|n| n.checked_add(restore_host)) .ok_or_else(|| invalid("prepared input staging overflows host memory"))?; (device, host, tier_host) @@ -872,10 +880,7 @@ impl NativeModel { }; #[cfg(not(feature = "images"))] let source_window = 0; - let host_future = offload_host - .checked_add(input_window) - .and_then(|bytes| bytes.checked_add(source_window)) - .ok_or_else(|| invalid("CPU image input windows overflow host memory"))?; + let host_future = planned_host_future(offload_host, input_window, source_window)?; let mut available = Vec::new(); let mut loaded_bytes = Vec::new(); for (index, (rank, core)) in self.ranks.iter().zip(cores.iter()).enumerate() { @@ -1576,7 +1581,15 @@ mod tests { let (_, warm_host) = warm_and_disk .headroom_with_inputs_for_budget(1, &layout, inputs, None, orin_warm_budget) .unwrap(); - assert_eq!(warm_host, warm_bytes + full); + assert_eq!(warm_host, warm_bytes + bounded); + let discrete_inputs = crate::offload::PrepareInputs { + integrated: false, + ..inputs + }; + let (_, discrete_warm_host) = warm_and_disk + .headroom_with_inputs_for_budget(1, &layout, discrete_inputs, None, orin_warm_budget) + .unwrap(); + assert_eq!(discrete_warm_host, warm_bytes + full); } #[test] @@ -2060,4 +2073,22 @@ mod tests { ); } } + + #[test] + fn planned_host_future_counts_input_window_once() { + let tier_host = 256u64 << 20; + let input_window = 64u64 << 20; + let index_headroom = flare_selene::input::INDEX_HEADROOM_BYTES; + let restore_host = 32u64 << 20; + let source_window = 16u64 << 20; + let offload_host = tier_host + index_headroom + restore_host; + assert_eq!( + planned_host_future(offload_host, input_window, source_window).unwrap(), + tier_host + index_headroom + restore_host + input_window + source_window + ); + assert_eq!( + planned_host_future(0, input_window, source_window).unwrap(), + input_window + source_window + ); + } } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 1f2f01cf3..beca5ae75 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -204,6 +204,7 @@ impl NativeResources { /// Cooperative kernels must tolerate fewer worker CTAs in the largest grid dimension. /// This method makes the owner's context current on the calling thread. pub unsafe fn load(authorized: AuthorizedCore, ordinal: i32) -> Result { + authorized.require_loadable()?; let (archive, mut index) = match authorized.kind { protection::AuthorizedKind::Legacy { archive, index } => (archive, index), protection::AuthorizedKind::Payload(payload) => { diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index b9561b074..43762687a 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -271,9 +271,11 @@ impl NativeModel { Self::load_agreeing(authorized, devices, options, progress, agree) }, super::ModelCore::Payload(payload) => unsafe { + let loadable = payload.is_loadable(); Self::load_agreeing( AuthorizedCore { kind: AuthorizedKind::Payload(payload), + loadable, }, devices, options, @@ -295,6 +297,7 @@ impl NativeModel { progress: &StartupProgress, agree: &mut dyn CacheAgreement, ) -> Result { + authorized.require_loadable()?; let device_labels = options.device_labels.as_deref().unwrap_or(devices); if device_labels.len() != devices.len() { return Err(invalid("GPU label count must match selected devices")); diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index affa8624f..df173554b 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -222,9 +222,29 @@ pub struct LegacyVerified { } pub struct AuthorizedCore { pub(super) kind: AuthorizedKind, + pub(super) loadable: bool, } impl AuthorizedCore { + /// Whether this authorization verified supporting payloads and may enter a GPU loader. + pub fn is_loadable(&self) -> bool { + self.loadable + && match &self.kind { + AuthorizedKind::Legacy { .. } => true, + AuthorizedKind::Payload(core) => core.source.supporting_verified, + } + } + + pub(super) fn require_loadable(&self) -> Result<()> { + if self.is_loadable() { + Ok(()) + } else { + Err(invalid( + "metadata-only authorized core cannot be loaded; authorize with payload verification", + )) + } + } + /// Canonical model ID followed by serving aliases from the signed serving contract. pub fn model_names(&self) -> Result> { let contract = match &self.kind { @@ -425,6 +445,20 @@ impl PayloadSource { pub(super) fn rank_position(&self, rank: usize) -> Result { payload_rank_position(self.authorized.verified().ranks(), rank) } + fn unique_files(&self) -> Vec<&File> { + let mut seen = std::collections::BTreeSet::new(); + let mut unique = Vec::new(); + if seen.insert(Arc::as_ptr(&self.primary) as usize) { + unique.push(self.primary.as_ref()); + } + for file in self.files.values() { + if seen.insert(Arc::as_ptr(&file.file) as usize) { + unique.push(file.file.as_ref()); + } + } + unique + } + fn token_span(&self, use_: &crate::core::schema::wire::PayloadUse) -> Result { let slice = use_ .slice @@ -638,7 +672,16 @@ impl LegacyVerified { self.archive.protection.verify_data(&self.archive) } /// Require explicit acceptance of the authenticated publisher namespace. - pub fn authorize(mut self, accepted: &str, verify_weights: bool) -> Result { + pub fn authorize(self, accepted: &str, verify_weights: bool) -> Result { + self.authorize_with_loadable(accepted, verify_weights, true) + } + + fn authorize_with_loadable( + mut self, + accepted: &str, + verify_weights: bool, + loadable: bool, + ) -> Result { if accepted != self.archive.protection.publisher.namespace { return Err(invalid("publisher namespace acceptance does not match")); } @@ -651,6 +694,7 @@ impl LegacyVerified { archive: self.archive, index: self.index, }, + loadable, }) } } @@ -808,7 +852,8 @@ impl VerifiedCore { } /// Authorize signed metadata without reading payload bytes. A controller that mirrors only a - /// node-held core's index leaves payload verification to the serving ranks. + /// node-held core's index leaves payload verification to the serving ranks. The returned core + /// is metadata-only and rejected by GPU loaders. pub fn authorize_metadata( self, accepted: &str, @@ -831,7 +876,7 @@ impl VerifiedCore { let phase = progress .filter(|_| verify) .map(|progress| progress.phase("Verify stored data", None)); - let authorized = core.authorize(accepted, verify)?; + let authorized = core.authorize_with_loadable(accepted, verify, verify_payloads)?; if let Some(phase) = phase { phase.finish("stored-data contents"); } @@ -844,6 +889,7 @@ impl VerifiedCore { verify_payloads, progress, )?), + loadable: verify_payloads, }), } } @@ -1867,7 +1913,11 @@ impl super::payload::Files for PayloadSource { }) } } - fn release_page_cache(&self) {} + fn release_page_cache(&self) { + for file in self.unique_files() { + crate::os::release_page_cache(file); + } + } fn direct_files(&self) -> Box>> + '_> { Box::new(self.files.values().map(|file| file.direct())) } @@ -2643,6 +2693,9 @@ impl PayloadAuthorizedCore { pub fn source(&self) -> &PayloadSource { &self.source } + pub fn is_loadable(&self) -> bool { + self.source.supporting_verified + } pub fn rank_count(&self) -> usize { self.cores.len() } @@ -2786,6 +2839,11 @@ impl PayloadAuthorizedCore { /// # Safety /// The core must be trusted and the selected device must match its architecture. pub unsafe fn load(mut self, rank: usize, ordinal: i32) -> Result { + if !self.source.supporting_verified { + return Err(invalid( + "metadata-only authorized core cannot be loaded; authorize with payload verification", + )); + } if rank >= self.cores.len() { return Err(invalid("payload rank is outside the deployment")); } @@ -4417,4 +4475,84 @@ mod payload_core_tests { } let _ = std::fs::remove_dir_all(root); } + + #[test] + fn authorize_metadata_is_not_loadable() { + let (root, publishers) = two_initializer_core(); + let verified = VerifiedCore::open_tensor_parallel(&root, &publishers, 1, None).unwrap(); + let authorized = verified + .authorize_metadata(&publishers[0].namespace, false) + .unwrap(); + assert!(!authorized.is_loadable()); + let error = unsafe { super::super::NativeResources::load(authorized, 0) } + .err() + .expect("metadata-only core must be rejected by NativeResources::load"); + assert!( + error.to_string().contains("metadata-only authorized core"), + "{error}" + ); + + let verified = VerifiedCore::open_tensor_parallel(&root, &publishers, 1, None).unwrap(); + let authorized = verified + .authorize_metadata(&publishers[0].namespace, false) + .unwrap(); + let error = unsafe { + super::super::NativeModel::load( + authorized, + &[0], + &super::super::LoadOptions::default(), + &crate::startup::StartupProgress::silent(), + ) + } + .err() + .expect("metadata-only core must be rejected by NativeModel::load"); + assert!( + error.to_string().contains("metadata-only authorized core"), + "{error}" + ); + + let verified = VerifiedCore::open_tensor_parallel(&root, &publishers, 1, None).unwrap(); + let authorized = verified + .authorize_metadata(&publishers[0].namespace, false) + .unwrap(); + let AuthorizedKind::Payload(payload) = authorized.kind else { + panic!("expected payload backend"); + }; + assert!(!payload.is_loadable()); + let error = unsafe { payload.load(0, 0) } + .err() + .expect("metadata-only payload core must be rejected by PayloadAuthorizedCore::load"); + assert!( + error.to_string().contains("metadata-only authorized core"), + "{error}" + ); + + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn payload_source_release_page_cache_deduplicates_unique_files() { + use super::super::payload::Files; + + let (root, publishers) = two_initializer_core(); + let verified = VerifiedCore::open_tensor_parallel(&root, &publishers, 1, None).unwrap(); + let authorized = verified.authorize(&publishers[0].namespace, true).unwrap(); + assert!(authorized.is_loadable()); + let AuthorizedKind::Payload(payload) = &authorized.kind else { + panic!("expected payload backend"); + }; + let unique = payload.source.unique_files(); + let mut expected = std::collections::BTreeSet::new(); + expected.insert(Arc::as_ptr(&payload.source.primary) as usize); + for file in payload.source.files.values() { + expected.insert(Arc::as_ptr(&file.file) as usize); + } + assert_eq!(unique.len(), expected.len()); + assert!( + unique.len() <= payload.source.files.len() + 1, + "deduplicated file count cannot exceed primary + payload entries" + ); + payload.source.release_page_cache(); + let _ = std::fs::remove_dir_all(root); + } } diff --git a/selene/src/offload.rs b/selene/src/offload.rs index 6a15d2446..3b183b325 100644 --- a/selene/src/offload.rs +++ b/selene/src/offload.rs @@ -180,7 +180,6 @@ impl PrefixCacheOffload { (target_intake_slots( layout, inputs.max_active, - self.disk_only(), inputs.integrated, ) as u64) .min(budget) @@ -224,16 +223,16 @@ pub fn intake_slots(layout: &Layout, max_active: usize) -> usize { /// Target intake slot count for local tiers before clamping to the host budget /// and the `intake_slots(layout, 1)` two-window floor. /// -/// Disk-only offload on an integrated-memory device (`CU_DEVICE_ATTRIBUTE_INTEGRATED`) -/// shares physical RAM with the GPU KV cache, so it targets two streaming windows and -/// two continuation rows (`intake_slots(layout, 1)`) rather than scaling with `max_active`. +/// Local offload tiers on an integrated-memory device (`CU_DEVICE_ATTRIBUTE_INTEGRATED`) +/// share physical RAM with the GPU KV cache, so they target two streaming windows and +/// two continuation rows (`intake_slots(layout, 1)`) rather than scaling with `max_active`, +/// whether warm host memory is zero or positive. fn target_intake_slots( layout: &Layout, max_active: usize, - disk_only: bool, integrated: bool, ) -> usize { - if integrated && disk_only { + if integrated { intake_slots(layout, 1) } else { intake_slots(layout, max_active) @@ -604,13 +603,8 @@ pub fn prepare_with_inputs_budget( disk_limit: Some(disk_limit), ..options.clone() }; - let sized_concurrency = if integrated && effective.disk_only() { - 1 - } else { - max_active - }; - let required_intake = - target_intake_slots(&layout, max_active, effective.disk_only(), integrated); + let sized_concurrency = if integrated { 1 } else { max_active }; + let required_intake = target_intake_slots(&layout, max_active, integrated); let directory_lock = directory .as_deref() .map(record::DirectoryLock::acquire) diff --git a/selene/src/offload/tests.rs b/selene/src/offload/tests.rs index f6de44a97..a69f605ae 100644 --- a/selene/src/offload/tests.rs +++ b/selene/src/offload/tests.rs @@ -771,7 +771,10 @@ fn prepare_with_inputs_budget_avoids_post_kv_alloc_shrinkage_and_capture_failure panic!("missing store"); }; let pool_mem = prepared.memory_pool.as_ref().unwrap(); - assert_eq!(pool_mem.intake_slots(), intake_slots(&layout, 16)); + assert_eq!( + pool_mem.intake_slots(), + intake_slots(&layout, if integrated { 1 } else { 16 }) + ); assert!(prepared.intake_warning().is_none()); } @@ -987,8 +990,8 @@ fn integrated_disk_only_bounds_intake_without_warning_and_preserves_other_modes( ); drop(discrete); - // Discrete GPUs, nonzero warm memory on integrated GPUs, disabled disk_limit = 0, - // and pool-only capture keep concurrency-scaled or capture-chain sizing. + // Discrete GPUs keep concurrency-scaled intake; integrated GPUs with nonzero warm memory + // (composite or memory-only) also bound intake to two streaming windows without warnings. let (_, discrete_host) = disk_only .headroom_with_inputs(1, &layout, inputs(active), None) .unwrap(); @@ -1005,11 +1008,11 @@ fn integrated_disk_only_bounds_intake_without_warning_and_preserves_other_modes( let (_, warm_host) = warm_and_disk .headroom_with_inputs_for_budget(1, &layout, integrated_inputs, None, soc_budget) .unwrap(); - assert_eq!(warm_host, warm_bytes + full_bytes); + assert_eq!(warm_host, warm_bytes + bounded_bytes); let Preparation::Store(warm_prepared) = super::prepare_with_inputs_budget( &warm_and_disk, [0; 32], - geometry, + geometry.clone(), vec![(0, 0)], integrated_inputs, Some(warm_host - warm_bytes), @@ -1018,13 +1021,28 @@ fn integrated_disk_only_bounds_intake_without_warning_and_preserves_other_modes( .unwrap() else { panic!("no warm+disk store") }; + assert_eq!(warm_prepared.required_intake, bounded); + assert_eq!(warm_prepared.sized_concurrency, 1); assert_eq!( warm_prepared.memory_pool.as_ref().unwrap().intake_slots(), - full + bounded ); assert!(warm_prepared.intake_warning().is_none()); drop(warm_prepared); + let warm_only = PrefixCacheOffload { + memory_bytes: Some(warm_bytes), + ..Default::default() + }; + let (_, warm_only_host) = warm_only + .headroom_with_inputs_for_budget(1, &layout, integrated_inputs, None, soc_budget) + .unwrap(); + assert_eq!(warm_only_host, warm_bytes + bounded_bytes); + let (_, discrete_warm_host) = warm_and_disk + .headroom_with_inputs_for_budget(1, &layout, inputs(active), None, soc_budget) + .unwrap(); + assert_eq!(discrete_warm_host, warm_bytes + full_bytes); + let disabled_disk = PrefixCacheOffload { disk_limit: Some(0), ..disk_only From 72def4d8fc161f2ac0e8ef515b8378fa046331c9 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Mon, 30 Nov 2026 12:37:02 -0800 Subject: [PATCH 2/2] Reclaim abandoned Orbit staging, fix marker ordering, and harden agent reaper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Interrupted `PUT` or `TRANSFER` operations left unleased directories under `/staging/orbit/cores/` (and companion hardlinks under `staging/orbit/blobs/`) without reclamation. In addition, multi-file `.flare-verified.json` matching zipped `Plan.files` positionally against unsorted `read_dir` output from `move_staged_tree`, `agent::stop` raced `child.wait()` before setting `exited`, `flare agent install` ignored `[paths].core_cache` and top-level `--core-cache` and wrote unquoted systemd `ExecStart=` arguments, `distribution::root` swallowed valid version/rank-mismatch `Join` frames, and `publish_orbit_entry` ignored marker-write failures. Changes: - Reclaim unleased `/staging/orbit/cores/` entries on agent startup, after core `PUT` and `TRANSFER`, and in `helios::core::cache::Root::collect()` (along with unreachable `staging/orbit/blobs/` files); hold shared `flock` leases on staged directories across live controller sessions (`PUT` -> `TRANSFER`), `FETCH`, and staging-backed `RUN` so concurrent GC preserves active staging. - Sort `move_staged_tree` and `write_verified_marker_for` file lists and match `verified_marker_matches` by filename instead of position. - Coordinate Linux child reaping with `stop()` via `waitid(P_PID, ..., WEXITED | WNOWAIT)` and `Group::reap` so `kill()` never targets a reused PID. - Propagate `[paths].core_cache` and top-level `flare agent --core-cache` into `flare agent install` (preserving subcommand precedence) and quote `--core-cache` for systemd `ExecStart=`. - Raise `MAX_PREAUTH_SESSIONS` to 1024 and `MAX_SESSIONS` to 1152 for 16-rank × 64-stream bursts and log when connections are shed; avoid redundant pre-`read_header` controller checks once authorized. - Fail fast in `distribution::root` on valid `Join` frames with an incompatible version or invalid/duplicate rank while still ignoring malformed TCP probes; propagate `.verified`/`.flare-verified.json` write errors in `publish_orbit_entry` and roll back the unpublished entry. - Share `helios::core::cache::ROOT_DIRECTORIES` with `core_cache::evict`, remove redundant `AuthorizedCore::is_loadable` and NVML `check(..)` wrappers, and document manual cleanup of legacy flat rank directories in `docs/orbit.md`. Verified with `--locked --release` tests: `helios` `core::`/`runtime_core::`/ `nvml` (505 passed, 12 ignored), `flare` (238 unit + 8 integration passed, 4 ignored), `flare-cli` (212 unit + 26 integration passed, 3 ignored), and `heliopause` (216 passed, 6 ignored). Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b --- docs/orbit.md | 13 +- flare-cli/src/config.rs | 65 +++++- flare-cli/src/core_cache.rs | 20 +- flare-cli/src/distribution.rs | 95 +++++++- flare-cli/src/orbit/agent.rs | 276 +++++++++++++++++++---- flare/src/hardware.rs | 26 +-- heliopause/src/export/capture.rs | 20 +- helios/src/core/cache.rs | 84 +++++++ helios/src/runtime_core/device_memory.rs | 16 +- helios/src/runtime_core/protection.rs | 6 +- 10 files changed, 504 insertions(+), 117 deletions(-) diff --git a/docs/orbit.md b/docs/orbit.md index 8a4aa4905..fe28ddfba 100644 --- a/docs/orbit.md +++ b/docs/orbit.md @@ -504,10 +504,15 @@ the staged directory without publishing an entry. `--verify-weights` asks each serving rank to digest its stored data during loading as well. Running groups and active controller sessions hold `flock` leases on published -model-cache entries. Receiving a core never sweeps or evicts directories inside -``; use `flare models remove` and `flare models gc` to reclaim -unleased entries and unreachable blobs. Receiving an executable override evicts -only unpinned files in `~/.cache/flare/bin/`. +model-cache entries. Receiving a core never sweeps or evicts published entries +inside `/models/`; abandoned unleased directories under +`/staging/orbit/` are reclaimed on agent startup, after subsequent +core transfers, and by `flare models gc`. Use `flare models remove` and +`flare models gc` to reclaim unleased published entries and unreachable blobs. +Receiving an executable override evicts only unpinned files in +`~/.cache/flare/bin/`. Flat rank directories left directly under +`/` (or `~/.cache/flare/cores/`) by older agents are not migrated +automatically and can be removed manually once unused. ## Prestaging diff --git a/flare-cli/src/config.rs b/flare-cli/src/config.rs index f32f64681..e13b5351b 100644 --- a/flare-cli/src/config.rs +++ b/flare-cli/src/config.rs @@ -135,9 +135,17 @@ impl Configuration { _ => {} } } - cli::Command::Agent(args) => { - args.core_cache.get_or_insert(cache); - } + cli::Command::Agent(args) => match &mut args.command { + None => { + args.core_cache.get_or_insert(cache); + } + Some(cli::AgentCommand::Install { core_cache, .. }) => { + if core_cache.is_none() { + *core_cache = args.core_cache.clone().or_else(|| self.core_cache(home)); + } + } + _ => {} + }, cli::Command::Orbit(args) => match &mut args.command { cli::OrbitCommand::Run(run) => { run.serving.hub.core_cache.get_or_insert(cache); @@ -812,4 +820,55 @@ namespace = "publisher" assert!(!options.iter().any(|arg| arg == "--roce-ring" || arg == "--roce-chain")); assert!(options.iter().any(|arg| arg == "--max-concurrency")); } + + #[test] + fn agent_install_propagates_config_and_top_level_core_cache_with_subcommand_precedence() { + let home = Path::new("/home/test-user"); + let configured = + Configuration::parse("[paths]\ncore_cache = '/data/flare-cores'\n").unwrap(); + let empty = Configuration::default(); + + let parse_install = |args: &[&str], cfg: &Configuration| -> Option { + let matches = cli::Cli::command().try_get_matches_from(args).unwrap(); + let mut parsed = cli::Cli::from_arg_matches(&matches).unwrap(); + cfg.apply(&mut parsed, &matches, home).unwrap(); + let cli::Command::Agent(agent) = parsed.command else { + panic!("expected agent command"); + }; + let Some(cli::AgentCommand::Install { core_cache, .. }) = agent.command else { + panic!("expected agent install"); + }; + core_cache + }; + + assert_eq!(parse_install(&["flare", "agent", "install"], &empty), None); + assert_eq!( + parse_install(&["flare", "agent", "install"], &configured).as_deref(), + Some(Path::new("/data/flare-cores")) + ); + assert_eq!( + parse_install( + &["flare", "agent", "--core-cache", "/top/cores", "install"], + &configured + ) + .as_deref(), + Some(Path::new("/top/cores")) + ); + assert_eq!( + parse_install( + &[ + "flare", + "agent", + "--core-cache", + "/top/cores", + "install", + "--core-cache", + "/sub/cores" + ], + &configured + ) + .as_deref(), + Some(Path::new("/sub/cores")) + ); + } } diff --git a/flare-cli/src/core_cache.rs b/flare-cli/src/core_cache.rs index 75546287d..1a8540107 100644 --- a/flare-cli/src/core_cache.rs +++ b/flare-cli/src/core_cache.rs @@ -70,7 +70,6 @@ impl Drop for Lease { } impl Lease { - #[cfg(test)] pub fn shared(directory: &Path) -> Result { let file = Self::open(directory)?; let lease = Self(file); @@ -86,6 +85,12 @@ impl Lease { Ok(lease) } + /// Atomically convert an exclusive lease into a shared lease on the same open file description. + pub fn downgrade(self) -> Result { + self.lock(libc::LOCK_SH)?; + Ok(self) + } + fn open(directory: &Path) -> Result { let locks = directory .parent() @@ -231,12 +236,6 @@ impl Drop for Pinned { } } -/// 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", -]; - /// Remove a kind directory's units that nothing pins, leaving transfers in progress. pub fn evict(directory: &Path, pins: &Pins) -> Result, Failure> { let pins = pins.lock().unwrap(); @@ -245,7 +244,8 @@ pub fn evict(directory: &Path, pins: &Pins) -> Result, Failure> { let path = entry?.path(); let name = path.file_name().and_then(|name| name.to_str()); let hidden = name.is_none_or(|name| name.starts_with('.')); - let managed = name.is_some_and(|name| HELIOS_CACHE_DIRS.contains(&name)); + let managed = name + .is_some_and(|name| flare_helios::core::cache::ROOT_DIRECTORIES.contains(&name)); if !hidden && !managed && !pins.contains_key(&path) { let Some(_lease) = Lease::evict(&path)? else { continue; @@ -1937,7 +1937,7 @@ mod entry_path_tests { let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("cores"); fs::create_dir_all(&root).unwrap(); - for managed in HELIOS_CACHE_DIRS { + for managed in flare_helios::core::cache::ROOT_DIRECTORIES { let dir = root.join(managed); fs::create_dir_all(&dir).unwrap(); fs::write(dir.join("sentinel"), b"keep").unwrap(); @@ -1949,7 +1949,7 @@ mod entry_path_tests { let removed = evict(&root, &Pins::default()).unwrap(); assert_eq!(removed, vec![stale.clone()]); assert!(!stale.exists()); - for managed in HELIOS_CACHE_DIRS { + for managed in flare_helios::core::cache::ROOT_DIRECTORIES { assert!( root.join(managed).join("sentinel").is_file(), "managed directory {managed} must survive evict" diff --git a/flare-cli/src/distribution.rs b/flare-cli/src/distribution.rs index 5c390420e..ec6f38612 100644 --- a/flare-cli/src/distribution.rs +++ b/flare-cli/src/distribution.rs @@ -213,11 +213,10 @@ pub fn root( || join.rank >= world || peers[join.rank].is_some() { - eprintln!( - "ignoring unexpected rendezvous join from {peer_addr} (version {}, rank {})", - join.version, join.rank + return Err( + "serving rank has an incompatible protocol, duplicate rank, or invalid rank" + .into(), ); - continue; } endpoints[join.rank] = join.endpoint; configure(&socket, TIMEOUT)?; @@ -661,6 +660,7 @@ pub(crate) fn write_verified_marker_for( device, }); } + files.sort_by(|a, b| a.name.cmp(&b.name)); let marker = VerifiedMarker { version: 2, envelope: hex_bytes(&envelope), @@ -716,11 +716,21 @@ fn verified_marker_matches(root: &Path, plan: &Plan, rank: usize) -> bool { return false; } // Cheap identity checks first: a file that was replaced, truncated, or rewritten fails - // without reading its contents. - for (file, expected) in plan.files.iter().zip(&marker.files) { - if entry_file_name(plan, file) != expected.name { + // without reading its contents. Match by filename so marker generation order cannot cause + // false misses on multi-file cores. + let by_name: std::collections::BTreeMap<&str, &VerifiedFile> = marker + .files + .iter() + .map(|file| (file.name.as_str(), file)) + .collect(); + if by_name.len() != plan.files.len() { + return false; + } + for file in &plan.files { + let name = entry_file_name(plan, file); + let Some(expected) = by_name.get(name.as_str()) else { return false; - } + }; let Ok(metadata) = fs::metadata(root.join(&expected.name)) else { return false; }; @@ -1609,6 +1619,75 @@ mod tests { assert!(socket.read_exact(&mut [0; 8]).is_err()); assert!(source.finish().is_err()); } + + #[test] + fn verified_marker_matches_independent_of_file_order() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + fs::create_dir_all(root.join("weights")).unwrap(); + fs::write(root.join("model.safetensors"), b"primary-bytes").unwrap(); + fs::write(root.join("weights/b.safetensors"), b"companion-b").unwrap(); + fs::write(root.join("weights/a.safetensors"), b"companion-a").unwrap(); + + let envelope = [0x42u8; 32]; + // Write marker with unsorted order (as raw read_dir could produce). + write_verified_marker_for( + root, + envelope, + "exp-order", + 1, + &[ + "weights/b.safetensors".into(), + "model.safetensors".into(), + "weights/a.safetensors".into(), + ], + ) + .unwrap(); + + let plan = Plan { + version: VERSION, + rank: 1, + export: "exp-order".into(), + primary: "orig-primary.safetensors".into(), + directory: "exp-order-rank1".into(), + files: vec![ + FileSpec { + name: "orig-primary.safetensors".into(), + size: 13, + ranges: vec![(0, 13)], + }, + FileSpec { + name: "weights/b.safetensors".into(), + size: 11, + ranges: vec![(0, 11)], + }, + FileSpec { + name: "weights/a.safetensors".into(), + size: 11, + ranges: vec![(0, 11)], + }, + ], + model: "fixture".into(), + platform: "gb10".into(), + tensor_parallel: 2, + expected_envelope: envelope, + publisher: Publisher { + name: "Fixture".into(), + namespace: "local-development".into(), + development: true, + public_key: [0; 32], + }, + topology: Topology::plan(&vec![b"a 127.0.0.1/8 -\n".to_vec(); 2], &[1, 2], false) + .unwrap(), + streams: 1, + stage_only: false, + }; + assert!(verified_marker_matches(root, &plan, 1)); + + // Mutating one companion invalidates the marker. + fs::write(root.join("weights/a.safetensors"), b"companion-a-mutated").unwrap(); + assert!(!verified_marker_matches(root, &plan, 1)); + } } #[cfg(test)] diff --git a/flare-cli/src/orbit/agent.rs b/flare-cli/src/orbit/agent.rs index ce1f66bc7..0d5ac0dcb 100644 --- a/flare-cli/src/orbit/agent.rs +++ b/flare-cli/src/orbit/agent.rs @@ -290,15 +290,17 @@ struct Log { pins: Option, /// Managed `helios::core::cache::Root` lease held while the rank runs. core_lease: Option, + /// Shared staging-directory lock held when a rank runs directly from `staging/orbit`. + staging_lease: Option, } const RETAINED_BYTES: usize = 64 << 10; /// Maximum concurrent unauthenticated sessions awaiting handshake or authorization. -/// Sized above a multi-host burst of parallel fabric transfers (e.g. 64 streams per peer) while +/// Sized above a 16-rank burst of 64-stream fabric transfers (15 peers x 64 streams = 960) while /// still bounding pre-auth OS threads against connection floods. -const MAX_PREAUTH_SESSIONS: usize = 256; -/// Maximum total concurrent agent session threads (up to 16 ranks x 64 fabric streams plus control). -const MAX_SESSIONS: usize = 1024; +const MAX_PREAUTH_SESSIONS: usize = 1024; +/// Maximum total concurrent agent session threads (fabric burst plus control/attach sessions). +const MAX_SESSIONS: usize = 1152; /// Maximum time the rank reaper waits for stdout/stderr forwarders to reach EOF after the child /// exits before releasing GPUs, pins, leases, and notifying attached subscribers. const FORWARDER_DRAIN_TIMEOUT: Duration = Duration::from_secs(2); @@ -341,7 +343,9 @@ pub struct Group { /// UUIDs of the GPUs the rank holds while it runs. pub gpus: Vec, pub pid: i32, - /// Set immediately after `child.wait()` reaps the process so STOP cannot signal a reused PID. + /// Coordinates process reaping with STOP so `kill()` never targets a reused PID. + reap: Mutex<()>, + /// Set under `reap` before reaping the child so STOP cannot signal a reused PID. exited: AtomicBool, /// Rank zero's metrics URL, derived from its HTTP bind options; None for a peer rank. pub metrics_url: Option, @@ -372,6 +376,7 @@ impl Group { log.subscribers.clear(); log.pins = None; log.core_lease = None; + log.staging_lease = None; } pub fn running(&self) -> bool { @@ -497,8 +502,7 @@ const SAMPLE_PERIOD: Duration = Duration::from_secs(1); /// Parse `--rank` into `(, R)` when a directory name follows that form. 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 (prefix, rank) = parse_rank_selector(directory)?; let (export, len_str) = prefix.rsplit_once('-')?; if export.is_empty() || len_str.parse::().is_err() { return None; @@ -586,6 +590,9 @@ fn move_staged_tree( files.push(dest_rel.to_string_lossy().into_owned()); } } + if relative.as_os_str().is_empty() { + files.sort(); + } Ok(()) } @@ -692,7 +699,11 @@ impl Agent { fn init_core_cache(&self) -> Result<(), Failure> { let _ = self.core_root()?; - fs::create_dir_all(cache::cores_directory(&self.staging_root()))?; + let staging_cores = cache::cores_directory(&self.staging_root()); + fs::create_dir_all(&staging_cores)?; + for removed in cache::evict(&staging_cores, &self.pins)? { + eprintln!("removed abandoned staging {}", removed.display()); + } Ok(()) } @@ -801,18 +812,28 @@ impl Agent { } let entry = staging.commit().map_err(|e| Failure::from(e.to_string()))?; let _ = fs::remove_dir_all(staged_dir); - let _ = fs::write( - entry.directory().join(VERIFIED), - format!("{} {}\n", grant.primary(), grant.core.length), - ); - if real_core { - let _ = crate::distribution::write_verified_marker_for( - entry.directory(), - envelope, - &grant.core.export, - rank, - &entry_files, - ); + let marker_result = (|| -> Result<(), Failure> { + fs::write( + entry.directory().join(VERIFIED), + format!("{} {}\n", grant.primary(), grant.core.length), + )?; + if real_core { + crate::distribution::write_verified_marker_for( + entry.directory(), + envelope, + &grant.core.export, + rank, + &entry_files, + )?; + } + Ok(()) + })(); + if let Err(error) = marker_result { + let model = entry.model().to_owned(); + let id = entry.id().to_owned(); + drop(entry); + let _ = root.remove(&model, &id, false); + return Err(error); } root.publish_source_ref( &format!("orbit:{directory}"), @@ -1014,9 +1035,7 @@ impl Agent { } } let mut cores = Vec::with_capacity(by_name.len()); - let mut seen_names: std::collections::HashSet = std::collections::HashSet::new(); - for (name, entry) in by_name { - seen_names.insert(name.clone()); + for (name, entry) in &by_name { let directory = entry.directory(); let mut files = Vec::new(); let mut bytes = 0u64; @@ -1048,7 +1067,7 @@ impl Agent { .unwrap() .to_string_lossy() .into_owned(); - if seen_names.contains(&name) { + if by_name.contains_key(&name) { continue; } let mut files = Vec::new(); @@ -1110,11 +1129,23 @@ pub fn serve_on(listener: TcpListener, agent: Arc) -> Result<(), Failure> for connection in listener.incoming() { let Ok(stream) = connection else { continue }; let Some(session_guard) = SlotGuard::try_acquire(&active_sessions, MAX_SESSIONS) else { + let peer = stream + .peer_addr() + .map(|a| a.to_string()) + .unwrap_or_default(); + eprintln!("shedding connection from {peer}: active session limit ({MAX_SESSIONS}) reached"); drop(stream); continue; }; let Some(preauth_guard) = SlotGuard::try_acquire(&preauth_sessions, MAX_PREAUTH_SESSIONS) else { + let peer = stream + .peer_addr() + .map(|a| a.to_string()) + .unwrap_or_default(); + eprintln!( + "shedding connection from {peer}: pre-auth session limit ({MAX_PREAUTH_SESSIONS}) reached" + ); drop(stream); continue; }; @@ -1144,10 +1175,10 @@ fn session( // Downloads and staged entries stay leased for this controller session, which is the window in // which its transfers read those entries, and drop when the session ends. let mut downloads: Vec = Vec::new(); + let mut staged_leases: BTreeMap = BTreeMap::new(); let mut timeouts_cleared = false; loop { - let authorized = agent.is_controller(&session.remote())?; - if authorized && !timeouts_cleared { + if !timeouts_cleared && agent.is_controller(&session.remote())? { preauth_guard = None; session.clear_timeouts()?; timeouts_cleared = true; @@ -1197,10 +1228,16 @@ fn session( let request = json_body(&mut session, length)?; have(agent, &mut pinned, &mut downloads, &request) } - frame::PUT => put(agent, &mut session, &mut pinned, length), + frame::PUT => put(agent, &mut session, &mut pinned, &mut staged_leases, length), frame::TRANSFER => { let request = json_body(&mut session, length)?; - transfer(agent, &mut pinned, &mut downloads, &request) + transfer( + agent, + &mut pinned, + &mut downloads, + &mut staged_leases, + &request, + ) } frame::RUN | frame::ATTACH => { let request = json_body(&mut session, length)?; @@ -1421,6 +1458,7 @@ fn put( agent: &Agent, session: &mut Session, pinned: &mut Pinned, + staged_leases: &mut BTreeMap, length: u64, ) -> Result, Failure> { let mut body = session.body(); @@ -1446,11 +1484,17 @@ fn put( // `core_cache::evict` on `core_cache` or managed Helios directories. let staging = agent.staging_root(); let entry = cache::entry(&staging, cache::kind_directory(kind)?, name)?; - let _lease = cache::Lease::write(&cache::unit(&staging, &entry))?; + let unit = cache::unit(&staging, &entry); + staged_leases.remove(&unit); + let lease = cache::Lease::write(&unit)?; let path = cache::store(&staging, kind, name, size, &ranges, &mut body)?; let unit = cache::unit(&staging, &path); let _ = fs::remove_file(unit.join(VERIFIED)); - pinned.pin(unit); + pinned.pin(unit.clone()); + staged_leases.insert(unit, lease.downgrade()?); + for removed in cache::evict(&cache::cores_directory(&staging), &agent.pins)? { + eprintln!("removed abandoned staging {}", removed.display()); + } return Ok(Vec::new()); } let entry = cache::entry(&agent.cache, cache::kind_directory(kind)?, name)?; @@ -1470,6 +1514,7 @@ fn transfer( agent: &Agent, pinned: &mut Pinned, downloads: &mut Vec, + staged_leases: &mut BTreeMap, request: &Value, ) -> Result, Failure> { let grant = agent.grant(&request["grant"])?; @@ -1491,6 +1536,7 @@ fn transfer( &format!("{directory}/{}", grant.primary()), )?; let staged_dir = primary.parent().unwrap(); + staged_leases.remove(staged_dir); let _lease = cache::Lease::write(staged_dir)?; // If a verified entry is already published in `helios::core::cache::Root` and holds every // requested file at the expected size (and no fresh unverified staging overwrote it), @@ -1628,6 +1674,9 @@ fn transfer( } let published = agent.publish_orbit_entry(staged_dir, &grant, rank, directory, &publisher)?; downloads.push(published); + for removed in cache::evict(&cache::cores_directory(&staging), &agent.pins)? { + eprintln!("removed abandoned staging {}", removed.display()); + } eprintln!("{directory}: stored data verified"); Ok(json!({"received": received, "verified": true}) .to_string() @@ -1822,10 +1871,14 @@ fn fetch( } } }; + let _staging_lease = if _lease.is_none() && path.starts_with(&staging) { + let unit = cache::unit(&staging, &path); + pinned.pin(unit.clone()); + Some(cache::Lease::shared(&unit)?) + } else { + None + }; let file = File::open(&path).map_err(|e| format!("cannot open {}: {e}", path.display()))?; - if _lease.is_none() { - pinned.pin(cache::unit(&staging, &path)); - } let size = file.metadata()?.len(); let ranges = cache::ranges_from_json(size, request.get("ranges"))?; let mut reader = cache::RangeReader::new(&file, &ranges); @@ -1917,6 +1970,7 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { .as_ref() .is_some_and(|source| source.public_key == mine.to_hex()); let mut core_lease: Option = None; + let mut staging_lease: Option = None; let core = if local_core { let path = match &grant.core.source { Some(source) if source.public_key == mine.to_hex() => { @@ -1944,7 +1998,9 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { "cores", &format!("{directory}/{}", grant.primary()), )?; - pins.pin(cache::unit(&staging, &path)); + let unit = cache::unit(&staging, &path); + pins.pin(unit.clone()); + staging_lease = Some(cache::Lease::shared(&unit)?); path } } @@ -2084,6 +2140,7 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { core: core_display, gpus, pid: child.id() as i32, + reap: Mutex::new(()), exited: AtomicBool::new(false), metrics_url: (rank == 0).then(|| metrics_url(&grant.rank_zero)), started: Instant::now(), @@ -2095,6 +2152,7 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { subscribers: Vec::new(), pins: Some(pins), core_lease, + staging_lease, }), }); groups.push(group.clone()); @@ -2133,9 +2191,37 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { } let finished = group.clone(); thread::spawn(move || { - let status = child.wait(); - // Record process reaping before draining pipes so STOP can never signal a reused PID. - finished.exited.store(true, Ordering::Release); + #[cfg(target_os = "linux")] + let status = { + // Wait for the child to exit without reaping so its PID stays reserved until `reap` + // is locked and `exited` is published, preventing STOP from signaling a reused PID. + let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; + loop { + let rc = unsafe { + libc::waitid( + libc::P_PID, + finished.pid as libc::id_t, + &mut info, + libc::WEXITED | libc::WNOWAIT, + ) + }; + if rc == 0 + || std::io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) + { + break; + } + } + let _reap = finished.reap.lock().unwrap(); + finished.exited.store(true, Ordering::Release); + child.wait() + }; + #[cfg(not(target_os = "linux"))] + let status = { + let status = child.wait(); + let _reap = finished.reap.lock().unwrap(); + finished.exited.store(true, Ordering::Release); + status + }; let code = status.ok().and_then(|s| s.code()).unwrap_or(-1); let (lock, cvar) = &*forwarder_state; let deadline = Instant::now() + FORWARDER_DRAIN_TIMEOUT; @@ -2204,12 +2290,13 @@ fn stream_group(session: &mut Session, group: &Group) -> Result<(), Failure> { fn stop(agent: &Agent, request: &Value) -> Result, Failure> { let group = named_group(agent, request)?; let running = { - let log = group.log.lock().unwrap(); - let active = log.exit.is_none() && !group.exited.load(Ordering::Acquire); + let _reap = group.reap.lock().unwrap(); + let active = !group.exited.load(Ordering::Acquire) && group.running(); if active { // Signal the child's process group (created via `setpgid(0, 0)`); fall back to the // child PID if the group leader already changed groups. - // SAFETY: `group.pid` is an un-reaped child process of this agent while `exited` is false. + // SAFETY: Holding `group.reap` prevents the reaper from reaping `group.pid` while + // `exited` is false, so `group.pid` cannot have been recycled by the kernel. let rc = unsafe { libc::kill(-group.pid, libc::SIGTERM) }; if rc != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) { unsafe { libc::kill(group.pid, libc::SIGTERM) }; @@ -2294,6 +2381,33 @@ fn status(agent: &Agent, request: &Value) -> Result, Failure> { // ---- install ----------------------------------------------------------------------------------- +/// Quote one argument for a systemd `ExecStart=` line, escaping `%` specifiers and quotes. +fn systemd_quote(value: &str) -> String { + let mut quoted = String::with_capacity(value.len() + 2); + quoted.push('"'); + for ch in value.chars() { + match ch { + '\\' => quoted.push_str("\\\\"), + '"' => quoted.push_str("\\\""), + '%' => quoted.push_str("%%"), + '\n' => quoted.push_str("\\n"), + '\r' => quoted.push_str("\\r"), + _ => quoted.push(ch), + } + } + quoted.push('"'); + quoted +} + +fn systemd_unit(listen: &str, core_cache: Option<&Path>) -> String { + let cache_flag = core_cache + .map(|path| format!(" --core-cache {}", systemd_quote(&path.to_string_lossy()))) + .unwrap_or_default(); + format!( + "[Unit]\nDescription=Flare agent: runs this host's rank of a orbit's serving group\nAfter=network-online.target\n\n[Service]\nExecStart=%h/.local/lib/flare-agent/flare agent --listen {listen}{cache_flag}\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n" + ) +} + /// Install this executable as the host's agent service and prepare pairing. pub fn install( listen: &str, @@ -2313,14 +2427,9 @@ pub fn install( fs::rename(&temporary, &destination)?; let unit_dir = home.join(".config/systemd/user"); fs::create_dir_all(&unit_dir)?; - let cache_flag = core_cache - .map(|path| format!(" --core-cache {}", path.display())) - .unwrap_or_default(); fs::write( unit_dir.join("flare-agent.service"), - format!( - "[Unit]\nDescription=Flare agent: runs this host's rank of a orbit's serving group\nAfter=network-online.target\n\n[Service]\nExecStart=%h/.local/lib/flare-agent/flare agent --listen {listen}{cache_flag}\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n" - ), + systemd_unit(listen, core_cache), )?; let code = if accept_first { dir.set_accept_first()?; @@ -3473,6 +3582,7 @@ pub mod tests { core: "model.safetensors".into(), gpus: Vec::new(), pid: 0, + reap: Mutex::new(()), exited: AtomicBool::new(false), metrics_url: None, started, @@ -3483,6 +3593,7 @@ pub mod tests { subscribers: Vec::new(), pins: None, core_lease: None, + staging_lease: None, }), metrics: Mutex::new(None), }) @@ -4498,4 +4609,77 @@ pub mod tests { 0o600 ); } + + #[test] + fn abandoned_orbit_staging_reclaimed_on_startup_and_put_while_live_session_preserved() { + let harness = harness(34); + let staging_cores = cache::cores_directory(&harness.agent.staging_root()); + + // Startup (`init_core_cache`) reclaims unleased abandoned staging directories. + let startup_abandoned = staging_cores.join("abandoned-startup"); + fs::create_dir_all(&startup_abandoned).unwrap(); + fs::write(startup_abandoned.join("model.safetensors"), b"stale").unwrap(); + harness.agent.init_core_cache().unwrap(); + assert!(!startup_abandoned.exists()); + + // Live controller session A stages a core and stays connected; unleased `abandoned-put` + // is reclaimed when session B uploads another core, while session A's staged dir stays. + let mut session_a = pair_accept_first(&harness); + put( + &mut session_a, + "core", + "live-a/model.safetensors", + b"live-a-bytes", + None, + ); + let abandoned_put = staging_cores.join("abandoned-put"); + fs::create_dir_all(&abandoned_put).unwrap(); + fs::write(abandoned_put.join("model.safetensors"), b"stale").unwrap(); + + let mut session_b = connect(&harness, &harness.controller); + put( + &mut session_b, + "core", + "live-b/model.safetensors", + b"live-b-bytes", + None, + ); + assert!(!abandoned_put.exists()); + assert!(staging_cores.join("live-a/model.safetensors").is_file()); + assert!(staging_cores.join("live-b/model.safetensors").is_file()); + + // `Root::collect()` preserves both live-session staged directories, then reclaims `live-a` + // once session A disconnects and drops its shared staging lease. + let root = harness.agent.core_root().unwrap(); + assert_eq!(root.collect().unwrap().staging, 0); + drop(session_a); + // Wait briefly for the agent thread to observe EOF and drop `staged_leases`. + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline { + if root.collect().unwrap().staging > 0 { + break; + } + thread::sleep(Duration::from_millis(20)); + } + assert!(!staging_cores.join("live-a").exists()); + assert!(staging_cores.join("live-b/model.safetensors").is_file()); + } + + #[test] + fn systemd_unit_quotes_core_cache_with_spaces_and_percent() { + let plain = systemd_unit("0.0.0.0:29900", None); + assert!(plain.contains("ExecStart=%h/.local/lib/flare-agent/flare agent --listen 0.0.0.0:29900\n")); + assert!(!plain.contains("--core-cache")); + + let quoted = systemd_unit( + "0.0.0.0:29900", + Some(Path::new(r#"/data/my cores/%h/"quoted"\dir"#)), + ); + assert!( + quoted.contains( + r#"ExecStart=%h/.local/lib/flare-agent/flare agent --listen 0.0.0.0:29900 --core-cache "/data/my cores/%%h/\"quoted\"\\dir""# + ), + "{quoted}" + ); + } } diff --git a/flare/src/hardware.rs b/flare/src/hardware.rs index c909119cd..881a1bd01 100644 --- a/flare/src/hardware.rs +++ b/flare/src/hardware.rs @@ -35,23 +35,23 @@ pub fn detect(count: usize) -> Result<&'static str> { for entry in visible.split(',') { let device = if let Ok(index) = entry.parse::() { nvml.device_by_index(index) - .map_err(|code| check("nvmlDeviceGetHandleByIndex_v2", code).unwrap_err())? + .map_err(|code| nvml_error("nvmlDeviceGetHandleByIndex_v2", code))? } else if entry.len() == 40 { let uuid = CString::new(entry)?; nvml.device_by_uuid(&uuid) - .map_err(|code| check("nvmlDeviceGetHandleByUUID", code).unwrap_err())? + .map_err(|code| nvml_error("nvmlDeviceGetHandleByUUID", code))? } else { let total = nvml .device_count() - .map_err(|code| check("nvmlDeviceGetCount_v2", code).unwrap_err())?; + .map_err(|code| nvml_error("nvmlDeviceGetCount_v2", code))?; let mut candidates = Vec::new(); for index in 0..total { let candidate = nvml .device_by_index(index) - .map_err(|code| check("nvmlDeviceGetHandleByIndex_v2", code).unwrap_err())?; + .map_err(|code| nvml_error("nvmlDeviceGetHandleByIndex_v2", code))?; let uuid = nvml .device_uuid(candidate) - .map_err(|code| check("nvmlDeviceGetUUID", code).unwrap_err())?; + .map_err(|code| nvml_error("nvmlDeviceGetUUID", code))?; candidates.push((uuid, candidate)); } candidates[unique_uuid(entry, &candidates)?].1 @@ -72,10 +72,7 @@ pub fn detect(count: usize) -> Result<&'static str> { ) })? } - Err(code) => { - check("nvmlDeviceGetPciInfo_v3", code)?; - unreachable!() - } + Err(code) => return Err(nvml_error("nvmlDeviceGetPciInfo_v3", code)), Ok(pci) => platform(pci.device_id).ok_or_else(|| { format!( "GPU {entry} has unsupported PCI ID {:#010x}; specify --revision", @@ -212,14 +209,9 @@ fn unique_uuid(prefix: &str, candidates: &[(String, T)]) -> Result { } } -fn check(operation: &str, code: c_int) -> Result<()> { - if code != 0 { - return Err(format!( - "hardware detection: {operation} failed with NVML error {code}; specify --revision" - ) - .into()); - } - Ok(()) +fn nvml_error(operation: &str, code: c_int) -> Box { + format!("hardware detection: {operation} failed with NVML error {code}; specify --revision") + .into() } #[cfg(test)] diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index 5136c5289..7003373fe 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -2138,20 +2138,12 @@ fn current_platform(cuda: &Cuda) -> ExportResult> { let bus_id = std::ffi::CString::new(format!("{domain:04x}:{bus:02x}:{slot:02x}.0"))?; let nvml = helios_core::nvml::Nvml::load() .map_err(|error| invalid(format!("NVML is required to name an export: {error}")))?; - let handle = match nvml.device_by_pci_bus_id(&bus_id) { - Ok(handle) => handle, - Err(code) => { - cuda.check("nvmlDeviceGetHandleByPciBusId_v2", code)?; - unreachable!() - } - }; - let pci = match nvml.device_pci_info(handle) { - Ok(pci) => pci, - Err(code) => { - cuda.check("nvmlDeviceGetPciInfo_v3", code)?; - unreachable!() - } - }; + let handle = nvml + .device_by_pci_bus_id(&bus_id) + .map_err(|code| invalid(format!("nvmlDeviceGetHandleByPciBusId_v2: NVML error {code}")))?; + let pci = nvml + .device_pci_info(handle) + .map_err(|code| invalid(format!("nvmlDeviceGetPciInfo_v3: NVML error {code}")))?; match helios_core::core::naming::platform_from_pci(pci.device_id) { Some(platform) => Ok(Some(platform.to_string())), None => Err(invalid(format!( diff --git a/helios/src/core/cache.rs b/helios/src/core/cache.rs index 39809a427..f08636393 100644 --- a/helios/src/core/cache.rs +++ b/helios/src/core/cache.rs @@ -51,6 +51,11 @@ use crate::core::container::{ const MAX_NAME: usize = 128; +/// Top-level directories owned by a [`Root`] cache layout. +pub const ROOT_DIRECTORIES: &[&str] = &[ + "blobs", "models", "refs", "sources", "origins", "staging", "locks", +]; + static TRANSACTION: AtomicU64 = AtomicU64::new(0); /// Lossless, filesystem-safe cache namespace for a model identity. @@ -3174,6 +3179,28 @@ impl Root { remove_tree(&tree)?; collected.staging += 1; } + let orbit_cores = self.root.join("staging/orbit/cores"); + if orbit_cores.is_dir() { + for item in read_dir(&orbit_cores)? { + let Some(name) = item.file_name().and_then(|name| name.to_str()) else { + continue; + }; + if name.starts_with('.') { + continue; + } + let Some(_lease) = Lock::try_exclusive(orbit_cores.join(".locks").join(name))? + else { + collect_inodes(&item, &mut live)?; + continue; + }; + if item.is_dir() { + remove_tree(&item)?; + } else { + remove_file(&item).map_err(failure)?; + } + collected.staging += 1; + } + } for (directory, legacy) in [("blobs", false), ("blobs/legacy", true)] { let path = self.root.join(directory); for item in read_dir(&path)? { @@ -3198,6 +3225,22 @@ impl Root { } syncdir(&path)?; } + let orbit_blobs = self.root.join("staging/orbit/blobs"); + if orbit_blobs.is_dir() { + for item in read_dir(&orbit_blobs)? { + let Some(identity) = inode(&item) else { + continue; + }; + if live.contains(&identity) { + continue; + } + if item.is_file() { + remove_file(&item).map_err(failure)?; + collected.objects += 1; + } + } + syncdir(&orbit_blobs)?; + } for directory in ["staging/incoming", "staging/wrapped"] { for item in read_dir(&self.root.join(directory))? { let Some(token) = item.file_name().and_then(|name| name.to_str()) else { @@ -9519,4 +9562,45 @@ mod selection_tests { .is_err()); let _ = fs::remove_dir_all(path); } + + #[test] + fn collect_reclaims_unleased_orbit_staging_and_preserves_leased() { + let path = std::env::temp_dir().join(format!( + "flare-cache-orbit-staging-gc-{}", + TRANSACTION.fetch_add(1, Ordering::Relaxed) + )); + let _ = fs::remove_dir_all(&path); + let root = Root::open(&path).unwrap(); + let orbit_cores = path.join("staging/orbit/cores"); + let orbit_blobs = path.join("staging/orbit/blobs"); + fs::create_dir_all(orbit_cores.join("abandoned-1")).unwrap(); + fs::create_dir_all(orbit_cores.join("active-2")).unwrap(); + fs::create_dir_all(&orbit_blobs).unwrap(); + + let abandoned_file = orbit_cores.join("abandoned-1/data.safetensors"); + let active_file = orbit_cores.join("active-2/data.safetensors"); + fs::write(&abandoned_file, b"abandoned payload").unwrap(); + fs::write(&active_file, b"active payload").unwrap(); + let abandoned_blob = orbit_blobs.join("abandoned.safetensors"); + let active_blob = orbit_blobs.join("active.safetensors"); + fs::hard_link(&abandoned_file, &abandoned_blob).unwrap(); + fs::hard_link(&active_file, &active_blob).unwrap(); + + let _active_lock = Lock::shared(orbit_cores.join(".locks/active-2")).unwrap(); + let collected = root.collect().unwrap(); + assert_eq!(collected.staging, 1); + assert_eq!(collected.objects, 1); + assert!(!orbit_cores.join("abandoned-1").exists()); + assert!(!abandoned_blob.exists()); + assert!(orbit_cores.join("active-2").is_dir()); + assert!(active_blob.is_file()); + + drop(_active_lock); + let collected = root.collect().unwrap(); + assert_eq!(collected.staging, 1); + assert_eq!(collected.objects, 1); + assert!(!orbit_cores.join("active-2").exists()); + assert!(!active_blob.exists()); + let _ = fs::remove_dir_all(path); + } } \ No newline at end of file diff --git a/helios/src/runtime_core/device_memory.rs b/helios/src/runtime_core/device_memory.rs index 194cd52d9..7c256df66 100644 --- a/helios/src/runtime_core/device_memory.rs +++ b/helios/src/runtime_core/device_memory.rs @@ -11,14 +11,10 @@ use super::{NativeResources, driver::Driver, format::invalid, memory::MemorySnap use crate::Result; use crate::nvml::Nvml; -fn check(operation: &str, status: c_int) -> Result<()> { - if status == 0 { - Ok(()) - } else { - Err(invalid(format!( - "occupied memory accounting: {operation} failed with NVML error {status}" - ))) - } +fn nvml_error(operation: &str, status: c_int) -> crate::Error { + invalid(format!( + "occupied memory accounting: {operation} failed with NVML error {status}" + )) } /// CUDA's cuMemGetInfo requires a context. NVML can observe discrete memory without one. @@ -30,10 +26,10 @@ unsafe fn discrete_free(pci: &[c_char]) -> Result { let bus_id = unsafe { CStr::from_ptr(pci.as_ptr()) }; let handle = nvml .device_by_pci_bus_id(bus_id) - .map_err(|code| check("nvmlDeviceGetHandleByPciBusId_v2", code).unwrap_err())?; + .map_err(|code| nvml_error("nvmlDeviceGetHandleByPciBusId_v2", code))?; let memory = nvml .device_memory_info(handle) - .map_err(|code| check("nvmlDeviceGetMemoryInfo", code).unwrap_err())?; + .map_err(|code| nvml_error("nvmlDeviceGetMemoryInfo", code))?; Ok(memory.free) } diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index df173554b..2e1915f22 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -229,10 +229,6 @@ impl AuthorizedCore { /// Whether this authorization verified supporting payloads and may enter a GPU loader. pub fn is_loadable(&self) -> bool { self.loadable - && match &self.kind { - AuthorizedKind::Legacy { .. } => true, - AuthorizedKind::Payload(core) => core.source.supporting_verified, - } } pub(super) fn require_loadable(&self) -> Result<()> { @@ -2839,7 +2835,7 @@ impl PayloadAuthorizedCore { /// # Safety /// The core must be trusted and the selected device must match its architecture. pub unsafe fn load(mut self, rank: usize, ordinal: i32) -> Result { - if !self.source.supporting_verified { + if !self.is_loadable() { return Err(invalid( "metadata-only authorized core cannot be loaded; authorize with payload verification", ));