From 37496883466f52017c08d51e7bdf1afef81885d0 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Thu, 3 Dec 2026 21:42:58 -0800 Subject: [PATCH] helios,heliopause,ignition: unify RankBody and RankOutput payload visitors for external_extents and align config.toml schema Independent payload walkers across Helios and Heliopause omitted RankBody.external_extents (the authenticated extent directories and backing segments for Execution.async_transfers), creating six defects: multi-host rank export dropped external_extents files and left sender-local paths unrewritten; keyless pack/unpack and combine dropped external_extents from location closures and PublishRank.payloads; runtime-core verification omitted external_extents directories from supporting_payload_ids (leaving directories unhashed once supporting_verified is set), omitted segments from verification_payloads(true), and omitted external_extents companions from multi-host serving bootstrap (rank_ranges); weight reuse and export planning omitted external_extents from cached-weight checks, file descriptor preflight accounting, and cache-lease deduplication; capture validation checked external_extents at seg_base_offset=0, allowing alignments above the 4 KiB core container alignment to pass export and fail at load; and Ignition's config.toml validator rejected [memory] pool_vram and pool_ram that Flare already accepts. Separately, a test Core literal in helios/src/runtime_core/cache_memory.rs omitted external_extents, breaking cargo test --features runtime-core,server compilation while the Helios lifecycle workflow only built --features server. Unifying rank traversal through exhaustively destructured visitors ensures future payload-bearing fields on RankBody or RankOutput fail compilation until every consumer classifies them. Changes: - helios/src/core/schema.rs: add RankPayloadUse and exhaustively destructured wire::RankBody::{visit_payload_uses, try_visit_payload_uses}; fix validate_external_extents to validate directory.slice.nbytes rather than the enclosing payload length. - helios/src/core/reader.rs, helios/src/core/conversion.rs, helios/src/runtime_core/protection.rs, flare-cli/src/distribution/cache_tests.rs: replace manual rank payload loops with RankBody::visit_payload_uses / try_visit_payload_uses. supporting_payload_ids now always includes ExternalExtentDirectory (independent of PayloadRole, preserving compatibility with cores whose directories use PayloadRole::Weights) plus any InitialState ExternalExtentSegment; verification_payloads(true) includes all ExternalExtentSegment payloads; rank_ranges includes all rank external_extents companions. - helios/src/runtime_core/format.rs, helios/src/runtime_core/cache_memory.rs, .github/workflows/helios-lifecycle.yml: reject nonempty Core.external_extents without an execution manifest, add missing external_extents: vec![] to the cache_memory test Core literal, and add runtime-core,server test compilation to the Helios lifecycle workflow. - heliopause/src/export/{mod,transfer,weight_reuse,core,capture}.rs and ignition/preparation/execution.py: add RankSourcePath and exhaustively destructured RankOutput::{visit_source_paths, try_visit_source_paths, visit_source_paths_mut}; transfer and rewrite external_extents paths in send_rank/receive_rank; route weight_reuse::open_source through RankBody::try_visit_payload_uses; account for external_extents file descriptors in estimated_export_fds and deduplicate them against core-cache leases in rank_plan; extract and enforce 4 KiB container::ALIGNMENT (validating at seg_base_offset=4096 and rejecting empty directories) in capture.rs and AsyncTransferChannel. - ignition/cli/config.py, docs/cli-design.md, tests/cli/test_config.py, flare-cli/src/config.rs: accept and validate [memory] pool_vram and pool_ram matching flare_helios::runtime_core::PoolMemoryLimit, update the configuration specification, and add a Rust-vs-Python schema parity test that parses flare/src/configuration.rs and loads every Rust configuration key through Configuration.load. Result: Restores flare-helios --features runtime-core,server test compilation, closes multi-host export transfer, keyless pack/unpack, combine, multi-host serving rank_ranges, --reuse-weights, and cryptographic verification coverage for RankBody.external_extents, prevents exporting unloadable external_extents channels above 4 KiB container alignment, unblocks Ignition commands sharing config.toml files with [memory] pool_vram or pool_ram, and turns future omitted payload fields on RankBody or RankOutput into compile-time errors. Validation (CPU suites on Linux x86_64): - cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib --no-run: compiled cleanly (0 warnings). - cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --lib (with FLARE_TEST_TEMPLATE_DIR=/tmp/flare-test-templates): 1899 passed, 49 ignored, 6 failed solely in external chat-template tests due to missing nemotron_h/qwen38/step5 fixtures in /tmp/flare-test-templates; all new schema, conversion, combine, and protection external_extents tests and all 52 cache_memory unit tests passed. - cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --test unverified_empty --test actual_qwen38_tp2 --test actual_w4a16: 3 passed, 0 failed, 2 ignored. - cargo test --locked --release --manifest-path heliopause/Cargo.toml --lib: 234 passed, 0 failed, 6 ignored (including new capture alignment, transfer roundtrip, FD preflight, cache dedup, and weight_reuse::open_source tests). - cargo test --locked --release --manifest-path flare/Cargo.toml --tests: 255 passed, 0 failed, 4 ignored. - cargo test --locked --release --manifest-path flare-cli/Cargo.toml --tests: 249 passed, 0 failed, 3 ignored (including new pool_vram and pool_ram config precedence tests). - pytest tests/cli tests/preparation/test_execution.py: 260 passed, 0 failed (including pool_vram/pool_ram validation, Rust-vs-Python config parity, and AsyncTransferChannel alignment tests); tests/preparation/test_runtime_core.py and test_core_boundary.py: 26 passed, 14 skipped (CUDA/optional fixtures). Limitations: live CUDA execution, GPU-only tests, multi-host live fabric serving with external_extents, and the 6 missing-template frontend tests were not executed here. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b Signed-off-by: Luke Alonso --- .github/workflows/helios-lifecycle.yml | 2 + docs/cli-design.md | 4 +- flare-cli/src/config.rs | 56 +++ flare-cli/src/distribution/cache_tests.rs | 26 +- heliopause/src/export/capture.rs | 201 ++++++++--- heliopause/src/export/core.rs | 175 +++++++-- heliopause/src/export/mod.rs | 138 +++++++ heliopause/src/export/transfer.rs | 104 ++++-- heliopause/src/export/weight_reuse.rs | 30 +- helios/src/core/conversion.rs | 286 +++++++++++++-- helios/src/core/reader.rs | 38 +- helios/src/core/schema.rs | 297 ++++++++++++++- helios/src/runtime_core/cache_memory.rs | 1 + helios/src/runtime_core/format.rs | 4 + helios/src/runtime_core/protection.rs | 421 +++++++++++++++++++--- ignition/cli/config.py | 37 +- ignition/preparation/execution.py | 5 + tests/cli/test_config.py | 118 ++++++ tests/preparation/test_execution.py | 35 ++ 19 files changed, 1741 insertions(+), 237 deletions(-) diff --git a/.github/workflows/helios-lifecycle.yml b/.github/workflows/helios-lifecycle.yml index 2b97e47e6..13f5017e7 100644 --- a/.github/workflows/helios-lifecycle.yml +++ b/.github/workflows/helios-lifecycle.yml @@ -32,6 +32,8 @@ jobs: run: curl --fail --location --retry 2 --output "$RUNNER_TEMP/tla2tools.jar" https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar - name: Check lifecycle model and Rust conformance run: python3 verification/helios-lifecycle/check.py --tlc-jar "$RUNNER_TEMP/tla2tools.jar" + - name: Compile Helios runtime-core and server tests + run: cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server --lib --no-run kani: runs-on: ubuntu-24.04 diff --git a/docs/cli-design.md b/docs/cli-design.md index 57bca7948..e9c861f53 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -1365,7 +1365,7 @@ file or an invalid runtime setting is an error. Help does not read the file. Native `flare run` applies `[server] host`, `port`, `api_key`, `advertise`, `thinking_token_budget`, and `scheduler_checkpoint_extra_work_fraction`, -`[memory] reserve`, `[defaults] max_concurrency`, `[models.] max_concurrency`, all `[prefix_cache]` +`[memory] reserve`, `pool_vram`, and `pool_ram`, `[defaults] max_concurrency`, `[models.] max_concurrency`, all `[prefix_cache]` settings, and `[paths] prefix_cache`. Prepared-model acquisition and cache commands use `[paths] core_cache`. Flags override these defaults, including explicit zero limits and values equal to the built-in defaults. An empty `--api-key-file` @@ -1409,6 +1409,8 @@ max_concurrency = 4 [memory] reserve = "0" # GPU memory left for processes started later. +# pool_vram = "" # Per-GPU ceiling for Capacity::DEVICE_POOL allocations (0, 12G, -8G, 0.25). +# pool_ram = "" # Per-rank ceiling for pinned AsyncTransfer host pools (0, 32G, -16G, 0.5). [prefix_cache] memory = "" # Warm checkpoints and CPU inputs; empty or 0: no warm tier. Intake is additional. diff --git a/flare-cli/src/config.rs b/flare-cli/src/config.rs index aa410a63a..5b33be280 100644 --- a/flare-cli/src/config.rs +++ b/flare-cli/src/config.rs @@ -905,4 +905,60 @@ namespace = "publisher" Some(Path::new("/sub/cores")) ); } + + #[test] + fn pool_memory_configuration_and_flag_precedence() { + let args = ["flare", "run", "model.safetensors"]; + let (_, empty) = configured("", &args, &[]); + assert_eq!(empty.pool_vram_memory, None); + assert_eq!(empty.pool_ram_memory, None); + + let text = "[memory]\npool_vram = '12G'\npool_ram = '-16G'\n"; + let (_, from_cfg) = configured(text, &args, &[]); + assert_eq!( + from_cfg.pool_vram_memory, + Some("12G".parse::().unwrap()) + ); + assert_eq!( + from_cfg.pool_ram_memory, + Some("-16G".parse::().unwrap()) + ); + + let (_, overridden) = configured( + text, + &[ + "flare", + "run", + "model.safetensors", + "--pool-vram-memory", + "0", + "--pool-ram-memory", + "0.5", + ], + &[], + ); + assert_eq!( + overridden.pool_vram_memory, + Some("0".parse::().unwrap()) + ); + assert_eq!( + overridden.pool_ram_memory, + Some("0.5".parse::().unwrap()) + ); + + let (_, blank) = configured("[memory]\npool_vram = ''\npool_ram = ' '\n", &args, &[]); + assert_eq!(blank.pool_vram_memory, None); + assert_eq!(blank.pool_ram_memory, None); + + for invalid in ["-0.5", "-0", "1.1", "30", "NaN", "inf", "1e-1", "2P"] { + assert!( + Configuration::parse(&format!("[memory]\npool_vram = '{invalid}'")).is_err(), + "pool_vram={invalid}" + ); + assert!( + Configuration::parse(&format!("[memory]\npool_ram = '{invalid}'")).is_err(), + "pool_ram={invalid}" + ); + } + } } diff --git a/flare-cli/src/distribution/cache_tests.rs b/flare-cli/src/distribution/cache_tests.rs index b96fa0805..c299ae190 100644 --- a/flare-cli/src/distribution/cache_tests.rs +++ b/flare-cli/src/distribution/cache_tests.rs @@ -716,31 +716,11 @@ fn selected_tp2_rank1_closure_excludes_other_deployments_and_ranks() { .find(|rank| rank.rank == 1) .unwrap(); let mut expected_ids = std::collections::BTreeSet::new(); - for initializer in &rank.initializers { - if let Some(slice) = initializer - .source - .as_ref() - .and_then(|use_| use_.slice.as_ref()) - { + rank.visit_payload_uses(|use_| { + if let Some(slice) = use_.slice() { expected_ids.insert(slice.payload_id.clone()); } - } - for resource in &rank.resources { - if let Some(stored) = resource.stored.as_ref() { - expected_ids.insert(stored.payload_id.clone()); - } - } - for module in &rank.modules { - for global in &module.globals { - if let Some(slice) = global - .contents - .as_ref() - .and_then(|use_| use_.slice.as_ref()) - { - expected_ids.insert(slice.payload_id.clone()); - } - } - } + }); for asset in &core_verified.core().assets { if let Some(slice) = asset.payload.as_ref().and_then(|use_| use_.slice.as_ref()) { expected_ids.insert(slice.payload_id.clone()); diff --git a/heliopause/src/export/capture.rs b/heliopause/src/export/capture.rs index e446bc1f6..e1224a177 100644 --- a/heliopause/src/export/capture.rs +++ b/heliopause/src/export/capture.rs @@ -2899,6 +2899,91 @@ fn file_source(path: PathBuf) -> ExportResult { }) } +fn validate_external_extents( + execution: &wire::Execution, + external_extents: &[super::ExternalExtentInput], +) -> ExportResult<()> { + let container_align = helios_core::core::container::ALIGNMENT; + let min_align = u64::from(helios_core::async_transfer::MIN_ALIGNMENT); + let mut seen_channels = BTreeSet::new(); + for ext in external_extents { + if !seen_channels.insert(ext.channel.clone()) { + return Err(invalid(format!( + "duplicate external_extents table for channel {:?}", + ext.channel + ))); + } + let channel = execution + .async_transfers + .iter() + .find(|ch| ch.name == ext.channel) + .ok_or_else(|| { + invalid(format!( + "external_extents references unknown async transfer channel {:?}", + ext.channel + )) + })?; + if ext.segments.is_empty() { + return Err(invalid(format!( + "external_extents channel {:?} requires at least one segment", + ext.channel + ))); + } + let align = u64::from(channel.alignment); + if align < min_align || !align.is_power_of_two() { + return Err(invalid(format!( + "external_extents channel {:?} alignment {align} must be a power of two >= {min_align}", + ext.channel + ))); + } + if align > container_align { + return Err(invalid(format!( + "external_extents channel {:?} alignment {align} exceeds core container alignment {container_align}", + ext.channel + ))); + } + let dir_bytes = fs::read(&ext.directory).map_err(|e| { + invalid(format!( + "read external extent directory {}: {e}", + ext.directory.display() + )) + })?; + if dir_bytes.is_empty() { + return Err(invalid(format!( + "external_extents channel {:?} directory {} is empty", + ext.channel, + ext.directory.display() + ))); + } + let mut resolved_segments = Vec::with_capacity(ext.segments.len()); + for (seg_idx, seg_path) in ext.segments.iter().enumerate() { + let meta = fs::metadata(seg_path).map_err(|e| { + invalid(format!( + "stat external extent segment {}: {e}", + seg_path.display() + )) + })?; + let len = meta.len(); + if len == 0 || len % align != 0 { + return Err(invalid(format!( + "external extent segment {} length {len} must be a positive multiple of {align}", + seg_path.display() + ))); + } + // Payload containers guarantee `container::ALIGNMENT` (4 KiB) base alignment; + // validating at `container_align` exercises the real nonzero container offset. + resolved_segments.push((seg_idx as u32, container_align, len)); + } + helios_core::async_transfer::decode_extent_directory( + &dir_bytes, + &resolved_segments, + channel.alignment, + ) + .map_err(invalid)?; + } + Ok(()) +} + pub(crate) fn capture_rank( request: &CaptureRequest, recorder: Option<&Recorder>, @@ -3271,61 +3356,7 @@ pub(crate) fn capture_rank( let execution = super::binding::execution(execution, &allocations)?; reach.execution(&execution)?; if !request.external_extents.is_empty() { - let mut seen_channels = BTreeSet::new(); - for ext in &request.external_extents { - if !seen_channels.insert(ext.channel.clone()) { - return Err(invalid(format!( - "duplicate external_extents table for channel {:?}", - ext.channel - ))); - } - let channel = execution - .async_transfers - .iter() - .find(|ch| ch.name == ext.channel) - .ok_or_else(|| { - invalid(format!( - "external_extents references unknown async transfer channel {:?}", - ext.channel - )) - })?; - if ext.segments.is_empty() { - return Err(invalid(format!( - "external_extents channel {:?} requires at least one segment", - ext.channel - ))); - } - let dir_bytes = fs::read(&ext.directory).map_err(|e| { - invalid(format!( - "read external extent directory {}: {e}", - ext.directory.display() - )) - })?; - let mut resolved_segments = Vec::with_capacity(ext.segments.len()); - let align = u64::from(channel.alignment); - for (seg_idx, seg_path) in ext.segments.iter().enumerate() { - let meta = fs::metadata(seg_path).map_err(|e| { - invalid(format!( - "stat external extent segment {}: {e}", - seg_path.display() - )) - })?; - let len = meta.len(); - if len == 0 || len % align != 0 { - return Err(invalid(format!( - "external extent segment {} length {len} must be a positive multiple of {align}", - seg_path.display() - ))); - } - resolved_segments.push((seg_idx as u32, 0u64, len)); - } - helios_core::async_transfer::decode_extent_directory( - &dir_bytes, - &resolved_segments, - channel.alignment, - ) - .map_err(invalid)?; - } + validate_external_extents(&execution, &request.external_extents)?; output.external_extents = request.external_extents.clone(); } output.index.ranks[0].execution = Some(execution); @@ -5495,4 +5526,64 @@ mod tests { assert!(reused.is_empty()); Ok(()) } + + #[test] + fn validate_external_extents_enforces_container_alignment_and_nonempty_directory() + -> ExportResult<()> { + let dir = tempfile::tempdir()?; + let seg_path = dir.path().join("seg0.bin"); + let dir_path = dir.path().join("dir.bin"); + let empty_dir_path = dir.path().join("empty.bin"); + std::fs::write(&seg_path, vec![0xAAu8; 8192])?; + let mut entry = Vec::with_capacity(24); + entry.extend_from_slice(&0u32.to_le_bytes()); + entry.extend_from_slice(&0u32.to_le_bytes()); + entry.extend_from_slice(&0u64.to_le_bytes()); + entry.extend_from_slice(&4096u64.to_le_bytes()); + std::fs::write(&dir_path, &entry)?; + std::fs::write(&empty_dir_path, b"")?; + + let make_exec = |alignment: u32| wire::Execution { + async_transfers: vec![wire::AsyncTransfer { + name: "experts".into(), + alignment, + ..Default::default() + }], + ..Default::default() + }; + let input = vec![crate::export::ExternalExtentInput { + channel: "experts".into(), + directory: dir_path.clone(), + segments: vec![seg_path.clone()], + }]; + + // 4 KiB matches core container alignment and passes validation. + validate_external_extents(&make_exec(4096), &input)?; + + // Any alignment above container::ALIGNMENT (4 KiB) would pass at base=0 yet fail at load. + let err = validate_external_extents(&make_exec(8192), &input) + .unwrap_err() + .to_string(); + assert!(err.contains("exceeds core container alignment 4096"), "{err}"); + + // Invalid alignments below MIN_ALIGNMENT (including 0) fail cleanly without panicking. + for bad in [0, 512, 6144] { + assert!( + validate_external_extents(&make_exec(bad), &input).is_err(), + "alignment {bad} must be rejected" + ); + } + + // Empty directory cannot be wrapped as a non-empty safetensors payload. + let empty_input = vec![crate::export::ExternalExtentInput { + channel: "experts".into(), + directory: empty_dir_path, + segments: vec![seg_path], + }]; + let err = validate_external_extents(&make_exec(4096), &empty_input) + .unwrap_err() + .to_string(); + assert!(err.contains("is empty"), "{err}"); + Ok(()) + } } diff --git a/heliopause/src/export/core.rs b/heliopause/src/export/core.rs index b0e2f5379..745874187 100644 --- a/heliopause/src/export/core.rs +++ b/heliopause/src/export/core.rs @@ -1345,6 +1345,7 @@ fn estimated_export_fds( ) -> (usize, usize, usize) { let mut distinct_cached = BTreeSet::new(); let mut uncached_groups = 0usize; + let mut external_extent_cached_leases = 0usize; for rank in ranks { if let Some(sources) = &rank.weight_payload { for group in sources @@ -1366,6 +1367,17 @@ fn estimated_export_fds( } } } + rank.visit_source_paths(|source| match source { + super::RankSourcePath::PayloadPart { .. } => {} + super::RankSourcePath::ExternalExtentDirectory { .. } + | super::RankSourcePath::ExternalExtentSegment { .. } => { + if has_cache { + external_extent_cached_leases += 1; + } else { + uncached_groups += 1; + } + } + }); } let mut engram_cached_leases = 0usize; let mut engram_planes = 0usize; @@ -1409,7 +1421,7 @@ fn estimated_export_fds( } else { 0 }; - let cached_leases = distinct_cached.len() + engram_cached_leases; + let cached_leases = distinct_cached.len() + engram_cached_leases + external_extent_cached_leases; // Each deduplicated cache lease holds 2 FDs (data + flock); each uncached payload and // rank staging file holds 1 FD, plus parallel Engram assembly I/O and runtime headroom. let required = cached_leases * 2 @@ -2181,39 +2193,47 @@ fn rank_plan( attributes: function.attributes.clone(), }) .collect(); + let resolve_extent_file = |path: &Path, + leases: &mut LeaseMap| + -> Result<( + helios_core::core::PayloadId, + u64, + helios_core::core::container::Slice, + )> { + let nbytes = fs::metadata(path)?.len(); + if nbytes == 0 { + return Err(invalid(format!( + "external extent file {} is empty", + path.display() + ))); + } + let pinned = payload_export::pin_file(path, nbytes)?; + let id = pinned.digest()?; + if let Some(root) = cache + && let Some(object) = lease_payload(root, leases, id)? + && object.length() == nbytes + { + return Ok((id, nbytes, object.slice().clone())); + } + Ok((id, nbytes, pinned)) + }; let mut external_extents = Vec::with_capacity(rank.external_extents.len()); for ext in &rank.external_extents { let safe_ch = safe_group(&ext.channel)?; - let dir_nbytes = fs::metadata(&ext.directory)?.len(); - let dir_id = stream_pieces( - &[FileSource { - path: ext.directory.clone(), - offset: 0, - nbytes: dir_nbytes, - }], - None, - )?; + let (dir_id, dir_nbytes, dir_source) = resolve_extent_file(&ext.directory, leases)?; let dir_relative = format!( "deployments/{deployment_id}/rank-{rank_index}/extents-{safe_ch}-dir.safetensors" ); payloads.push(payload_export::PublishPayload { role: pwire::PayloadRole::Weights, relative: dir_relative, - source: payload_export::pin_file(&ext.directory, dir_nbytes)?, + source: dir_source, id: dir_id, tensor: None, }); let mut segment_uses = Vec::with_capacity(ext.segments.len()); for (seg_idx, seg_path) in ext.segments.iter().enumerate() { - let seg_nbytes = fs::metadata(seg_path)?.len(); - let seg_id = stream_pieces( - &[FileSource { - path: seg_path.clone(), - offset: 0, - nbytes: seg_nbytes, - }], - None, - )?; + let (seg_id, seg_nbytes, seg_source) = resolve_extent_file(seg_path, leases)?; let seg_relative = if canonical { format!("weights/extents-{safe_ch}-seg-{seg_idx}.safetensors") } else { @@ -2224,7 +2244,7 @@ fn rank_plan( payloads.push(payload_export::PublishPayload { role: pwire::PayloadRole::Weights, relative: seg_relative, - source: payload_export::pin_file(seg_path, seg_nbytes)?, + source: seg_source, id: seg_id, tensor: None, }); @@ -6154,6 +6174,119 @@ mod payload_export_tests { tuned_slice.read_at(0, &mut actual_tuned).unwrap(); assert_eq!(actual_tuned, tuned_bytes); } + + #[test] + fn external_extents_fd_preflight_cache_dedup_and_weight_reuse_open_source() -> Result<()> { + use helios_core::core::{PayloadId, cache::Root}; + + let directory = tempfile::tempdir()?; + let root = Root::open(directory.path().join("cache"))?; + let stages = directory.path().join("stages"); + fs::create_dir_all(&stages)?; + + let dir_path = stages.join("experts.dir"); + let seg0_path = stages.join("experts-0.seg"); + let seg1_path = stages.join("experts-1.seg"); + let mut dir_bytes = Vec::with_capacity(48); + for seg_idx in 0u32..2 { + dir_bytes.extend_from_slice(&seg_idx.to_le_bytes()); + dir_bytes.extend_from_slice(&0u32.to_le_bytes()); + dir_bytes.extend_from_slice(&0u64.to_le_bytes()); + dir_bytes.extend_from_slice(&4096u64.to_le_bytes()); + } + let seg0_bytes = vec![0xA1u8; 4096]; + let seg1_bytes = vec![0xB2u8; 4096]; + fs::write(&dir_path, &dir_bytes)?; + fs::write(&seg0_path, &seg0_bytes)?; + fs::write(&seg1_path, &seg1_bytes)?; + let dir_id = PayloadId::of(&dir_bytes); + let seg0_id = PayloadId::of(&seg0_bytes); + let seg1_id = PayloadId::of(&seg1_bytes); + + let bare = staged_rank(&stages); + let mut with_extents = staged_rank(&stages); + with_extents.external_extents = vec![super::super::ExternalExtentInput { + channel: "experts".into(), + directory: dir_path.clone(), + segments: vec![seg0_path.clone(), seg1_path.clone()], + }]; + + // 1. FD preflight accounts for directory + 2 segments (3 cached leases or 3 pinned FDs). + let (bare_req_cached, bare_leases_cached, bare_uncached_cached) = + estimated_export_fds(std::slice::from_ref(&bare), 0, true); + let (ext_req_cached, ext_leases_cached, ext_uncached_cached) = + estimated_export_fds(std::slice::from_ref(&with_extents), 0, true); + assert_eq!(ext_leases_cached, bare_leases_cached + 3); + assert_eq!(ext_uncached_cached, bare_uncached_cached); + assert_eq!(ext_req_cached, bare_req_cached + 6); + + let (bare_req_uncached, bare_leases_uncached, bare_uncached_uncached) = + estimated_export_fds(std::slice::from_ref(&bare), 0, false); + let (ext_req_uncached, ext_leases_uncached, ext_uncached_uncached) = + estimated_export_fds(std::slice::from_ref(&with_extents), 0, false); + assert_eq!(ext_leases_uncached, bare_leases_uncached); + assert_eq!(ext_uncached_uncached, bare_uncached_uncached + 3); + assert_eq!(ext_req_uncached, bare_req_uncached + 3); + + // 2. Publish a core whose only Weights payloads are external_extents (allocations use InitialState). + publish_payload( + Path::new(""), + std::slice::from_ref(&with_extents), + vec![], + None, + &publisher(), + Some(root.path().to_path_buf()), + false, + "directory", + )?; + + // 3. Re-planning against the populated cache deduplicates external_extents via cache leases. + let replan_staging = directory.path().join("replan-stage"); + fs::create_dir_all(&replan_staging)?; + let mut leases = LeaseMap::new(); + let plan = rank_plan( + &with_extents, + 0, + 1, + &[], + &replan_staging, + "sm120-tp1", + Some(&root), + &mut leases, + )?; + assert!(leases.contains_key(&dir_id)); + assert!(leases.contains_key(&seg0_id)); + assert!(leases.contains_key(&seg1_id)); + for id in [dir_id, seg0_id, seg1_id] { + let payload = plan + .payloads + .iter() + .find(|payload| payload.id == id) + .expect("external extent payload in rank plan"); + // Cached payload slice starts past the 4 KiB safetensors header, not at raw offset 0. + assert_eq!(payload.source.offset(), helios_core::core::container::ALIGNMENT); + } + + // 4. `--reuse-weights` `open_source` recognizes external_extents weight payloads and fails if one is missing. + let signer = publisher(); + let profiles = serde_json::json!([{ + "namespace": signer.namespace, + "name": "fixture", + "public_key": signer.public_key(), + "development": false + }]) + .to_string(); + assert!(super::super::weight_reuse::open_source(root.path(), "model", &profiles).is_ok()); + + let seg1_blob = root.path().join("blobs").join(format!("{seg1_id}.safetensors")); + fs::remove_file(&seg1_blob)?; + let err = super::super::weight_reuse::open_source(root.path(), "model", &profiles) + .err() + .expect("missing cached external_extents blob must fail open_source") + .to_string(); + assert!(err.contains("missing cached payload"), "{err}"); + Ok(()) + } } #[cfg(test)] diff --git a/heliopause/src/export/mod.rs b/heliopause/src/export/mod.rs index 1bdebae7a..507838a83 100644 --- a/heliopause/src/export/mod.rs +++ b/heliopause/src/export/mod.rs @@ -389,3 +389,141 @@ pub(crate) struct RankOutput { #[serde(skip)] pub payload_leases: PayloadLeases, } + +/// One file-backed source path referenced by a captured [`RankOutput`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RankSourcePath<'a> { + PayloadPart { + path: &'a PathBuf, + offset: u64, + nbytes: u64, + }, + ExternalExtentDirectory { + channel: &'a str, + path: &'a PathBuf, + }, + ExternalExtentSegment { + channel: &'a str, + segment_index: usize, + path: &'a PathBuf, + }, +} + +impl<'a> RankSourcePath<'a> { + pub(crate) fn path(self) -> &'a PathBuf { + match self { + Self::PayloadPart { path, .. } + | Self::ExternalExtentDirectory { path, .. } + | Self::ExternalExtentSegment { path, .. } => path, + } + } +} + +impl RankOutput { + /// Visits every source file path referenced by this rank output. + pub(crate) fn visit_source_paths(&self, mut visit: impl FnMut(RankSourcePath<'_>)) { + let _ = self.try_visit_source_paths::(|path| { + visit(path); + Ok(()) + }); + } + + /// Fallibly visits every source file path referenced by this rank output. + /// + /// Destructuring every field of `RankOutput`, `FilePart`, `FileSource`, and + /// `ExternalExtentInput` without `..` ensures new path-bearing fields fail to compile + /// until handled across rank transfer and export preflight. + pub(crate) fn try_visit_source_paths( + &self, + mut visit: impl FnMut(RankSourcePath<'_>) -> std::result::Result<(), E>, + ) -> std::result::Result<(), E> { + let Self { + index: _, + payload, + allocations: _, + module_globals: _, + external: _, + staging: _, + weight_payload: _, + hardware: _, + external_extents, + payload_leases: _, + } = self; + + for part in payload { + let FilePart { + offset: _, + source: + FileSource { + path, + offset, + nbytes, + }, + } = part; + visit(RankSourcePath::PayloadPart { + path, + offset: *offset, + nbytes: *nbytes, + })?; + } + for ext in external_extents { + let ExternalExtentInput { + channel, + directory, + segments, + } = ext; + visit(RankSourcePath::ExternalExtentDirectory { + channel, + path: directory, + })?; + for (segment_index, path) in segments.iter().enumerate() { + visit(RankSourcePath::ExternalExtentSegment { + channel, + segment_index, + path, + })?; + } + } + Ok(()) + } + + /// Visits mutable references to every source file path referenced by this rank output. + pub(crate) fn visit_source_paths_mut(&mut self, mut visit: impl FnMut(&mut PathBuf)) { + let Self { + index: _, + payload, + allocations: _, + module_globals: _, + external: _, + staging: _, + weight_payload: _, + hardware: _, + external_extents, + payload_leases: _, + } = self; + + for part in payload { + let FilePart { + offset: _, + source: + FileSource { + path, + offset: _, + nbytes: _, + }, + } = part; + visit(path); + } + for ext in external_extents { + let ExternalExtentInput { + channel: _, + directory, + segments, + } = ext; + visit(directory); + for path in segments { + visit(path); + } + } + } +} diff --git a/heliopause/src/export/transfer.rs b/heliopause/src/export/transfer.rs index 72286157f..dea8502eb 100644 --- a/heliopause/src/export/transfer.rs +++ b/heliopause/src/export/transfer.rs @@ -553,10 +553,10 @@ pub(crate) fn send_rank( let mut hashed_bytes = 0; let mut files = BTreeMap::new(); let mut identities = BTreeMap::new(); - for part in &output.payload { - let path = &part.source.path; + output.try_visit_source_paths(|source_path| -> Result<()> { + let path = source_path.path(); if files.contains_key(path) { - continue; + return Ok(()); } let _transaction = FileTransaction::acquire(FileDirection::Send, 3)?; let file = Arc::new(super::io::open_read(path)?); @@ -586,7 +586,8 @@ pub(crate) fn send_rank( }, ); identities.insert(path.clone(), before); - } + Ok(()) + })?; scan_phase.finish(format!( "{} files, {hashed_bytes} bytes hashed", files.len() @@ -901,12 +902,10 @@ fn receive_rank( "declared payload objects are missing from the rank export inventory", )); } - let referenced: BTreeSet<_> = manifest - .output - .payload - .iter() - .map(|p| p.source.path.clone()) - .collect(); + let mut referenced = BTreeSet::new(); + manifest.output.visit_source_paths(|source_path| { + referenced.insert(source_path.path().clone()); + }); // Cache-backed declared payload objects are inventory entries that no logical // payload part references, so both sets together must describe the manifest. let objects: BTreeSet<_> = manifest @@ -978,17 +977,30 @@ fn receive_rank( } targets.insert(name.clone(), target); } - for part in &manifest.output.payload { - if part - .source - .offset - .checked_add(part.source.nbytes) - .filter(|&end| end <= manifest.files[&part.source.path].size) - .is_none() - { - return Err(invalid("rank export source range exceeds its file")); + manifest.output.try_visit_source_paths(|source_path| -> Result<()> { + match source_path { + super::RankSourcePath::PayloadPart { + path, + offset, + nbytes, + } => { + if offset + .checked_add(nbytes) + .filter(|&end| end <= manifest.files[path].size) + .is_none() + { + return Err(invalid("rank export source range exceeds its file")); + } + } + super::RankSourcePath::ExternalExtentDirectory { path, .. } + | super::RankSourcePath::ExternalExtentSegment { path, .. } => { + if manifest.files[path].size == 0 { + return Err(invalid("rank export external extent source file is empty")); + } + } } - } + Ok(()) + })?; cache_phase.finish(format!( "{cached_files} cached files, {cached_bytes} bytes available" )); @@ -1090,9 +1102,9 @@ fn receive_rank( } completion(channel, &names, &manifest.files, false) })?; - for part in &mut manifest.output.payload { - part.source.path = targets[&part.source.path].clone(); - } + manifest.output.visit_source_paths_mut(|path| { + *path = targets[path].clone(); + }); manifest.output.staging = None; let leases = crate::export::PayloadLeases( installed.into_inner().map_err(|_| invalid("payload lease lock poisoned"))?, @@ -2261,4 +2273,50 @@ mod tests { assert!(err.contains("--no-weights"), "{err}"); let _ = &mut peer_rank; } + + #[test] + fn rank_transfer_roundtrips_external_extents_and_rewrites_paths() { + let directory = Directory::new(); + let sender_dir = directory.0.join("sender"); + fs::create_dir_all(&sender_dir).unwrap(); + let payload_path = sender_dir.join("payload.bin"); + let ext_dir_path = sender_dir.join("experts.dir"); + let ext_seg0_path = sender_dir.join("experts-0.seg"); + let ext_seg1_path = sender_dir.join("experts-1.seg"); + let payload_bytes = b"rank-local-payload".to_vec(); + let ext_dir_bytes = vec![0x11u8; 48]; + let ext_seg0_bytes = vec![0x22u8; 4096]; + let ext_seg1_bytes = vec![0x33u8; 8192]; + fs::write(&payload_path, &payload_bytes).unwrap(); + fs::write(&ext_dir_path, &ext_dir_bytes).unwrap(); + fs::write(&ext_seg0_path, &ext_seg0_bytes).unwrap(); + fs::write(&ext_seg1_path, &ext_seg1_bytes).unwrap(); + + let mut source = output(payload_path.clone(), payload_bytes.len() as u64); + source.external_extents = vec![super::super::ExternalExtentInput { + channel: "experts".into(), + directory: ext_dir_path.clone(), + segments: vec![ext_seg0_path.clone(), ext_seg1_path.clone()], + }]; + + let received = roundtrip(&directory, "rank0.sources", &source, false).unwrap(); + assert_eq!(received.output.external_extents.len(), 1); + let transferred = &received.output.external_extents[0]; + assert_eq!(transferred.channel, "experts"); + assert_ne!(transferred.directory, ext_dir_path); + assert_eq!(transferred.segments.len(), 2); + assert_ne!(transferred.segments[0], ext_seg0_path); + assert_ne!(transferred.segments[1], ext_seg1_path); + + // Removing sender-local files proves coordinator reads only rewritten local copies. + fs::remove_dir_all(&sender_dir).unwrap(); + assert_eq!(fs::read(&transferred.directory).unwrap(), ext_dir_bytes); + assert_eq!(fs::read(&transferred.segments[0]).unwrap(), ext_seg0_bytes); + assert_eq!(fs::read(&transferred.segments[1]).unwrap(), ext_seg1_bytes); + + let reloaded = super::super::core::read_sources(&directory.0.join("rank0.sources")).unwrap(); + assert_eq!(reloaded.external_extents.len(), 1); + assert_eq!(reloaded.external_extents[0].directory, transferred.directory); + assert_eq!(reloaded.external_extents[0].segments, transferred.segments); + } } diff --git a/heliopause/src/export/weight_reuse.rs b/heliopause/src/export/weight_reuse.rs index 551b361f4..02d3b79be 100644 --- a/heliopause/src/export/weight_reuse.rs +++ b/heliopause/src/export/weight_reuse.rs @@ -7,7 +7,10 @@ use std::collections::{BTreeMap, BTreeSet}; -use helios_core::core::{cache, protection, reader, schema::wire as pwire}; +use helios_core::core::{ + cache, protection, reader, + schema::{RankPayloadUse, wire as pwire}, +}; use pyo3::{exceptions::PyValueError, prelude::*}; use serde::{Deserialize, Serialize}; @@ -130,20 +133,24 @@ pub(crate) fn open_source( }, )?; for rank in verified.ranks() { - for initializer in &rank.initializers { - let Some(source) = initializer - .source - .as_ref() - .filter(|source| is_weight(source.role)) - else { - continue; + rank.try_visit_payload_uses(|use_| -> Result<()> { + let source = match use_ { + RankPayloadUse::Initializer(_, source) + | RankPayloadUse::ExternalExtentDirectory(_, source) => source, + RankPayloadUse::ExternalExtentSegment(_, source) => Some(source), + RankPayloadUse::ModuleGlobal(..) | RankPayloadUse::ExecutableResource(..) => { + return Ok(()); + } + }; + let Some(source) = source.filter(|source| is_weight(source.role)) else { + return Ok(()); }; let slice = source .slice .as_ref() - .ok_or_else(|| invalid("weight initializer has no payload slice"))?; + .ok_or_else(|| invalid("weight payload use has no slice"))?; if payloads.contains(&slice.payload_id) { - continue; + return Ok(()); } let id = helios_core::core::PayloadId::from_bytes( slice.payload_id.as_slice().try_into()?, @@ -157,7 +164,8 @@ pub(crate) fn open_source( ))); } payloads.insert(slice.payload_id.clone()); - } + Ok(()) + })?; } if let Some(engram) = verified.deployment().and_then(|body| body.engram.as_ref()) { for source in engram_uses(engram) { diff --git a/helios/src/core/conversion.rs b/helios/src/core/conversion.rs index 237093006..d45718018 100644 --- a/helios/src/core/conversion.rs +++ b/helios/src/core/conversion.rs @@ -756,27 +756,11 @@ enum SourceVerification { } fn rank_consumers(body: &wire::RankBody, out: &mut BTreeSet>) { - for initializer in &body.initializers { - if let Some(use_) = &initializer.source - && let Some(slice) = &use_.slice - { - out.insert(slice.payload_id.clone()); - } - } - for module in &body.modules { - for global in &module.globals { - if let Some(use_) = &global.contents - && let Some(slice) = &use_.slice - { - out.insert(slice.payload_id.clone()); - } - } - } - for resource in &body.resources { - if let Some(slice) = &resource.stored { + body.visit_payload_uses(|use_| { + if let Some(slice) = use_.slice() { out.insert(slice.payload_id.clone()); } - } + }); } fn recipes_bytes( @@ -3689,22 +3673,20 @@ fn publish_rank( let mut body = rank.clone(); body.resources.clear(); let mut roles: BTreeMap, i32> = BTreeMap::new(); - for initializer in &body.initializers { - if let Some(source) = &initializer.source - && let Some(slice) = &source.slice - { - roles.entry(slice.payload_id.clone()).or_insert(source.role); - } - } - for module in &body.modules { - for global in &module.globals { - if let Some(use_) = &global.contents - && let Some(slice) = &use_.slice - { + body.visit_payload_uses(|use_| match use_ { + schema::RankPayloadUse::Initializer(_, Some(use_)) + | schema::RankPayloadUse::ModuleGlobal(_, Some(use_)) + | schema::RankPayloadUse::ExternalExtentDirectory(_, Some(use_)) + | schema::RankPayloadUse::ExternalExtentSegment(_, use_) => { + if let Some(slice) = &use_.slice { roles.entry(slice.payload_id.clone()).or_insert(use_.role); } } - } + schema::RankPayloadUse::Initializer(_, None) + | schema::RankPayloadUse::ModuleGlobal(_, None) + | schema::RankPayloadUse::ExternalExtentDirectory(_, None) + | schema::RankPayloadUse::ExecutableResource(..) => {} + }); let exception_ids: BTreeSet = exceptions.iter().map(|payload| payload.id).collect(); for id in recipe_sources { if exception_ids.contains(id) { @@ -9709,4 +9691,244 @@ mod tests { .unwrap(); assert_eq!(authorized.ranks().len(), 1); } + + #[test] + fn pack_unpack_and_combine_preserve_external_extents_payloads() { + use crate::core::export::{ + Destination, PublishDeployment, PublishPayload, PublishRank, PublishRequest, + PublishResource, + }; + + let scratch = Scratch::new("external-extents-conversion"); + let rng = SystemRandom::new(); + let pkcs8 = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); + let key = signature::Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let publisher = Publisher { + name: "Example".into(), + namespace: "example".into(), + public_key, + development: false, + }; + let mut dir_bytes = Vec::with_capacity(24); + dir_bytes.extend_from_slice(&0u32.to_le_bytes()); + dir_bytes.extend_from_slice(&0u32.to_le_bytes()); + dir_bytes.extend_from_slice(&0u64.to_le_bytes()); + dir_bytes.extend_from_slice(&4096u64.to_le_bytes()); + let dir_id = PayloadId::of(&dir_bytes); + let seg_bytes = vec![0x5Au8; 4096]; + let seg_id = PayloadId::of(&seg_bytes); + + let publish_source = |name: &str, dep_id: &str, seed: u8, include_extents: bool| { + let root = scratch.join(name); + fs::create_dir_all(&root).unwrap(); + let weight_bytes = vec![seed; 64]; + let weight_id = PayloadId::of(&weight_bytes); + let weight_path = root.join("weights.bin"); + let cubin_path = root.join("cubin.bin"); + let graph_path = root.join("graph.bin"); + fs::write(&weight_path, &weight_bytes).unwrap(); + fs::write(&cubin_path, b"cubin").unwrap(); + fs::write(&graph_path, b"graph").unwrap(); + let mut payloads = vec![PublishPayload { + role: wire::PayloadRole::Weights, + relative: "weights/layer-0.safetensors".into(), + source: crate::core::export::pin_file(&weight_path, weight_bytes.len() as u64) + .unwrap(), + id: weight_id, + tensor: None, + }]; + let external_extents = if include_extents { + let dir_path = root.join("ext-dir.bin"); + let seg_path = root.join("ext-seg.bin"); + fs::write(&dir_path, &dir_bytes).unwrap(); + fs::write(&seg_path, &seg_bytes).unwrap(); + payloads.push(PublishPayload { + role: wire::PayloadRole::Weights, + relative: format!("deployments/{dep_id}/rank-0/extents-experts-dir.safetensors"), + source: crate::core::export::pin_file(&dir_path, dir_bytes.len() as u64) + .unwrap(), + id: dir_id, + tensor: None, + }); + payloads.push(PublishPayload { + role: wire::PayloadRole::Weights, + relative: "weights/extents-experts-seg-0.safetensors".into(), + source: crate::core::export::pin_file(&seg_path, seg_bytes.len() as u64) + .unwrap(), + id: seg_id, + tensor: None, + }); + vec![wire::ExternalExtentTable { + channel: "experts".into(), + directory: Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: dir_id.as_bytes().to_vec(), + offset: 0, + nbytes: dir_bytes.len() as u64, + }), + role: wire::PayloadRole::Weights as i32, + }), + segments: vec![wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: seg_id.as_bytes().to_vec(), + offset: 0, + nbytes: seg_bytes.len() as u64, + }), + role: wire::PayloadRole::Weights as i32, + }], + }] + } else { + vec![] + }; + let rank = wire::RankBody { + rank: 0, + deployment_id: dep_id.into(), + context: Some(runtime::Context::default()), + allocations: vec![wire::Allocation { + name: "weights".into(), + nbytes: 64, + alignment: 256, + address: Some(0x1000), + memory: runtime::Memory::Device as i32, + sizing: None, + relocations: vec![], + }], + initializers: vec![wire::Initializer { + allocation: "weights".into(), + destination_offset: 0, + source: Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: weight_id.as_bytes().to_vec(), + offset: 0, + nbytes: weight_bytes.len() as u64, + }), + role: wire::PayloadRole::Weights as i32, + }), + }], + modules: vec![wire::Module { + name: "kernel".into(), + cubin: 0, + globals: vec![], + }], + functions: vec![wire::Function { + module: "kernel".into(), + symbol: "decode".into(), + parameter_sizes: vec![], + attributes: vec![], + }], + graphs: vec![wire::Graph { + name: "decode".into(), + resource: 1, + node_count: 1, + functions: vec![0], + ..Default::default() + }], + external_extents, + ..Default::default() + }; + let out_dir = scratch.join(&format!("{name}-core")); + fs::create_dir_all(&out_dir).unwrap(); + let request = PublishRequest { + core: wire::CoreBody { + model_identity: "example/extents-model".into(), + hardware_identity: "sm120".into(), + frontend: Some(runtime::FrontendSettings::default()), + sampling_defaults: Some(runtime::DefaultSamplingParameters::default()), + publisher: Some(wire::PublisherMetadata { + namespace: "example".into(), + official_source: "https://huggingface.co/example/extents-model".into(), + ..Default::default() + }), + ..Default::default() + }, + payloads: vec![], + deployments: vec![PublishDeployment { + body: wire::DeploymentBody { + deployment_id: dep_id.into(), + architecture: vec![12, 0], + tensor_parallel: 1, + contract: Some(runtime::ServingContract::default()), + ..Default::default() + }, + ranks: vec![PublishRank { + body: rank, + payloads, + resources: vec![ + PublishResource { + kind: wire::ExecutableKind::Cubin, + path: cubin_path, + nbytes: 5, + }, + PublishResource { + kind: wire::ExecutableKind::Graph, + path: graph_path, + nbytes: 5, + }, + ], + }], + payloads: vec![], + }], + core_id: [seed; 32], + public_key, + accepted: "example".into(), + no_weights: false, + }; + crate::core::export::publish(&request, &key, Destination::Directory(&out_dir)).unwrap(); + out_dir + }; + + let first = publish_source("src-a", "sm120-tp1-a", 11, true); + let second = publish_source("src-b", "sm120-tp1-b", 22, true); + + // 1. Keyless pack and unpack must preserve external_extents locations and bytes. + let packed = scratch.join("packed.safetensors"); + pack(&first, &packed).unwrap(); + let unpacked = scratch.join("unpacked"); + unpack(&packed, &unpacked).unwrap(); + let unpacked_verified = Verified::open(&unpacked, None).unwrap(); + let unpacked_files = unpacked_verified.payload_files().unwrap(); + unpacked_files.verify().unwrap(); + assert_eq!(unpacked_files.get(dir_id.as_bytes()).unwrap().len(), dir_bytes.len() as u64); + assert_eq!(unpacked_files.get(seg_id.as_bytes()).unwrap().len(), seg_bytes.len() as u64); + + // 2. `combine` must copy external_extents payloads into PublishRank.payloads and pass validation. + let combined = scratch.join("combined"); + combine(&CombineRequest { + sources: &[first.clone(), second.clone()], + output: &combined, + publishers: std::slice::from_ref(&publisher), + accepted: "example", + target_accepted: "example", + target_publisher: None, + key: &key, + }) + .unwrap(); + + let metadata = Metadata::open(&combined).unwrap(); + for deployment in 0..2 { + let verified = protect::verify_metadata( + &metadata, + std::slice::from_ref(&publisher), + protect::Selection::Deployment { + deployment, + rank: None, + }, + ) + .unwrap(); + let required = reader::required_payloads(&verified).unwrap(); + assert!(required.contains(dir_id.as_bytes().as_slice())); + assert!(required.contains(seg_id.as_bytes().as_slice())); + let files = metadata + .payloads(verified.catalog(), required.iter().map(Vec::as_slice)) + .unwrap(); + files.verify().unwrap(); + let mut got_dir = vec![0u8; dir_bytes.len()]; + files.get(dir_id.as_bytes()).unwrap().read_at(0, &mut got_dir).unwrap(); + assert_eq!(got_dir, dir_bytes); + let mut got_seg = vec![0u8; seg_bytes.len()]; + files.get(seg_id.as_bytes()).unwrap().read_at(0, &mut got_seg).unwrap(); + assert_eq!(got_seg, seg_bytes); + } + } } diff --git a/helios/src/core/reader.rs b/helios/src/core/reader.rs index f8734bda8..15cf52df7 100644 --- a/helios/src/core/reader.rs +++ b/helios/src/core/reader.rs @@ -213,22 +213,6 @@ pub fn required_payloads(core: &VerifiedCore) -> Result>> { for asset in &core.core().assets { add(asset.payload.as_ref())?; } - for rank in core.ranks() { - for initializer in &rank.initializers { - add(initializer.source.as_ref())?; - } - for module in &rank.modules { - for global in &module.globals { - add(global.contents.as_ref())?; - } - } - for table in &rank.external_extents { - add(table.directory.as_ref())?; - for segment in &table.segments { - add(Some(segment))?; - } - } - } if let Some(engram) = core .deployment() .and_then(|deployment| deployment.engram.as_ref()) @@ -253,14 +237,24 @@ pub fn required_payloads(core: &VerifiedCore) -> Result>> { } } for rank in core.ranks() { - for resource in &rank.resources { - let slice = resource - .stored - .as_ref() - .ok_or_else(|| invalid("executable resource has no stored slice"))?; + rank.try_visit_payload_uses(|use_| -> Result<()> { + let slice = use_.slice().ok_or_else(|| { + invalid(match use_ { + schema::RankPayloadUse::ExecutableResource(..) => { + "executable resource has no stored slice" + } + schema::RankPayloadUse::Initializer(..) + | schema::RankPayloadUse::ModuleGlobal(..) + | schema::RankPayloadUse::ExternalExtentDirectory(..) + | schema::RankPayloadUse::ExternalExtentSegment(..) => { + "payload consumer has no source slice" + } + }) + })?; core.catalog().check_slice(slice)?; ids.insert(slice.payload_id.clone()); - } + Ok(()) + })?; } Ok(ids) } diff --git a/helios/src/core/schema.rs b/helios/src/core/schema.rs index 0e31b860d..91229571d 100644 --- a/helios/src/core/schema.rs +++ b/helios/src/core/schema.rs @@ -19,6 +19,133 @@ pub mod wire { include!(concat!(env!("OUT_DIR"), "/flare.core.rs")); } +/// One payload reference inside a [`wire::RankBody`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RankPayloadUse<'a> { + Initializer(&'a wire::Initializer, Option<&'a wire::PayloadUse>), + ModuleGlobal(&'a wire::ModuleGlobal, Option<&'a wire::PayloadUse>), + ExternalExtentDirectory(&'a wire::ExternalExtentTable, Option<&'a wire::PayloadUse>), + ExternalExtentSegment(&'a wire::ExternalExtentTable, &'a wire::PayloadUse), + ExecutableResource(&'a wire::ExecutableResource, Option<&'a wire::PayloadSlice>), +} + +impl<'a> RankPayloadUse<'a> { + /// Returns the typed `PayloadUse` for non-executable rank payload references. + pub fn payload_use(self) -> Option<&'a wire::PayloadUse> { + match self { + Self::Initializer(_, use_) + | Self::ModuleGlobal(_, use_) + | Self::ExternalExtentDirectory(_, use_) => use_, + Self::ExternalExtentSegment(_, use_) => Some(use_), + Self::ExecutableResource(..) => None, + } + } + + /// Returns the underlying `PayloadSlice` for any rank payload reference. + pub fn slice(self) -> Option<&'a wire::PayloadSlice> { + match self { + Self::Initializer(_, use_) + | Self::ModuleGlobal(_, use_) + | Self::ExternalExtentDirectory(_, use_) => { + use_.and_then(|value| value.slice.as_ref()) + } + Self::ExternalExtentSegment(_, use_) => use_.slice.as_ref(), + Self::ExecutableResource(_, slice) => slice, + } + } +} + +impl wire::RankBody { + /// Visits every payload-bearing field of a rank body in deterministic order. + pub fn visit_payload_uses(&self, mut visit: impl FnMut(RankPayloadUse<'_>)) { + let _ = self.try_visit_payload_uses::(|use_| { + visit(use_); + Ok(()) + }); + } + + /// Fallibly visits every payload-bearing field of a rank body in deterministic order. + /// + /// Destructuring every field of `RankBody` and its payload-bearing records without `..` + /// ensures new fields in `core.proto` fail compilation until classified here. + pub fn try_visit_payload_uses( + &self, + mut visit: impl FnMut(RankPayloadUse<'_>) -> std::result::Result<(), E>, + ) -> std::result::Result<(), E> { + let Self { + rank: _, + deployment_id: _, + context: _, + reservations: _, + allocations: _, + initializers, + payloads: _, + resources, + modules, + functions: _, + graphs: _, + events: _, + peers: _, + execution: _, + roce: _, + prepared_weights: _, + compressed_prepared_weights: _, + external_extents, + } = self; + + for initializer in initializers { + let wire::Initializer { + allocation: _, + destination_offset: _, + source, + } = initializer; + visit(RankPayloadUse::Initializer(initializer, source.as_ref()))?; + } + for module in modules { + let wire::Module { + name: _, + cubin: _, + globals, + } = module; + for global in globals { + let wire::ModuleGlobal { + symbol: _, + nbytes: _, + contents, + relocations: _, + } = global; + visit(RankPayloadUse::ModuleGlobal(global, contents.as_ref()))?; + } + } + for table in external_extents { + let wire::ExternalExtentTable { + channel: _, + segments, + directory, + } = table; + visit(RankPayloadUse::ExternalExtentDirectory( + table, + directory.as_ref(), + ))?; + for segment in segments { + visit(RankPayloadUse::ExternalExtentSegment(table, segment))?; + } + } + for resource in resources { + let wire::ExecutableResource { + resource_id: _, + kind: _, + stored, + decoded_nbytes: _, + chunk_nbytes: _, + chunk_sha256: _, + } = resource; + visit(RankPayloadUse::ExecutableResource(resource, stored.as_ref()))?; + } + Ok(()) + } +} + /// Envelope and body format version this build understands. pub const FORMAT_VERSION: u32 = 2; /// Bound on one serialized signed body, matching the metadata tensor limit. @@ -745,7 +872,8 @@ fn validate_external_extents(body: &wire::RankBody, catalog: &Catalog) -> Result .directory .as_ref() .ok_or_else(|| invalid("external extent table lacks a directory payload"))?; - let dir_bytes = catalog.check_use(directory, &roles)?; + catalog.check_use(directory, &roles)?; + let dir_bytes = directory.slice.as_ref().map_or(0, |slice| slice.nbytes); if dir_bytes % (crate::async_transfer::EXTENT_ENTRY_BYTES as u64) != 0 { return Err(invalid( "external extent directory length is not a multiple of entry size", @@ -1979,4 +2107,171 @@ mod tests { .to_string(); assert!(error.contains("relocation is outside its module global"), "{error}"); } + + #[test] + fn visit_payload_uses_covers_all_rank_payload_categories() { + let (mut rank, _) = module_rank(); + let init_id = vec![0x11; 32]; + let dir_id = vec![0x22; 32]; + let seg0_id = vec![0x33; 32]; + let seg1_id = vec![0x44; 32]; + rank.initializers.push(wire::Initializer { + allocation: "weights".into(), + destination_offset: 0, + source: Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: init_id.clone(), + offset: 0, + nbytes: 16, + }), + role: wire::PayloadRole::Weights as i32, + }), + }); + rank.external_extents.push(wire::ExternalExtentTable { + channel: "experts".into(), + directory: Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: dir_id.clone(), + offset: 0, + nbytes: 24, + }), + role: wire::PayloadRole::Weights as i32, + }), + segments: vec![ + wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: seg0_id.clone(), + offset: 0, + nbytes: 4096, + }), + role: wire::PayloadRole::Weights as i32, + }, + wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: seg1_id.clone(), + offset: 0, + nbytes: 8192, + }), + role: wire::PayloadRole::InitialState as i32, + }, + ], + }); + + let mut visited = Vec::new(); + rank.visit_payload_uses(|use_| { + let tag = match use_ { + RankPayloadUse::Initializer(..) => "init", + RankPayloadUse::ModuleGlobal(..) => "global", + RankPayloadUse::ExternalExtentDirectory(..) => "ext_dir", + RankPayloadUse::ExternalExtentSegment(..) => "ext_seg", + RankPayloadUse::ExecutableResource(..) => "exec", + }; + visited.push((tag, use_.slice().unwrap().payload_id.clone())); + }); + let existing_init = rank.initializers[0] + .source + .as_ref() + .unwrap() + .slice + .as_ref() + .unwrap() + .payload_id + .clone(); + let existing_globals: Vec<_> = rank + .modules + .iter() + .flat_map(|module| module.globals.iter()) + .map(|global| { + ( + "global", + global + .contents + .as_ref() + .unwrap() + .slice + .as_ref() + .unwrap() + .payload_id + .clone(), + ) + }) + .collect(); + let mut expected = vec![("init", existing_init), ("init", init_id)]; + expected.extend(existing_globals); + expected.extend([ + ("ext_dir", dir_id), + ("ext_seg", seg0_id), + ("ext_seg", seg1_id), + ( + "exec", + rank.resources[0].stored.as_ref().unwrap().payload_id.clone(), + ), + ( + "exec", + rank.resources[1].stored.as_ref().unwrap().payload_id.clone(), + ), + ]); + assert_eq!(visited, expected); + } + + #[test] + fn validate_external_extents_checks_directory_slice_length() { + let (mut rank, mut catalog) = module_rank(); + // Whole payload is 30 bytes (not a multiple of 24), while the directory slice is 24 bytes. + let combined_id = vec![0x55; 32]; + let seg_id = vec![0x66; 32]; + catalog + .insert_all(&[ + wire::PayloadDescriptor { + id: combined_id.clone(), + nbytes: 30, + }, + wire::PayloadDescriptor { + id: seg_id.clone(), + nbytes: 4096, + }, + ]) + .unwrap(); + rank.external_extents.push(wire::ExternalExtentTable { + channel: "experts".into(), + directory: Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: combined_id.clone(), + offset: 4, + nbytes: 24, + }), + role: wire::PayloadRole::InitialState as i32, + }), + segments: vec![wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: seg_id, + offset: 0, + nbytes: 4096, + }), + role: wire::PayloadRole::Weights as i32, + }], + }); + validate_rank(&rank, 1, &mut catalog.clone(), &mut BTreeSet::new()).unwrap(); + + // Whole payload is 48 bytes (multiple of 24), while the directory slice is 12 bytes (invalid). + let bad_id = vec![0x77; 32]; + catalog + .insert(&wire::PayloadDescriptor { + id: bad_id.clone(), + nbytes: 48, + }) + .unwrap(); + rank.external_extents[0].directory = Some(wire::PayloadUse { + slice: Some(wire::PayloadSlice { + payload_id: bad_id, + offset: 0, + nbytes: 12, + }), + role: wire::PayloadRole::InitialState as i32, + }); + let err = validate_rank(&rank, 1, &mut catalog, &mut BTreeSet::new()) + .unwrap_err() + .to_string(); + assert!(err.contains("multiple of entry size"), "{err}"); + } } diff --git a/helios/src/runtime_core/cache_memory.rs b/helios/src/runtime_core/cache_memory.rs index 4f4052522..9ba82a9c3 100644 --- a/helios/src/runtime_core/cache_memory.rs +++ b/helios/src/runtime_core/cache_memory.rs @@ -1667,6 +1667,7 @@ mod tests { execution: None, context: Context::default(), allocations: vec![], + external_extents: vec![], }; let mut owner = NativeResources::initialize(&core, 0).unwrap(); let properties = AllocationProperties { diff --git a/helios/src/runtime_core/format.rs b/helios/src/runtime_core/format.rs index 066a804d2..81adcdefd 100644 --- a/helios/src/runtime_core/format.rs +++ b/helios/src/runtime_core/format.rs @@ -517,6 +517,10 @@ impl Core { if let Some(execution) = self.execution.as_ref() { super::protobuf::validate_persistent_workers(self, execution)?; super::protobuf::validate_async_transfers(self, execution)?; + } else if !self.external_extents.is_empty() { + return Err(invalid( + "external extent tables require an execution manifest", + )); } Ok(()) } diff --git a/helios/src/runtime_core/protection.rs b/helios/src/runtime_core/protection.rs index e7a31369d..ce9bbc6e1 100644 --- a/helios/src/runtime_core/protection.rs +++ b/helios/src/runtime_core/protection.rs @@ -1712,27 +1712,27 @@ impl PayloadSource { fn supporting_payload_ids(&self) -> Result>> { let mut ids = std::collections::BTreeSet::new(); for rank in self.authorized.verified().ranks() { - for initializer in &rank.initializers { - let Some(use_) = initializer.source.as_ref() else { - continue; - }; - if use_.role == payload_wire::PayloadRole::InitialState as i32 - && let Some(slice) = use_.slice.as_ref() + rank.visit_payload_uses(|use_| match use_ { + crate::core::schema::RankPayloadUse::Initializer(_, Some(use_)) + | crate::core::schema::RankPayloadUse::ExternalExtentSegment(_, use_) + if use_.role == payload_wire::PayloadRole::InitialState as i32 => { - ids.insert(slice.payload_id.clone()); + if let Some(slice) = use_.slice.as_ref() { + ids.insert(slice.payload_id.clone()); + } } - } - for module in &rank.modules { - for global in &module.globals { - if let Some(slice) = global - .contents - .as_ref() - .and_then(|use_| use_.slice.as_ref()) - { + crate::core::schema::RankPayloadUse::ModuleGlobal(_, Some(use_)) + | crate::core::schema::RankPayloadUse::ExternalExtentDirectory(_, Some(use_)) => { + if let Some(slice) = use_.slice.as_ref() { ids.insert(slice.payload_id.clone()); } } - } + crate::core::schema::RankPayloadUse::Initializer(..) + | crate::core::schema::RankPayloadUse::ModuleGlobal(_, None) + | crate::core::schema::RankPayloadUse::ExternalExtentDirectory(_, None) + | crate::core::schema::RankPayloadUse::ExternalExtentSegment(..) + | crate::core::schema::RankPayloadUse::ExecutableResource(..) => {} + }); } for asset in &self.authorized.verified().core().assets { let Some(slice) = asset.payload.as_ref().and_then(|use_| use_.slice.as_ref()) else { @@ -1750,15 +1750,19 @@ impl PayloadSource { let mut ids = self.supporting_payload_ids()?; if verify_weights { for rank in self.authorized.verified().ranks() { - for initializer in &rank.initializers { - if let Some(slice) = initializer - .source - .as_ref() - .and_then(|use_| use_.slice.as_ref()) - { - ids.insert(slice.payload_id.clone()); + rank.visit_payload_uses(|use_| match use_ { + crate::core::schema::RankPayloadUse::Initializer(_, Some(use_)) + | crate::core::schema::RankPayloadUse::ExternalExtentDirectory(_, Some(use_)) + | crate::core::schema::RankPayloadUse::ExternalExtentSegment(_, use_) => { + if let Some(slice) = use_.slice.as_ref() { + ids.insert(slice.payload_id.clone()); + } } - } + crate::core::schema::RankPayloadUse::ModuleGlobal(..) + | crate::core::schema::RankPayloadUse::Initializer(_, None) + | crate::core::schema::RankPayloadUse::ExternalExtentDirectory(_, None) + | crate::core::schema::RankPayloadUse::ExecutableResource(..) => {} + }); } if let Some(engram) = self .authorized @@ -2737,31 +2741,11 @@ impl PayloadAuthorizedCore { .find(|body| body.rank as usize == rank) .ok_or_else(|| invalid("rank is not part of the verified deployment"))?; let mut ids: std::collections::BTreeSet> = Default::default(); - for initializer in &body.initializers { - if let Some(slice) = initializer - .source - .as_ref() - .and_then(|use_| use_.slice.as_ref()) - { - ids.insert(slice.payload_id.clone()); - } - } - for resource in &body.resources { - if let Some(slice) = resource.stored.as_ref() { + body.visit_payload_uses(|use_| { + if let Some(slice) = use_.slice() { ids.insert(slice.payload_id.clone()); } - } - for module in &body.modules { - for global in &module.globals { - if let Some(slice) = global - .contents - .as_ref() - .and_then(|use_| use_.slice.as_ref()) - { - ids.insert(slice.payload_id.clone()); - } - } - } + }); for asset in &self.source.authorized.verified().core().assets { if let Some(slice) = asset.payload.as_ref().and_then(|use_| use_.slice.as_ref()) { ids.insert(slice.payload_id.clone()); @@ -4555,4 +4539,347 @@ mod payload_core_tests { payload.source.release_page_cache(); let _ = std::fs::remove_dir_all(root); } + + #[test] + fn external_extents_verification_and_rank_ranges_cover_directory_and_segments() { + use crate::core::export::{ + Destination, PublishDeployment, PublishPayload, PublishRank, PublishRequest, + PublishResource, + }; + use crate::core::{PayloadId, schema::wire as pw}; + + let root = std::env::temp_dir().join(format!( + "flare-ext-verify-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&root).unwrap(); + let rng = ring::rand::SystemRandom::new(); + let pkcs8 = ring::signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); + let key = ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap(); + let public_key: [u8; 32] = key.public_key().as_ref().try_into().unwrap(); + let publisher = Publisher { + name: "ext-test".into(), + namespace: "ext-test".into(), + public_key, + development: false, + }; + + let weights = vec![0x11u8; 32]; + let weights_id = PayloadId::of(&weights); + let mut dir = Vec::with_capacity(48); + for seg_idx in 0u32..2 { + dir.extend_from_slice(&seg_idx.to_le_bytes()); + dir.extend_from_slice(&0u32.to_le_bytes()); + dir.extend_from_slice(&0u64.to_le_bytes()); + dir.extend_from_slice(&4096u64.to_le_bytes()); + } + let dir_id = PayloadId::of(&dir); + let weight_seg = vec![0x22u8; 4096]; + let weight_seg_id = PayloadId::of(&weight_seg); + let state_seg = vec![0x33u8; 4096]; + let state_seg_id = PayloadId::of(&state_seg); + + let stage = root.join("stage"); + std::fs::create_dir_all(&stage).unwrap(); + let weights_path = write(&stage, "w.bin", &weights); + let dir_path = write(&stage, "dir.bin", &dir); + let weight_seg_path = write(&stage, "wseg.bin", &weight_seg); + let state_seg_path = write(&stage, "sseg.bin", &state_seg); + let cubin_path = write(&stage, "k.bin", b"fake cubin"); + let graph_path = write(&stage, "g.bin", b"fake graph"); + + let dir_rel = "deployments/sm120-tp1/rank-0/extents-experts-dir.safetensors"; + let weight_seg_rel = "weights/extents-experts-seg-0.safetensors"; + let state_seg_rel = "weights/extents-experts-seg-1.safetensors"; + let rank = pw::RankBody { + rank: 0, + deployment_id: "sm120-tp1".into(), + context: Some(crate::runtime_core::wire::Context::default()), + allocations: vec![ + pw::Allocation { + name: "device-0".into(), + nbytes: 32, + alignment: 256, + address: Some(0x1000), + memory: 0, + sizing: None, + relocations: vec![], + }, + pw::Allocation { + name: "dev-pool".into(), + nbytes: 0, + alignment: 4096, + address: Some(0x2000_0000), + memory: 0, + sizing: Some(crate::runtime_core::wire::Sizing { + capacity: crate::runtime_core::wire::Capacity::DevicePool as i32, + unit_bytes: 4096, + maximum: 4, + }), + relocations: vec![], + }, + pw::Allocation { + name: "xfer-ctrl".into(), + nbytes: 8192, + alignment: 4096, + address: Some(0x3000_0000), + memory: crate::runtime_core::wire::Memory::MappedHost as i32, + sizing: None, + relocations: vec![], + }, + ], + initializers: vec![pw::Initializer { + allocation: "device-0".into(), + destination_offset: 0, + source: Some(pw::PayloadUse { + slice: Some(pw::PayloadSlice { + payload_id: weights_id.as_bytes().to_vec(), + offset: 0, + nbytes: weights.len() as u64, + }), + role: pw::PayloadRole::Weights as i32, + }), + }], + modules: vec![pw::Module { + name: "kernel".into(), + cubin: 0, + globals: vec![], + }], + functions: vec![pw::Function { + module: "kernel".into(), + symbol: "decode".into(), + parameter_sizes: vec![], + attributes: vec![], + }], + graphs: vec![pw::Graph { + name: "decode".into(), + flags: 0, + resource: 1, + node_count: 1, + edge_count: 0, + functions: vec![0], + }], + execution: Some(crate::runtime_core::wire::Execution { + abi_version: 2, + max_active: 4, + async_transfers: vec![crate::runtime_core::wire::AsyncTransfer { + name: "experts".into(), + device_pool: "dev-pool".into(), + control: Some(crate::runtime_core::wire::Reference { + allocation: "xfer-ctrl".into(), + offset: 0, + }), + control_bytes: 256 + 16 * 64 + 8 * 8, + device_completions: None, + completion_slots: 8, + ring_capacity: 16, + max_host_pool_bytes: 0, + alignment: 4096, + extents: vec![], + }], + ..Default::default() + }), + external_extents: vec![pw::ExternalExtentTable { + channel: "experts".into(), + directory: Some(pw::PayloadUse { + slice: Some(pw::PayloadSlice { + payload_id: dir_id.as_bytes().to_vec(), + offset: 0, + nbytes: dir.len() as u64, + }), + role: pw::PayloadRole::Weights as i32, + }), + segments: vec![ + pw::PayloadUse { + slice: Some(pw::PayloadSlice { + payload_id: weight_seg_id.as_bytes().to_vec(), + offset: 0, + nbytes: weight_seg.len() as u64, + }), + role: pw::PayloadRole::Weights as i32, + }, + pw::PayloadUse { + slice: Some(pw::PayloadSlice { + payload_id: state_seg_id.as_bytes().to_vec(), + offset: 0, + nbytes: state_seg.len() as u64, + }), + role: pw::PayloadRole::InitialState as i32, + }, + ], + }], + ..Default::default() + }; + let core_dir = root.join("core"); + std::fs::create_dir_all(&core_dir).unwrap(); + let request = PublishRequest { + core: pw::CoreBody { + model_identity: "ext-test/model".into(), + hardware_identity: "sm120".into(), + frontend: Some(crate::runtime_core::wire::FrontendSettings::default()), + sampling_defaults: Some( + crate::runtime_core::wire::DefaultSamplingParameters::default(), + ), + publisher: Some(pw::PublisherMetadata { + namespace: "ext-test".into(), + official_source: "https://huggingface.co/ext-test/model".into(), + ..Default::default() + }), + ..Default::default() + }, + payloads: vec![], + deployments: vec![PublishDeployment { + payloads: vec![], + body: pw::DeploymentBody { + deployment_id: "sm120-tp1".into(), + architecture: vec![12, 0], + tensor_parallel: 1, + contract: Some(crate::runtime_core::wire::ServingContract { + model_id: "ext-test/model".into(), + identity: "ext-test".into(), + max_sequence_tokens: 8, + prefill_chunk_size: 1, + pages: 1, + state_rows: 1, + page_tokens: 1, + model_contract: Some(crate::runtime_core::wire::ModelContract { + vocabulary: 8, + graphs: vec![crate::runtime_core::wire::GraphContract { + graph: "decode".into(), + ..Default::default() + }], + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }, + ranks: vec![PublishRank { + body: rank, + payloads: vec![ + PublishPayload { + role: pw::PayloadRole::Weights, + relative: "weights/layer-0.safetensors".into(), + source: crate::core::export::pin_file(&weights_path, weights.len() as u64) + .unwrap(), + id: weights_id, + tensor: None, + }, + PublishPayload { + role: pw::PayloadRole::Weights, + relative: dir_rel.into(), + source: crate::core::export::pin_file(&dir_path, dir.len() as u64) + .unwrap(), + id: dir_id, + tensor: None, + }, + PublishPayload { + role: pw::PayloadRole::Weights, + relative: weight_seg_rel.into(), + source: crate::core::export::pin_file( + &weight_seg_path, + weight_seg.len() as u64, + ) + .unwrap(), + id: weight_seg_id, + tensor: None, + }, + PublishPayload { + role: pw::PayloadRole::InitialState, + relative: state_seg_rel.into(), + source: crate::core::export::pin_file( + &state_seg_path, + state_seg.len() as u64, + ) + .unwrap(), + id: state_seg_id, + tensor: None, + }, + ], + resources: vec![ + PublishResource { + kind: pw::ExecutableKind::Cubin, + path: cubin_path, + nbytes: 10, + }, + PublishResource { + kind: pw::ExecutableKind::Graph, + path: graph_path, + nbytes: 10, + }, + ], + }], + }], + core_id: [42u8; 32], + public_key, + accepted: "ext-test".into(), + no_weights: false, + }; + crate::core::export::publish(&request, &key, Destination::Directory(&core_dir)).unwrap(); + let publishers = vec![publisher]; + + // 1. Clean authorization succeeds and `rank_ranges(0)` includes directory and all segments. + let verified = + VerifiedCore::open_tensor_parallel(&core_dir, &publishers, 1, None).unwrap(); + let authorized = verified.authorize(&publishers[0].namespace, true).unwrap(); + let AuthorizedKind::Payload(payload) = &authorized.kind else { + panic!("expected payload backend"); + }; + let ranges: std::collections::BTreeSet = payload + .rank_ranges(0) + .unwrap() + .into_iter() + .map(|file| file.filename) + .collect(); + assert!(ranges.contains(dir_rel), "{ranges:?}"); + assert!(ranges.contains(weight_seg_rel), "{ranges:?}"); + assert!(ranges.contains(state_seg_rel), "{ranges:?}"); + drop(authorized); + + let flip_last_byte = |relative: &str| { + let path = core_dir.join(relative); + let mut bytes = std::fs::read(&path).unwrap(); + let last = bytes.last_mut().unwrap(); + *last ^= 0xFF; + std::fs::write(&path, bytes).unwrap(); + }; + + // 2. Tampering with the extent directory must fail even with `verify_weights = false`. + flip_last_byte(dir_rel); + let verified = + VerifiedCore::open_tensor_parallel(&core_dir, &publishers, 1, None).unwrap(); + assert!( + verified.authorize(&publishers[0].namespace, false).is_err(), + "tampered external_extents directory must fail supporting verification" + ); + flip_last_byte(dir_rel); + + // 3. Tampering with an InitialState segment must fail even with `verify_weights = false`. + flip_last_byte(state_seg_rel); + let verified = + VerifiedCore::open_tensor_parallel(&core_dir, &publishers, 1, None).unwrap(); + assert!( + verified.authorize(&publishers[0].namespace, false).is_err(), + "tampered InitialState external_extents segment must fail supporting verification" + ); + flip_last_byte(state_seg_rel); + + // 4. Tampering with a Weights segment passes `verify_weights = false` and fails `verify_weights = true`. + flip_last_byte(weight_seg_rel); + let verified = + VerifiedCore::open_tensor_parallel(&core_dir, &publishers, 1, None).unwrap(); + assert!(verified.authorize(&publishers[0].namespace, false).is_ok()); + let verified = + VerifiedCore::open_tensor_parallel(&core_dir, &publishers, 1, None).unwrap(); + assert!( + verified.authorize(&publishers[0].namespace, true).is_err(), + "tampered external_extents weight segment must fail verify_weights=true" + ); + + let _ = std::fs::remove_dir_all(root); + } } diff --git a/ignition/cli/config.py b/ignition/cli/config.py index 7787eb64a..17148c06d 100644 --- a/ignition/cli/config.py +++ b/ignition/cli/config.py @@ -24,7 +24,7 @@ "server": {"host": str, "port": int, "api_key": str, "advertise": bool, "thinking_token_budget": int, "scheduler_checkpoint_extra_work_fraction": (int, float)}, "defaults": {"model": str, "max_concurrency": int}, - "memory": {"reserve": str}, + "memory": {"reserve": str, "pool_vram": str, "pool_ram": str}, "preparation": {"compile_workers": int, "autotune_effort": str, "checkpoint_token_file": str}, "prefix_cache": {"memory": str, "disk_limit": str, "drain_on_shutdown": str, "max_age": str, "compression": str}, @@ -39,6 +39,8 @@ "server.thinking_token_budget": None, "server.scheduler_checkpoint_extra_work_fraction": 0.05, "memory.reserve": "0", + "memory.pool_vram": "", + "memory.pool_ram": "", "preparation.compile_workers": 0, "preparation.autotune_effort": "default", "preparation.checkpoint_token_file": "~/.config/flare/agent.token", @@ -61,6 +63,35 @@ def parse_size(text: str, what: str = "memory size") -> int: return int(float(match[1]) * (1 << 10 * " KMGT".index((match[2] or " ").upper()))) +def _validate_pool_memory_limit(text: str, what: str) -> None: + """Validate a `[memory] pool_vram` or `pool_ram` limit matching `PoolMemoryLimit`.""" + value = text.strip() + if not value or value == "0": + return + message = ( + f"{what} {text!r} must be a nonnegative size (0, 12G), a reserve (-8G), " + "or a fraction in [0, 1] (0.25)" + ) + reserve = value.startswith("-") + number = value[1:] if reserve else value + if any(ch.isascii() and ch.isalpha() for ch in number): + try: + nbytes = parse_size(number, what) + except (UsageError, OverflowError) as error: + raise UsageError(message) from error + if nbytes >= (1 << 64): + raise UsageError(message) + return + if reserve or not number or not all(ch.isascii() and (ch.isdigit() or ch == ".") for ch in number): + raise UsageError(message) + try: + fraction = float(number) + except ValueError as error: + raise UsageError(message) from error + if not (math.isfinite(fraction) and 0.0 <= fraction <= 1.0): + raise UsageError(message) + + @dataclass(frozen=True) class Setting: value: object @@ -98,6 +129,10 @@ def load(cls, path: Path | None = None) -> "Configuration": raise UsageError(f"{resolved}: unknown section [{section}]") configuration = cls(resolved, values, True) parse_size(configuration.get("memory.reserve").value) + for key in ("memory.pool_vram", "memory.pool_ram"): + value = configuration.get(key).value + if value.strip(): + _validate_pool_memory_limit(value, key.replace(".", " ")) for key in ("prefix_cache.memory", "prefix_cache.disk_limit"): if configuration.get(key).value: parse_size(configuration.get(key).value, key.replace(".", " ")) diff --git a/ignition/preparation/execution.py b/ignition/preparation/execution.py index f31fa810f..238c214dc 100644 --- a/ignition/preparation/execution.py +++ b/ignition/preparation/execution.py @@ -219,6 +219,11 @@ def __post_init__(self): raise ValueError("async transfer alignment must be a power of two >= 4096") if bool(self.extent_directory) != bool(self.extent_segments): raise ValueError("async transfer extent_directory and extent_segments must be set together") + if self.extent_directory and self.alignment > 4096: + raise ValueError( + f"async transfer alignment {self.alignment} exceeds core container alignment 4096 " + "for external extents" + ) class PreparedExecution(PreparedGraphBundle): diff --git a/tests/cli/test_config.py b/tests/cli/test_config.py index 0a5e2d5e0..14fc467e2 100644 --- a/tests/cli/test_config.py +++ b/tests/cli/test_config.py @@ -236,3 +236,121 @@ def test_checkpoint_extra_work_fraction_configuration(tmp_path, value): def test_checkpoint_extra_work_fraction_rejects_invalid_configuration(tmp_path, value): with pytest.raises(UsageError, match="scheduler_checkpoint_extra_work_fraction"): load(tmp_path, f"[server]\nscheduler_checkpoint_extra_work_fraction = {value}\n") + + +@pytest.mark.parametrize("key", ["pool_vram", "pool_ram"]) +@pytest.mark.parametrize("value", ["", " ", "0", "0G", "0.0", "12G", "-8G", "-0KiB", "0.25", "1", "1.0", "1.5GiB", "0.001K"]) +def test_pool_memory_limits_accept_valid_values(tmp_path, key, value): + config = load(tmp_path, f'[memory]\n{key} = "{value}"\n') + assert config.get(f"memory.{key}") == Setting(value, "[memory]") + + +@pytest.mark.parametrize("key", ["pool_vram", "pool_ram"]) +@pytest.mark.parametrize("value", ["-0.5", "-0", "1.1", "30", "NaN", "inf", "1e-1", "--2G", "2P", "18446744073709551616T", "lots"]) +def test_pool_memory_limits_reject_invalid_values(tmp_path, key, value): + with pytest.raises(UsageError, match=f"memory {key}"): + load(tmp_path, f'[memory]\n{key} = "{value}"\n') + + +@pytest.mark.parametrize("key", ["pool_vram", "pool_ram"]) +@pytest.mark.parametrize("literal", ["12", "0.5", "true"]) +def test_pool_memory_limits_require_string_values(tmp_path, key, literal): + with pytest.raises(UsageError, match=f"{key} in .* must be str"): + load(tmp_path, f"[memory]\n{key} = {literal}\n") + + +def _parse_rust_configuration_schema(rust_source: str) -> tuple[dict[str, set[str]], dict[str, set[str]]]: + """Extract section fields and serde aliases declared by `flare::configuration::Configuration`.""" + import re + + structs: dict[str, list[tuple[str, str, list[str]]]] = {} + for match in re.finditer(r"pub struct (\w+)\s*\{([^}]*)\}", rust_source, re.DOTALL): + name, body = match.group(1), match.group(2) + fields: list[tuple[str, str, list[str]]] = [] + pending_aliases: list[str] = [] + for raw_line in body.splitlines(): + line = raw_line.strip() + if not line or line.startswith("//"): + continue + alias_matches = re.findall(r'alias\s*=\s*"([^"]+)"', line) + if alias_matches: + pending_aliases.extend(alias_matches) + continue + field_match = re.match(r"pub\s+(\w+)\s*:\s*(.+?)\s*,?$", line) + if field_match: + fields.append((field_match.group(1), field_match.group(2).strip(), pending_aliases)) + pending_aliases = [] + structs[name] = fields + + sections: dict[str, set[str]] = {} + aliases: dict[str, set[str]] = {} + for section, ty, _ in structs["Configuration"]: + struct_name = ty.split(",")[-1].strip().rstrip(">") if "<" in ty else ty + sections[section] = {field for field, _, _ in structs[struct_name]} + section_aliases = {alias for _, _, field_aliases in structs[struct_name] for alias in field_aliases} + if section_aliases: + aliases[section] = section_aliases + return sections, aliases + + +def test_python_config_schema_matches_rust_configuration(tmp_path): + from pathlib import Path + from ignition.cli import config as py_config + + rust_path = Path(__file__).resolve().parents[2] / "flare" / "src" / "configuration.rs" + assert rust_path.is_file() + rust_sections, rust_aliases = _parse_rust_configuration_schema(rust_path.read_text()) + assert rust_sections, "expected non-empty Rust Configuration schema" + + for section, fields in rust_sections.items(): + if section == "models": + assert fields <= set(py_config._MODEL_KEYS), f"missing [models.*] keys: {fields - set(py_config._MODEL_KEYS)}" + else: + assert section in py_config._SECTIONS, f"missing Rust section [{section}] in ignition/cli/config.py" + missing = fields - set(py_config._SECTIONS[section]) + assert not missing, f"missing keys in [{section}]: {sorted(missing)}" + + # Exercise `Configuration.load` against a TOML file populating every Rust field. + sample_values: dict[tuple[str, str], str] = { + ("server", "host"): '"127.0.0.1"', + ("server", "port"): "9001", + ("server", "api_key"): '"secret"', + ("server", "advertise"): "false", + ("server", "thinking_token_budget"): "1024", + ("server", "scheduler_checkpoint_extra_work_fraction"): "0.1", + ("defaults", "max_concurrency"): "4", + ("models", "max_concurrency"): "2", + ("memory", "reserve"): '"4G"', + ("memory", "pool_vram"): '"12G"', + ("memory", "pool_ram"): '"-16G"', + ("prefix_cache", "memory"): '"2G"', + ("prefix_cache", "disk_limit"): '"10G"', + ("prefix_cache", "drain_on_shutdown"): '"30s"', + ("prefix_cache", "max_age"): '"2h"', + ("prefix_cache", "compression"): '"cpu"', + ("paths", "core_cache"): '"/tmp/cores"', + ("paths", "prefix_cache"): '"/tmp/prefix"', + ("paths", "hub_cache"): '"/tmp/hub"', + } + rust_pairs = {(section, field) for section, fields in rust_sections.items() for field in fields} + assert set(sample_values) == rust_pairs, ( + f"update parity test sample_values to match flare/src/configuration.rs: " + f"missing={sorted(rust_pairs - set(sample_values))}, extra={sorted(set(sample_values) - rust_pairs)}" + ) + + lines: list[str] = [] + for section, fields in rust_sections.items(): + header = '[models."demo"]' if section == "models" else f"[{section}]" + lines.append(header) + for field in sorted(fields): + lines.append(f"{field} = {sample_values[(section, field)]}") + lines.append("") + loaded = load(tmp_path, "\n".join(lines)) + assert loaded.get("memory.pool_vram") == Setting("12G", "[memory]") + assert loaded.get("memory.pool_ram") == Setting("-16G", "[memory]") + + for section, section_aliases in rust_aliases.items(): + for alias in section_aliases: + assert section == "paths" and alias == "package_cache" + aliased = load(tmp_path, f'[{section}]\n{alias} = "/tmp/legacy-cores"\n') + assert aliased.get("paths.core_cache") == Setting("/tmp/legacy-cores", "[paths]") diff --git a/tests/preparation/test_execution.py b/tests/preparation/test_execution.py index 26ae3e43f..d5ce02ec5 100644 --- a/tests/preparation/test_execution.py +++ b/tests/preparation/test_execution.py @@ -369,3 +369,38 @@ def test_native_round_metadata_retains_full_proposal_depth(width, depth): assert (graph.token_capacity, graph.draft_tokens, graph.confidence_width) == (width, depth, depth) with pytest.raises(ValueError, match="draft depth"): GraphSignature("speculative", 4, width, draft_tokens=(1 << 31) - 1) + + +def test_async_transfer_channel_rejects_external_extents_alignment_above_container_alignment(): + from ignition.preparation.execution import AsyncTransferChannel + + # 4 KiB matches core container alignment. + channel = AsyncTransferChannel( + name="experts", + device_pool="dev_pool", + control_buffer="ctrl", + alignment=4096, + extent_directory="/tmp/ext.dir", + extent_segments=("/tmp/ext.seg",), + ) + assert channel.alignment == 4096 + + # Alignment > 4 KiB is allowed when no external_extents files are attached. + no_extents = AsyncTransferChannel( + name="experts", + device_pool="dev_pool", + control_buffer="ctrl", + alignment=8192, + ) + assert no_extents.alignment == 8192 + + # Alignment > 4 KiB with external_extents exceeds core container alignment. + with pytest.raises(ValueError, match="exceeds core container alignment 4096"): + AsyncTransferChannel( + name="experts", + device_pool="dev_pool", + control_buffer="ctrl", + alignment=8192, + extent_directory="/tmp/ext.dir", + extent_segments=("/tmp/ext.seg",), + )