From 7908ac3fc0e2ced8c1e795c87be08d4d63eb485a Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Tue, 1 Dec 2026 14:24:19 -0800 Subject: [PATCH] Harden Orbit payload integrity, multi-deployment TP seams, GB10 page-cache release, Unix flock drop, and multi-host peer exports Why this change is needed: Five operational defects remain in Orbit core distribution, integrated-GPU memory reclamation (#630), Unix file locking across `fork()`, and multi-host peer export caching: 1. Silent stale-weights execution on single-host Payload cores: `orbit/controller.rs` derived single-host `Core.export` from the primary filename stem (`model.safetensors` -> `"model"`), `Grant.core` omitted the signed envelope digest, and `orbit/agent.rs` (`have`, `transfer`, `run`) keyed and reused cached entries solely by directory name (`model-`) and file byte length. Two different single-host checkpoints sharing the same architecture and fixed-width manifest/layer byte lengths collided on `model-`, causing `have` and `transfer` to report cache hits and launch stale weights without transferring or verifying the updated checkpoint. 2. Broken Orbit seams on multi-deployment Payload cores (e.g., TP1+TP2+TP4): `VerifiedCore::open(..., None)` rejects cores with more than one deployment, causing `orbit/agent.rs` `verify_core` to fail and delete staged transfers, `publish_orbit_entry` to swallow metadata errors via `.ok()` and record a zeroed `[0u8; 32]` envelope without `.flare-verified.json`, `ServingOptions::rank_options` to omit `--tensor-parallel`, and rank zero launches under `agent::run` to start without `--tensor-parallel` (where `trust::load_with` cannot infer TP size because `args.hosts` is empty and `args.rank` is `Some(0)`). 3. Residual page-cache pressure on unified-memory GPUs such as GB10 (#630): `distribution.rs` never released Linux page cache after hashing primaries in `sha256_file` or streaming peer shard files (~95 GiB/peer) in `serve_source`. Because rank zero's model loader never opens peer shard files, `model.rs` could not evict those pages before CUDA context creation and KV sizing. Buffered writes in `core_cache.rs`, `agent::fetch`, and payload hashing in `protection.rs` likewise left verified bytes in page cache, and `model.rs` did not re-release page cache immediately after `load_payload` on integrated GPUs. 4. Unix `flock` retention across `fork()`: `helios::core::cache::Lock`, `helios::core::conversion::CoreLock`, and raw locked `File` guards in `flare` (`hub.rs`, `download_cache.rs`, `trust.rs`) had no `Drop` implementation calling `flock(LOCK_UN)`. When another thread forked a child process (`agent::run`) before `execve` closed `O_CLOEXEC` descriptors, the inherited open file description kept the advisory lock held after the parent dropped its guard. 5. Multi-host `--no-weights` peer failure and orphan peer blob leaks: Remote peers running `ignition join` (`host_ranks.py`) captured into their local `~/.cache/flare/cores` even though only rank zero commits a model entry. Normal multi-host exports leaked 40-100+ GiB of unreferenced blobs into each peer's cache, while `--no-weights` failed on cold or GC'd peers because `capture_group_into_cache` required cached weight blobs locally on the peer rather than deferring verification to rank zero's coordinator cache. What changed: - Orbit envelope binding and multi-deployment TP selection (`flare-cli/src/orbit/{grant,controller,agent}.rs`, `flare-cli/src/cli.rs`, `flare-cli/src/launch.rs`): - Before: `Grant.core` carried only `export`, `length`, `files`, and `source`; single-host `describe()` set `export` to the sanitized primary stem; `verify_core` and `publish_orbit_entry` called `VerifiedCore::open(..., None)`; `ServingOptions::rank_options` and `agent::run` omitted `--tensor-parallel`. - After: Added `#[serde(default)] envelope_digest: [u8; 32]` and `#[serde(default)] tensor_parallel: Option` to `Grant.core` (backward compatible with earlier grants). Single-host `describe()` appends the first 8 bytes (16 hex chars) of `authorized.envelope_digest()` to `export`. Controller `HAVE` sends `envelope_digest`; `agent.rs` checks `SourceRef::expected_envelope()` in `have()`, `transfer()`, `fetch()`, and `run()`, ignores unverified staging hits in `have()` when an envelope is bound, and verifies metadata envelopes before spawning `flare run`. `open_verified_core` dispatches Payload cores with `tensor_parallel` to `VerifiedCore::open_tensor_parallel`; `verify_core` returns `VerifiedCoreMeta` directly to `publish_orbit_entry`; `rank_options` forwards `--tensor-parallel`; `Controller::run` deduplicates saved vs. CLI `--tensor-parallel`; and `agent::run` emits `--tensor-parallel ` once. - Page-cache release (`eos/src/{unix,windows}.rs`, `helios/src/lib.rs`, `helios/src/runtime_core/{model,protection}.rs`, `flare-cli/src/{distribution,core_cache}.rs`, `flare-cli/src/orbit/agent.rs`): - Before: `sha256_file`, `serve_source`, `Source` teardown, `store_parallel`, `store_partial`, `agent::fetch`, and `hash_payload` left buffered I/O in Linux page cache; `model.rs` released page cache at lines 618 and 917 only. - After: Added `release_page_cache_range` in `eos` (re-exported with `release_page_cache` from `helios`). Called `release_page_cache` / `release_page_cache_range` in `sha256_file`, `serve_source`, `Source` worker teardown (deduplicated across all peer file handles), `store_parallel` and `store_partial` after `sync_all()`, `agent::fetch`, `hash_payload`, and immediately after `load_payload` on integrated GPUs in `model.rs`. - Explicit Unix `flock(LOCK_UN)` on drop (`helios/src/core/{cache,conversion}.rs`, `flare/src/{file_lock,lib,hub,download_cache,trust}.rs`): - Before: `Lock`, `CoreLock`, and raw `File` locks in `flare` relied solely on descriptor close. - After: Added Unix `Drop` calling `libc::flock(fd, libc::LOCK_UN)` on `helios::core::cache::Lock` and `CoreLock`, and introduced shared RAII `flare::file_lock::FileLock` used across `hub.rs`, `download_cache.rs`, and `trust.rs`. - Multi-host peer export caching (`heliopause/src/export/{mod,capture,transfer}.rs`, `ignition/preparation/{core_snapshot,runtime_core,host_ranks}.py`): - Before: `host_ranks.py` exported peers into their persistent `core_cache` with local `--no-weights` cache checks. - After: Added `ExportOptions.remote_cache` (default `false`). Remote peers in `host_ranks.py` capture into a transient `peer-cache` inside `NativeExportStage` with `remote_cache=True` and drop `core` before `native_stage.close()`, reclaiming all transient peer blobs after transfer. Under `no_weights && remote_cache`, `capture_group_into_cache` hashes weight groups in a single pass and places them in `WeightPayloadSources.cached` without local cache lookup; rank zero's `receive_rank` checks existence and length in the coordinator cache while keeping zero payload reads. Claimed benefit and result: - Distinct single-host Payload cores with identical filenames and sizes no longer collide or launch stale weights in Orbit. - Multi-deployment Payload cores verify, publish with real envelope digests and `.flare-verified.json` markers, and launch rank zero with the selected `--tensor-parallel` size across Orbit and `--hosts`. - Peer shard distribution, verification hashing, and integrated-GPU weight loading are expected to keep Linux page cache reclaimed on unified-memory GPUs such as GB10 so KV cache sizing retains full available memory (#630). - Dropping cache/trust/hub locks releases Unix `flock` immediately even across concurrent `fork()` calls. - Multi-host `--no-weights` exports succeed on cold or GC'd peers, and normal multi-host exports leave zero orphan weight blobs on peer hosts. Supporting evidence and limitations: - Release CPU unit and integration tests (`--locked --release`): - `eos`: 12 passed, 0 failed. - `helios` (`--features runtime-core,server --lib -- core:: runtime_core::`): 507 passed, 0 failed, 12 ignored (GPU/hardware-gated), including `lock_drop_releases_flock_even_with_duplicate_descriptor`. - `flare`: 246 unit + 8 integration passed, 0 failed, 4 ignored, including `file_lock::tests::drop_releases_flock_even_when_duplicate_descriptor_stays_open`. - `flare-cli`: 219 unit + 26 integration passed, 0 failed, 3 ignored (4 consecutive full runs), including `rank_options_forward_tensor_parallel`, `single_host_describe_derives_distinct_exports_from_envelope_digest`, `envelope_digest_blocks_stale_single_host_cache_hits_and_wrong_weights`, and `multi_deployment_payload_core_verifies_publishes_and_launches_rank_zero_with_tp`. - `heliopause`: 229 passed, 0 failed, 6 ignored (CUDA-gated), including `capture_group_into_cache_reads_source_once_for_miss_hit_and_no_weights` and `remote_no_weights_peer_reuses_coordinator_cache_and_rejects_missing_or_corrupt`. - Python tests: `tests/cli` and `tests/preparation/test_core_boundary.py` (140 passed); `tests/preparation -k "host_ranks or core_snapshot or export"` (94 passed, 8 CUDA-gated skipped). - Limitations: Live multi-host GB10 KV sizing (#630), multi-host CUDA/RoCE exports (`FLARE_RUN_CUDA_TESTS=1` / `FLARE_RUN_TP_CUDA_TESTS=1`), and `helios` chat-template tests (`FLARE_TEST_TEMPLATE_DIR`) were not run on this host. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b Signed-off-by: Luke Alonso --- eos/src/unix.rs | 13 + eos/src/windows.rs | 1 + flare-cli/src/cli.rs | 55 ++ flare-cli/src/core_cache.rs | 3 + flare-cli/src/distribution.rs | 37 +- flare-cli/src/launch.rs | 6 + flare-cli/src/orbit/agent.rs | 748 +++++++++++++++++++++++--- flare-cli/src/orbit/controller.rs | 336 ++++++++++-- flare-cli/src/orbit/grant.rs | 26 + flare/src/download_cache.rs | 107 +--- flare/src/file_lock.rs | 168 ++++++ flare/src/hub.rs | 107 +--- flare/src/lib.rs | 1 + flare/src/trust.rs | 19 +- heliopause/src/export/capture.rs | 137 ++++- heliopause/src/export/mod.rs | 5 + heliopause/src/export/transfer.rs | 97 +++- helios/src/core/cache.rs | 38 +- helios/src/core/conversion.rs | 8 + helios/src/lib.rs | 2 +- helios/src/runtime_core/model.rs | 3 + helios/src/runtime_core/protection.rs | 8 +- ignition/preparation/core_snapshot.py | 4 +- ignition/preparation/host_ranks.py | 10 +- ignition/preparation/runtime_core.py | 1 + 25 files changed, 1588 insertions(+), 352 deletions(-) create mode 100644 flare/src/file_lock.rs diff --git a/eos/src/unix.rs b/eos/src/unix.rs index f0932fd20..9a05ece1f 100644 --- a/eos/src/unix.rs +++ b/eos/src/unix.rs @@ -71,6 +71,19 @@ pub fn release_page_cache(file: &File) { } } +pub fn release_page_cache_range(file: &File, offset: u64, len: u64) { + if len == 0 { + return; + } + if let (Ok(offset), Ok(len)) = (libc::off_t::try_from(offset), libc::off_t::try_from(len)) { + unsafe { + libc::posix_fadvise(file.as_raw_fd(), offset, len, libc::POSIX_FADV_DONTNEED); + } + } else { + release_page_cache(file); + } +} + pub fn page_size() -> usize { usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap_or(4096) } diff --git a/eos/src/windows.rs b/eos/src/windows.rs index 1e63ff6a3..b56c3dd53 100644 --- a/eos/src/windows.rs +++ b/eos/src/windows.rs @@ -148,6 +148,7 @@ fn reopen_direct(file: &File, sharing: u32) -> io::Result { } pub fn release_page_cache(_: &File) {} +pub fn release_page_cache_range(_: &File, _: u64, _: u64) {} pub fn page_size() -> usize { let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() }; diff --git a/flare-cli/src/cli.rs b/flare-cli/src/cli.rs index 7601adc9b..b5abcb17c 100644 --- a/flare-cli/src/cli.rs +++ b/flare-cli/src/cli.rs @@ -1164,6 +1164,17 @@ impl ServingOptions { if self.verify_weights { options.push("--verify-weights".into()); } + if !self.hub.tensor_parallel.is_empty() { + options.extend([ + "--tensor-parallel".into(), + self.hub + .tensor_parallel + .iter() + .map(u32::to_string) + .collect::>() + .join(","), + ]); + } if let Some(n) = self.max_concurrency { options.extend(["--max-concurrency".into(), n.to_string()]); } @@ -2584,4 +2595,48 @@ mod cache_cli_tests { "--json and --plain must conflict" ); } + + #[test] + fn rank_options_forward_tensor_parallel() { + use clap::{CommandFactory, FromArgMatches}; + let cli = Cli::try_parse_from([ + "flare", + "run", + "model.safetensors", + "--tensor-parallel", + "2", + ]) + .unwrap(); + let Command::Run(run) = cli.command else { + panic!("expected run"); + }; + assert_eq!(run.rank_options(), vec!["--tensor-parallel", "2"]); + + let matches = Cli::command() + .try_get_matches_from([ + "flare", + "orbit", + "run", + "model.safetensors", + "--tensor-parallel", + "4", + ]) + .unwrap(); + let cli = Cli::from_arg_matches(&matches).unwrap(); + let Command::Orbit(orbit) = cli.command else { + panic!("expected orbit"); + }; + let OrbitCommand::Run(run) = orbit.command else { + panic!("expected orbit run"); + }; + let run_matches = matches + .subcommand_matches("orbit") + .unwrap() + .subcommand_matches("run") + .unwrap(); + assert_eq!( + run.rank_options(run_matches), + vec!["--tensor-parallel", "4"] + ); + } } diff --git a/flare-cli/src/core_cache.rs b/flare-cli/src/core_cache.rs index 1a8540107..d0d67c7f0 100644 --- a/flare-cli/src/core_cache.rs +++ b/flare-cli/src/core_cache.rs @@ -447,10 +447,12 @@ pub fn store_parallel( let mut digest = Sha256::new(); std::io::copy(&mut &output, &mut digest)?; if format!("{}.safetensors", hex(&digest.finalize())) != blob { + flare_helios::release_page_cache(&output); return Err(format!("{name}: payload digest mismatch").into()); } output.set_permissions(fs::Permissions::from_mode(0o444))?; } + flare_helios::release_page_cache(&output); Ok(()) }) } @@ -555,6 +557,7 @@ fn store_partial( } fs::set_permissions(partial, fs::Permissions::from_mode(0o444))?; } + flare_helios::release_page_cache(&output); Ok(()) } diff --git a/flare-cli/src/distribution.rs b/flare-cli/src/distribution.rs index ec6f38612..e3fb73192 100644 --- a/flare-cli/src/distribution.rs +++ b/flare-cli/src/distribution.rs @@ -614,13 +614,18 @@ fn sha256_file(path: &Path) -> Result<[u8; 32], Failure> { let mut file = File::open(path).map_err(|e| e.to_string())?; let mut context = ring::digest::Context::new(&ring::digest::SHA256); let mut buffer = vec![0u8; 4 << 20]; - loop { - let read = file.read(&mut buffer).map_err(|e| e.to_string())?; - if read == 0 { - break; + let result = (|| -> Result<(), Failure> { + loop { + let read = file.read(&mut buffer).map_err(|e| e.to_string())?; + if read == 0 { + break; + } + context.update(&buffer[..read]); } - context.update(&buffer[..read]); - } + Ok(()) + })(); + flare_helios::release_page_cache(&file); + result?; Ok(context .finish() .as_ref() @@ -1122,6 +1127,16 @@ impl Source { for worker in workers { worker.join().map_err(|_| "core source panicked")?; } + // Peer shard files are not opened by rank zero's model loader, so release their + // Linux page cache here before CUDA initialization and KV cache sizing. + let mut seen = std::collections::HashSet::new(); + for rank_files in &files { + for file in rank_files { + if seen.insert(Arc::as_ptr(file) as usize) { + flare_helios::release_page_cache(file); + } + } + } for result in receiver.try_iter() { if let Err(e) = result { error.get_or_insert(e); @@ -1197,10 +1212,12 @@ fn serve_source( return Err("requested bytes are outside the rank's core ranges".into()); } socket.write_all(&cache::range_bytes(&request.ranges).to_le_bytes())?; - io::copy( - &mut cache::RangeReader::new(&files[rank][request.file], &request.ranges), - &mut socket, - )?; + let file = &files[rank][request.file]; + let copied = io::copy(&mut cache::RangeReader::new(file, &request.ranges), &mut socket); + for &(offset, size) in &request.ranges { + flare_helios::release_page_cache_range(file, offset, size); + } + copied?; } } diff --git a/flare-cli/src/launch.rs b/flare-cli/src/launch.rs index 99950993d..10f01b149 100644 --- a/flare-cli/src/launch.rs +++ b/flare-cli/src/launch.rs @@ -141,6 +141,12 @@ impl Peers { .to_owned(), ], source: None, + envelope_digest: core.envelope_digest(), + tensor_parallel: core + .identity() + .ok() + .map(|id| id.tensor_parallel) + .filter(|&tp| tp > 0), }, members, rendezvous, diff --git a/flare-cli/src/orbit/agent.rs b/flare-cli/src/orbit/agent.rs index 25badaae6..0f10c6180 100644 --- a/flare-cli/src/orbit/agent.rs +++ b/flare-cli/src/orbit/agent.rs @@ -30,7 +30,7 @@ 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 flare_helios::runtime_core::{CoreFormat, NativeResources, Publisher, VerifiedCore}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -434,10 +434,29 @@ impl Group { // ---- state ------------------------------------------------------------------------------------- -/// Verifies a core's stored data at `primary` for `rank` (None for a complete copy) against +/// Authenticated metadata extracted from a verified core before publication. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedCoreMeta { + pub model_id: String, + pub hardware: String, + pub tensor_parallel: u32, + pub envelope: [u8; 32], +} + +/// Verifies a core's stored data at `primary` for `rank` (None for a complete copy), +/// optional `tensor_parallel` deployment size, and optional `expected_envelope` against /// the publisher's signing key. -pub type Verifier = - Box, &Publisher) -> Result<(), Failure> + Send + Sync>; +pub type Verifier = Box< + dyn Fn( + &Path, + Option, + Option, + Option<[u8; 32]>, + &Publisher, + ) -> Result, Failure> + + Send + + Sync, +>; /// The marker a core cache directory holds once its stored data verified. const VERIFIED: &str = ".verified"; @@ -466,11 +485,53 @@ fn prune_groups(groups: &mut Vec>, now: Instant) { /// Enumerates the host's GPUs. pub type Gpus = Box Result, Failure> + Send + Sync>; -fn verify_core(primary: &Path, rank: Option, publisher: &Publisher) -> Result<(), Failure> { - VerifiedCore::open(primary, std::slice::from_ref(publisher), rank) - .and_then(|core| core.verify_stored_data()) - .map_err(|e| e.to_string())?; - Ok(()) +fn open_verified_core( + primary: &Path, + publisher: &Publisher, + rank: Option, + tensor_parallel: Option, +) -> Result { + let publishers = std::slice::from_ref(publisher); + match NativeResources::core_format(primary).map_err(|e| e.to_string())? { + CoreFormat::Payload => match tensor_parallel { + Some(tp) => { + let rank_id = rank + .map(|r| { + u32::try_from(r) + .map_err(|_| Failure::from("rank id exceeds the core rank domain")) + }) + .transpose()?; + VerifiedCore::open_tensor_parallel(primary, publishers, tp, rank_id) + } + None => VerifiedCore::open(primary, publishers, rank), + }, + CoreFormat::Legacy => VerifiedCore::open(primary, publishers, rank), + } + .map_err(|e| Failure::from(e.to_string())) +} + +fn verify_core( + primary: &Path, + rank: Option, + tensor_parallel: Option, + expected_envelope: Option<[u8; 32]>, + publisher: &Publisher, +) -> Result, Failure> { + let core = open_verified_core(primary, publisher, rank, tensor_parallel)?; + let envelope = core.envelope_digest(); + if let Some(expected) = expected_envelope + && envelope != expected + { + return Err("staged core signed envelope differs from the grant".into()); + } + core.verify_stored_data().map_err(|e| e.to_string())?; + let identity = core.identity().map_err(|e| e.to_string())?; + Ok(Some(VerifiedCoreMeta { + model_id: identity.model, + hardware: identity.hardware, + tensor_parallel: identity.tensor_parallel, + envelope, + })) } type SpawnRequest = (Command, mpsc::SyncSender>); @@ -544,6 +605,8 @@ pub struct Agent { groups: Mutex>>, spawner: RankSpawner, verifier: Verifier, + /// True for production `Agent::new`; checks metadata envelope before launching `flare run`. + verify_envelope_on_run: bool, gpus: Gpus, /// The GPU inventory the sampler last read, with the Unix millisecond it was read. sampled_gpus: Mutex)>>, @@ -708,7 +771,9 @@ fn entry_file_path(entry: &CacheEntry, primary: &str, name: &str) -> PathBuf { impl Agent { pub fn new(dir: AgentDir, cache: PathBuf) -> Result { - Self::with_fakes(dir, cache, Box::new(verify_core), Box::new(gpu::enumerate)) + let mut agent = Self::with_fakes(dir, cache, Box::new(verify_core), Box::new(gpu::enumerate))?; + agent.verify_envelope_on_run = true; + Ok(agent) } /// An agent verifying fetched cores with `verifier` and enumerating GPUs with `gpus` @@ -736,6 +801,7 @@ impl Agent { groups: Mutex::new(Vec::new()), spawner: RankSpawner::new(), verifier, + verify_envelope_on_run: false, gpus, sampled_gpus: Mutex::new(None), #[cfg(test)] @@ -773,18 +839,37 @@ impl Agent { } /// Resolve a published verified Orbit or serving-bootstrap entry in `core_cache`. + #[cfg(test)] pub(crate) fn resolve_orbit_entry(&self, directory: &str) -> Result, Failure> { + self.resolve_orbit_entry_matching(directory, None) + } + + /// Resolve a published verified Orbit or serving-bootstrap entry in `core_cache`, requiring + /// its recorded signed envelope digest to match `expected_envelope` when provided. + pub(crate) fn resolve_orbit_entry_matching( + &self, + directory: &str, + expected_envelope: Option<[u8; 32]>, + ) -> Result, Failure> { let root = self.core_root()?; - if let Some((_, entry)) = root - .resolve_source_ref(&format!("orbit:{directory}")) + let matches = |record: &helios_cache::SourceRef| -> bool { + match expected_envelope { + None => true, + Some(expected) => record.expected_envelope() == Some(expected), + } + }; + if let Some((record, entry)) = root + .resolve_source_ref_record(&format!("orbit:{directory}")) .map_err(|e| Failure::from(e.to_string()))? + && matches(&record) { return Ok(Some(entry)); } if let Some((export, rank)) = parse_rank_directory(directory) - && let Some((_, entry)) = root - .resolve_source_ref(&format!("{export}-rank{rank}")) + && let Some((record, entry)) = root + .resolve_source_ref_record(&format!("{export}-rank{rank}")) .map_err(|e| Failure::from(e.to_string()))? + && matches(&record) { return Ok(Some(entry)); } @@ -799,39 +884,20 @@ impl Agent { grant: &Grant, rank: usize, directory: &str, - publisher: &Publisher, + verified_meta: Option, ) -> 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) + let key = helios_cache::model_key(&verified.model_id) .unwrap_or_else(|_| "orbit".to_owned()); - (key, hardware, tp, envelope, true) + ( + key, + verified.hardware, + verified.tensor_parallel, + verified.envelope, + true, + ) } else { let fallback_model = if grant.name.is_empty() { grant.core.export.as_str() @@ -840,7 +906,16 @@ impl Agent { }; 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) + ( + key, + String::new(), + grant + .core + .tensor_parallel + .unwrap_or(grant.members.len() as u32), + grant.core.envelope_digest, + false, + ) }; let base_id = orbit_entry_id(&platform, tensor_parallel, directory); @@ -1470,6 +1545,15 @@ fn pair( Ok(reply.to_string().into_bytes()) } +fn parse_expected_envelope(request: &Value) -> Result, Failure> { + let Some(value) = request.get("envelope_digest").filter(|v| !v.is_null()) else { + return Ok(None); + }; + let digest: [u8; 32] = + serde_json::from_value(value.clone()).map_err(|_| "invalid envelope_digest")?; + Ok((digest != [0u8; 32]).then_some(digest)) +} + fn have( agent: &Agent, pinned: &mut Pinned, @@ -1480,11 +1564,13 @@ fn have( let kind = field(request, "kind")?; let name = field(request, "name")?; if matches!(kind, "core" | "package") { + let expected_envelope = parse_expected_envelope(request)?; if let Some((directory, file)) = name.split_once('/') - && let Some(entry) = agent.resolve_orbit_entry(directory)? + && let Some(entry) = agent.resolve_orbit_entry_matching(directory, expected_envelope)? { let direct = entry.directory().join(file); - let primary_alias = (!file.contains('/')).then(|| entry.directory().join("model.safetensors")); + 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| { @@ -1495,6 +1581,11 @@ fn have( return Ok(vec![1]); } } + // Unverified staging files carry no authenticated envelope digest; do not treat them + // as cache hits when the caller binds the request to a specific signed envelope. + if expected_envelope.is_some() { + return Ok(vec![0]); + } let staging = agent.staging_root(); let held = cache::have(&staging, kind, name, size)?; if let Some(path) = &held { @@ -1593,11 +1684,12 @@ fn transfer( 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), - // reuse it directly with zero bytes transferred. + // If a verified entry is already published in `helios::core::cache::Root` with a matching + // signed envelope and holds every requested file at the expected size (and no fresh + // unverified staging overwrote it), reuse it directly with zero bytes transferred. + let expected_envelope = grant.core.expected_envelope(); if !staged_dir.exists() - && let Some(entry) = agent.resolve_orbit_entry(directory)? + && let Some(entry) = agent.resolve_orbit_entry_matching(directory, expected_envelope)? { let mut all_present = true; for file in files { @@ -1720,14 +1812,23 @@ fn transfer( ); } let complete = rank == 0; - if let Err(error) = (agent.verifier)(&primary, (!complete).then_some(rank), &publisher) { - let _ = fs::remove_dir_all(staged_dir); - return Err(format!( - "{directory}: stored data fetched from {address} failed verification and was removed: {error}" - ) - .into()); - } - let published = agent.publish_orbit_entry(staged_dir, &grant, rank, directory, &publisher)?; + let verified_meta = match (agent.verifier)( + &primary, + (!complete).then_some(rank), + grant.core.tensor_parallel, + expected_envelope, + &publisher, + ) { + Ok(meta) => meta, + Err(error) => { + let _ = fs::remove_dir_all(staged_dir); + return Err(format!( + "{directory}: stored data fetched from {address} failed verification and was removed: {error}" + ) + .into()); + } + }; + let published = agent.publish_orbit_entry(staged_dir, &grant, rank, directory, verified_meta)?; downloads.push(published); for removed in cache::evict(&cache::cores_directory(&staging), &agent.pins)? { eprintln!("removed abandoned staging {}", removed.display()); @@ -1891,14 +1992,17 @@ fn fetch( .ok_or("source path has no directory")? .join(name), _ => { - if let Some(entry) = agent.resolve_orbit_entry(&grant.complete_directory())? + let expected_envelope = grant.core.expected_envelope(); + if let Some(entry) = + agent.resolve_orbit_entry_matching(&grant.complete_directory(), expected_envelope)? && 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))? + && let Some(entry) = + agent.resolve_orbit_entry_matching(&grant.cache_directory(rank), expected_envelope)? && entry_file_path(&entry, grant.primary(), name).is_file() { let file_path = entry_file_path(&entry, grant.primary(), name); @@ -1937,7 +2041,11 @@ fn fetch( let size = file.metadata()?.len(); let ranges = cache::ranges_from_json(size, request.get("ranges"))?; let mut reader = cache::RangeReader::new(&file, &ranges); - session.write_frame_from(frame::OK, cache::range_bytes(&ranges), &mut reader) + let result = session.write_frame_from(frame::OK, cache::range_bytes(&ranges), &mut reader); + for &(offset, nbytes) in &ranges { + flare_helios::release_page_cache_range(&file, offset, nbytes); + } + result } /// Read a range of a node-local file: how a controller mirrors a core's header and index. @@ -2026,6 +2134,7 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { .is_some_and(|source| source.public_key == mine.to_hex()); let mut core_lease: Option = None; let mut staging_lease: Option = None; + let expected_envelope = grant.core.expected_envelope(); let core = if local_core { let path = match &grant.core.source { Some(source) if source.public_key == mine.to_hex() => { @@ -2042,7 +2151,9 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { } else { grant.cache_directory(rank) }; - if let Some(entry) = agent.resolve_orbit_entry(&directory)? { + if let Some(entry) = + agent.resolve_orbit_entry_matching(&directory, expected_envelope)? + { let path = entry.directory().join("model.safetensors"); core_lease = Some(entry); path @@ -2063,6 +2174,24 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { if !path.is_file() { return Err(format!("core {} is not on this node", path.display()).into()); } + if agent.verify_envelope_on_run + && let Some(expected) = expected_envelope + { + let complete = rank == 0 || grant.single_host; + let verified = open_verified_core( + &path, + &publisher, + (!complete).then_some(rank), + grant.core.tensor_parallel, + )?; + if verified.envelope_digest() != expected { + return Err(format!( + "core {} signed envelope differs from the grant", + path.display() + ) + .into()); + } + } Some(path) } else { None @@ -2097,12 +2226,30 @@ fn run(agent: &Arc, request: &Value) -> Result, Failure> { 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"), - ); + let strip_tp = grant.core.tensor_parallel.is_some(); + let mut skip_next = false; + for arg in &grant.serving { + if skip_next { + skip_next = false; + continue; + } + if arg == "--roce-ring" || arg == "--roce-chain" { + continue; + } + if strip_tp { + if arg == "--tensor-parallel" { + skip_next = true; + continue; + } + if arg.starts_with("--tensor-parallel=") { + continue; + } + } + command.arg(arg); + } + if let Some(tp) = grant.core.tensor_parallel { + command.arg("--tensor-parallel").arg(tp.to_string()); + } if rank == 0 { command.args(&grant.rank_zero); } @@ -2769,7 +2916,7 @@ pub mod tests { let mut agent = Agent::with_fakes( dir, temp.path().join("cache"), - Box::new(move |primary, rank, publisher| { + Box::new(move |primary, rank, _tp, _envelope, publisher| { if !primary.is_file() { return Err(format!("{} is not a file", primary.display()).into()); } @@ -2777,7 +2924,7 @@ pub mod tests { return Err("stored-data content verification failed".into()); } record.lock().unwrap().push((primary.to_owned(), rank)); - Ok(()) + Ok(None) }), Box::new(|| Ok(fake_gpus())), ) @@ -2898,6 +3045,8 @@ pub mod tests { length: 13, files: vec!["model.safetensors".into()], source, + envelope_digest: [0u8; 32], + tensor_parallel: None, }, members: vec![Member { rank, @@ -3482,6 +3631,8 @@ pub mod tests { length: 13, files: vec!["model.safetensors".into()], source: None, + envelope_digest: [0u8; 32], + tensor_parallel: None, }, members: vec![Member { rank: 0, @@ -3923,6 +4074,8 @@ pub mod tests { length: 13, files: vec!["model.safetensors".into()], source: None, + envelope_digest: [0u8; 32], + tensor_parallel: None, }, members: vec![Member { rank: 0, @@ -4029,6 +4182,8 @@ pub mod tests { public_key: nodes[0].public_key.clone(), path: core.display().to_string(), }), + envelope_digest: [0u8; 32], + tensor_parallel: None, }, members: nodes .iter() @@ -4223,6 +4378,8 @@ pub mod tests { public_key: source.agent.key.public().to_hex(), path: core.display().to_string(), }), + envelope_digest: [0u8; 32], + tensor_parallel: None, }, members: vec![ Member { @@ -4433,6 +4590,8 @@ pub mod tests { public_key: source.agent.key.public().to_hex(), path: core.display().to_string(), }), + envelope_digest: [0u8; 32], + tensor_parallel: None, }, members: vec![ Member { @@ -4532,6 +4691,8 @@ pub mod tests { length: 4096, files: vec!["gb10-tp1+tp2-20261130".into()], source: None, + envelope_digest: [0u8; 32], + tensor_parallel: None, }, members: vec![ Member { @@ -4784,4 +4945,453 @@ pub mod tests { .request(frame::STOP, &json!({"group": "detached-rank"})) .unwrap(); } + + fn build_signed_payload_core( + parent: &Path, + name: &str, + tensor_parallel: &[u32], + weight_fill: u8, + core_id_byte: u8, + export_id: Option<&str>, + ) -> (PathBuf, Publisher, [u8; 32], Vec<(String, u64)>) { + use flare_helios::core::{PayloadId, container, export as publish, schema::wire}; + use ring::signature::{Ed25519KeyPair, KeyPair}; + + let core_dir = parent.join(name); + fs::create_dir_all(&core_dir).unwrap(); + let key = Ed25519KeyPair::from_seed_unchecked(&[29u8; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let publisher = Publisher { + name: "OrbitTest".into(), + namespace: "local-development".into(), + public_key, + development: true, + }; + let contract = flare_helios::runtime_core::wire::ServingContract { + model_id: "owner/orbit-test".into(), + identity: "orbit-test-sm120".into(), + max_sequence_tokens: 8, + prefill_chunk_size: 1, + pages: 1, + state_rows: 1, + page_tokens: 1, + model_contract: Some(flare_helios::runtime_core::wire::ModelContract { + vocabulary: 8, + graphs: vec![flare_helios::runtime_core::wire::GraphContract { + graph: "decode".into(), + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + }; + let graph = parent.join(format!("{name}-graph.bin")); + fs::write(&graph, b"graph-bytes").unwrap(); + let deployments = tensor_parallel + .iter() + .map(|&tp| { + let ranks = (0..tp) + .map(|rank| { + let mut weights = vec![weight_fill; 4096]; + weights[0] = tp as u8; + weights[1] = rank as u8; + let id = PayloadId::of(&weights); + let raw = parent.join(format!("{name}-w-{tp}-{rank}.bin")); + fs::write(&raw, &weights).unwrap(); + publish::PublishRank { + body: wire::RankBody { + rank, + deployment_id: format!("sm120-tp{tp}"), + context: Some(Default::default()), + allocations: vec![wire::Allocation { + name: "device-0".into(), + nbytes: weights.len() as u64, + alignment: 4096, + ..Default::default() + }], + initializers: vec![wire::Initializer { + allocation: "device-0".into(), + destination_offset: 0, + source: Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: id.as_bytes().to_vec(), + offset: 0, + nbytes: weights.len() as u64, + }), + role: wire::PayloadRole::Weights as i32, + }), + }], + graphs: vec![wire::Graph { + name: "decode".into(), + resource: 0, + node_count: 1, + ..Default::default() + }], + ..Default::default() + }, + payloads: vec![publish::PublishPayload { + role: wire::PayloadRole::Weights, + relative: format!("weights/tp{tp}/rank-{rank}.safetensors"), + source: container::Slice::new( + Arc::new(File::open(&raw).unwrap()), + 0, + weights.len() as u64, + ) + .unwrap(), + id, + tensor: None, + }], + resources: vec![publish::PublishResource { + kind: wire::ExecutableKind::Graph, + path: graph.clone(), + nbytes: 11, + }], + } + }) + .collect(); + publish::PublishDeployment { + body: wire::DeploymentBody { + deployment_id: format!("sm120-tp{tp}"), + architecture: vec![12, 0], + tensor_parallel: tp, + contract: Some(contract.clone()), + cluster: export_id.map(|id| flare_helios::runtime_core::wire::Cluster { + world: tp, + export_id: id.into(), + }), + ..Default::default() + }, + ranks, + payloads: vec![], + } + }) + .collect(); + let request = publish::PublishRequest { + core: wire::CoreBody { + model_identity: "owner/orbit-test".into(), + hardware_identity: "sm120".into(), + frontend: Some(flare_helios::runtime_core::wire::FrontendSettings::default()), + sampling_defaults: Some( + flare_helios::runtime_core::wire::DefaultSamplingParameters::default(), + ), + publisher: Some(wire::PublisherMetadata { + namespace: "local-development".into(), + official_source: "local-development".into(), + development: true, + ..Default::default() + }), + ..Default::default() + }, + payloads: vec![], + deployments, + core_id: [core_id_byte; 32], + public_key, + accepted: "local-development".into(), + no_weights: false, + }; + publish::publish(&request, &key, publish::Destination::Directory(&core_dir)).unwrap(); + let primary = core_dir.join("model.safetensors"); + let envelope = VerifiedCore::open_tensor_parallel( + &primary, + std::slice::from_ref(&publisher), + *tensor_parallel.last().unwrap(), + None, + ) + .unwrap() + .envelope_digest(); + let mut files = vec![( + "model.safetensors".to_owned(), + fs::metadata(&primary).unwrap().len(), + )]; + for companion in flare_helios::runtime_core::core_companions(&primary).unwrap() { + let size = fs::metadata(core_dir.join(&companion)).unwrap().len(); + files.push((companion, size)); + } + (primary, publisher, envelope, files) + } + + fn real_agent_harness(seed: u8) -> Harness { + let temp = tempfile::tempdir().unwrap(); + let dir = AgentDir::new(temp.path().join("agent")); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap().to_string(); + let mut agent = Agent::new(dir, temp.path().join("cache")).unwrap(); + agent.gpus = Box::new(|| Ok(fake_gpus())); + agent.executable = temp.path().join("installed-flare"); + agent.fabric_endpoints = Some(b"loopback 127.0.0.1/8 -\n".to_vec()); + fs::write(&agent.executable, "#!/bin/sh\necho \"$@\"\n").unwrap(); + fs::set_permissions(&agent.executable, fs::Permissions::from_mode(0o755)).unwrap(); + let agent = Arc::new(agent); + { + let agent = agent.clone(); + thread::spawn(move || serve_on(listener, agent)); + } + Harness { + address, + agent, + controller: Key::from_seed(&[seed; 32]).unwrap(), + temp, + verified: Arc::new(Mutex::new(Vec::new())), + } + } + + #[test] + fn envelope_digest_blocks_stale_single_host_cache_hits_and_wrong_weights() { + let node = real_agent_harness(41); + let mut session = pair_accept_first(&node); + let (primary_a, publisher, envelope_a, files_a) = + build_signed_payload_core(node.temp.path(), "core-a", &[1], 0x11, 1, None); + let (primary_b, _, envelope_b, files_b) = + build_signed_payload_core(node.temp.path(), "core-b", &[1], 0x22, 2, None); + assert_eq!(files_a, files_b, "same-arch checkpoints share filenames and lengths"); + assert_ne!(envelope_a, envelope_b); + + // Simulate a colliding directory name (`model-`) on disk. + let dir = format!("model-{}", files_a[0].1); + let root_a = primary_a.parent().unwrap(); + for (name, _) in &files_a { + let bytes = fs::read(root_a.join(name)).unwrap(); + put(&mut session, "core", &format!("{dir}/{name}"), &bytes, None); + } + let make_grant = |envelope: [u8; 32], source: Option| { + Signed::sign( + &node.controller, + &Grant { + group: "single".into(), + name: "single".into(), + core: Core { + export: "model".into(), + length: files_a[0].1, + files: files_a.iter().map(|(n, _)| n.clone()).collect(), + source, + envelope_digest: envelope, + tensor_parallel: Some(1), + }, + members: vec![Member { + rank: 0, + name: node.agent.name.clone(), + public_key: node.agent.key.public().to_hex(), + address: node.address.clone(), + gpus: vec![], + }], + rendezvous: String::new(), + serving: vec![], + rank_zero: vec![], + roce_ring: false, + transfer_fabric: None, + single_host: true, + roce_chain: false, + issued: now(), + expires: now() + 60, + }, + ) + .unwrap() + }; + + let grant_a = make_grant(envelope_a, None); + let transfer_files: Vec = files_a + .iter() + .map(|(n, s)| json!({"name": n, "size": s, "ranges": [[0, s]]})) + .collect(); + let reply: Value = serde_json::from_slice( + &session + .request( + frame::TRANSFER, + &json!({ + "grant": grant_a, + "publisher": publisher, + "source": {"public_key": node.agent.key.public().to_hex(), "address": node.address}, + "directory": dir, + "files": transfer_files, + }), + ) + .unwrap(), + ) + .unwrap(); + assert_eq!(reply["verified"], true); + + // HAVE with matching envelope hits; HAVE with core_b's envelope misses despite identical + // directory, filename, and byte length. + let hit = session + .request( + frame::HAVE, + &json!({ + "kind": "core", + "name": format!("{dir}/model.safetensors"), + "size": files_a[0].1, + "envelope_digest": envelope_a, + }), + ) + .unwrap(); + assert_eq!(hit, vec![1]); + let miss = session + .request( + frame::HAVE, + &json!({ + "kind": "core", + "name": format!("{dir}/model.safetensors"), + "size": files_b[0].1, + "envelope_digest": envelope_b, + }), + ) + .unwrap(); + assert_eq!(miss, vec![0]); + + // TRANSFER with core_b's envelope must NOT reuse core_a (`received:0, verified:false`), + // and staging core_a's bytes under core_b's grant must fail verification. + let grant_b = make_grant(envelope_b, None); + for (name, _) in &files_a { + let bytes = fs::read(root_a.join(name)).unwrap(); + put(&mut session, "core", &format!("{dir}/{name}"), &bytes, None); + } + let err = session + .request( + frame::TRANSFER, + &json!({ + "grant": grant_b, + "publisher": publisher, + "source": {"public_key": node.agent.key.public().to_hex(), "address": node.address}, + "directory": dir, + "files": transfer_files, + }), + ) + .unwrap_err() + .to_string(); + assert!(err.contains("signed envelope differs from the grant"), "{err}"); + + // RUN with core_b's grant pointing at core_a on disk must reject before spawning. + let mismatched_run = make_grant( + envelope_b, + Some(Source { + public_key: node.agent.key.public().to_hex(), + path: primary_a.display().to_string(), + }), + ); + let mut run_session = connect(&node, &node.controller); + let err = run_session + .request( + frame::RUN, + &json!({"grant": mismatched_run, "rank": 0, "binary": Value::Null, "publisher": publisher}), + ) + .unwrap_err() + .to_string(); + assert!(err.contains("signed envelope differs from the grant"), "{err}"); + let _ = primary_b; + } + + #[test] + fn multi_deployment_payload_core_verifies_publishes_and_launches_rank_zero_with_tp() { + let zero = real_agent_harness(42); + let peer = Harness { + controller: Key::from_seed(&[42; 32]).unwrap(), + ..real_agent_harness(43) + }; + let mut zero_session = pair_accept_first(&zero); + let mut peer_session = pair_accept_first(&peer); + + let (primary, publisher, envelope, files) = build_signed_payload_core( + zero.temp.path(), + "multi-tp", + &[1, 2], + 0x33, + 3, + Some("multi-export"), + ); + // Confirm `VerifiedCore::open(..., None)` genuinely fails on this multi-deployment core. + assert!( + VerifiedCore::open(&primary, std::slice::from_ref(&publisher), None).is_err(), + "multi-deployment core must require explicit tensor-parallel selection" + ); + + let grant = Signed::sign( + &zero.controller, + &Grant { + group: "multi".into(), + name: "multi".into(), + core: Core { + export: "multi-export".into(), + length: files[0].1, + files: files.iter().map(|(n, _)| n.clone()).collect(), + source: Some(Source { + public_key: zero.agent.key.public().to_hex(), + path: primary.display().to_string(), + }), + envelope_digest: envelope, + tensor_parallel: Some(2), + }, + members: vec![ + Member { + rank: 0, + name: "zero".into(), + public_key: zero.agent.key.public().to_hex(), + address: zero.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!["--tensor-parallel".into(), "2".into()], + rank_zero: vec!["--port".into(), "8011".into()], + roce_ring: false, + transfer_fabric: None, + single_host: false, + roce_chain: false, + issued: now(), + expires: now() + 60, + }, + ) + .unwrap(); + + // 1. Peer TRANSFER verifies TP2 rank 1 and publishes with the real non-zero envelope. + let peer_dir = format!("multi-export-{}-rank1", files[0].1); + let transfer_files: Vec = files + .iter() + .map(|(n, s)| json!({"name": n, "size": s, "ranges": [[0, s]]})) + .collect(); + let reply: Value = serde_json::from_slice( + &peer_session + .request( + frame::TRANSFER, + &json!({ + "grant": grant, + "publisher": publisher, + "source": {"public_key": zero.agent.key.public().to_hex(), "address": zero.address}, + "directory": peer_dir, + "files": transfer_files, + }), + ) + .unwrap(), + ) + .unwrap(); + assert_eq!(reply["verified"], true); + let entry = peer + .agent + .resolve_orbit_entry_matching(&peer_dir, Some(envelope)) + .unwrap() + .expect("peer entry published with real non-zero envelope digest"); + assert!( + entry.directory().join(".flare-verified.json").is_file(), + "publish_orbit_entry must write .flare-verified.json for multi-deployment cores" + ); + + // 2. Rank zero RUN forwards `--tensor-parallel 2` exactly once (not missing, not doubled). + zero_session + .request( + frame::RUN, + &json!({"grant": grant, "rank": 0, "binary": Value::Null, "publisher": publisher}), + ) + .unwrap(); + let (lines, code) = collect(&mut zero_session); + assert_eq!(code, 0, "{lines:?}"); + let args = lines.join(" "); + let tp_count = args.matches("--tensor-parallel").count(); + assert_eq!(tp_count, 1, "expected exactly one --tensor-parallel: {args}"); + assert!(args.contains("--tensor-parallel 2"), "{args}"); + } } diff --git a/flare-cli/src/orbit/controller.rs b/flare-cli/src/orbit/controller.rs index 3bdf3d8fe..3ccbce23b 100644 --- a/flare-cli/src/orbit/controller.rs +++ b/flare-cli/src/orbit/controller.rs @@ -250,9 +250,13 @@ pub struct CoreNeeds { /// core, or one member holding the complete core for a single-host one. #[derive(Clone, Debug)] pub struct ResolvedCore { - /// The export identity every rank's file records, or the primary's stem for a single-host - /// core; with the primary's length it names cache directories. + /// The export identity every rank's file records, or the primary's stem plus envelope + /// digest prefix for a single-host core; with the primary's length it names cache directories. pub export: String, + /// SHA-256 of the signed core envelope (`AuthorizedCore::envelope_digest`). + pub envelope_digest: [u8; 32], + /// Selected tensor-parallel deployment size, when known. + pub tensor_parallel: Option, /// The primary file, then its companions. pub files: Vec, /// Each member's files and ranges, indexed by rank. @@ -687,6 +691,20 @@ impl Controller { // 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"); + // Keep only the last `--tensor-parallel` so CLI overrides replace a saved group's value + // rather than appending into clap's `Vec`, and feed it to `resolve_core` when the + // command line omitted it. + if let Some(last_tp) = deduplicate_tensor_parallel(&mut serving) + && options.run_args.serving.hub.tensor_parallel.is_empty() + { + options.run_args.serving.hub.tensor_parallel = last_tp + .split(',') + .map(|part| { + part.parse::() + .map_err(|_| Failure::from(format!("invalid --tensor-parallel value {last_tp:?}"))) + }) + .collect::, _>>()?; + } let verify_weights = options.verify_weights || options.run_args.serving.verify_weights || serving.iter().any(|arg| arg == "--verify-weights"); @@ -1356,6 +1374,8 @@ impl Controller { path: path.clone(), }), }, + envelope_digest: core.envelope_digest, + tensor_parallel: core.tensor_parallel, }, members: nodes .iter() @@ -1401,7 +1421,7 @@ impl Controller { let send_binary = match &binary { Some((name, bytes)) if !options.stage_only - && !have(session, "binary", name, bytes.len() as u64)? => + && !have(session, "binary", name, bytes.len() as u64, None)? => { needed += bytes.len() as u64; Some((name, *bytes)) @@ -1410,9 +1430,11 @@ impl Controller { }; let mut sends = Vec::new(); if let (0, Holder::Controller { primary }) = (rank, &core.holder) { + let expected_envelope = + (core.envelope_digest != [0u8; 32]).then_some(core.envelope_digest); for file in &core.files { let name = format!("{complete}/{}", file.name); - if !have(session, "core", &name, file.size)? { + if !have(session, "core", &name, file.size, expected_envelope)? { needed += file.size; let root = primary.parent().unwrap_or_else(|| Path::new(".")); sends.push((root.join(&file.name), name, file.size)); @@ -1442,6 +1464,7 @@ impl Controller { // Controller-uploaded files on rank zero still need agent-side verification and // publication into the managed model cache before peers fetch or ranks launch. + let expected_envelope = grant.core.expected_envelope(); if matches!(&core.holder, Holder::Controller { .. }) { let files: Vec = core .files @@ -1462,6 +1485,7 @@ impl Controller { &complete, &files, 1, + expected_envelope, ) .map_err(|e| at(&nodes[0].name, e))?; } @@ -1496,6 +1520,7 @@ impl Controller { &complete, &files, 1, + expected_envelope, )?; source = nodes[0].clone(); } @@ -1527,6 +1552,7 @@ impl Controller { &directory, &files, streams, + expected_envelope, ) .map_err(|e| at(&nodes[rank].name, e)) }))?; @@ -1913,16 +1939,54 @@ fn status_on(session: &mut Session, toward: Option<&str>) -> Result Result { - let reply = session.request( - frame::HAVE, - &json!({"kind": kind, "name": name, "size": size}), - )?; +/// Whether the node's cache holds the entry at `size` bytes (and matching `expected_envelope` +/// when provided); a held entry stays pinned for the session. +fn have( + session: &mut Session, + kind: &str, + name: &str, + size: u64, + expected_envelope: Option<[u8; 32]>, +) -> Result { + let mut request = json!({"kind": kind, "name": name, "size": size}); + if let Some(digest) = expected_envelope { + request["envelope_digest"] = json!(digest); + } + let reply = session.request(frame::HAVE, &request)?; Ok(reply == [1]) } +/// Retain only the final `--tensor-parallel` occurrence in `args` and return its value. +fn deduplicate_tensor_parallel(args: &mut Vec) -> Option { + let mut last: Option = None; + let mut cleaned = Vec::with_capacity(args.len()); + let mut index = 0; + while index < args.len() { + let arg = &args[index]; + if arg == "--tensor-parallel" { + if let Some(value) = args.get(index + 1) { + last = Some(value.clone()); + index += 2; + continue; + } + index += 1; + continue; + } + if let Some(value) = arg.strip_prefix("--tensor-parallel=") { + last = Some(value.to_owned()); + index += 1; + continue; + } + cleaned.push(arg.clone()); + index += 1; + } + if let Some(value) = &last { + cleaned.extend(["--tensor-parallel".into(), value.clone()]); + } + *args = cleaned; + last +} + /// Store `size` bytes read from `source` as a complete cache entry on the node. fn put( session: &mut Session, @@ -1962,26 +2026,30 @@ fn transfer( directory: &str, files: &[RankFile], streams: u8, + expected_envelope: Option<[u8; 32]>, ) -> Result<(), Failure> { - let mut needed = 0; - for file in files { - if !have( - session, - "core", - &format!("{directory}/{}", file.name), - file.size, - )? { - needed += cache::range_bytes(&file.ranges); - } - } - check_space(status, needed)?; - if needed > 0 { - eprintln!( - "{}: fetching {} from {}, then verifying", - node.name, - gib(needed), - source.name - ); + if source.public_key != node.public_key { + let mut needed = 0; + for file in files { + if !have( + session, + "core", + &format!("{directory}/{}", file.name), + file.size, + expected_envelope, + )? { + needed += cache::range_bytes(&file.ranges); + } + } + check_space(status, needed)?; + if needed > 0 { + eprintln!( + "{}: fetching {} from {}, then verifying", + node.name, + gib(needed), + source.name + ); + } } let request = json!({ "grant": grant, @@ -2350,18 +2418,23 @@ fn describe( .ok_or("the core path names no file")? .to_owned(); let cluster = runtime_core::core_cluster(authorized); - let hardware = authorized.identity().map_err(|e| e.to_string())?.hardware; + let identity = authorized.identity().map_err(|e| e.to_string())?; + let envelope_digest = authorized.envelope_digest(); + let tensor_parallel = (identity.tensor_parallel > 0).then_some(identity.tensor_parallel); let needs = CoreNeeds { - revision: super::gpu::core_revision(&hardware, first.architecture[0], first.architecture[1]), + revision: super::gpu::core_revision( + &identity.hardware, + first.architecture[0], + first.architecture[1], + ), multi_host: cluster.is_some(), rank_bytes: rank_needs.iter().map(|r| r.device_bytes).collect(), reserve_bytes: runtime_core::reserve_bytes(authorized), }; let (world, export) = match cluster { Some((world, export)) => (world, export), - None => ( - 1, - primary_name + None => { + let stem: String = primary_name .trim_end_matches(".safetensors") .chars() .map(|c| { @@ -2371,8 +2444,15 @@ fn describe( '_' } }) - .collect(), - ), + .collect(); + let digest_prefix = hex(&envelope_digest[..8]); + let export = if stem.is_empty() { + digest_prefix + } else { + format!("{stem}-{digest_prefix}") + }; + (1, export) + } }; let mut files = vec![CoreEntry { name: primary_name.clone(), @@ -2415,6 +2495,8 @@ fn describe( } Ok(ResolvedCore { export, + envelope_digest, + tensor_parallel, files, ranks, needs, @@ -2896,6 +2978,8 @@ mod tests { fs::write(&primary, &bytes).unwrap(); let core = ResolvedCore { export: "export".into(), + envelope_digest: [0u8; 32], + tensor_parallel: None, files: vec![CoreEntry { name: "model.safetensors".into(), size: bytes.len() as u64, @@ -3487,4 +3571,182 @@ mod tests { fs::metadata(&nested).unwrap().len() ); } + + #[test] + fn single_host_describe_derives_distinct_exports_from_envelope_digest() { + use flare_helios::core::{PayloadId, container, export as publish, schema::wire}; + use ring::signature::{Ed25519KeyPair, KeyPair}; + + let temp = tempfile::tempdir().unwrap(); + let key = Ed25519KeyPair::from_seed_unchecked(&[17u8; 32]).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let publisher = Publisher { + name: "Single".into(), + namespace: "local-development".into(), + public_key, + development: true, + }; + let contract = flare_helios::runtime_core::wire::ServingContract { + model_id: "single".into(), + identity: "single-sm120".into(), + max_sequence_tokens: 8, + prefill_chunk_size: 1, + pages: 1, + state_rows: 1, + page_tokens: 1, + model_contract: Some(flare_helios::runtime_core::wire::ModelContract { + vocabulary: 8, + graphs: vec![flare_helios::runtime_core::wire::GraphContract { + graph: "decode".into(), + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + }; + let build = |name: &str, fill: u8, core_id_byte: u8| { + let dir = temp.path().join(name); + fs::create_dir_all(&dir).unwrap(); + let weights = vec![fill; 4096]; + let id = PayloadId::of(&weights); + let raw = temp.path().join(format!("{name}-weights.bin")); + fs::write(&raw, &weights).unwrap(); + let graph = temp.path().join(format!("{name}-graph.bin")); + fs::write(&graph, b"graph-bytes").unwrap(); + let request = publish::PublishRequest { + core: wire::CoreBody { + model_identity: "owner/single".into(), + hardware_identity: "sm120".into(), + frontend: Some(flare_helios::runtime_core::wire::FrontendSettings::default()), + sampling_defaults: Some( + flare_helios::runtime_core::wire::DefaultSamplingParameters::default(), + ), + publisher: Some(wire::PublisherMetadata { + namespace: "local-development".into(), + official_source: "local-development".into(), + development: true, + ..Default::default() + }), + ..Default::default() + }, + payloads: vec![], + deployments: vec![publish::PublishDeployment { + body: wire::DeploymentBody { + deployment_id: "sm120-tp1".into(), + architecture: vec![12, 0], + tensor_parallel: 1, + contract: Some(contract.clone()), + cluster: None, + ..Default::default() + }, + ranks: vec![publish::PublishRank { + body: wire::RankBody { + rank: 0, + deployment_id: "sm120-tp1".into(), + context: Some(Default::default()), + allocations: vec![wire::Allocation { + name: "device-0".into(), + nbytes: weights.len() as u64, + alignment: 4096, + ..Default::default() + }], + initializers: vec![wire::Initializer { + allocation: "device-0".into(), + destination_offset: 0, + source: Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: id.as_bytes().to_vec(), + offset: 0, + nbytes: weights.len() as u64, + }), + role: wire::PayloadRole::Weights as i32, + }), + }], + graphs: vec![wire::Graph { + name: "decode".into(), + resource: 0, + node_count: 1, + ..Default::default() + }], + ..Default::default() + }, + payloads: vec![publish::PublishPayload { + role: wire::PayloadRole::Weights, + relative: "weights/layer-000.safetensors".into(), + source: container::Slice::new( + std::sync::Arc::new(File::open(&raw).unwrap()), + 0, + weights.len() as u64, + ) + .unwrap(), + id, + tensor: None, + }], + resources: vec![publish::PublishResource { + kind: wire::ExecutableKind::Graph, + path: graph, + nbytes: 11, + }], + }], + payloads: vec![], + }], + core_id: [core_id_byte; 32], + public_key, + accepted: "local-development".into(), + no_weights: false, + }; + publish::publish(&request, &key, publish::Destination::Directory(&dir)).unwrap(); + let primary = dir.join("model.safetensors"); + let verified = flare_helios::runtime_core::VerifiedCore::open( + &primary, + std::slice::from_ref(&publisher), + None, + ) + .unwrap(); + let authorized = verified.authorize("local-development", false).unwrap(); + describe( + &authorized, + &primary, + publisher.clone(), + Holder::Controller { + primary: primary.clone(), + }, + ) + .unwrap() + }; + + let first = build("v1", 0x11, 1); + let second = build("v2", 0x22, 2); + // Same-arch single-host Payload cores share `model.safetensors` and identical lengths. + assert_eq!(first.files[0].name, "model.safetensors"); + assert_eq!(second.files[0].name, "model.safetensors"); + assert_eq!(first.files[0].size, second.files[0].size); + assert_ne!(first.envelope_digest, second.envelope_digest); + assert_ne!( + first.export, second.export, + "single-host Payload cores must not collide on export=\"model\"" + ); + assert!( + first.export.starts_with("model-") + && first.export.ends_with(&hex(&first.envelope_digest[..8])), + "{}", + first.export + ); + assert_eq!(first.tensor_parallel, Some(1)); + assert_eq!(second.tensor_parallel, Some(1)); + + // Saved `--tensor-parallel` overridden on the CLI keeps only the last value. + let mut serving = vec![ + "--tensor-parallel".into(), + "2".into(), + "--max-concurrency".into(), + "8".into(), + "--tensor-parallel=4".into(), + ]; + assert_eq!(deduplicate_tensor_parallel(&mut serving), Some("4".into())); + assert_eq!( + serving, + vec!["--max-concurrency", "8", "--tensor-parallel", "4"] + ); + } } diff --git a/flare-cli/src/orbit/grant.rs b/flare-cli/src/orbit/grant.rs index 354ad8fed..6efaa9762 100644 --- a/flare-cli/src/orbit/grant.rs +++ b/flare-cli/src/orbit/grant.rs @@ -83,6 +83,20 @@ pub struct Core { pub files: Vec, /// Set when a node holds the core; absent when the controller sends it. pub source: Option, + /// SHA-256 of the signed core envelope (`AuthorizedCore::envelope_digest`). + /// All zeros only on legacy grants signed before envelope binding existed. + #[serde(default)] + pub envelope_digest: [u8; 32], + /// Selected tensor-parallel deployment size for multi-deployment payload cores. + #[serde(default)] + pub tensor_parallel: Option, +} + +impl Core { + /// Expected signed envelope digest when the grant binds one. + pub fn expected_envelope(&self) -> Option<[u8; 32]> { + (self.envelope_digest != [0u8; 32]).then_some(self.envelope_digest) + } } /// The controller's signed statement of one launch. @@ -221,6 +235,8 @@ mod tests { length: 10, files: vec!["model.safetensors".into()], source: None, + envelope_digest: [7u8; 32], + tensor_parallel: Some(2), }, members: vec![Member { rank: 0, @@ -248,6 +264,16 @@ mod tests { assert!(body.get("package").is_some()); assert!(body.get("core").is_none()); assert_eq!(serde_json::from_value::(body).unwrap(), expected); + + // Legacy grants lacking envelope_digest and tensor_parallel still deserialize cleanly. + let mut legacy = serde_json::to_value(&expected).unwrap(); + let package = legacy["package"].as_object_mut().unwrap(); + package.remove("envelope_digest"); + package.remove("tensor_parallel"); + let decoded: Grant = serde_json::from_value(legacy).unwrap(); + assert_eq!(decoded.core.envelope_digest, [0u8; 32]); + assert_eq!(decoded.core.expected_envelope(), None); + assert_eq!(decoded.core.tensor_parallel, None); } #[test] diff --git a/flare/src/download_cache.rs b/flare/src/download_cache.rs index 9c7c6ec8a..da8daf219 100644 --- a/flare/src/download_cache.rs +++ b/flare/src/download_cache.rs @@ -17,11 +17,9 @@ //! free, preserves the transport root and its marker, and never removes lock //! inodes. -#[cfg(unix)] -use std::fs::OpenOptions; use std::{ collections::HashSet, - fs::{self, File}, + fs, io, path::{Path, PathBuf}, }; @@ -862,7 +860,10 @@ struct LegacyTree { enum LegacyAccess { /// Every applicable lock is held by this pass; the tree can be removed before /// the guards are dropped. - Held { _lease: File, _locks: Vec }, + Held { + _lease: crate::file_lock::FileLock, + _locks: Vec, + }, /// A staging lease or transfer lock is held by another process. Active, /// Safe inactivity cannot be established, so the tree is preserved. @@ -991,9 +992,9 @@ fn legacy_trees(parent: &Path, model_root: &Path) -> Result, Fai } enum LockState { - /// No transfer holds the lock. The file keeps the exclusive lock while it + /// No transfer holds the lock. The lock guard keeps the exclusive lock while it /// stays alive, so reclamation holds it until the guarded file is removed. - Free(Option), + Free(Option), Held, } @@ -1003,64 +1004,19 @@ enum LockState { /// Reclamation passes `create = true` and keeps the returned lock until the /// guarded file is gone. fn lock_free(path: &Path, create: bool) -> Result { - let file = match open_lock(path, create) { + let file = match crate::file_lock::open_lock_file(path, create) { Ok(file) => file, Err(error) if error.kind() == io::ErrorKind::NotFound => { return Ok(LockState::Free(None)); } Err(error) => return Err(error.into()), }; - if try_exclusive(&file)? { - Ok(LockState::Free(Some(file))) - } else { - Ok(LockState::Held) - } -} - -#[cfg(unix)] -fn open_lock(path: &Path, create: bool) -> io::Result { - use std::os::unix::fs::OpenOptionsExt; - if create { - OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .mode(0o600) - .open(path) - } else { - File::open(path) - } -} - -#[cfg(not(unix))] -fn open_lock(path: &Path, create: bool) -> io::Result { - if create { - crate::windows::private_file(path, false) - } else { - File::open(path) - } -} - -#[cfg(unix)] -fn try_exclusive(file: &File) -> io::Result { - use std::os::fd::AsRawFd; - if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { - return Ok(true); - } - let error = io::Error::last_os_error(); - if error.kind() == io::ErrorKind::WouldBlock { - Ok(false) - } else { - Err(error) + match crate::file_lock::FileLock::try_exclusive_file(file)? { + Some(lock) => Ok(LockState::Free(Some(lock))), + None => Ok(LockState::Held), } } -#[cfg(not(unix))] -fn try_exclusive(file: &File) -> io::Result { - crate::windows::try_lock(file) -} - /// Metadata for a directory entry that another pass may have removed. fn entry_metadata(entry: &fs::DirEntry) -> Result, Failure> { match entry.metadata() { @@ -1347,42 +1303,17 @@ use crate::windows::file_identity as windows_file_identity; #[cfg(all(test, unix))] mod tests { use super::*; - use std::os::fd::AsRawFd; - fn hold(path: &Path) -> File { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).unwrap(); - } - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(path) - .unwrap(); - assert_eq!( - unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, - 0 - ); - file + fn hold(path: &Path) -> crate::file_lock::FileLock { + crate::file_lock::FileLock::try_exclusive(path) + .unwrap() + .expect("test lock should be free") } - fn hold_shared(path: &Path) -> File { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent).unwrap(); - } - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(path) - .unwrap(); - assert_eq!( - unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) }, - 0 - ); - file + fn hold_shared(path: &Path) -> crate::file_lock::FileLock { + crate::file_lock::FileLock::try_shared(path) + .unwrap() + .expect("test shared lock should be free") } fn write(path: &Path, bytes: &[u8]) { diff --git a/flare/src/file_lock.rs b/flare/src/file_lock.rs new file mode 100644 index 000000000..be1167ecc --- /dev/null +++ b/flare/src/file_lock.rs @@ -0,0 +1,168 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! RAII file locks with explicit Unix `flock(LOCK_UN)` on drop. +//! +//! On Unix, a concurrent `fork()` inherits open file descriptions until `execve` closes `O_CLOEXEC` +//! descriptors. Closing the parent's descriptor alone does not release an `flock` while the child +//! still holds a duplicate descriptor to the same open file description. Unlocking explicitly in +//! `Drop` releases the lock immediately when the guard ends. + +use std::fs::{self, File, OpenOptions}; +use std::io; +use std::path::Path; + +/// Process-owned advisory file lock that unlocks explicitly on drop on Unix. +pub(crate) struct FileLock(File); + +#[cfg(unix)] +impl Drop for FileLock { + fn drop(&mut self) { + use std::os::fd::AsRawFd; + let _ = unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) }; + } +} + +impl FileLock { + /// Blocking exclusive lock on `path`, creating parent directories and a private lock file. + pub(crate) fn exclusive(path: &Path) -> io::Result { + let file = open_lock_file(path, true)?; + lock_file(&file, true, true)?; + Ok(Self(file)) + } + + /// Blocking shared lock on `path`, creating parent directories and a private lock file. + pub(crate) fn shared(path: &Path) -> io::Result { + let file = open_lock_file(path, true)?; + lock_file(&file, false, true)?; + Ok(Self(file)) + } + + /// Non-blocking exclusive lock on `path`, creating parent directories and a private lock file. + /// Returns `Ok(None)` when another holder owns the lock. + pub(crate) fn try_exclusive(path: &Path) -> io::Result> { + let file = open_lock_file(path, true)?; + Self::try_exclusive_file(file) + } + + /// Non-blocking exclusive lock on an already-opened descriptor. + /// Returns `Ok(None)` when another holder owns the lock. + pub(crate) fn try_exclusive_file(file: File) -> io::Result> { + match lock_file(&file, true, false) { + Ok(()) => Ok(Some(Self(file))), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None), + Err(error) => Err(error), + } + } + + /// Non-blocking shared lock on `path` for tests. + #[cfg(test)] + pub(crate) fn try_shared(path: &Path) -> io::Result> { + let file = open_lock_file(path, true)?; + match lock_file(&file, false, false) { + Ok(()) => Ok(Some(Self(file))), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None), + Err(error) => Err(error), + } + } +} + +pub(crate) fn open_lock_file(path: &Path, create: bool) -> io::Result { + if create && let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; + } + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + if create { + OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(path) + } else { + File::open(path) + } + } + #[cfg(windows)] + { + if create { + crate::windows::private_file(path, false) + } else { + File::open(path) + } + } +} + +#[cfg(unix)] +fn lock_file(file: &File, exclusive: bool, blocking: bool) -> io::Result<()> { + use std::os::fd::AsRawFd; + let mut mode = if exclusive { + libc::LOCK_EX + } else { + libc::LOCK_SH + }; + if !blocking { + mode |= libc::LOCK_NB; + } + if unsafe { libc::flock(file.as_raw_fd(), mode) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +#[cfg(windows)] +fn lock_file(file: &File, exclusive: bool, blocking: bool) -> io::Result<()> { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION; + use windows_sys::Win32::Storage::FileSystem::{ + LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, + }; + use windows_sys::Win32::System::IO::OVERLAPPED; + let mut operation: OVERLAPPED = unsafe { std::mem::zeroed() }; + let mut flags = 0u32; + if exclusive { + flags |= LOCKFILE_EXCLUSIVE_LOCK; + } + if !blocking { + flags |= LOCKFILE_FAIL_IMMEDIATELY; + } + if unsafe { LockFileEx(file.as_raw_handle(), flags, 0, 1, 0, &mut operation) } == 0 { + let error = io::Error::last_os_error(); + if !blocking && error.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32) { + return Err(io::ErrorKind::WouldBlock.into()); + } + return Err(error); + } + Ok(()) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + #[test] + fn drop_releases_flock_even_when_duplicate_descriptor_stays_open() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("fork-inherited.lock"); + let lock = FileLock::exclusive(&path).unwrap(); + // Simulate a concurrent `fork()` inheriting the same open file description pre-`execve`. + let inherited = lock.0.try_clone().unwrap(); + assert!(FileLock::try_exclusive(&path).unwrap().is_none()); + drop(lock); + // Even while the duplicated descriptor remains open, `Drop` called `LOCK_UN`, so a new + // opener acquires the lock immediately. + let reacquired = FileLock::try_exclusive(&path).unwrap(); + assert!( + reacquired.is_some(), + "dropping FileLock must unlock the open file description despite inherited descriptors" + ); + drop(reacquired); + drop(inherited); + } +} diff --git a/flare/src/hub.rs b/flare/src/hub.rs index 5b6a46cfb..262a84faf 100644 --- a/flare/src/hub.rs +++ b/flare/src/hub.rs @@ -822,7 +822,7 @@ struct Transport { /// Shared lease for this acquisition. Reclamation takes the same inode /// exclusively, so repository snapshot metadata cannot be removed while an /// acquisition still opens files through it. - _lease: std::fs::File, + _lease: crate::file_lock::FileLock, } /// Free bytes on the filesystem that would hold `path`, walking up to the @@ -1517,7 +1517,7 @@ impl Transport { recovered } - fn legacy_blob_dirs(&self, folder: &str) -> Vec<(PathBuf, Option)> { + fn legacy_blob_dirs(&self, folder: &str) -> Vec<(PathBuf, Option)> { let mut directories = Vec::new(); if let Ok(entries) = std::fs::read_dir(self.model_root.join("staging/trees")) { for entry in entries.flatten() { @@ -1780,110 +1780,19 @@ fn sync_directory(path: &Path) -> Result<()> { Ok(()) } -fn open_lock(path: &Path) -> Result { - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - #[cfg(unix)] - let file = { - use std::os::unix::fs::OpenOptionsExt; - std::fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .mode(0o600) - .open(path)? - }; - #[cfg(windows)] - let file = crate::windows::private_file(path, false)?; - Ok(file) -} - /// Blocking exclusive lock on `path`, used to serialize one content transfer. -fn content_lock(path: &Path) -> Result { - let file = open_lock(path)?; - #[cfg(unix)] - { - use std::os::unix::io::AsRawFd; - if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 { - return Err(std::io::Error::last_os_error().into()); - } - } - #[cfg(windows)] - if !lock_windows(&file, true, true)? { - return Err(format!("cannot lock {}", path.display()).into()); - } - Ok(file) +fn content_lock(path: &Path) -> Result { + Ok(crate::file_lock::FileLock::exclusive(path)?) } /// Blocking shared lock, used for the acquisition lifetime lease. -fn shared_lock(path: &Path) -> Result { - let file = open_lock(path)?; - #[cfg(unix)] - { - use std::os::unix::io::AsRawFd; - if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_SH) } != 0 { - return Err(std::io::Error::last_os_error().into()); - } - } - #[cfg(windows)] - if !lock_windows(&file, false, true)? { - return Err(format!("cannot lock {}", path.display()).into()); - } - Ok(file) +fn shared_lock(path: &Path) -> Result { + Ok(crate::file_lock::FileLock::shared(path)?) } /// Exclusive lock that reports whether another holder already owns `path`. -fn try_lock_exclusive(path: &Path) -> Result> { - let file = open_lock(path)?; - #[cfg(unix)] - { - use std::os::unix::io::AsRawFd; - if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { - return Ok(Some(file)); - } - let error = std::io::Error::last_os_error(); - if error.kind() == std::io::ErrorKind::WouldBlock { - return Ok(None); - } - return Err(error.into()); - } - #[cfg(windows)] - { - if lock_windows(&file, true, false)? { - Ok(Some(file)) - } else { - Ok(None) - } - } -} - -/// Byte-range lock over the whole (empty) lock file. Shared locks are compatible -/// with other acquisitions; exclusive locks serialize transfers and reclamation. -#[cfg(windows)] -fn lock_windows(file: &std::fs::File, exclusive: bool, wait: bool) -> std::io::Result { - use std::os::windows::io::AsRawHandle; - use windows_sys::Win32::Storage::FileSystem::{ - LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, - }; - use windows_sys::Win32::System::IO::OVERLAPPED; - let mut operation: OVERLAPPED = unsafe { std::mem::zeroed() }; - let mut flags = 0u32; - if exclusive { - flags |= LOCKFILE_EXCLUSIVE_LOCK; - } - if !wait { - flags |= LOCKFILE_FAIL_IMMEDIATELY; - } - let acquired = unsafe { LockFileEx(file.as_raw_handle(), flags, 0, 1, 0, &mut operation) } != 0; - if acquired { - return Ok(true); - } - if wait { - return Err(std::io::Error::last_os_error()); - } - Ok(false) +fn try_lock_exclusive(path: &Path) -> Result> { + Ok(crate::file_lock::FileLock::try_exclusive(path)?) } fn source_selector( diff --git a/flare/src/lib.rs b/flare/src/lib.rs index e42a651cc..b0ce6c313 100644 --- a/flare/src/lib.rs +++ b/flare/src/lib.rs @@ -5,6 +5,7 @@ pub mod controller; pub mod cache_support; pub mod download_cache; pub mod environment; +pub(crate) mod file_lock; pub mod hardware; pub(crate) mod http_client; pub mod hub; diff --git a/flare/src/trust.rs b/flare/src/trust.rs index 3bbdd08c3..6c507ac9f 100644 --- a/flare/src/trust.rs +++ b/flare/src/trust.rs @@ -14,7 +14,7 @@ #[cfg(unix)] use std::fs::OpenOptions; #[cfg(unix)] -use std::os::{fd::AsRawFd, unix::fs::OpenOptionsExt}; +use std::os::unix::fs::OpenOptionsExt; use flare_helios::runtime_core::{AuthorizedCore, CoreClaim, Publisher, VerifiedCore}; use serde::{Deserialize, Serialize}; @@ -252,23 +252,8 @@ fn modify(path: &Path, update: impl FnOnce(&mut Store) -> Result<()>) -> Result< fs::create_dir_all(parent)?; let mut lock_name = path.as_os_str().to_owned(); lock_name.push(".lock"); - #[cfg(windows)] - let lock = crate::windows::private_file(Path::new(&lock_name), false)?; - #[cfg(unix)] - let lock = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .mode(0o600) - .open(PathBuf::from(lock_name))?; // The lock serializes read/modify/rename across concurrent startup processes. - #[cfg(unix)] - if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 { - return Err(io::Error::last_os_error().into()); - } - #[cfg(windows)] - crate::windows::lock(&lock)?; + let _lock = crate::file_lock::FileLock::exclusive(Path::new(&lock_name))?; let mut store = load_store(path)?; update(&mut store)?; let mut temporary = path.as_os_str().to_owned(); diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index c28220936..a783e39fb 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -2264,6 +2264,7 @@ fn resolve_weight_payload( Vec, u64, )> = Vec::with_capacity(payloads.len()); + let mut remote_cached: Vec = Vec::new(); for (is_weight, name, storage, spans) in payloads.drain(..) { if let Some(root) = &root { let mut download = device_reader @@ -2271,9 +2272,10 @@ fn resolve_weight_payload( .map(|downloader| WeightDownload::new(downloader, device_allocations, spans)) .transpose()?; let mut cache_reader = RetainedReader::new(&retained, &parts); - let Some((object, mapped, length)) = capture_group_into_cache( + let Some((captured, mapped, length)) = capture_group_into_cache( root, request.options.no_weights, + request.options.remote_cache, is_weight, &name, spans, @@ -2285,8 +2287,20 @@ fn resolve_weight_payload( else { continue; }; - let payload_id = object.id(); - output.payload_leases.0.push(object); + let payload_id = match captured { + CapturedGroupPayload::Local(object) => { + let id = object.id(); + output.payload_leases.0.push(object); + id + } + CapturedGroupPayload::Remote(id) => { + remote_cached.push(helios_core::core::schema::wire::PayloadDescriptor { + id: id.as_bytes().to_vec(), + nbytes: length, + }); + id + } + }; resolved.push(( is_weight, name, @@ -2389,8 +2403,18 @@ fn resolve_weight_payload( spans: Vec::new(), payload_id: Vec::new(), }); - let cached = reused.as_ref().map(|groups| groups.iter().map(|group| - helios_core::core::schema::wire::PayloadDescriptor { id: group.payload_id.clone(), nbytes: group.nbytes }).collect()).unwrap_or_default(); + let cached = reused + .as_ref() + .map(|groups| { + groups + .iter() + .map(|group| helios_core::core::schema::wire::PayloadDescriptor { + id: group.payload_id.clone(), + nbytes: group.nbytes, + }) + .collect() + }) + .unwrap_or(remote_cached); let sources = WeightPayloadSources { cached, engram: output.weight_payload.as_ref().and_then(|sources| sources.engram.clone()), groups: reused.unwrap_or(groups), @@ -2499,25 +2523,32 @@ where Ok(()) } +enum CapturedGroupPayload { + Local(helios_core::core::cache::PayloadObject), + Remote(helios_core::core::PayloadId), +} + /// Capture one weight or state group directly into the core cache in a single /// source read pass. /// /// For `--no-weights` weight groups, hashes the source stream once and verifies -/// the installed cached blob on disk without writing a staging file. For all -/// other groups, streams non-zero blocks once into the cache's deterministic -/// companion wrapper, discarding the temporary file on a cache hit and publishing -/// it directly on a miss. +/// the installed cached blob on disk without writing a staging file (or returns +/// only the computed identity when `remote_cache` defers cache verification to +/// the multi-host coordinator). For all other groups, streams non-zero blocks +/// once into the cache's deterministic companion wrapper, discarding the +/// temporary file on a cache hit and publishing it directly on a miss. #[allow(clippy::type_complexity)] fn capture_group_into_cache( root: &helios_core::core::cache::Root, no_weights: bool, + remote_cache: bool, is_weight: bool, name: &str, spans: &[weight_payload::PayloadSpan], read_into: &mut R, ) -> ExportResult< Option<( - helios_core::core::cache::PayloadObject, + CapturedGroupPayload, Vec, u64, )>, @@ -2535,11 +2566,6 @@ where // catalog entry; `no_weights` must not look for an empty object. return Ok(None); } - let object = root.verified_payload(payload_id, length)?.ok_or_else(|| { - invalid(format!( - "no-weights export is missing cached payload {payload_id} (group {name})" - )) - })?; let mapped = blocks .into_iter() .map(|(allocation, destination_offset, source_offset, nbytes)| { @@ -2551,7 +2577,23 @@ where } }) .collect(); - return Ok(Some((object, mapped, length))); + if remote_cache { + return Ok(Some(( + CapturedGroupPayload::Remote(payload_id), + mapped, + length, + ))); + } + let object = root.verified_payload(payload_id, length)?.ok_or_else(|| { + invalid(format!( + "no-weights export is missing cached payload {payload_id} (group {name})" + )) + })?; + return Ok(Some(( + CapturedGroupPayload::Local(object), + mapped, + length, + ))); } let mut mapped = Vec::new(); @@ -2592,7 +2634,11 @@ where "streamed payload length {length} differs from recorded span total {total} (group {name})" ))); } - Ok(Some((object, mapped, length))) + Ok(Some(( + CapturedGroupPayload::Local(object), + mapped, + length, + ))) } /// Sequential reader over the same blocks, used by tests to cross-check block streams. @@ -3437,7 +3483,7 @@ pub(crate) fn capture_rank( &mut reach, if cache_scan { None } else { store.as_ref() }, commits, - request.options.no_weights, + request.options.no_weights && !request.options.remote_cache, !cache_scan, &skip_numeric, &storage_phase, @@ -5189,15 +5235,19 @@ mod tests { // 1. Cold miss: reads each of the 3 blocks exactly once (3 reads, not 6). let miss_reads = std::cell::Cell::new(0usize); let mut reader = read_from(&backing, &miss_reads); - let (object, mapped, length) = capture_group_into_cache( + let (captured, mapped, length) = capture_group_into_cache( &root, false, + false, true, "layer-000", &spans, &mut reader, )? .expect("non-empty weight group must publish"); + let CapturedGroupPayload::Local(object) = captured else { + panic!("cold miss must produce a local cached object"); + }; assert_eq!(miss_reads.get(), 3, "cold miss must read source in one pass"); assert_eq!(object.id(), expected_id); assert_eq!(length, (2 * block) as u64); @@ -5210,15 +5260,19 @@ mod tests { // 2. Warm hit: reads each block once and returns the verified cached object. let hit_reads = std::cell::Cell::new(0usize); let mut reader = read_from(&backing, &hit_reads); - let (hit_object, hit_mapped, hit_length) = capture_group_into_cache( + let (captured, hit_mapped, hit_length) = capture_group_into_cache( &root, false, + false, true, "layer-000", &spans, &mut reader, )? .expect("warm hit must return cached object"); + let CapturedGroupPayload::Local(hit_object) = captured else { + panic!("warm hit must produce a local cached object"); + }; assert_eq!(hit_reads.get(), 3, "warm hit must read source in one pass"); assert_eq!(hit_object.id(), expected_id); assert_eq!(hit_length, length); @@ -5228,15 +5282,19 @@ mod tests { let locks_before = fs::read_dir(root.path().join("locks/staging"))?.count(); let no_weights_reads = std::cell::Cell::new(0usize); let mut reader = read_from(&backing, &no_weights_reads); - let (nw_object, nw_mapped, nw_length) = capture_group_into_cache( + let (captured, nw_mapped, nw_length) = capture_group_into_cache( &root, true, + false, true, "layer-000", &spans, &mut reader, )? .expect("no-weights hit must return verified cached object"); + let CapturedGroupPayload::Local(nw_object) = captured else { + panic!("local no-weights hit must produce a local cached object"); + }; assert_eq!( no_weights_reads.get(), 3, @@ -5264,6 +5322,7 @@ mod tests { let err = match capture_group_into_cache( &root, true, + false, true, "layer-000", &spans, @@ -5279,18 +5338,52 @@ mod tests { "unexpected error: {err}" ); + // 4b. Remote peer `--no-weights` hashes in one pass on a completely cold/empty local cache + // without requiring a local blob or writing anything to staging. + let cold_peer_temp = tempfile::tempdir()?; + let cold_peer_root = helios_core::core::cache::Root::open(cold_peer_temp.path())?; + let remote_reads = std::cell::Cell::new(0usize); + let mut reader = read_from(&missing_backing, &remote_reads); + let (remote_captured, remote_mapped, remote_length) = capture_group_into_cache( + &cold_peer_root, + true, + true, + true, + "layer-000", + &spans, + &mut reader, + )? + .expect("remote no-weights peer must return hashed identity"); + let CapturedGroupPayload::Remote(remote_id) = remote_captured else { + panic!("remote no-weights peer must defer cache lookup to coordinator"); + }; + assert_eq!(remote_reads.get(), 3); + assert_eq!(remote_length, length); + assert_eq!(remote_mapped.len(), 2); + assert_ne!(remote_id, expected_id); + assert!(cold_peer_root.payload(remote_id)?.is_none()); + let blob_files = fs::read_dir(cold_peer_root.path().join("blobs"))? + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_string_lossy().ends_with(".safetensors")) + .count(); + assert_eq!(blob_files, 0); + // 5. `--no-weights` for initial-state (`is_weight == false`) publishes in one pass. let state_reads = std::cell::Cell::new(0usize); let mut reader = read_from(&missing_backing, &state_reads); - let (state_object, _, _) = capture_group_into_cache( + let (state_captured, _, _) = capture_group_into_cache( &root, true, false, + false, "initial-state", &spans, &mut reader, )? .expect("state group under no-weights must publish"); + let CapturedGroupPayload::Local(state_object) = state_captured else { + panic!("initial-state must publish a local object"); + }; assert_eq!(state_reads.get(), 3); assert_ne!(state_object.id(), expected_id); Ok(()) diff --git a/heliopause/src/export/mod.rs b/heliopause/src/export/mod.rs index a65f98be3..d1e76e18c 100644 --- a/heliopause/src/export/mod.rs +++ b/heliopause/src/export/mod.rs @@ -134,6 +134,11 @@ pub(crate) struct ExportOptions { pub cache: Option, #[serde(default)] pub no_weights: bool, + /// True when a remote multi-host peer exports sources for a coordinator whose own cache + /// validates `--no-weights` payloads. Weight payloads are hashed once without requiring local + /// cache blobs on the peer. + #[serde(default)] + pub remote_cache: bool, #[serde(default)] pub reuse_weights: Option, } diff --git a/heliopause/src/export/transfer.rs b/heliopause/src/export/transfer.rs index 781fa9d0e..d6418c54e 100644 --- a/heliopause/src/export/transfer.rs +++ b/heliopause/src/export/transfer.rs @@ -875,13 +875,22 @@ fn receive_rank( return Err(invalid("cached rank payload differs from its declared group")); } if cached_objects.insert(id) { + let payload_id = helios_core::core::PayloadId::from_bytes(id); let root = helios_core::core::cache::Root::open(cache)?; - let object = root.payload(helios_core::core::PayloadId::from_bytes(id))? - .ok_or_else(|| invalid("reused payload object disappeared"))?; + let object = root.payload(payload_id)?.ok_or_else(|| { + invalid(if no_weights { + "--no-weights requires the peer payload object in the coordinator cache" + } else { + "reused payload object disappeared" + }) + })?; if object.length() != descriptor.nbytes { return Err(invalid("reused payload object has the wrong length")); } - installed.lock().map_err(|_| invalid("payload lease lock poisoned"))?.push(object); + installed + .lock() + .map_err(|_| invalid("payload lease lock poisoned"))? + .push(object); cached_bytes += descriptor.nbytes; cached_files += 1; } @@ -2168,4 +2177,86 @@ mod tests { .contains("capacity") ); } + + #[test] + fn remote_no_weights_peer_reuses_coordinator_cache_and_rejects_missing_or_corrupt() { + let directory = Directory::new(); + let cache = directory.0.join("cache"); + let root = helios_core::core::cache::Root::open(&cache).unwrap(); + let payload_bytes = vec![0x5a; 4096]; + let (cached_object, payload_len) = root + .capture_streaming_payload(|writer| { + writer.write_all(&payload_bytes)?; + Ok(()) + }) + .unwrap() + .unwrap(); + let payload_id = cached_object.id(); + drop(cached_object); + + // Cold peer has no local blob leases and declares its hashed weights in `cached`. + let mut peer_rank = RankOutput { + index: super::super::wire::ModelIndex { + version: 4, + ranks: vec![Default::default()], + ..Default::default() + }, + payload: Vec::new(), + allocations: Vec::new(), + module_globals: Vec::new(), + external: Vec::new(), + hardware: None, + staging: None, + weight_payload: Some(crate::export::WeightPayloadSources { + groups: vec![crate::export::WeightPayloadGroup { + name: "layer-000".into(), + storage: "stable".into(), + spans: Vec::new(), + payload_id: payload_id.as_bytes().to_vec(), + nbytes: payload_len, + }], + initial_state: crate::export::WeightPayloadGroup { + name: "initial-state".into(), + storage: "stable".into(), + spans: Vec::new(), + payload_id: Vec::new(), + nbytes: 0, + }, + views: Vec::new(), + cached: vec![helios_core::core::schema::wire::PayloadDescriptor { + id: payload_id.as_bytes().to_vec(), + nbytes: payload_len, + }], + engram: None, + }), + payload_leases: Default::default(), + }; + + // 1. Coordinator cache holds the blob -> succeeds with 0 payload bytes transferred. + let received = roundtrip(&directory, "cold-peer-ok.json", &peer_rank, true).unwrap(); + assert_eq!(received.stats["payload_bytes"], 0); + assert_eq!(received.leases.0.len(), 1); + assert_eq!(received.leases.0[0].id(), payload_id); + drop(received); + + // 2. Declared length mismatch -> rejected before publication. + let mut wrong_len = peer_rank.clone(); + wrong_len.weight_payload.as_mut().unwrap().groups[0].nbytes = payload_len + 1; + wrong_len.weight_payload.as_mut().unwrap().cached[0].nbytes = payload_len + 1; + let err = roundtrip(&directory, "cold-peer-wrong-len.json", &wrong_len, true) + .err() + .unwrap() + .to_string(); + assert!(err.contains("wrong length"), "{err}"); + + // 3. Missing blob in coordinator cache -> fails with clear `--no-weights` error. + let blob_path = cache.join("blobs").join(format!("{payload_id}.safetensors")); + fs::remove_file(&blob_path).unwrap(); + let err = roundtrip(&directory, "cold-peer-missing.json", &peer_rank, true) + .err() + .unwrap() + .to_string(); + assert!(err.contains("--no-weights"), "{err}"); + let _ = &mut peer_rank; + } } diff --git a/helios/src/core/cache.rs b/helios/src/core/cache.rs index f08636393..48a0b9dc9 100644 --- a/helios/src/core/cache.rs +++ b/helios/src/core/cache.rs @@ -4243,10 +4243,21 @@ impl Pruned { } } -/// Process-owned file lock; dropping the descriptor releases it. +/// Process-owned file lock; dropping it releases the lock immediately. #[allow(dead_code)] struct Lock(File); +#[cfg(unix)] +impl Drop for Lock { + fn drop(&mut self) { + use std::os::fd::AsRawFd; + // A concurrent `fork()` can briefly inherit this open file description before `execve` + // closes it via `O_CLOEXEC`. Unlock explicitly so releasing the guard frees the `flock` + // immediately instead of keeping it held until the child reaches `execve`. + let _ = unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) }; + } +} + impl Lock { fn shared(path: impl AsRef) -> Result { let file = open_lock(path.as_ref())?; @@ -9603,4 +9614,29 @@ mod selection_tests { assert!(!active_blob.exists()); let _ = fs::remove_dir_all(path); } + + #[cfg(unix)] + #[test] + fn lock_drop_releases_flock_even_with_duplicate_descriptor() { + let path = std::env::temp_dir().join(format!( + "flare-cache-lock-drop-{}", + TRANSACTION.fetch_add(1, Ordering::Relaxed) + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).unwrap(); + let lock_file = path.join("entry.lock"); + let lock = Lock::exclusive(&lock_file).unwrap(); + // Simulate a concurrent `fork()` inheriting the open file description before `execve`. + let inherited = lock.0.try_clone().unwrap(); + assert!(Lock::try_exclusive(&lock_file).unwrap().is_none()); + drop(lock); + let reacquired = Lock::try_exclusive(&lock_file).unwrap(); + assert!( + reacquired.is_some(), + "dropping Lock must unlock the open file description even while an inherited descriptor remains open" + ); + drop(reacquired); + drop(inherited); + let _ = fs::remove_dir_all(path); + } } \ No newline at end of file diff --git a/helios/src/core/conversion.rs b/helios/src/core/conversion.rs index 9f76c0326..237093006 100644 --- a/helios/src/core/conversion.rs +++ b/helios/src/core/conversion.rs @@ -2693,6 +2693,14 @@ struct CoreLock { _file: File, } +#[cfg(unix)] +impl Drop for CoreLock { + fn drop(&mut self) { + use std::os::fd::AsRawFd; + let _ = unsafe { libc::flock(self._file.as_raw_fd(), libc::LOCK_UN) }; + } +} + fn lock_core(directory: &Path) -> Result { // Cross-version conversion writers synchronize through this same lock path. let path = directory.join(".flare-package.lock"); diff --git a/helios/src/lib.rs b/helios/src/lib.rs index ab331ff2f..9e2ee8dca 100644 --- a/helios/src/lib.rs +++ b/helios/src/lib.rs @@ -35,7 +35,7 @@ pub mod startup; pub mod frontend; pub use cuda::current_context; -pub use flare_eos::raise_open_file_limit; +pub use flare_eos::{raise_open_file_limit, release_page_cache, release_page_cache_range}; pub use replay::{BufferSpan, Completion, GraphBundle, ReplayWorker, Shutdown}; pub use error::{AdmissionError, CudaError, Error, ExecutionError, Failure, FrontendError}; diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index 66017c50f..0796c7ffa 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -804,6 +804,9 @@ impl NativeModel { model.parallel(&cores, &files, |rank, core, path| { rank.load_payload(path, core, &phase, devices.len()) })?; + if model.ranks.iter().any(|rank| rank.integrated) { + Files::release_page_cache(&files); + } phase.finish(format!( "{:.1} GiB", payload_bytes as f64 / (1u64 << 30) as f64 diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index 2e1915f22..e7a31369d 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -1702,7 +1702,9 @@ impl PayloadSource { context.update(&buffer[..count]); offset += count as u64; } - if context.finish().as_ref() != id { + let digest = context.finish(); + crate::os::release_page_cache_range(&file.file, file.start, nbytes); + if digest.as_ref() != id { return Err(invalid("payload content verification failed")); } Ok(()) @@ -2380,7 +2382,9 @@ impl PayloadVerifiedCore { context.update(&buffer[..count]); offset += count as u64; } - if context.finish().as_ref() != id { + let digest = context.finish(); + crate::os::release_page_cache_range(&file.file, file.start, placement.nbytes); + if digest.as_ref() != id { return Err(invalid("payload content verification failed")); } Ok(()) diff --git a/ignition/preparation/core_snapshot.py b/ignition/preparation/core_snapshot.py index d859dc395..e9952e01e 100644 --- a/ignition/preparation/core_snapshot.py +++ b/ignition/preparation/core_snapshot.py @@ -19,16 +19,18 @@ class ExportOptions: no_weights: bool = False reuse_weights: dict | None = None kernel_cache: Path | None = None + remote_cache: bool = False @contextmanager -def export_options(cache, *, no_weights=False, reuse_weights=None, kernel_cache=None): +def export_options(cache, *, no_weights=False, reuse_weights=None, kernel_cache=None, remote_cache=False): token = _OPTIONS.set( ExportOptions( Path(cache), no_weights, reuse_weights, None if kernel_cache is None else Path(kernel_cache), + remote_cache, ) ) try: diff --git a/ignition/preparation/host_ranks.py b/ignition/preparation/host_ranks.py index 5945f6b24..10211d9d7 100644 --- a/ignition/preparation/host_ranks.py +++ b/ignition/preparation/host_ranks.py @@ -676,12 +676,17 @@ def serve_peer(control, executor, rank, world, *, hub_cache, progress=None, expo _, options, settings = command native_stage = flare_heliopause.NativeExportStage( None, export_staging, core_cache) + core = None try: path = Path(native_stage.rank_path(rank)) + # Peer hosts never commit a local model entry; capture transient blobs inside the + # export stage so `native_stage.close()` reclaims them immediately post-transfer, + # and defer `--no-weights` cache verification to rank zero's coordinator cache. + peer_cache = Path(native_stage.path) / "peer-cache" if progress is not None: progress(f"exporting rank {rank}") - context = export_options(core_cache, no_weights=settings.no_weights, - reuse_weights=settings.reuse_weights) if core_cache is not None else contextlib.nullcontext() + context = export_options(peer_cache, no_weights=settings.no_weights, + reuse_weights=settings.reuse_weights, remote_cache=True) with context: core = export_model(model, recorder, storage, path, options=options, bundle_only=True, sources=True) @@ -689,6 +694,7 @@ def serve_peer(control, executor, rank, world, *, hub_cache, progress=None, expo channels=[channel for channel, _ in source.channel_stats]) source.close_transport() finally: + core = None native_stage.close() command = receive_object(control) source.close_transport() diff --git a/ignition/preparation/runtime_core.py b/ignition/preparation/runtime_core.py index 1067a4d9f..b697235ed 100644 --- a/ignition/preparation/runtime_core.py +++ b/ignition/preparation/runtime_core.py @@ -328,6 +328,7 @@ def _cache_options(cache, options=None): rebuild_manifest=None if options is None else options.get('rebuild_manifest'), ) return dict(cache=None if cache is None else str(cache.cache), no_weights=False if cache is None else cache.no_weights, + remote_cache=False if cache is None else cache.remote_cache, reuse_weights=reuse)