From 49bf8800a7ff0e5a874556b45735bfe87b78477c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 17:22:37 +0100 Subject: [PATCH] STRA-338 size-fn: strata-control: prepare_preview and model_pipeline functions within limits (fn>30 22 -> 0) --- control-plane/src/model_pipeline.rs | 293 +++++++++---- control-plane/src/prepare_preview.rs | 8 + .../prepare_preview/encode_preview_tensor.rs | 284 ++++++------ .../minimum_part_payload_bytes.rs | 3 +- control-plane/src/prepare_preview/prepare.rs | 412 +++++++++++------- .../src/prepare_preview/prepare_sharded.rs | 177 ++------ .../prepare_sharded_streamed_with_policy.rs | 278 ++++-------- .../src/prepare_preview/preview_common.rs | 199 +++++++++ .../src/prepare_preview/sharded_encode.rs | 123 ++++++ .../src/prepare_preview/spool_raw_f32.rs | 68 +-- .../src/prepare_preview/streamed_encode.rs | 210 +++++++++ .../src/prepare_preview/tests/convert.rs | 88 ++-- .../src/prepare_preview/tests/fixtures.rs | 79 ++++ .../src/prepare_preview/tests/overlay.rs | 150 +++---- .../prepare_preview/tests/ple_partition.rs | 93 ++-- .../src/prepare_preview/tests/sharded.rs | 255 ++++++----- .../src/prepare_preview/tests/source_kinds.rs | 167 ++++--- .../src/prepare_preview/verify_derived.rs | 88 ++-- .../prepare_preview/verify_sharded_parts.rs | 132 ++++++ 19 files changed, 1923 insertions(+), 1184 deletions(-) create mode 100644 control-plane/src/prepare_preview/preview_common.rs create mode 100644 control-plane/src/prepare_preview/sharded_encode.rs create mode 100644 control-plane/src/prepare_preview/streamed_encode.rs create mode 100644 control-plane/src/prepare_preview/verify_sharded_parts.rs diff --git a/control-plane/src/model_pipeline.rs b/control-plane/src/model_pipeline.rs index 67f6ed75..ad167b43 100644 --- a/control-plane/src/model_pipeline.rs +++ b/control-plane/src/model_pipeline.rs @@ -13,46 +13,89 @@ pub enum PreviewOutcome { Reused(kar::Summary), } -pub async fn ensure_sharded_preview( - manifest: &model::Manifest, - source_dir: &Path, - archive: &Path, - levels: u8, -) -> Result { +fn require_levels(levels: u8, message: &str) -> Result<(), crate::BoxError> { if !(1..=8).contains(&levels) { - return Err("sharded preview requires 1..=8 KAR levels".into()); + return Err(message.into()); } + Ok(()) +} + +fn require_regular_archive(metadata: &fs::Metadata) -> Result<(), crate::BoxError> { + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("existing KAR path must be a regular file".into()); + } + Ok(()) +} + +fn require_preview_source_limit(manifest: &model::Manifest) -> Result<(), crate::BoxError> { let source_bytes = manifest .files .iter() .try_fold(0u64, |sum, file| sum.checked_add(file.size)) .ok_or("sharded source byte count overflow")?; if source_bytes > 64 * 1024 * 1024 { - return Err("sharded preview accepts at most 64 MiB of GGUF input; full-model preparation is not implemented".into()); + return Err( + "sharded preview accepts at most 64 MiB of GGUF input; full-model preparation is not implemented".into(), + ); } + Ok(()) +} +fn reuse_sharded_preview( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, +) -> Result { + let summary = prepare_preview::verify_sharded(manifest, source_dir, archive)?; + if summary.max_planes != levels { + return Err(format!( + "existing KAR has {} levels, requested {levels}; choose another output path", + summary.max_planes + ) + .into()); + } + Ok(PreviewOutcome::Reused(summary)) +} + +fn create_sharded_preview( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, +) -> Result { + let created = prepare_preview::prepare_sharded(manifest, source_dir, archive, levels)?; + prepare_preview::verify_sharded(manifest, source_dir, archive)?; + Ok(PreviewOutcome::Created(created)) +} + +async fn fetch_and_verify( + manifest: &model::Manifest, + source_dir: &Path, +) -> Result<(), crate::BoxError> { model::fetch(manifest, source_dir).await?; model::verify(manifest, source_dir).await?; + Ok(()) +} + +pub async fn ensure_sharded_preview( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, +) -> Result { + require_levels(levels, "sharded preview requires 1..=8 KAR levels")?; + require_preview_source_limit(manifest)?; + + fetch_and_verify(manifest, source_dir).await?; match fs::symlink_metadata(archive) { Ok(metadata) => { - if !metadata.is_file() || metadata.file_type().is_symlink() { - return Err("existing KAR path must be a regular file".into()); - } - let summary = prepare_preview::verify_sharded(manifest, source_dir, archive)?; - if summary.max_planes != levels { - return Err(format!( - "existing KAR has {} levels, requested {levels}; choose another output path", - summary.max_planes - ) - .into()); - } - Ok(PreviewOutcome::Reused(summary)) + require_regular_archive(&metadata)?; + reuse_sharded_preview(manifest, source_dir, archive, levels) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let created = prepare_preview::prepare_sharded(manifest, source_dir, archive, levels)?; - prepare_preview::verify_sharded(manifest, source_dir, archive)?; - Ok(PreviewOutcome::Created(created)) + create_sharded_preview(manifest, source_dir, archive, levels) } Err(error) => Err(error.into()), } @@ -84,6 +127,60 @@ pub async fn ensure_sharded_streamed_ple( .await } +fn verify_streamed( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, + ple_part_elements: Option, +) -> Result { + if let Some(limit) = ple_part_elements { + prepare_preview::verify_sharded_streamed_ple(manifest, source_dir, archive, levels, limit) + } else { + prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels) + } +} + +fn prepare_streamed( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, + ple_part_elements: Option, +) -> Result { + if let Some(limit) = ple_part_elements { + prepare_preview::prepare_sharded_streamed_ple(manifest, source_dir, archive, levels, limit) + } else { + prepare_preview::prepare_sharded_streamed(manifest, source_dir, archive, levels) + } +} + +fn require_streamed_request( + levels: u8, + ple_part_elements: Option, +) -> Result<(), crate::BoxError> { + require_levels( + levels, + "streamed sharded preparation requires 1..=8 KAR levels", + )?; + if let Some(limit) = ple_part_elements { + stream_parts::validate_ple_limit(limit)?; + } + Ok(()) +} + +fn create_streamed( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, + ple_part_elements: Option, +) -> Result { + let created = prepare_streamed(manifest, source_dir, archive, levels, ple_part_elements)?; + verify_streamed(manifest, source_dir, archive, levels, ple_part_elements)?; + Ok(PreviewOutcome::Created(created)) +} + async fn ensure_sharded_streamed_with_policy( manifest: &model::Manifest, source_dir: &Path, @@ -91,50 +188,91 @@ async fn ensure_sharded_streamed_with_policy( levels: u8, ple_part_elements: Option, ) -> Result { - if !(1..=8).contains(&levels) { - return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); - } - if let Some(limit) = ple_part_elements { - stream_parts::validate_ple_limit(limit)?; - } + require_streamed_request(levels, ple_part_elements)?; preflight_existing_shards(manifest, source_dir, archive, levels)?; - model::fetch(manifest, source_dir).await?; - model::verify(manifest, source_dir).await?; + fetch_and_verify(manifest, source_dir).await?; match fs::symlink_metadata(archive) { Ok(metadata) => { - if !metadata.is_file() || metadata.file_type().is_symlink() { - return Err("existing KAR path must be a regular file".into()); - } - let summary = if let Some(limit) = ple_part_elements { - prepare_preview::verify_sharded_streamed_ple( - manifest, source_dir, archive, levels, limit, - )? - } else { - prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)? - }; + require_regular_archive(&metadata)?; + let summary = + verify_streamed(manifest, source_dir, archive, levels, ple_part_elements)?; Ok(PreviewOutcome::Reused(summary)) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let created = if let Some(limit) = ple_part_elements { - prepare_preview::prepare_sharded_streamed_ple( - manifest, source_dir, archive, levels, limit, - )? - } else { - prepare_preview::prepare_sharded_streamed(manifest, source_dir, archive, levels)? - }; - if let Some(limit) = ple_part_elements { - prepare_preview::verify_sharded_streamed_ple( - manifest, source_dir, archive, levels, limit, - )?; - } else { - prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)?; - } - Ok(PreviewOutcome::Created(created)) + create_streamed(manifest, source_dir, archive, levels, ple_part_elements) } Err(error) => Err(error.into()), } } +fn archive_exists(archive: &Path) -> Result { + match fs::symlink_metadata(archive) { + Ok(_) => Ok(true), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error.into()), + } +} + +fn require_plain_shard_name(name: &Path) -> Result<(), crate::BoxError> { + if name.components().count() != 1 + || !matches!(name.components().next(), Some(Component::Normal(_))) + { + return Err("invalid model shard name".into()); + } + Ok(()) +} + +/// Adds the minimum payload of every tensor of the shard to `minimum`. +fn add_tensor_minimums( + tensors: Vec, + levels: u8, + mut minimum: u64, +) -> Result { + for tensor in tensors { + let derived_bytes = tensor + .dimensions + .iter() + .try_fold(4u64, |bytes, dim| bytes.checked_mul(*dim)) + .ok_or("GGUF tensor F32 byte count overflow")?; + minimum = minimum + .checked_add(prepare_preview::minimum_part_payload_bytes( + derived_bytes, + levels, + )?) + .ok_or("KAR minimum payload size overflow")?; + } + Ok(minimum) +} + +/// The running minimum after this shard, or `None` when the shard is absent +/// or incomplete and the check cannot be decided yet. +fn add_shard_minimum( + source_dir: &Path, + shard: &model::ModelFile, + levels: u8, + minimum: u64, +) -> Result, crate::BoxError> { + let name = Path::new(&shard.name); + require_plain_shard_name(name)?; + let path = source_dir.join(name); + let metadata = match fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(format!("model shard is not a regular file: {}", path.display()).into()); + } + if metadata.len() != shard.size { + return Ok(None); // Fetch will reject or resume this shard. + } + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.summary.file_size != shard.size { + return Err("GGUF shard size differs from manifest".into()); + } + add_tensor_minimums(index.tensors, levels, minimum).map(Some) +} + /// Reject an impossible new archive before hashing already-present large /// shards. GGUF metadata is only a rejection hint; fetch/verify still pins /// every source byte before preparation when the volume has enough space. @@ -144,47 +282,14 @@ fn preflight_existing_shards( archive: &Path, levels: u8, ) -> Result<(), crate::BoxError> { - match fs::symlink_metadata(archive) { - Ok(_) => return Ok(()), // Reusing an archive needs no new payload space. - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(error.into()), + if archive_exists(archive)? { + return Ok(()); // Reusing an archive needs no new payload space. } let mut minimum = 0u64; for shard in &manifest.files { - let name = Path::new(&shard.name); - if name.components().count() != 1 - || !matches!(name.components().next(), Some(Component::Normal(_))) - { - return Err("invalid model shard name".into()); - } - let path = source_dir.join(name); - let metadata = match fs::symlink_metadata(&path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(error.into()), - }; - if !metadata.is_file() || metadata.file_type().is_symlink() { - return Err(format!("model shard is not a regular file: {}", path.display()).into()); - } - if metadata.len() != shard.size { - return Ok(()); // Fetch will reject or resume this shard. - } - let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - if index.summary.file_size != shard.size { - return Err("GGUF shard size differs from manifest".into()); - } - for tensor in index.tensors { - let derived_bytes = tensor - .dimensions - .iter() - .try_fold(4u64, |bytes, dim| bytes.checked_mul(*dim)) - .ok_or("GGUF tensor F32 byte count overflow")?; - minimum = minimum - .checked_add(prepare_preview::minimum_part_payload_bytes( - derived_bytes, - levels, - )?) - .ok_or("KAR minimum payload size overflow")?; + match add_shard_minimum(source_dir, shard, levels, minimum)? { + Some(next) => minimum = next, + None => return Ok(()), } } let parent = archive diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index bbcab8b8..e5609e5e 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -100,3 +100,11 @@ pub use encode_preview_tensor::*; mod verify_derived; #[allow(unused_imports)] pub use verify_derived::*; +mod preview_common; +use preview_common::*; +mod sharded_encode; +use sharded_encode::*; +mod streamed_encode; +use streamed_encode::*; +mod verify_sharded_parts; +use verify_sharded_parts::*; diff --git a/control-plane/src/prepare_preview/encode_preview_tensor.rs b/control-plane/src/prepare_preview/encode_preview_tensor.rs index 2912a861..03ed39b3 100644 --- a/control-plane/src/prepare_preview/encode_preview_tensor.rs +++ b/control-plane/src/prepare_preview/encode_preview_tensor.rs @@ -1,8 +1,118 @@ -//! Moved out of the parent module by STRA-338: fn encode_preview_tensor, fn verify_iq3, fn verify_mixed, fn verify_sharded, fn verify_sharded_streamed, fn verify_sharded_streamed_ple .... +//! Moved out of the parent module by STRA-338: fn encode_preview_tensor, fn verify_iq3, fn verify_mixed, fn +//! verify_sharded, fn verify_sharded_streamed, fn verify_sharded_streamed_ple .... #[allow(unused_imports)] use super::*; +/// The calibrated planes of one tensor, before they are written as a section. +struct Quantized { + calibration: kar_codec::Calibration, + encoded: kar_codec::EncodedPlanes, + levels: u8, +} + +impl Quantized { + fn fit(weights: &[f32], levels: u8) -> Result { + let normalized = kar_codec::normalize_for_calibration(weights, 32)?; + let calibration = kar_codec::fit_topdown(&normalized.values, levels)?; + let encoded = + kar_codec::encode_with_boundaries(weights, 32, &calibration.boundaries, levels)?; + Ok(Self { + calibration, + encoded, + levels, + }) + } + + fn plane_refs(&self) -> Vec<&[u32]> { + self.encoded.planes.iter().map(Vec::as_slice).collect() + } + + fn book_refs(&self) -> Vec<&[u16]> { + self.calibration.books.iter().map(Vec::as_slice).collect() + } + + fn relative_l2(&self, weights: &[f32], plane_refs: &[&[u32]]) -> Result { + let mut decoded = vec![0.0f32; weights.len()]; + kar_codec::decode_range( + &self.encoded.scales, + &self.calibration.books[usize::from(self.levels) - 1], + plane_refs, + 32, + 0, + &mut decoded, + )?; + Ok(relative_l2_error(weights, &decoded)) + } + + fn tensor<'a>( + &'a self, + source: SourceTensorRef<'a>, + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], + ) -> kar_writer::Tensor<'a> { + kar_writer::Tensor { + name: source.name, + dims: source.dimensions, + source_dtype: 0, + source_digest: source.digest, + source_offset: source.offset, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: self.levels, + scales: &self.encoded.scales, + books, + planes, + }, + } + } +} + +/// Identity of the source tensor a section is derived from. +#[derive(Clone, Copy)] +struct SourceTensorRef<'a> { + name: &'a str, + dimensions: &'a [u64], + digest: [u8; 32], + offset: u64, +} + +fn relative_l2_error(weights: &[f32], decoded: &[f32]) -> f64 { + let (error_sum, reference_sum) = weights.iter().zip(decoded).fold( + (0.0f64, 0.0f64), + |(error_sum, reference_sum), (original, rebuilt)| { + let delta = f64::from(*original) - f64::from(*rebuilt); + ( + error_sum + delta * delta, + reference_sum + f64::from(*original).powi(2), + ) + }, + ); + if reference_sum == 0.0 { + error_sum.sqrt() + } else { + (error_sum / reference_sum).sqrt() + } +} + +fn prepared_tensor( + source: SourceTensorRef<'_>, + section_path: &Path, + section: &kar_writer::SectionSummary, +) -> PreparedTensor { + PreparedTensor { + name: source.name.to_owned(), + dims: source.dimensions.to_vec(), + source_digest: source.digest, + source_offset: source.offset, + section_path: section_path.to_path_buf(), + section_bytes: section.bytes, + section_digest: section.digest, + } +} + pub(super) fn encode_preview_tensor( name: &str, dimensions: &[u64], @@ -12,68 +122,20 @@ pub(super) fn encode_preview_tensor( section_path: &Path, levels: u8, ) -> Result<(PreparedTensor, f64), String> { - let normalized = kar_codec::normalize_for_calibration(weights, 32)?; - let calibration = kar_codec::fit_topdown(&normalized.values, levels)?; - let encoded = kar_codec::encode_with_boundaries(weights, 32, &calibration.boundaries, levels)?; - let plane_refs = encoded.planes.iter().map(Vec::as_slice).collect::>(); - let mut decoded = vec![0.0f32; weights.len()]; - kar_codec::decode_range( - &encoded.scales, - &calibration.books[usize::from(levels) - 1], - &plane_refs, - 32, - 0, - &mut decoded, - )?; - let (error_sum, reference_sum) = weights.iter().zip(&decoded).fold( - (0.0f64, 0.0f64), - |(error_sum, reference_sum), (original, rebuilt)| { - let delta = f64::from(*original) - f64::from(*rebuilt); - ( - error_sum + delta * delta, - reference_sum + f64::from(*original).powi(2), - ) - }, - ); - let relative_l2 = if reference_sum == 0.0 { - error_sum.sqrt() - } else { - (error_sum / reference_sum).sqrt() - }; - let books = calibration - .books - .iter() - .map(Vec::as_slice) - .collect::>(); - let coded_tensor = kar_writer::Tensor { + let quantized = Quantized::fit(weights, levels)?; + let plane_refs = quantized.plane_refs(); + let relative_l2 = quantized.relative_l2(weights, &plane_refs)?; + let books = quantized.book_refs(); + let source = SourceTensorRef { name, - dims: dimensions, - source_dtype: 0, - source_digest, - source_offset, - data: kar_writer::TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: levels, - scales: &encoded.scales, - books: &books, - planes: &plane_refs, - }, + dimensions, + digest: source_digest, + offset: source_offset, }; + let coded_tensor = quantized.tensor(source, &books, &plane_refs); let section = kar_writer::write_nested_section(section_path, &coded_tensor)?; - Ok(( - PreparedTensor { - name: name.to_owned(), - dims: dimensions.to_vec(), - source_digest, - source_offset, - section_path: section_path.to_path_buf(), - section_bytes: section.bytes, - section_digest: section.digest, - }, - relative_l2, - )) + let prepared = prepared_tensor(source, section_path, §ion); + Ok((prepared, relative_l2)) } pub fn verify_iq3(source_path: &Path, archive_path: &Path) -> Result { @@ -148,97 +210,17 @@ pub(super) fn verify_sharded_inner( ple_part_elements: Option, ) -> Result { let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; - let archive_parts = if streamed_levels.is_some() { - Some(if let Some(limit) = ple_part_elements { - stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)? - } else { - stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)? - }) - } else { - None - }; + let archive_parts = streamed_levels + .map(|_| plan_verified_parts(&identity, source_dir, max_part_elements, ple_part_elements)) + .transpose()?; let (summary, sources) = kar::verify_with_sources(archive_path)?; - let expected_count = archive_parts - .as_ref() - .map_or(identity.tensors.len(), |parts| { - parts.iter().map(Vec::len).sum() - }); - if summary.source_digest != identity.derived_sha256 - || summary.source_bytes != identity.derived_bytes - || summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes) - || sources.len() != expected_count - { - return Err("KAR header differs from sharded derived source".into()); - } - if let Some(parts) = &archive_parts { - for (record, part) in sources.iter().zip(parts.iter().flatten()) { - let record_bytes = record - .dimensions - .iter() - .try_fold(4u64, |size, dim| size.checked_mul(*dim)) - .ok_or("KAR tensor source byte count overflow")?; - if record.name != part.name - || record.dimensions != part.dimensions - || record.dtype != 0 - || record.digest != part.f32_sha256 - || record.offset != part.derived_offset - || record_bytes != part.derived_bytes - { - return Err(format!("{}: sharded KAR part source mismatch", part.name)); - } - } - } else { - for (record, tensor) in sources.iter().zip(&identity.tensors) { - let record_bytes = record - .dimensions - .iter() - .try_fold(4u64, |size, dim| size.checked_mul(*dim)) - .ok_or("KAR tensor source byte count overflow")?; - if record.name != tensor.name - || record.dtype != 0 - || record.digest != tensor.f32_sha256 - || record.offset != tensor.derived_offset - || record_bytes != tensor.derived_bytes - { - return Err(format!( - "{}: sharded KAR tensor source mismatch", - tensor.name - )); - } - } - } - let archive_digest = hash_file(archive_path)?; - let provenance = provenance_path(archive_path)?; - let file = File::open(provenance).map_err(|error| error.to_string())?; - let recorded: serde_json::Value = - serde_json::from_reader(file).map_err(|error| error.to_string())?; - let mut expected = sharded_provenance_value(&identity, archive_digest); - if let Some(levels) = streamed_levels { - if summary.max_planes > levels { - return Err("KAR stream levels exceed declared preparation level".into()); - } - expected["schema"] = serde_json::json!(if ple_part_elements.is_some() { - "strata-next/sharded-stream-provenance-v5" - } else { - "strata-next/sharded-stream-provenance-v4" - }); - expected["derivation"] = - serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); - expected["levels"] = serde_json::json!(levels); - expected["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); - expected["partitioned_tensors"] = partitioned_provenance( - archive_parts - .as_ref() - .ok_or("missing streamed KAR part plan")?, - ); - if let Some(limit) = ple_part_elements { - expected["ple_part_elements"] = serde_json::json!(limit); - } - } - if recorded != expected { - return Err( - "sharded provenance differs from source, archive, or preparation policy".into(), - ); - } + let parts = archive_parts.as_deref(); + require_sharded_header(&identity, parts, &summary, sources.len())?; + require_sharded_sources(&identity, parts, &sources)?; + let policy = StreamPolicy { + levels: streamed_levels, + ple_part_elements, + }; + require_sharded_provenance(&identity, parts, archive_path, &summary, policy)?; Ok(summary) } diff --git a/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs b/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs index f6233719..aa6208e0 100644 --- a/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs +++ b/control-plane/src/prepare_preview/minimum_part_payload_bytes.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn minimum_part_payload_bytes, impl DerivedIdentity, impl Drop_for_StagingDir, fn prepare_f32, fn prepare_iq3, fn prepare_mixed. +//! Moved out of the parent module by STRA-338: fn minimum_part_payload_bytes, impl DerivedIdentity, impl +//! Drop_for_StagingDir, fn prepare_f32, fn prepare_iq3, fn prepare_mixed. #[allow(unused_imports)] use super::*; diff --git a/control-plane/src/prepare_preview/prepare.rs b/control-plane/src/prepare_preview/prepare.rs index 2de0cbc0..5ff37e3a 100644 --- a/control-plane/src/prepare_preview/prepare.rs +++ b/control-plane/src/prepare_preview/prepare.rs @@ -9,125 +9,180 @@ pub(super) fn prepare( levels: u8, kind: PreviewKind, ) -> Result { - if !(1..=8).contains(&levels) { - return Err("F32 preview requires 1..=8 KAR levels".into()); - } - let index = gguf::tensor_index(source_path).map_err(|error| error.to_string())?; + let plan = PreviewPlan::load(source_path, levels, kind)?; + let staged = plan.encode_tensors(source_path, destination)?; + plan.write_archive(destination, &staged) +} + +/// What the source file says about the preview before any tensor is read. +struct PreviewPlan { + index: gguf::TensorIndex, + architecture: String, + source_name: String, + derived_identity: Option, + original_digest: [u8; 32], + levels: u8, + kind: PreviewKind, +} + +/// The encoded sections; the staging directory lives until the archive is written. +struct StagedTensors { + staging: StagingDir, + prepared: Vec, + total_elements: u64, + maximum_relative_l2: f64, +} + +fn require_source_limits(index: &gguf::TensorIndex) -> Result<(), String> { if index.summary.file_size > MAX_SOURCE_BYTES || index.tensors.is_empty() || index.tensors.len() > MAX_TENSORS { return Err("F32 preview exceeds its source or tensor-count limit".into()); } - let architecture = index - .summary - .architecture - .as_deref() - .ok_or("GGUF source has no architecture")?; - let filename = source_path - .file_name() - .ok_or("GGUF source has no file name")? - .to_string_lossy(); - let derived_identity = match kind { + Ok(()) +} + +fn derive_identity( + kind: PreviewKind, + source_path: &Path, +) -> Result, String> { + Ok(match kind { PreviewKind::F32 => None, PreviewKind::Iq3 => Some(DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?)), PreviewKind::Mixed => Some(DerivedIdentity::Mixed(derived_mixed::fingerprint( source_path, )?)), - }; - let source_name = match kind { + }) +} + +fn preview_source_name(kind: PreviewKind, filename: &str) -> String { + match kind { PreviewKind::F32 => filename.to_string(), PreviewKind::Iq3 => format!("{filename}#derived-f32-le-v1"), PreviewKind::Mixed => format!("{filename}#mixed-derived-f32-le-v1"), - }; - let original_digest = match &derived_identity { - Some(identity) => identity.gguf_digest(), - None => hash_file(source_path)?, - }; - let staging_name = format!( - "{}.parts-{}", - destination + } +} + +fn supports_tensor_kind(kind: PreviewKind, tensor_kind: u32) -> bool { + match kind { + PreviewKind::F32 => tensor_kind == 0, + PreviewKind::Iq3 => tensor_kind == 21, + PreviewKind::Mixed => matches!(tensor_kind, 0 | 1 | 21 | 30), + } +} + +fn supported_kinds_label(kind: PreviewKind) -> &'static str { + match kind { + PreviewKind::F32 => "F32", + PreviewKind::Iq3 => "IQ3_S", + PreviewKind::Mixed => "F32/F16/BF16/IQ3_S", + } +} + +fn builder_label(kind: PreviewKind) -> &'static str { + match kind { + PreviewKind::F32 => "f32", + PreviewKind::Iq3 => "iq3-derived-f32", + PreviewKind::Mixed => "mixed-derived-f32", + } +} + +impl PreviewPlan { + fn load(source_path: &Path, levels: u8, kind: PreviewKind) -> Result { + require_levels(levels, "F32 preview requires 1..=8 KAR levels")?; + let index = gguf::tensor_index(source_path).map_err(|error| error.to_string())?; + require_source_limits(&index)?; + let architecture = index + .summary + .architecture + .as_deref() + .ok_or("GGUF source has no architecture")? + .to_owned(); + let filename = source_path .file_name() - .ok_or("KAR destination has no file name")? - .to_string_lossy(), - std::process::id() - ); - let staging_path = destination.with_file_name(staging_name); - fs::create_dir(&staging_path).map_err(|error| error.to_string())?; - let staging = StagingDir(staging_path); - let mut source_file = File::open(source_path).map_err(|error| error.to_string())?; - let mut total_elements = 0u64; - let mut maximum_relative_l2 = 0.0f64; - let mut prepared = Vec::with_capacity(index.tensors.len()); - for (number, tensor) in index.tensors.iter().enumerate() { - let supported = match kind { - PreviewKind::F32 => tensor.kind == 0, - PreviewKind::Iq3 => tensor.kind == 21, - PreviewKind::Mixed => matches!(tensor.kind, 0 | 1 | 21 | 30), + .ok_or("GGUF source has no file name")? + .to_string_lossy(); + let derived_identity = derive_identity(kind, source_path)?; + let source_name = preview_source_name(kind, &filename); + let original_digest = match &derived_identity { + Some(identity) => identity.gguf_digest(), + None => hash_file(source_path)?, }; - if !supported || tensor.dimensions.len() > 4 { + Ok(Self { + index, + architecture, + source_name, + derived_identity, + original_digest, + levels, + kind, + }) + } + + fn require_supported(&self, tensor: &gguf::TensorInfo) -> Result<(), String> { + if !supports_tensor_kind(self.kind, tensor.kind) || tensor.dimensions.len() > 4 { return Err(format!( "{}: preview supports only {} tensors with up to four dimensions", tensor.name, - match kind { - PreviewKind::F32 => "F32", - PreviewKind::Iq3 => "IQ3_S", - PreviewKind::Mixed => "F32/F16/BF16/IQ3_S", - } + supported_kinds_label(self.kind) )); } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |product, dim| product.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - total_elements = total_elements + Ok(()) + } + + fn encode_tensors( + &self, + source_path: &Path, + destination: &Path, + ) -> Result { + let staging = staging_dir(destination, "parts")?; + let mut source_file = File::open(source_path).map_err(|error| error.to_string())?; + let mut staged = StagedTensors { + staging, + prepared: Vec::with_capacity(self.index.tensors.len()), + total_elements: 0, + maximum_relative_l2: 0.0, + }; + for (number, tensor) in self.index.tensors.iter().enumerate() { + self.encode_tensor(&mut source_file, number, tensor, &mut staged)?; + } + self.require_source_unchanged(&source_file, source_path)?; + Ok(staged) + } + + /// Checks one tensor against the preview limits and counts its elements. + fn count_tensor( + &self, + tensor: &gguf::TensorInfo, + staged: &mut StagedTensors, + ) -> Result { + self.require_supported(tensor)?; + let elements = tensor_elements(&tensor.dimensions)?; + staged.total_elements = staged + .total_elements .checked_add(elements) .ok_or("GGUF model element count overflow")?; if elements > MAX_TENSOR_ELEMENTS { return Err("F32 preview exceeds its per-tensor element limit".into()); } - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - source_file - .seek(SeekFrom::Start(absolute)) - .map_err(|error| error.to_string())?; - let mut raw = vec![0u8; tensor.bytes as usize]; - source_file - .read_exact(&mut raw) - .map_err(|error| error.to_string())?; - let (weights, tensor_digest, source_offset) = if let Some(identity) = &derived_identity { - let derived = identity.tensor(number); - if derived.name != tensor.name - || derived.source_kind != tensor.kind - || Sha256::digest(&raw).as_slice() != derived.source_digest - { - return Err("GGUF tensor differs from derived source identity".into()); - } - let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; - let mut digest = Sha256::new(); - for value in &weights { - digest.update(value.to_le_bytes()); - } - if digest.finalize().as_slice() != derived.f32_digest || derived.bytes != elements * 4 { - return Err("decoded F32 tensor differs from derived source identity".into()); - } - (weights, *derived.f32_digest, derived.offset) - } else { - let digest = Sha256::digest(&raw).into(); - let weights = raw - .as_chunks::<4>() - .0 - .iter() - .map(|chunk| f32::from_le_bytes(*chunk)) - .collect::>(); - (weights, digest, absolute) - }; - drop(raw); - let section_path = staging.0.join(format!("{number:06}.section")); + Ok(elements) + } + + fn encode_tensor( + &self, + source_file: &mut File, + number: usize, + tensor: &gguf::TensorInfo, + staged: &mut StagedTensors, + ) -> Result<(), String> { + let elements = self.count_tensor(tensor, staged)?; + let data_start = self.index.summary.data_start; + let absolute = checked_offset(data_start, tensor.offset, "GGUF tensor offset overflow")?; + let raw = read_raw_tensor(source_file, absolute, tensor.bytes)?; + let (weights, tensor_digest, source_offset) = + self.source_weights(number, tensor, raw, elements, absolute)?; + let section_path = staged.staging.0.join(format!("{number:06}.section")); let (coded, relative_l2) = encode_preview_tensor( &tensor.name, &tensor.dimensions, @@ -135,79 +190,108 @@ pub(super) fn prepare( tensor_digest, source_offset, §ion_path, - levels, + self.levels, )?; - maximum_relative_l2 = maximum_relative_l2.max(relative_l2); - prepared.push(coded); + staged.maximum_relative_l2 = staged.maximum_relative_l2.max(relative_l2); + staged.prepared.push(coded); + Ok(()) } - if source_file - .metadata() - .map_err(|error| error.to_string())? - .len() - != index.summary.file_size - || hash_file(source_path)? != original_digest - { - return Err("GGUF source changed during F32 preparation".into()); + + /// Decodes one tensor and returns its weights, F32 digest and source offset. + fn source_weights( + &self, + number: usize, + tensor: &gguf::TensorInfo, + raw: Vec, + elements: u64, + absolute: u64, + ) -> Result<(Vec, [u8; 32], u64), String> { + let Some(identity) = &self.derived_identity else { + let digest = Sha256::digest(&raw).into(); + return Ok((f32_from_le(&raw), digest, absolute)); + }; + let derived = identity.tensor(number); + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || Sha256::digest(&raw).as_slice() != derived.source_digest + { + return Err("GGUF tensor differs from derived source identity".into()); + } + let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; + if f32_digest(&weights) != *derived.f32_digest || derived.bytes != elements * 4 { + return Err("decoded F32 tensor differs from derived source identity".into()); + } + Ok((weights, *derived.f32_digest, derived.offset)) } - let tensors = prepared - .iter() - .map(|tensor| kar_writer::Tensor { - name: &tensor.name, - dims: &tensor.dims, - source_dtype: 0, - source_digest: tensor.source_digest, - source_offset: tensor.source_offset, - data: kar_writer::TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: levels, - levels, - path: &tensor.section_path, - offset: 0, - bytes: tensor.section_bytes, - digest: tensor.section_digest, - }, + + fn require_source_unchanged( + &self, + source_file: &File, + source_path: &Path, + ) -> Result<(), String> { + let size = source_file + .metadata() + .map_err(|error| error.to_string())? + .len(); + if size != self.index.summary.file_size || hash_file(source_path)? != self.original_digest { + return Err("GGUF source changed during F32 preparation".into()); + } + Ok(()) + } + + /// The digest and byte count the archive records for its source. + fn source_digest_and_bytes(&self) -> ([u8; 32], u64) { + self.derived_identity + .as_ref() + .map(|identity| (identity.derived_digest(), identity.derived_bytes())) + .unwrap_or((self.original_digest, self.index.summary.file_size)) + } + + fn builder(&self) -> String { + format!( + "strata-next/experimental-{}-topdown-v1:g32:l{}:sample-all", + builder_label(self.kind), + self.levels + ) + } + + fn write_archive( + &self, + destination: &Path, + staged: &StagedTensors, + ) -> Result { + let tensors = nested_tensors(&staged.prepared, self.levels); + let builder = self.builder(); + let (source_digest, source_bytes) = self.source_digest_and_bytes(); + let source = kar_writer::SourceIdentity { + name: &self.source_name, + architecture: &self.architecture, + builder: &builder, + digest: source_digest, + total_elements: staged.total_elements, + bytes: source_bytes, + }; + let archive = kar_writer::write_archive(destination, &source, &tensors)?; + let archive_digest = hash_file(destination)?; + let provenance_path = self.write_provenance(destination, archive_digest)?; + Ok(PreviewSummary { + archive, + archive_digest, + maximum_relative_l2: staged.maximum_relative_l2, + tensor_distortions: Vec::new(), + provenance_path, }) - .collect::>(); - let builder = format!( - "strata-next/experimental-{}-topdown-v1:g32:l{levels}:sample-all", - match kind { - PreviewKind::F32 => "f32", - PreviewKind::Iq3 => "iq3-derived-f32", - PreviewKind::Mixed => "mixed-derived-f32", - } - ); - let (source_digest, source_bytes) = derived_identity - .as_ref() - .map(|identity| (identity.derived_digest(), identity.derived_bytes())) - .unwrap_or((original_digest, index.summary.file_size)); - let source = kar_writer::SourceIdentity { - name: &source_name, - architecture, - builder: &builder, - digest: source_digest, - total_elements, - bytes: source_bytes, - }; - let archive = kar_writer::write_archive(destination, &source, &tensors)?; - let archive_digest = hash_file(destination)?; - let provenance_path = if let Some(identity) = derived_identity { - let path = provenance_path(destination)?; - let manifest = provenance_value(&identity, archive_digest); - if let Err(error) = write_provenance(&path, &manifest) { - let _ = fs::remove_file(destination); - return Err(error); - } - Some(path) - } else { - None - }; - Ok(PreviewSummary { - archive, - archive_digest, - maximum_relative_l2, - tensor_distortions: Vec::new(), - provenance_path, - }) + } + + fn write_provenance( + &self, + destination: &Path, + archive_digest: [u8; 32], + ) -> Result, String> { + let Some(identity) = &self.derived_identity else { + return Ok(None); + }; + let manifest = provenance_value(identity, archive_digest); + write_sibling_provenance(destination, &manifest).map(Some) + } } diff --git a/control-plane/src/prepare_preview/prepare_sharded.rs b/control-plane/src/prepare_preview/prepare_sharded.rs index adbc03a1..69708e69 100644 --- a/control-plane/src/prepare_preview/prepare_sharded.rs +++ b/control-plane/src/prepare_preview/prepare_sharded.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn prepare_sharded, fn prepare_sharded_streamed, fn prepare_sharded_streamed_ple, fn prepare_sharded_streamed_with_limit. +//! Moved out of the parent module by STRA-338: fn prepare_sharded, fn prepare_sharded_streamed, fn +//! prepare_sharded_streamed_ple, fn prepare_sharded_streamed_with_limit. #[allow(unused_imports)] use super::*; @@ -9,9 +10,16 @@ pub fn prepare_sharded( destination: &Path, levels: u8, ) -> Result { - if !(1..=8).contains(&levels) { - return Err("sharded preview requires 1..=8 KAR levels".into()); - } + require_levels(levels, "sharded preview requires 1..=8 KAR levels")?; + require_sharded_source_limit(manifest)?; + let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + require_sharded_tensor_count(&identity)?; + let staging = staging_dir(destination, "parts")?; + let encoding = encode_shards(&identity, source_dir, &staging, levels)?; + write_sharded_preview(destination, levels, &identity, &encoding) +} + +fn require_sharded_source_limit(manifest: &Manifest) -> Result<(), String> { let total_source_bytes = manifest .files .iter() @@ -20,139 +28,32 @@ pub fn prepare_sharded( if total_source_bytes > MAX_SOURCE_BYTES { return Err("sharded preview exceeds its 64 MiB source limit".into()); } - let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + Ok(()) +} + +fn require_sharded_tensor_count(identity: &derived_mixed::ShardedIdentity) -> Result<(), String> { if identity.tensors.is_empty() || identity.tensors.len() > MAX_TENSORS { return Err("sharded preview exceeds its tensor-count limit".into()); } - let staging_path = destination.with_file_name(format!( - "{}.parts-{}", - destination - .file_name() - .ok_or("KAR destination has no file name")? - .to_string_lossy(), - std::process::id() - )); - fs::create_dir(&staging_path).map_err(|error| error.to_string())?; - let staging = StagingDir(staging_path); - let mut architecture = None::; - let mut maximum_relative_l2 = 0.0f64; - let mut prepared = Vec::with_capacity(identity.tensors.len()); - let mut number = 0usize; - for shard in &identity.shards { - let path = source_dir.join(&shard.name); - let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - if let Some(shard_architecture) = index.summary.architecture.as_deref() { - if architecture - .as_deref() - .is_some_and(|expected| expected != shard_architecture) - { - return Err("GGUF shard architectures differ".into()); - } - architecture.get_or_insert_with(|| shard_architecture.to_owned()); - } - if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes - { - return Err("GGUF shard changed after identity derivation".into()); - } - let mut source = File::open(&path).map_err(|error| error.to_string())?; - for tensor in &index.tensors { - if tensor.dimensions.len() > 4 { - return Err(format!( - "{}: KAR preview supports up to four dimensions", - tensor.name - )); - } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |count, dim| count.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - if elements > MAX_TENSOR_ELEMENTS { - return Err("sharded preview exceeds its per-tensor element limit".into()); - } - let derived = &identity.tensors[number]; - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - source - .seek(SeekFrom::Start(absolute)) - .map_err(|error| error.to_string())?; - let mut raw = vec![0u8; tensor.bytes as usize]; - source - .read_exact(&mut raw) - .map_err(|error| error.to_string())?; - if derived.name != tensor.name - || derived.source_kind != tensor.kind - || Sha256::digest(&raw).as_slice() != derived.source_sha256 - || derived.derived_bytes != elements * 4 - { - return Err(format!( - "{}: sharded source tensor identity mismatch", - tensor.name - )); - } - let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; - let mut f32_digest = Sha256::new(); - for value in &weights { - f32_digest.update(value.to_le_bytes()); - } - if f32_digest.finalize().as_slice() != derived.f32_sha256 { - return Err(format!( - "{}: sharded derived F32 tensor mismatch", - tensor.name - )); - } - let section_path = staging.0.join(format!("{number:06}.section")); - let (coded, relative_l2) = encode_preview_tensor( - &tensor.name, - &tensor.dimensions, - &weights, - derived.f32_sha256, - derived.derived_offset, - §ion_path, - levels, - )?; - maximum_relative_l2 = maximum_relative_l2.max(relative_l2); - prepared.push(coded); - number += 1; - } - if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes - || hash_file(&path)? != shard.gguf_sha256 - { - return Err(format!( - "{}: GGUF shard changed during preparation", - shard.name - )); - } - } - let tensors = prepared - .iter() - .map(|tensor| kar_writer::Tensor { - name: &tensor.name, - dims: &tensor.dims, - source_dtype: 0, - source_digest: tensor.source_digest, - source_offset: tensor.source_offset, - data: kar_writer::TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: levels, - levels, - path: &tensor.section_path, - offset: 0, - bytes: tensor.section_bytes, - digest: tensor.section_digest, - }, - }) - .collect::>(); - let builder = - format!("strata-next/experimental-sharded-derived-f32-topdown-v1:g32:l{levels}:sample-all"); + Ok(()) +} + +fn sharded_builder(levels: u8) -> String { + format!("strata-next/experimental-sharded-derived-f32-topdown-v1:g32:l{levels}:sample-all") +} + +fn write_sharded_preview( + destination: &Path, + levels: u8, + identity: &derived_mixed::ShardedIdentity, + encoding: &ShardedEncoding, +) -> Result { + let tensors = nested_tensors(&encoding.prepared, levels); + let builder = sharded_builder(levels); let source = kar_writer::SourceIdentity { name: "gguf-shards#derived-f32-le-v1", - architecture: architecture + architecture: encoding + .architecture .as_deref() .ok_or("GGUF shards have no architecture")?, builder: &builder, @@ -162,18 +63,12 @@ pub fn prepare_sharded( }; let archive = kar_writer::write_archive(destination, &source, &tensors)?; let archive_digest = hash_file(destination)?; - let provenance_path = provenance_path(destination)?; - if let Err(error) = write_provenance( - &provenance_path, - &sharded_provenance_value(&identity, archive_digest), - ) { - let _ = fs::remove_file(destination); - return Err(error); - } + let provenance = sharded_provenance_value(identity, archive_digest); + let provenance_path = write_sibling_provenance(destination, &provenance)?; Ok(PreviewSummary { archive, archive_digest, - maximum_relative_l2, + maximum_relative_l2: encoding.maximum_relative_l2, tensor_distortions: Vec::new(), provenance_path: Some(provenance_path), }) diff --git a/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs b/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs index dc1cf75e..909e1ea0 100644 --- a/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs +++ b/control-plane/src/prepare_preview/prepare_sharded_streamed_with_policy.rs @@ -11,21 +11,56 @@ pub(super) fn prepare_sharded_streamed_with_policy( max_part_elements: u64, ple_part_elements: Option, ) -> Result { - if !(1..=8).contains(&levels) { - return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); - } + require_levels( + levels, + "streamed sharded preparation requires 1..=8 KAR levels", + )?; + require_free_destination(destination)?; + let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + let archive_parts = + plan_stream_parts(&identity, source_dir, max_part_elements, ple_part_elements)?; + let archive_tensor_count = archive_parts.iter().map(Vec::len).sum::(); + require_stream_budget(&archive_parts, archive_tensor_count, destination, levels)?; + let staging = staging_dir(destination, "stream-parts")?; + let run = StreamedRun { + identity: &identity, + archive_parts: &archive_parts, + source_dir, + staging: &staging, + levels, + }; + let encoding = run.encode(archive_tensor_count)?; + write_streamed_preview(destination, &run, ple_part_elements, encoding) +} + +fn require_free_destination(destination: &Path) -> Result<(), String> { if fs::symlink_metadata(destination).is_ok() || fs::symlink_metadata(provenance_path(destination)?).is_ok() { return Err("KAR archive or provenance destination already exists".into()); } - let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; - let archive_parts = if let Some(limit) = ple_part_elements { - stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)? + Ok(()) +} + +fn plan_stream_parts( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, + max_part_elements: u64, + ple_part_elements: Option, +) -> Result>, String> { + if let Some(limit) = ple_part_elements { + stream_parts::plan_shards_with_ple_limit(identity, source_dir, limit) } else { - stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)? - }; - let archive_tensor_count = archive_parts.iter().map(Vec::len).sum::(); + stream_parts::plan_shards_with_limit(identity, source_dir, max_part_elements) + } +} + +fn require_stream_budget( + archive_parts: &[Vec], + archive_tensor_count: usize, + destination: &Path, + levels: u8, +) -> Result<(), String> { if archive_tensor_count == 0 || archive_tensor_count > 100_000 { return Err("streamed sharded tensor count exceeds KAR-2 limits".into()); } @@ -45,152 +80,11 @@ pub(super) fn prepare_sharded_streamed_with_policy( .filter(|parent| !parent.as_os_str().is_empty()) .unwrap_or(Path::new(".")); model::require_space(destination_parent, minimum_payload_bytes) - .map_err(|error| format!("KAR minimum payload does not fit: {error}"))?; - let staging_path = destination.with_file_name(format!( - "{}.stream-parts-{}", - destination - .file_name() - .ok_or("KAR destination has no file name")? - .to_string_lossy(), - std::process::id() - )); - fs::create_dir(&staging_path).map_err(|error| error.to_string())?; - let staging = StagingDir(staging_path); - let mut architecture = None::; - let mut prepared = Vec::with_capacity(archive_tensor_count); - let mut maximum_relative_l2 = 0.0f64; - let mut tensor_distortions = Vec::with_capacity(archive_tensor_count); - let mut number = 0usize; - for shard in &identity.shards { - let path = source_dir.join(&shard.name); - let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; - if let Some(shard_architecture) = index.summary.architecture.as_deref() { - if architecture - .as_deref() - .is_some_and(|expected| expected != shard_architecture) - { - return Err("GGUF shard architectures differ".into()); - } - architecture.get_or_insert_with(|| shard_architecture.to_owned()); - } - if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes - { - return Err("GGUF shard changed after identity derivation".into()); - } - let mut source = File::open(&path).map_err(|error| error.to_string())?; - for tensor in &index.tensors { - if tensor.dimensions.len() > 4 { - return Err(format!( - "{}: KAR-2 supports up to four dimensions", - tensor.name - )); - } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |count, dim| count.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - let derived = &identity.tensors[number]; - if derived.name != tensor.name - || derived.source_kind != tensor.kind - || derived.derived_bytes - != elements - .checked_mul(4) - .ok_or("F32 tensor byte count overflow")? - { - return Err(format!("{}: sharded tensor identity mismatch", tensor.name)); - } - let absolute_base = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - for part in &archive_parts[number] { - let absolute = absolute_base - .checked_add(part.source_byte_offset) - .ok_or("GGUF part offset overflow")?; - let sample = kar_sample::sample_normalized( - &mut source, - absolute, - part.source_kind, - part.source_bytes, - part.derived_bytes / 4, - part.source_sha256, - kar_sample::MAX_SAMPLE_VALUES, - )?; - let calibration = kar_codec::fit_topdown(&sample, levels).ok(); - let section_path = staging.0.join(format!("{:06}.section", prepared.len())); - let (section_bytes, section_digest, nested, relative_l2) = - if let Some(calibration) = calibration { - let result = kar_stream_encode::encode_section( - &mut source, - absolute, - part.source_kind, - part.source_bytes, - part.derived_bytes / 4, - &calibration, - §ion_path, - )?; - if result.source_digest != part.source_sha256 - || result.derived_digest != part.f32_sha256 - { - return Err(format!( - "{}: streamed source or F32 digest mismatch", - part.name - )); - } - (result.bytes, result.digest, true, result.relative_l2) - } else { - let result = spool_raw_f32( - &mut source, - absolute, - part.source_kind, - part.source_bytes, - §ion_path, - )?; - if result.0 != part.source_sha256 - || result.1 != part.f32_sha256 - || result.2 != part.derived_bytes - { - return Err(format!( - "{}: streamed RAW source or F32 digest mismatch", - part.name - )); - } - (result.2, result.1, false, 0.0) - }; - maximum_relative_l2 = maximum_relative_l2.max(relative_l2); - tensor_distortions.push(TensorDistortion { - name: part.name.clone(), - relative_l2, - source_kind: part.source_kind, - section_bytes, - }); - prepared.push(StreamedTensor { - prepared: PreparedTensor { - name: part.name.clone(), - dims: part.dimensions.clone(), - source_digest: part.f32_sha256, - source_offset: part.derived_offset, - section_path, - section_bytes, - section_digest, - }, - nested, - }); - } - number += 1; - } - if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes - || hash_file(&path)? != shard.gguf_sha256 - { - return Err(format!( - "{}: GGUF shard changed during preparation", - shard.name - )); - } - } - let tensors = prepared + .map_err(|error| format!("KAR minimum payload does not fit: {error}")) +} + +fn streamed_tensors(prepared: &[StreamedTensor], levels: u8) -> Vec> { + prepared .iter() .map(|entry| { let tensor = &entry.prepared; @@ -201,17 +95,7 @@ pub(super) fn prepare_sharded_streamed_with_policy( source_digest: tensor.source_digest, source_offset: tensor.source_offset, data: if entry.nested { - kar_writer::TensorData::NestedFile { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: levels, - levels, - path: &tensor.section_path, - offset: 0, - bytes: tensor.section_bytes, - digest: tensor.section_digest, - } + nested_file_data(tensor, levels) } else { kar_writer::TensorData::RawFile { path: &tensor.section_path, @@ -221,17 +105,32 @@ pub(super) fn prepare_sharded_streamed_with_policy( }, } }) - .collect::>(); - let builder = if let Some(limit) = ple_part_elements { + .collect() +} + +fn stream_builder(levels: u8, ple_part_elements: Option) -> String { + if let Some(limit) = ple_part_elements { format!( "strata-next/experimental-sharded-stream-v5:g32:l{levels}:sample65536:plepart{limit}" ) } else { format!("strata-next/experimental-sharded-stream-v4:g32:l{levels}:sample65536") - }; + } +} + +fn write_streamed_archive( + destination: &Path, + run: &StreamedRun<'_>, + ple_part_elements: Option, + encoding: &StreamedEncoding, +) -> Result { + let identity = run.identity; + let tensors = streamed_tensors(&encoding.prepared, run.levels); + let builder = stream_builder(run.levels, ple_part_elements); let source_identity = kar_writer::SourceIdentity { name: "gguf-shards#derived-f32-le-v4", - architecture: architecture + architecture: encoding + .architecture .as_deref() .ok_or("GGUF shards have no architecture")?, builder: &builder, @@ -239,33 +138,26 @@ pub(super) fn prepare_sharded_streamed_with_policy( total_elements: identity.derived_bytes / 4, bytes: identity.derived_bytes, }; - let archive = - kar_writer::write_archive_consuming_files(destination, &source_identity, &tensors)?; + kar_writer::write_archive_consuming_files(destination, &source_identity, &tensors) +} + +fn write_streamed_preview( + destination: &Path, + run: &StreamedRun<'_>, + ple_part_elements: Option, + encoding: StreamedEncoding, +) -> Result { + let archive = write_streamed_archive(destination, run, ple_part_elements, &encoding)?; let archive_digest = hash_file(destination)?; - let provenance_path = provenance_path(destination)?; - let mut provenance = sharded_provenance_value(&identity, archive_digest); - provenance["schema"] = serde_json::json!(if ple_part_elements.is_some() { - "strata-next/sharded-stream-provenance-v5" - } else { - "strata-next/sharded-stream-provenance-v4" - }); - provenance["derivation"] = - serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); - provenance["levels"] = serde_json::json!(levels); - provenance["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); - provenance["partitioned_tensors"] = partitioned_provenance(&archive_parts); - if let Some(limit) = ple_part_elements { - provenance["ple_part_elements"] = serde_json::json!(limit); - } - if let Err(error) = write_provenance(&provenance_path, &provenance) { - let _ = fs::remove_file(destination); - return Err(error); - } + let mut provenance = sharded_provenance_value(run.identity, archive_digest); + let parts = run.archive_parts; + apply_stream_policy(&mut provenance, run.levels, parts, ple_part_elements); + let provenance_path = write_sibling_provenance(destination, &provenance)?; Ok(PreviewSummary { archive, archive_digest, - maximum_relative_l2, - tensor_distortions, + maximum_relative_l2: encoding.maximum_relative_l2, + tensor_distortions: encoding.tensor_distortions, provenance_path: Some(provenance_path), }) } diff --git a/control-plane/src/prepare_preview/preview_common.rs b/control-plane/src/prepare_preview/preview_common.rs new file mode 100644 index 00000000..fc30e280 --- /dev/null +++ b/control-plane/src/prepare_preview/preview_common.rs @@ -0,0 +1,199 @@ +//! Helpers shared by the preview preparation and verification paths (STRA-338 size-fn). + +#[allow(unused_imports)] +use super::*; + +pub(super) fn require_levels(levels: u8, message: &str) -> Result<(), String> { + if !(1..=8).contains(&levels) { + return Err(message.into()); + } + Ok(()) +} + +pub(super) fn staging_dir(destination: &Path, infix: &str) -> Result { + let staging_path = destination.with_file_name(format!( + "{}.{infix}-{}", + destination + .file_name() + .ok_or("KAR destination has no file name")? + .to_string_lossy(), + std::process::id() + )); + fs::create_dir(&staging_path).map_err(|error| error.to_string())?; + Ok(StagingDir(staging_path)) +} + +pub(super) fn tensor_elements(dimensions: &[u64]) -> Result { + let count = dimensions + .iter() + .try_fold(1u64, |count, dim| count.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + Ok(count) +} + +pub(super) fn checked_offset(base: u64, add: u64, message: &str) -> Result { + base.checked_add(add).ok_or_else(|| message.to_string()) +} + +pub(super) fn read_raw_tensor( + source: &mut File, + absolute: u64, + bytes: u64, +) -> Result, String> { + source + .seek(SeekFrom::Start(absolute)) + .map_err(|error| error.to_string())?; + let mut raw = vec![0u8; bytes as usize]; + source + .read_exact(&mut raw) + .map_err(|error| error.to_string())?; + Ok(raw) +} + +pub(super) fn f32_digest(weights: &[f32]) -> [u8; 32] { + let mut digest = Sha256::new(); + for value in weights { + digest.update(value.to_le_bytes()); + } + digest.finalize().into() +} + +pub(super) fn f32_from_le(raw: &[u8]) -> Vec { + raw.as_chunks::<4>() + .0 + .iter() + .map(|chunk| f32::from_le_bytes(*chunk)) + .collect() +} + +pub(super) fn nested_file_data(tensor: &PreparedTensor, levels: u8) -> kar_writer::TensorData<'_> { + kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: levels, + levels, + path: &tensor.section_path, + offset: 0, + bytes: tensor.section_bytes, + digest: tensor.section_digest, + } +} + +pub(super) fn nested_tensors( + prepared: &[PreparedTensor], + levels: u8, +) -> Vec> { + prepared + .iter() + .map(|tensor| kar_writer::Tensor { + name: &tensor.name, + dims: &tensor.dims, + source_dtype: 0, + source_digest: tensor.source_digest, + source_offset: tensor.source_offset, + data: nested_file_data(tensor, levels), + }) + .collect() +} + +/// A source shard opened for tensor-by-tensor preparation. +pub(super) struct OpenShard { + pub(super) path: PathBuf, + pub(super) index: gguf::TensorIndex, + pub(super) source: File, +} + +fn require_same_architecture( + architecture: &mut Option, + index: &gguf::TensorIndex, +) -> Result<(), String> { + let Some(shard_architecture) = index.summary.architecture.as_deref() else { + return Ok(()); + }; + if architecture + .as_deref() + .is_some_and(|expected| expected != shard_architecture) + { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert_with(|| shard_architecture.to_owned()); + Ok(()) +} + +pub(super) fn open_shard( + source_dir: &Path, + shard: &derived_mixed::ShardIdentity, + architecture: &mut Option, +) -> Result { + let path = source_dir.join(&shard.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + require_same_architecture(architecture, &index)?; + if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes { + return Err("GGUF shard changed after identity derivation".into()); + } + let source = File::open(&path).map_err(|error| error.to_string())?; + Ok(OpenShard { + path, + index, + source, + }) +} + +pub(super) fn require_shard_unchanged( + open: &OpenShard, + shard: &derived_mixed::ShardIdentity, +) -> Result<(), String> { + let size = open + .source + .metadata() + .map_err(|error| error.to_string())? + .len(); + if size != shard.gguf_bytes || hash_file(&open.path)? != shard.gguf_sha256 { + return Err(format!( + "{}: GGUF shard changed during preparation", + shard.name + )); + } + Ok(()) +} + +/// Adds the streamed-preparation fields shared by the writer and the verifier. +pub(super) fn apply_stream_policy( + value: &mut serde_json::Value, + levels: u8, + parts: &[Vec], + ple_part_elements: Option, +) { + value["schema"] = serde_json::json!(if ple_part_elements.is_some() { + "strata-next/sharded-stream-provenance-v5" + } else { + "strata-next/sharded-stream-provenance-v4" + }); + value["derivation"] = serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); + value["levels"] = serde_json::json!(levels); + value["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); + value["partitioned_tensors"] = partitioned_provenance(parts); + if let Some(limit) = ple_part_elements { + value["ple_part_elements"] = serde_json::json!(limit); + } +} + +pub(super) fn read_recorded_provenance(archive_path: &Path) -> Result { + let provenance = provenance_path(archive_path)?; + let file = File::open(provenance).map_err(|error| error.to_string())?; + serde_json::from_reader(file).map_err(|error| error.to_string()) +} + +/// Writes the provenance next to the archive and removes the archive when that fails. +pub(super) fn write_sibling_provenance( + destination: &Path, + provenance: &serde_json::Value, +) -> Result { + let path = provenance_path(destination)?; + if let Err(error) = write_provenance(&path, provenance) { + let _ = fs::remove_file(destination); + return Err(error); + } + Ok(path) +} diff --git a/control-plane/src/prepare_preview/sharded_encode.rs b/control-plane/src/prepare_preview/sharded_encode.rs new file mode 100644 index 00000000..3c29061c --- /dev/null +++ b/control-plane/src/prepare_preview/sharded_encode.rs @@ -0,0 +1,123 @@ +//! Tensor-by-tensor encoding of the sharded preview (STRA-338 size-fn). + +#[allow(unused_imports)] +use super::*; + +pub(super) struct ShardedEncoding { + pub(super) prepared: Vec, + pub(super) architecture: Option, + pub(super) maximum_relative_l2: f64, +} + +pub(super) fn encode_shards( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, + staging: &StagingDir, + levels: u8, +) -> Result { + let mut encoding = ShardedEncoding { + prepared: Vec::with_capacity(identity.tensors.len()), + architecture: None, + maximum_relative_l2: 0.0, + }; + let mut number = 0usize; + for shard in &identity.shards { + let mut open = open_shard(source_dir, shard, &mut encoding.architecture)?; + let data_start = open.index.summary.data_start; + for tensor in &open.index.tensors { + let section_path = staging.0.join(format!("{number:06}.section")); + let derived = TensorSlot::new(&identity.tensors, number, data_start); + let (coded, relative_l2) = + encode_sharded_tensor(&mut open.source, tensor, &derived, §ion_path, levels)?; + encoding.maximum_relative_l2 = encoding.maximum_relative_l2.max(relative_l2); + encoding.prepared.push(coded); + number += 1; + } + require_shard_unchanged(&open, shard)?; + } + Ok(encoding) +} + +/// Where a shard tensor sits in the derived identity and in the shard file. +struct TensorSlot<'a> { + tensors: &'a [derived_mixed::TensorIdentity], + number: usize, + data_start: u64, +} + +impl<'a> TensorSlot<'a> { + fn new(tensors: &'a [derived_mixed::TensorIdentity], number: usize, data_start: u64) -> Self { + Self { + tensors, + number, + data_start, + } + } +} + +fn require_preview_shape(tensor: &gguf::TensorInfo) -> Result { + if tensor.dimensions.len() > 4 { + return Err(format!( + "{}: KAR preview supports up to four dimensions", + tensor.name + )); + } + let elements = tensor_elements(&tensor.dimensions)?; + if elements > MAX_TENSOR_ELEMENTS { + return Err("sharded preview exceeds its per-tensor element limit".into()); + } + Ok(elements) +} + +fn decode_sharded_tensor( + tensor: &gguf::TensorInfo, + derived: &derived_mixed::TensorIdentity, + raw: &[u8], + elements: u64, +) -> Result, String> { + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || Sha256::digest(raw).as_slice() != derived.source_sha256 + || derived.derived_bytes != elements * 4 + { + return Err(format!( + "{}: sharded source tensor identity mismatch", + tensor.name + )); + } + let weights = decode_source_tensor(tensor.kind, raw, elements as usize)?; + if f32_digest(&weights) != derived.f32_sha256 { + return Err(format!( + "{}: sharded derived F32 tensor mismatch", + tensor.name + )); + } + Ok(weights) +} + +fn encode_sharded_tensor( + source: &mut File, + tensor: &gguf::TensorInfo, + slot: &TensorSlot<'_>, + section_path: &Path, + levels: u8, +) -> Result<(PreparedTensor, f64), String> { + let elements = require_preview_shape(tensor)?; + let derived = &slot.tensors[slot.number]; + let absolute = checked_offset( + slot.data_start, + tensor.offset, + "GGUF tensor offset overflow", + )?; + let raw = read_raw_tensor(source, absolute, tensor.bytes)?; + let weights = decode_sharded_tensor(tensor, derived, &raw, elements)?; + encode_preview_tensor( + &tensor.name, + &tensor.dimensions, + &weights, + derived.f32_sha256, + derived.derived_offset, + section_path, + levels, + ) +} diff --git a/control-plane/src/prepare_preview/spool_raw_f32.rs b/control-plane/src/prepare_preview/spool_raw_f32.rs index f116b78f..7c36983a 100644 --- a/control-plane/src/prepare_preview/spool_raw_f32.rs +++ b/control-plane/src/prepare_preview/spool_raw_f32.rs @@ -15,36 +15,48 @@ pub(super) fn spool_raw_f32( .create_new(true) .open(path) .map_err(|error| error.to_string())?; - let result = (|| { - let mut writer = BufWriter::new(file); - let mut source_hash = Sha256::new(); - let mut derived_hash = Sha256::new(); - let bytes = gguf_f32_stream::visit( - reader, - absolute, - source_kind, - source_bytes, - |raw, f32_bytes| { - source_hash.update(raw); - derived_hash.update(f32_bytes); - writer - .write_all(f32_bytes) - .map_err(|error| error.to_string()) - }, - )?; - writer.flush().map_err(|error| error.to_string())?; - writer - .get_ref() - .sync_all() - .map_err(|error| error.to_string())?; - Ok(( - source_hash.finalize().into(), - derived_hash.finalize().into(), - bytes, - )) - })(); + let result = write_raw_f32(reader, absolute, source_kind, source_bytes, file); if result.is_err() { let _ = fs::remove_file(path); } result } + +fn write_raw_f32( + reader: &mut R, + absolute: u64, + source_kind: u32, + source_bytes: u64, + file: File, +) -> Result<([u8; 32], [u8; 32], u64), String> { + let mut writer = BufWriter::new(file); + let mut source_hash = Sha256::new(); + let mut derived_hash = Sha256::new(); + let bytes = gguf_f32_stream::visit( + reader, + absolute, + source_kind, + source_bytes, + |raw, f32_bytes| { + source_hash.update(raw); + derived_hash.update(f32_bytes); + writer + .write_all(f32_bytes) + .map_err(|error| error.to_string()) + }, + )?; + finish_writer(writer)?; + Ok(( + source_hash.finalize().into(), + derived_hash.finalize().into(), + bytes, + )) +} + +fn finish_writer(mut writer: BufWriter) -> Result<(), String> { + writer.flush().map_err(|error| error.to_string())?; + writer + .get_ref() + .sync_all() + .map_err(|error| error.to_string()) +} diff --git a/control-plane/src/prepare_preview/streamed_encode.rs b/control-plane/src/prepare_preview/streamed_encode.rs new file mode 100644 index 00000000..2cb608ba --- /dev/null +++ b/control-plane/src/prepare_preview/streamed_encode.rs @@ -0,0 +1,210 @@ +//! Part-by-part encoding of the streamed sharded preview (STRA-338 size-fn). + +#[allow(unused_imports)] +use super::*; + +type Parts = [Vec]; + +pub(super) struct StreamedEncoding { + pub(super) prepared: Vec, + pub(super) architecture: Option, + pub(super) maximum_relative_l2: f64, + pub(super) tensor_distortions: Vec, +} + +pub(super) struct StreamedRun<'a> { + pub(super) identity: &'a derived_mixed::ShardedIdentity, + pub(super) archive_parts: &'a Parts, + pub(super) source_dir: &'a Path, + pub(super) staging: &'a StagingDir, + pub(super) levels: u8, +} + +/// The encoded section of one part, before it is recorded. +struct EncodedPart { + section_bytes: u64, + section_digest: [u8; 32], + nested: bool, + relative_l2: f64, +} + +impl StreamedEncoding { + fn record( + &mut self, + part: &stream_parts::PartIdentity, + section_path: PathBuf, + done: EncodedPart, + ) { + self.maximum_relative_l2 = self.maximum_relative_l2.max(done.relative_l2); + self.tensor_distortions.push(TensorDistortion { + name: part.name.clone(), + relative_l2: done.relative_l2, + source_kind: part.source_kind, + section_bytes: done.section_bytes, + }); + self.prepared.push(StreamedTensor { + prepared: PreparedTensor { + name: part.name.clone(), + dims: part.dimensions.clone(), + source_digest: part.f32_sha256, + source_offset: part.derived_offset, + section_path, + section_bytes: done.section_bytes, + section_digest: done.section_digest, + }, + nested: done.nested, + }); + } +} + +impl StreamedRun<'_> { + pub(super) fn encode(&self, archive_tensor_count: usize) -> Result { + let mut encoding = StreamedEncoding { + prepared: Vec::with_capacity(archive_tensor_count), + architecture: None, + maximum_relative_l2: 0.0, + tensor_distortions: Vec::with_capacity(archive_tensor_count), + }; + let mut number = 0usize; + for shard in &self.identity.shards { + let mut open = open_shard(self.source_dir, shard, &mut encoding.architecture)?; + let data_start = open.index.summary.data_start; + for tensor in &open.index.tensors { + let base = self.tensor_base(tensor, number, data_start)?; + self.encode_tensor_parts(&mut open.source, &mut encoding, number, base)?; + number += 1; + } + require_shard_unchanged(&open, shard)?; + } + Ok(encoding) + } + + /// Checks the tensor against its identity and returns its absolute file offset. + fn tensor_base( + &self, + tensor: &gguf::TensorInfo, + number: usize, + data_start: u64, + ) -> Result { + if tensor.dimensions.len() > 4 { + return Err(format!( + "{}: KAR-2 supports up to four dimensions", + tensor.name + )); + } + let elements = tensor_elements(&tensor.dimensions)?; + let derived = &self.identity.tensors[number]; + let derived_bytes = elements + .checked_mul(4) + .ok_or("F32 tensor byte count overflow"); + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || derived.derived_bytes != derived_bytes? + { + return Err(format!("{}: sharded tensor identity mismatch", tensor.name)); + } + checked_offset(data_start, tensor.offset, "GGUF tensor offset overflow") + } + + fn encode_tensor_parts( + &self, + source: &mut File, + encoding: &mut StreamedEncoding, + number: usize, + base: u64, + ) -> Result<(), String> { + for part in &self.archive_parts[number] { + let absolute = + checked_offset(base, part.source_byte_offset, "GGUF part offset overflow")?; + let section_path = self + .staging + .0 + .join(format!("{:06}.section", encoding.prepared.len())); + let done = encode_part(source, absolute, part, §ion_path, self.levels)?; + encoding.record(part, section_path, done); + } + Ok(()) + } +} + +fn encode_part( + source: &mut File, + absolute: u64, + part: &stream_parts::PartIdentity, + section_path: &Path, + levels: u8, +) -> Result { + let sample = kar_sample::sample_normalized( + source, + absolute, + part.source_kind, + part.source_bytes, + part.derived_bytes / 4, + part.source_sha256, + kar_sample::MAX_SAMPLE_VALUES, + )?; + match kar_codec::fit_topdown(&sample, levels).ok() { + Some(calibration) => encode_nested_part(source, absolute, part, &calibration, section_path), + None => encode_raw_part(source, absolute, part, section_path), + } +} + +fn encode_nested_part( + source: &mut File, + absolute: u64, + part: &stream_parts::PartIdentity, + calibration: &kar_codec::Calibration, + section_path: &Path, +) -> Result { + let result = kar_stream_encode::encode_section( + source, + absolute, + part.source_kind, + part.source_bytes, + part.derived_bytes / 4, + calibration, + section_path, + )?; + if result.source_digest != part.source_sha256 || result.derived_digest != part.f32_sha256 { + return Err(format!( + "{}: streamed source or F32 digest mismatch", + part.name + )); + } + Ok(EncodedPart { + section_bytes: result.bytes, + section_digest: result.digest, + nested: true, + relative_l2: result.relative_l2, + }) +} + +fn encode_raw_part( + source: &mut File, + absolute: u64, + part: &stream_parts::PartIdentity, + section_path: &Path, +) -> Result { + let result = spool_raw_f32( + source, + absolute, + part.source_kind, + part.source_bytes, + section_path, + )?; + if result.0 != part.source_sha256 + || result.1 != part.f32_sha256 + || result.2 != part.derived_bytes + { + return Err(format!( + "{}: streamed RAW source or F32 digest mismatch", + part.name + )); + } + Ok(EncodedPart { + section_bytes: result.2, + section_digest: result.1, + nested: false, + relative_l2: 0.0, + }) +} diff --git a/control-plane/src/prepare_preview/tests/convert.rs b/control-plane/src/prepare_preview/tests/convert.rs index 5f151b0b..0d58729e 100644 --- a/control-plane/src/prepare_preview/tests/convert.rs +++ b/control-plane/src/prepare_preview/tests/convert.rs @@ -1,7 +1,7 @@ //! Volume preflight, f32 tensor conversion and the refusal of quantized sources. use super::super::*; -use super::fixtures::string; +use super::fixtures::{align_data, header_with_arch, string, tensor_entry}; #[test] fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { @@ -14,28 +14,50 @@ fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { assert!(minimum_part_payload_bytes(u64::MAX, 8).is_err()); } -#[test] -fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&2u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); +fn two_f32_source() -> Vec { + let mut gguf = header_with_arch(2); for (name, offset) in [("first", 0u64), ("second", 128)] { - string(&mut gguf, name); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&32u64.to_le_bytes()); - gguf.extend_from_slice(&0u32.to_le_bytes()); - gguf.extend_from_slice(&offset.to_le_bytes()); + tensor_entry(&mut gguf, name, 32, 0, offset); } - let data_start = gguf.len().div_ceil(32) * 32; - gguf.resize(data_start, 0); + align_data(&mut gguf); for index in 0..64 { let value = [-1.0f32, -0.25, 0.25, 1.0][index % 4]; gguf.extend_from_slice(&value.to_le_bytes()); } + gguf +} + +fn staging_of(output: &Path) -> PathBuf { + output.with_file_name(format!( + "{}.parts-{}", + output.file_name().unwrap().to_string_lossy(), + std::process::id() + )) +} + +fn assert_nan_tensor_is_refused(gguf: &[u8]) { + let failed_source = + std::env::temp_dir().join(format!("strata-preview-bad-{}.gguf", std::process::id())); + let failed_output = + std::env::temp_dir().join(format!("strata-preview-bad-{}.kar", std::process::id())); + let _ = fs::remove_file(&failed_output); + let mut broken = gguf.to_vec(); + let last = broken.len() - 4; + broken[last..].copy_from_slice(&f32::NAN.to_le_bytes()); + fs::write(&failed_source, broken).unwrap(); + assert!( + prepare_f32(&failed_source, &failed_output, 2) + .unwrap_err() + .contains("invalid KAR normalization input") + ); + assert!(!failed_output.exists()); + assert!(!staging_of(&failed_output).exists()); + fs::remove_file(failed_source).unwrap(); +} + +#[test] +fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() { + let gguf = two_f32_source(); let source_path = std::env::temp_dir().join(format!("strata-preview-{}.gguf", std::process::id())); let output = std::env::temp_dir().join(format!("strata-preview-{}.kar", std::process::id())); @@ -50,36 +72,10 @@ fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() { hash_file(&source_path).unwrap() ); assert_eq!(summary.archive_digest, hash_file(&output).unwrap()); - let staging = output.with_file_name(format!( - "{}.parts-{}", - output.file_name().unwrap().to_string_lossy(), - std::process::id() - )); - assert!(!staging.exists()); + assert!(!staging_of(&output).exists()); assert!(prepare_f32(&source_path, &output, 2).is_err()); - assert!(!staging.exists()); - let failed_source = - std::env::temp_dir().join(format!("strata-preview-bad-{}.gguf", std::process::id())); - let failed_output = - std::env::temp_dir().join(format!("strata-preview-bad-{}.kar", std::process::id())); - let _ = fs::remove_file(&failed_output); - let mut broken = gguf.clone(); - let last = broken.len() - 4; - broken[last..].copy_from_slice(&f32::NAN.to_le_bytes()); - fs::write(&failed_source, broken).unwrap(); - assert!( - prepare_f32(&failed_source, &failed_output, 2) - .unwrap_err() - .contains("invalid KAR normalization input") - ); - assert!(!failed_output.exists()); - let failed_staging = failed_output.with_file_name(format!( - "{}.parts-{}", - failed_output.file_name().unwrap().to_string_lossy(), - std::process::id() - )); - assert!(!failed_staging.exists()); - fs::remove_file(failed_source).unwrap(); + assert!(!staging_of(&output).exists()); + assert_nan_tensor_is_refused(&gguf); fs::remove_file(&output).unwrap(); fs::remove_file(&source_path).unwrap(); } diff --git a/control-plane/src/prepare_preview/tests/fixtures.rs b/control-plane/src/prepare_preview/tests/fixtures.rs index fb92d4bb..82ed37e5 100644 --- a/control-plane/src/prepare_preview/tests/fixtures.rs +++ b/control-plane/src/prepare_preview/tests/fixtures.rs @@ -1,5 +1,8 @@ //! Builders and helpers shared by the tests of the sibling modules. +use super::super::*; +use crate::model::ModelFile; + pub(in super::super) fn string(out: &mut Vec, value: &str) { out.extend_from_slice(&(value.len() as u64).to_le_bytes()); out.extend_from_slice(value.as_bytes()); @@ -34,3 +37,79 @@ pub(in super::super) fn one_shard_with_arch( gguf.extend_from_slice(payload); gguf } + +/// A GGUF header with `tensors` tensor entries to come and the architecture key. +pub(in super::super) fn header_with_arch(tensors: u64) -> Vec { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&tensors.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + gguf +} + +pub(in super::super) fn tensor_entry( + gguf: &mut Vec, + name: &str, + elements: u64, + kind: u32, + offset: u64, +) { + string(gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&elements.to_le_bytes()); + gguf.extend_from_slice(&kind.to_le_bytes()); + gguf.extend_from_slice(&offset.to_le_bytes()); +} + +/// Pads the header to the 32-byte data alignment and returns the data start. +pub(in super::super) fn align_data(gguf: &mut Vec) -> usize { + let data_start = gguf.len().div_ceil(32) * 32; + gguf.resize(data_start, 0); + data_start +} + +/// An IQ3_S block with a fixed non-trivial bit pattern. +pub(in super::super) fn iq3_pattern_block() -> [u8; iq3_s::BLOCK_BYTES] { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in block[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + block[74] = 0x55; + block +} + +pub(in super::super) fn pinned_file(name: &str, url: &str, bytes: &[u8]) -> ModelFile { + ModelFile { + name: name.into(), + url: url.into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(bytes)), + } +} + +/// Writes the shards into `directory` and pins them in a manifest. +pub(in super::super) fn write_manifest(directory: &Path, shards: Vec<(&str, Vec)>) -> Manifest { + let files = shards + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + pinned_file(name, "https://example.invalid/source", &bytes) + }) + .collect(); + Manifest { + schema_version: 1, + files, + } +} + +/// A fresh scratch directory named after the test and the process. +pub(in super::super) fn scratch_dir(label: &str) -> PathBuf { + let directory = std::env::temp_dir().join(format!("{label}-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + directory +} diff --git a/control-plane/src/prepare_preview/tests/overlay.rs b/control-plane/src/prepare_preview/tests/overlay.rs index edb18594..3a193472 100644 --- a/control-plane/src/prepare_preview/tests/overlay.rs +++ b/control-plane/src/prepare_preview/tests/overlay.rs @@ -1,34 +1,20 @@ //! Streamed preparation of unsplittable tensors and the selected overlay. use super::super::*; -use super::fixtures::{one_shard, one_shard_with_arch}; -use crate::model::ModelFile; +use super::fixtures::{one_shard, one_shard_with_arch, scratch_dir, write_manifest}; + +/// An IQ3_S shard and a kind-20 shard that cannot be split or calibrated. +fn unsplittable_shards(directory: &Path) -> Manifest { + let first = one_shard_with_arch("a", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], true); + let second = one_shard_with_arch("b", 20, 32, &[0u8; 18], false); + write_manifest(directory, vec![("a.gguf", first), ("b.gguf", second)]) +} #[cfg(unix)] // archive preparation is an offline Unix tool #[test] fn streamed_preparation_keeps_unsplittable_tensors_exact() { - let directory = std::env::temp_dir().join(format!("strata-stream-raw-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); - let mut files = Vec::new(); - for (name, kind, elements, payload) in [ - ("a", 21, 256, vec![0u8; iq3_s::BLOCK_BYTES]), - ("b", 20, 32, vec![0u8; 18]), - ] { - let bytes = one_shard_with_arch(name, kind, elements, &payload, name == "a"); - let filename = format!("{name}.gguf"); - fs::write(directory.join(&filename), &bytes).unwrap(); - files.push(ModelFile { - name: filename, - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - }); - } - let manifest = Manifest { - schema_version: 1, - files, - }; + let directory = scratch_dir("strata-stream-raw"); + let manifest = unsplittable_shards(&directory); let archive = directory.join("raw.kar"); let result = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); assert_eq!(result.archive.max_planes, 0); @@ -50,19 +36,13 @@ fn streamed_preparation_keeps_unsplittable_tensors_exact() { .iter() .all(|record| record.relative_l2 == 0.0) ); - assert_eq!( - verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), - result.archive - ); + let verified = verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); + assert_eq!(verified, result.archive); fs::remove_dir_all(directory).unwrap(); } -#[cfg(unix)] // archive preparation is an offline Unix tool -#[test] -fn selected_overlay_reconstructs_source_and_cleans_staging() { - let directory = std::env::temp_dir().join(format!("strata-overlay-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); +/// A dense shard of 256 ramp values and an IQ3_S shard; returns the values. +fn overlay_shards(directory: &Path) -> (Manifest, Vec) { let values = (0..256) .map(|index| (index as f32 - 127.5) / 128.0) .collect::>(); @@ -70,86 +50,84 @@ fn selected_overlay_reconstructs_source_and_cleans_staging() { .iter() .flat_map(|value| value.to_le_bytes()) .collect::>(); - let files = [ + let extra = one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false); + let shards = vec![ ("a.gguf", one_shard("dense", 0, 256, &dense)), - ( - "b.gguf", - one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false), - ), - ] - .into_iter() - .map(|(name, bytes)| { - fs::write(directory.join(name), &bytes).unwrap(); - ModelFile { - name: name.into(), - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - } - }) - .collect(); - let manifest = Manifest { - schema_version: 1, - files, - }; - let base = directory.join("base.kar"); - let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap(); + ("b.gguf", extra), + ]; + (write_manifest(directory, shards), values) +} + +fn write_overlay_policy(directory: &Path, archive_digest: [u8; 32]) -> PathBuf { let policy = directory.join("candidates.json"); fs::write( &policy, serde_json::to_vec(&serde_json::json!({ "schema": "strata-next/proposed-kar-precision-candidates-v1", - "source_archive_sha256": hex::encode(prepared.archive_digest), + "source_archive_sha256": hex::encode(archive_digest), "proposed_levels": 3, "records": [{"name": "dense", "elements": 256}], })) .unwrap(), ) .unwrap(); - let overlay = directory.join("overlay.kar"); - let result = - crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap(); - assert_eq!(result.record_count, 1); - assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3); - assert!(result.maximum_relative_l2.is_finite()); - let decoded = kar::decode_preview_tensor(&overlay, "dense", 3).unwrap(); + policy +} + +fn assert_overlay_reconstructs(overlay: &Path, values: &[f32], maximum_relative_l2: f64) { + let decoded = kar::decode_preview_tensor(overlay, "dense", 3).unwrap(); let error_sum = decoded .iter() - .zip(&values) + .zip(values) .map(|(actual, expected)| f64::from(actual - expected).powi(2)) .sum::(); let reference_sum = values .iter() .map(|value| f64::from(*value).powi(2)) .sum::(); - assert!(((error_sum / reference_sum).sqrt() - result.maximum_relative_l2).abs() < 1e-7); - assert!(result.provenance_path.exists()); - let comparison = crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap(); - assert_eq!(comparison.records.len(), 1); - assert_eq!(comparison.records[0].name, "dense"); - let selection = crate::kar_overlay::resolve_verified(&base, &overlay).unwrap(); + assert!(((error_sum / reference_sum).sqrt() - maximum_relative_l2).abs() < 1e-7); +} + +fn assert_overlay_selection(base: &Path, overlay: &Path) { + let selection = crate::kar_overlay::resolve_verified(base, overlay).unwrap(); assert_eq!(selection.replacement_count, 1); assert_eq!(selection.records.len(), 2); assert_eq!(selection.records[0].name, "dense"); assert_eq!(selection.records[0].archive, "overlay"); assert_eq!(selection.records[1].archive, "base"); +} + +fn corrupt_overlay_provenance(provenance_path: &Path) { let mut provenance: serde_json::Value = - serde_json::from_slice(&fs::read(&result.provenance_path).unwrap()).unwrap(); + serde_json::from_slice(&fs::read(provenance_path).unwrap()).unwrap(); provenance["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32)); - fs::write( - &result.provenance_path, - serde_json::to_vec(&provenance).unwrap(), - ) - .unwrap(); + fs::write(provenance_path, serde_json::to_vec(&provenance).unwrap()).unwrap(); +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[test] +fn selected_overlay_reconstructs_source_and_cleans_staging() { + let directory = scratch_dir("strata-overlay"); + let (manifest, values) = overlay_shards(&directory); + let base = directory.join("base.kar"); + let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap(); + let policy = write_overlay_policy(&directory, prepared.archive_digest); + let overlay = directory.join("overlay.kar"); + let result = + crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap(); + assert_eq!(result.record_count, 1); + assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3); + assert!(result.maximum_relative_l2.is_finite()); + assert_overlay_reconstructs(&overlay, &values, result.maximum_relative_l2); + assert!(result.provenance_path.exists()); + let comparison = crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap(); + assert_eq!(comparison.records.len(), 1); + assert_eq!(comparison.records[0].name, "dense"); + assert_overlay_selection(&base, &overlay); + corrupt_overlay_provenance(&result.provenance_path); assert!(crate::kar_overlay::resolve_verified(&base, &overlay).is_err()); assert!((comparison.records[0].overlay_relative_l2 - result.maximum_relative_l2).abs() < 1e-7); - assert!( - !directory - .join(format!( - "overlay.kar.overlay-sections-{}", - std::process::id() - )) - .exists() - ); + let staging = format!("overlay.kar.overlay-sections-{}", std::process::id()); + assert!(!directory.join(staging).exists()); fs::remove_dir_all(directory).unwrap(); } diff --git a/control-plane/src/prepare_preview/tests/ple_partition.rs b/control-plane/src/prepare_preview/tests/ple_partition.rs index 078d819e..e602d3ad 100644 --- a/control-plane/src/prepare_preview/tests/ple_partition.rs +++ b/control-plane/src/prepare_preview/tests/ple_partition.rs @@ -1,8 +1,7 @@ //! The versioned PLE partition policy. use super::super::*; -use super::fixtures::{one_shard_with_arch, string}; -use crate::model::ModelFile; +use super::fixtures::{one_shard_with_arch, string, write_manifest}; fn ple_shard(payload: &[u8]) -> Vec { let mut gguf = b"GGUF".to_vec(); @@ -23,9 +22,8 @@ fn ple_shard(payload: &[u8]) -> Vec { gguf } -#[cfg(unix)] // archive preparation is an offline Unix tool -#[test] -fn ple_partition_policy_is_versioned_and_verified() { +/// A fresh directory that is unique per call, not only per process. +fn unique_directory() -> PathBuf { let directory = std::env::temp_dir().join(format!( "strata-ple-parts-{}-{}", std::process::id(), @@ -35,6 +33,11 @@ fn ple_partition_policy_is_versioned_and_verified() { .as_nanos() )); fs::create_dir(&directory).unwrap(); + directory +} + +/// A PLE shard, a dense shard and an IQ3_S shard. +fn ple_manifest(directory: &Path) -> Manifest { let ple_values = (0..512) .flat_map(|index| ((index as f32 - 255.5) / 256.0).to_le_bytes()) .collect::>(); @@ -44,7 +47,7 @@ fn ple_partition_policy_is_versioned_and_verified() { .map(|index| (index as f32 - 127.5) / 128.0) .flat_map(f32::to_le_bytes) .collect::>(); - let files = [ + let shards = vec![ ("a-ple.gguf", ple_shard(&ple_values)), ( "m-dense.gguf", @@ -54,33 +57,13 @@ fn ple_partition_policy_is_versioned_and_verified() { "z-expert.gguf", one_shard_with_arch("expert", 21, 256, &block, false), ), - ] - .into_iter() - .map(|(name, bytes)| { - fs::write(directory.join(name), &bytes).unwrap(); - ModelFile { - name: name.into(), - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - } - }) - .collect(); - let manifest = Manifest { - schema_version: 1, - files, - }; - let archive = directory.join("ple.kar"); - let prepared = prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); - assert_eq!(prepared.archive.tensor_count, 6); - assert_eq!( - verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(), - prepared.archive - ); - assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); - assert!(verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 256).is_err()); + ]; + write_manifest(directory, shards) +} + +fn assert_ple_record(provenance_path: PathBuf) { let provenance: serde_json::Value = - serde_json::from_slice(&fs::read(prepared.provenance_path.unwrap()).unwrap()).unwrap(); + serde_json::from_slice(&fs::read(provenance_path).unwrap()).unwrap(); assert_eq!( provenance["schema"], "strata-next/sharded-stream-provenance-v5" @@ -93,12 +76,15 @@ fn ple_partition_policy_is_versioned_and_verified() { .len(), 4 ); +} + +fn write_ple_policy(directory: &Path, archive_digest: [u8; 32]) -> PathBuf { let policy = directory.join("candidates.json"); fs::write( &policy, serde_json::to_vec(&serde_json::json!({ "schema": "strata-next/proposed-kar-precision-candidates-v1", - "source_archive_sha256": hex::encode(prepared.archive_digest), + "source_archive_sha256": hex::encode(archive_digest), "proposed_levels": 3, "records": [ {"name": "dense", "elements": 256}, @@ -108,12 +94,14 @@ fn ple_partition_policy_is_versioned_and_verified() { .unwrap(), ) .unwrap(); - let overlay = directory.join("overlay.kar"); - crate::kar_overlay::prepare(&manifest, &directory, &archive, &policy, &overlay).unwrap(); - let selection = crate::kar_overlay::resolve_verified(&archive, &overlay).unwrap(); + policy +} + +fn assert_selected_memory(archive: &Path, overlay: &Path) { + let selection = crate::kar_overlay::resolve_verified(archive, overlay).unwrap(); assert_eq!(selection.replacement_count, 2); assert_eq!(selection.records.len(), 6); - let memory = crate::kar_memory::plan_selected(&archive, &overlay, 2, 3, 1 << 20).unwrap(); + let memory = crate::kar_memory::plan_selected(archive, overlay, 2, 3, 1 << 20).unwrap(); assert_eq!(memory.record_count, 6); assert_eq!(memory.replacement_count, 2); assert!(memory.selected_overlay_compressed_bytes > 0); @@ -129,15 +117,38 @@ fn ple_partition_policy_is_versioned_and_verified() { memory.selected_compressed_bytes, memory.selected_base_compressed_bytes + memory.selected_overlay_compressed_bytes ); - let comparison = - crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).unwrap(); - assert_eq!(comparison.records.len(), 2); - assert_eq!(comparison.records[1].elements, 128); +} + +fn corrupt_sidecar_part_offset(archive: &Path) { let sidecar = archive.with_file_name("ple.kar.provenance.json"); let mut corrupted: serde_json::Value = serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap(); corrupted["partitioned_tensors"][0]["parts"][0]["source_byte_offset"] = 4.into(); fs::write(&sidecar, serde_json::to_vec(&corrupted).unwrap()).unwrap(); +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[test] +fn ple_partition_policy_is_versioned_and_verified() { + let directory = unique_directory(); + let manifest = ple_manifest(&directory); + let archive = directory.join("ple.kar"); + let prepared = prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); + assert_eq!(prepared.archive.tensor_count, 6); + let verified = verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); + assert_eq!(verified, prepared.archive); + assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); + assert!(verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 256).is_err()); + assert_ple_record(prepared.provenance_path.unwrap()); + let policy = write_ple_policy(&directory, prepared.archive_digest); + let overlay = directory.join("overlay.kar"); + crate::kar_overlay::prepare(&manifest, &directory, &archive, &policy, &overlay).unwrap(); + assert_selected_memory(&archive, &overlay); + let comparison = + crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).unwrap(); + assert_eq!(comparison.records.len(), 2); + assert_eq!(comparison.records[1].elements, 128); + corrupt_sidecar_part_offset(&archive); assert!(crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).is_err()); fs::remove_dir_all(directory).unwrap(); } diff --git a/control-plane/src/prepare_preview/tests/sharded.rs b/control-plane/src/prepare_preview/tests/sharded.rs index 7f49d19b..f1bef9a1 100644 --- a/control-plane/src/prepare_preview/tests/sharded.rs +++ b/control-plane/src/prepare_preview/tests/sharded.rs @@ -1,81 +1,56 @@ //! Manifest-pinned sharded previews and the partitioned archive round trip. use super::super::*; -use super::fixtures::{one_shard, one_shard_with_arch}; -use crate::model::ModelFile; +use super::fixtures::{ + iq3_pattern_block, one_shard, one_shard_with_arch, pinned_file, scratch_dir, write_manifest, +}; -#[cfg(unix)] // archive preparation is an offline Unix tool -#[tokio::test] -async fn prepares_and_verifies_manifest_pinned_sharded_preview() { - let directory = - std::env::temp_dir().join(format!("strata-preview-shards-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); +/// A dense F32 shard and an IQ3_S shard, pinned with the IQ3_S shard first. +fn mixed_shards(directory: &Path) -> (Manifest, Vec, Vec) { let mut dense = Vec::new(); for index in 0..32 { dense.extend_from_slice(&[-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()); } let f32 = one_shard("dense", 0, 32, &dense); - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in block[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } - block[74] = 0x55; - let iq3 = one_shard_with_arch("expert", 21, 256, &block, false); + let iq3 = one_shard_with_arch("expert", 21, 256, &iq3_pattern_block(), false); fs::write(directory.join("a-f32.gguf"), &f32).unwrap(); fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap(); - let mut manifest = Manifest { + let manifest = Manifest { schema_version: 1, files: vec![ - ModelFile { - name: "z-iq3.gguf".into(), - url: "https://example.invalid/z".into(), - size: iq3.len() as u64, - sha256: hex::encode(Sha256::digest(&iq3)), - }, - ModelFile { - name: "a-f32.gguf".into(), - url: "https://example.invalid/a".into(), - size: f32.len() as u64, - sha256: hex::encode(Sha256::digest(&f32)), - }, + pinned_file("z-iq3.gguf", "https://example.invalid/z", &iq3), + pinned_file("a-f32.gguf", "https://example.invalid/a", &f32), ], }; - let output = directory.join("sharded.kar"); - let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); - let result = prepare_sharded(&manifest, &directory, &output, 2).unwrap(); - assert_eq!(result.archive.tensor_count, 2); - assert_eq!(result.archive.source_digest, identity.derived_sha256); - assert_eq!(result.archive.source_bytes, identity.derived_bytes); - assert_eq!( - verify_sharded(&manifest, &directory, &output).unwrap(), - result.archive - ); + (manifest, dense, iq3) +} + +async fn assert_pipeline_reuses(manifest: &Manifest, directory: &Path, output: &Path) { + let reused = crate::model_pipeline::ensure_sharded_preview(manifest, directory, output, 2) + .await + .unwrap(); assert!(matches!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) - .await - .unwrap(), + reused, crate::model_pipeline::PreviewOutcome::Reused(_) )); - assert!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 3) - .await - .is_err() - ); + let other_levels = + crate::model_pipeline::ensure_sharded_preview(manifest, directory, output, 3); + assert!(other_levels.await.is_err()); +} + +fn assert_sharded_record(provenance_path: PathBuf) { let record: serde_json::Value = - serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); + serde_json::from_slice(&fs::read(provenance_path).unwrap()).unwrap(); assert_eq!( record["schema"], "strata-next/sharded-preview-provenance-v1" ); assert_eq!(record["shards"][0]["name"], "a-f32.gguf"); assert_eq!(record["tensors"][1]["derived_offset"], 128); - let streamed_output = directory.join("streamed.kar"); - let streamed = prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(); - assert_eq!(streamed.archive.source_digest, identity.derived_sha256); - assert_eq!(streamed.archive.tensor_count, 2); - let decoded = kar::decode_preview_tensor(&streamed_output, "dense", 2).unwrap(); +} + +fn assert_streamed_decodes(streamed_output: &Path, dense: &[u8]) { + let decoded = kar::decode_preview_tensor(streamed_output, "dense", 2).unwrap(); let reference = dense .as_chunks::<4>() .0 @@ -89,15 +64,16 @@ async fn prepares_and_verifies_manifest_pinned_sharded_preview() { .zip(&reference) .all(|(actual, expected)| (actual - expected).abs() < 0.1) ); - assert_eq!( - verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(), - streamed.archive - ); - let sampled = crate::kar_quality::analyze(&manifest, &directory, &streamed_output, 2).unwrap(); - assert_eq!( - sampled.records.len(), - streamed.archive.tensor_count as usize - ); +} + +fn assert_quality_samples( + manifest: &Manifest, + directory: &Path, + streamed_output: &Path, + tensor_count: usize, +) { + let sampled = crate::kar_quality::analyze(manifest, directory, streamed_output, 2).unwrap(); + assert_eq!(sampled.records.len(), tensor_count); assert!( sampled .records @@ -105,7 +81,7 @@ async fn prepares_and_verifies_manifest_pinned_sharded_preview() { .all(|record| { record.sampled_elements > 0 && record.relative_l2.is_finite() }) ); let reused = - crate::kar_quality::analyze_previously_verified(&manifest, &directory, &streamed_output, 2) + crate::kar_quality::analyze_previously_verified(manifest, directory, streamed_output, 2) .unwrap(); assert!( reused @@ -114,43 +90,80 @@ async fn prepares_and_verifies_manifest_pinned_sharded_preview() { .zip(&sampled.records) .all(|(a, b)| { a.name == b.name && a.relative_l2 == b.relative_l2 }) ); - assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 3).is_err()); - assert!(verify_sharded(&manifest, &directory, &streamed_output).is_err()); - let streamed_record: serde_json::Value = - serde_json::from_slice(&fs::read(streamed.provenance_path.unwrap()).unwrap()).unwrap(); - assert_eq!( - streamed_record["schema"], - "strata-next/sharded-stream-provenance-v4" - ); - assert_eq!( - streamed_record["partitioned_tensors"], - serde_json::json!([]) - ); - assert_eq!(streamed_record["levels"], 2); - assert!(prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); +} + +fn assert_streamed_record(provenance_path: PathBuf) { + let record: serde_json::Value = + serde_json::from_slice(&fs::read(provenance_path).unwrap()).unwrap(); + assert_eq!(record["schema"], "strata-next/sharded-stream-provenance-v4"); + assert_eq!(record["partitioned_tensors"], serde_json::json!([])); + assert_eq!(record["levels"], 2); +} + +/// Prepares the streamed archive and checks its decode, quality and record. +fn assert_streamed_preview( + manifest: &Manifest, + directory: &Path, + identity: &derived_mixed::ShardedIdentity, + dense: &[u8], +) -> PathBuf { + let output = directory.join("streamed.kar"); + let streamed = prepare_sharded_streamed(manifest, directory, &output, 2).unwrap(); + assert_eq!(streamed.archive.source_digest, identity.derived_sha256); + assert_eq!(streamed.archive.tensor_count, 2); + assert_streamed_decodes(&output, dense); + let verified = verify_sharded_streamed(manifest, directory, &output, 2).unwrap(); + assert_eq!(verified, streamed.archive); + let count = streamed.archive.tensor_count as usize; + assert_quality_samples(manifest, directory, &output, count); + assert!(verify_sharded_streamed(manifest, directory, &output, 3).is_err()); + assert!(verify_sharded(manifest, directory, &output).is_err()); + assert_streamed_record(streamed.provenance_path.unwrap()); + assert!(prepare_sharded_streamed(manifest, directory, &output, 2).is_err()); + output +} + +async fn assert_tampering_is_rejected( + manifest: &mut Manifest, + directory: &Path, + output: &Path, + streamed_output: &Path, + iq3: &[u8], +) { manifest.files[0].sha256 = "00".repeat(32); - assert!(verify_sharded(&manifest, &directory, &output).is_err()); - assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); - manifest.files[0].sha256 = hex::encode(Sha256::digest(&iq3)); - let mut corrupted = fs::read(&output).unwrap(); + assert!(verify_sharded(manifest, directory, output).is_err()); + assert!(verify_sharded_streamed(manifest, directory, streamed_output, 2).is_err()); + manifest.files[0].sha256 = hex::encode(Sha256::digest(iq3)); + let mut corrupted = fs::read(output).unwrap(); let last = corrupted.len() - 1; corrupted[last] ^= 1; - fs::write(&output, corrupted).unwrap(); - assert!( - crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) - .await - .is_err() - ); - fs::remove_dir_all(directory).unwrap(); + fs::write(output, corrupted).unwrap(); + let rejected = crate::model_pipeline::ensure_sharded_preview(manifest, directory, output, 2); + assert!(rejected.await.is_err()); } #[cfg(unix)] // archive preparation is an offline Unix tool -#[test] -fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { - let directory = - std::env::temp_dir().join(format!("strata-stream-split-{}", std::process::id())); - let _ = fs::remove_dir_all(&directory); - fs::create_dir(&directory).unwrap(); +#[tokio::test] +async fn prepares_and_verifies_manifest_pinned_sharded_preview() { + let directory = scratch_dir("strata-preview-shards"); + let (mut manifest, dense, iq3) = mixed_shards(&directory); + let output = directory.join("sharded.kar"); + let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); + let result = prepare_sharded(&manifest, &directory, &output, 2).unwrap(); + assert_eq!(result.archive.tensor_count, 2); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.source_bytes, identity.derived_bytes); + let verified = verify_sharded(&manifest, &directory, &output).unwrap(); + assert_eq!(verified, result.archive); + assert_pipeline_reuses(&manifest, &directory, &output).await; + assert_sharded_record(result.provenance_path.unwrap()); + let streamed = assert_streamed_preview(&manifest, &directory, &identity, &dense); + assert_tampering_is_rejected(&mut manifest, &directory, &output, &streamed, &iq3).await; + fs::remove_dir_all(directory).unwrap(); +} + +/// A dense shard of 512 values and an IQ3_S shard, for the partitioning tests. +fn split_shards(directory: &Path) -> (Manifest, Vec) { let dense = (0..512) .flat_map(|index| [-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()) .collect::>(); @@ -158,26 +171,11 @@ fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { let mut block = [0u8; iq3_s::BLOCK_BYTES]; block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); let iq3_shard = one_shard_with_arch("expert", 21, 256, &block, false); - let files = [("a-dense.gguf", dense_shard), ("z-iq3.gguf", iq3_shard)] - .into_iter() - .map(|(name, bytes)| { - fs::write(directory.join(name), &bytes).unwrap(); - ModelFile { - name: name.into(), - url: "https://example.invalid/source".into(), - size: bytes.len() as u64, - sha256: hex::encode(Sha256::digest(&bytes)), - } - }) - .collect(); - let manifest = Manifest { - schema_version: 1, - files, - }; - let archive = directory.join("split.kar"); - let result = - prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap(); - assert_eq!(result.archive.tensor_count, 3); + let shards = vec![("a-dense.gguf", dense_shard), ("z-iq3.gguf", iq3_shard)]; + (write_manifest(directory, shards), dense) +} + +fn assert_distortions_match(result: &PreviewSummary) { assert_eq!(result.tensor_distortions.len(), 3); assert_eq!( result.maximum_relative_l2, @@ -193,13 +191,11 @@ fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { .iter() .all(|entry| entry.section_bytes > 0 && entry.relative_l2.is_finite()) ); - assert_eq!( - verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap(), - result.archive - ); - assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); +} + +fn assert_partition_records(archive: &Path, dense: &[u8], provenance_path: PathBuf) { let provenance: serde_json::Value = - serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); + serde_json::from_slice(&fs::read(provenance_path).unwrap()).unwrap(); let parts = provenance["partitioned_tensors"][0]["parts"] .as_array() .unwrap(); @@ -208,7 +204,7 @@ fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { assert_eq!(parts[1]["derived_offset"], 1024); for (number, part) in parts.iter().enumerate() { let name = part["name"].as_str().unwrap(); - let decoded = kar::decode_preview_tensor(&archive, name, 2).unwrap(); + let decoded = kar::decode_preview_tensor(archive, name, 2).unwrap(); assert_eq!(decoded.len(), 256); for (actual, original) in decoded.iter().zip( dense[number * 1024..(number + 1) * 1024] @@ -220,5 +216,22 @@ fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { assert!((actual - original).abs() < 0.1); } } +} + +#[cfg(unix)] // archive preparation is an offline Unix tool +#[test] +fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { + let directory = scratch_dir("strata-stream-split"); + let (manifest, dense) = split_shards(&directory); + let archive = directory.join("split.kar"); + let result = + prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap(); + assert_eq!(result.archive.tensor_count, 3); + assert_distortions_match(&result); + let verified = + verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap(); + assert_eq!(verified, result.archive); + assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); + assert_partition_records(&archive, &dense, result.provenance_path.unwrap()); fs::remove_dir_all(directory).unwrap(); } diff --git a/control-plane/src/prepare_preview/tests/source_kinds.rs b/control-plane/src/prepare_preview/tests/source_kinds.rs index 3e4e0a63..04d2c946 100644 --- a/control-plane/src/prepare_preview/tests/source_kinds.rs +++ b/control-plane/src/prepare_preview/tests/source_kinds.rs @@ -1,40 +1,77 @@ //! Previews prepared from virtual f32, mixed and per-kind sources. use super::super::*; -use super::fixtures::string; +use super::fixtures::{align_data, header_with_arch, iq3_pattern_block, tensor_entry}; + +fn iq3_source() -> Vec { + let mut gguf = header_with_arch(1); + tensor_entry(&mut gguf, "expert", 256, 21, 0); + align_data(&mut gguf); + gguf.extend_from_slice(&iq3_pattern_block()); + gguf +} + +fn assert_iq3_record( + record: &serde_json::Value, + identity: &derived_iq3::Identity, + result: &PreviewSummary, +) { + assert_eq!( + record["original_gguf_sha256"], + hex::encode(identity.gguf_sha256) + ); + assert_eq!( + record["derived_f32_sha256"], + hex::encode(identity.derived_sha256) + ); + assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest)); +} + +fn assert_changed_provenance_is_refused( + source_path: &Path, + output: &Path, + provenance: &Path, + record: &serde_json::Value, +) { + let saved_provenance = fs::read(provenance).unwrap(); + let mut changed = record.clone(); + changed["archive_sha256"] = serde_json::Value::String("00".repeat(32)); + fs::write(provenance, serde_json::to_vec(&changed).unwrap()).unwrap(); + assert!( + verify_iq3(source_path, output) + .unwrap_err() + .contains("provenance differs") + ); + fs::write(provenance, saved_provenance).unwrap(); + assert!(verify_iq3(source_path, output).is_ok()); +} + +fn assert_reserved_provenance_blocks_output(base: &Path, source_path: &Path) { + let blocked_output = base.with_file_name(format!( + "strata-preview-iq3-blocked-{}.kar", + std::process::id() + )); + let blocked_provenance = provenance_path(&blocked_output).unwrap(); + let _ = fs::remove_file(&blocked_output); + fs::write(&blocked_provenance, b"reserved").unwrap(); + assert!( + prepare_iq3(source_path, &blocked_output, 2) + .unwrap_err() + .contains("provenance destination already exists") + ); + assert!(!blocked_output.exists()); + fs::remove_file(blocked_provenance).unwrap(); +} #[test] fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() { - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); - string(&mut gguf, "expert"); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&256u64.to_le_bytes()); - gguf.extend_from_slice(&21u32.to_le_bytes()); - gguf.extend_from_slice(&0u64.to_le_bytes()); - gguf.resize(gguf.len().div_ceil(32) * 32, 0); - let mut block = [0u8; iq3_s::BLOCK_BYTES]; - block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in block[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } - block[74] = 0x55; - gguf.extend_from_slice(&block); let base = std::env::temp_dir().join(format!("strata-preview-iq3-good-{}", std::process::id())); let source_path = base.with_extension("gguf"); let output = base.with_extension("kar"); - let provenance = output.with_file_name(format!( - "{}.provenance.json", - output.file_name().unwrap().to_string_lossy() - )); + let provenance = provenance_path(&output).unwrap(); let _ = fs::remove_file(&output); let _ = fs::remove_file(&provenance); - fs::write(&source_path, gguf).unwrap(); + fs::write(&source_path, iq3_source()).unwrap(); let identity = derived_iq3::fingerprint(&source_path).unwrap(); let result = prepare_iq3(&source_path, &output, 2).unwrap(); assert_eq!(result.archive.source_digest, identity.derived_sha256); @@ -46,78 +83,36 @@ fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() { assert_eq!(kar::verify(&output).unwrap(), result.archive); let record: serde_json::Value = serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); - assert_eq!( - record["original_gguf_sha256"], - hex::encode(identity.gguf_sha256) - ); - assert_eq!( - record["derived_f32_sha256"], - hex::encode(identity.derived_sha256) - ); - assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest)); + assert_iq3_record(&record, &identity, &result); assert!(result.maximum_relative_l2.is_finite()); assert_eq!(verify_iq3(&source_path, &output).unwrap(), result.archive); - let saved_provenance = fs::read(&provenance).unwrap(); - let mut changed = record.clone(); - changed["archive_sha256"] = serde_json::Value::String("00".repeat(32)); - fs::write(&provenance, serde_json::to_vec(&changed).unwrap()).unwrap(); - assert!( - verify_iq3(&source_path, &output) - .unwrap_err() - .contains("provenance differs") - ); - fs::write(&provenance, saved_provenance).unwrap(); - assert!(verify_iq3(&source_path, &output).is_ok()); - let blocked_output = base.with_file_name(format!( - "strata-preview-iq3-blocked-{}.kar", - std::process::id() - )); - let blocked_provenance = blocked_output.with_file_name(format!( - "{}.provenance.json", - blocked_output.file_name().unwrap().to_string_lossy() - )); - let _ = fs::remove_file(&blocked_output); - fs::write(&blocked_provenance, b"reserved").unwrap(); - assert!( - prepare_iq3(&source_path, &blocked_output, 2) - .unwrap_err() - .contains("provenance destination already exists") - ); - assert!(!blocked_output.exists()); - fs::remove_file(blocked_provenance).unwrap(); + assert_changed_provenance_is_refused(&source_path, &output, &provenance, &record); + assert_reserved_provenance_blocks_output(&base, &source_path); fs::remove_file(provenance).unwrap(); fs::remove_file(output).unwrap(); fs::remove_file(source_path).unwrap(); } -#[test] -fn prepares_and_verifies_mixed_preview_with_each_source_kind() { +/// One tensor of each source kind: BF16, IQ3_S, F16 and F32. +fn mixed_source() -> Vec { let tensors = [ ("bf16", 30u32, 320u64, 32u64), ("iq3", 21, 0, 256), ("f16", 1, 256, 32), ("f32", 0, 128, 32), ]; - let mut gguf = b"GGUF".to_vec(); - gguf.extend_from_slice(&3u32.to_le_bytes()); - gguf.extend_from_slice(&(tensors.len() as u64).to_le_bytes()); - gguf.extend_from_slice(&1u64.to_le_bytes()); - string(&mut gguf, "general.architecture"); - gguf.extend_from_slice(&8u32.to_le_bytes()); - string(&mut gguf, "qwen35"); + let mut gguf = header_with_arch(tensors.len() as u64); for (name, kind, offset, elements) in tensors { - string(&mut gguf, name); - gguf.extend_from_slice(&1u32.to_le_bytes()); - gguf.extend_from_slice(&elements.to_le_bytes()); - gguf.extend_from_slice(&kind.to_le_bytes()); - gguf.extend_from_slice(&offset.to_le_bytes()); + tensor_entry(&mut gguf, name, elements, kind, offset); } - gguf.resize(gguf.len().div_ceil(32) * 32, 0); + align_data(&mut gguf); + gguf.extend_from_slice(&mixed_payload()); + gguf +} + +fn mixed_payload() -> Vec { let mut payload = vec![0u8; 384]; - payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); - for (index, byte) in payload[2..66].iter_mut().enumerate() { - *byte = (index as u8).wrapping_mul(3); - } + payload[..66].copy_from_slice(&iq3_pattern_block()[..66]); payload[74] = 0x55; let values = [-1.0f32, -0.25, 0.25, 1.0]; for index in 0..32 { @@ -128,14 +123,18 @@ fn prepares_and_verifies_mixed_preview_with_each_source_kind() { let bf16 = (value.to_bits() >> 16) as u16; payload[320 + 2 * index..322 + 2 * index].copy_from_slice(&bf16.to_le_bytes()); } - gguf.extend_from_slice(&payload); + payload +} + +#[test] +fn prepares_and_verifies_mixed_preview_with_each_source_kind() { let base = std::env::temp_dir().join(format!("strata-preview-mixed-{}", std::process::id())); let source_path = base.with_extension("gguf"); let output = base.with_extension("kar"); let provenance = provenance_path(&output).unwrap(); let _ = fs::remove_file(&output); let _ = fs::remove_file(&provenance); - fs::write(&source_path, gguf).unwrap(); + fs::write(&source_path, mixed_source()).unwrap(); let identity = derived_mixed::fingerprint(&source_path).unwrap(); let result = prepare_mixed(&source_path, &output, 2).unwrap(); assert_eq!(result.archive.source_digest, identity.derived_sha256); diff --git a/control-plane/src/prepare_preview/verify_derived.rs b/control-plane/src/prepare_preview/verify_derived.rs index cb457b45..265f34ae 100644 --- a/control-plane/src/prepare_preview/verify_derived.rs +++ b/control-plane/src/prepare_preview/verify_derived.rs @@ -1,50 +1,70 @@ -//! Moved out of the parent module by STRA-338: fn verify_derived, fn decode_source_tensor, fn provenance_path, fn provenance_value, fn sharded_provenance_value, fn partitioned_provenance .... +//! Moved out of the parent module by STRA-338: fn verify_derived, fn decode_source_tensor, fn provenance_path, fn +//! provenance_value, fn sharded_provenance_value, fn partitioned_provenance .... #[allow(unused_imports)] use super::*; +fn load_derived_identity(source_path: &Path, kind: PreviewKind) -> Result { + Ok(match kind { + PreviewKind::F32 => return Err("F32 preview does not use derived provenance".into()), + PreviewKind::Iq3 => DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?), + PreviewKind::Mixed => DerivedIdentity::Mixed(derived_mixed::fingerprint(source_path)?), + }) +} + +fn require_derived_header( + identity: &DerivedIdentity, + summary: &kar::Summary, + source_count: usize, +) -> Result<(), String> { + if summary.source_digest != identity.derived_digest() + || summary.source_bytes != identity.derived_bytes() + || summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes()) + || source_count != identity.tensor_count() + { + return Err("KAR header differs from derived F32 source identity".into()); + } + Ok(()) +} + +fn require_derived_source( + identity: &DerivedIdentity, + number: usize, + record: &kar::TensorSource, +) -> Result<(), String> { + let tensor = identity.tensor(number); + let record_bytes = record + .dimensions + .iter() + .try_fold(4u64, |size, dim| size.checked_mul(*dim)) + .ok_or("KAR tensor source byte count overflow")?; + if record.name != tensor.name + || record.dtype != 0 + || &record.digest != tensor.f32_digest + || record.offset != tensor.offset + || record_bytes != tensor.bytes + { + return Err(format!( + "{}: KAR tensor source identity mismatch", + tensor.name + )); + } + Ok(()) +} + pub(super) fn verify_derived( source_path: &Path, archive_path: &Path, kind: PreviewKind, ) -> Result { - let identity = match kind { - PreviewKind::F32 => return Err("F32 preview does not use derived provenance".into()), - PreviewKind::Iq3 => DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?), - PreviewKind::Mixed => DerivedIdentity::Mixed(derived_mixed::fingerprint(source_path)?), - }; + let identity = load_derived_identity(source_path, kind)?; let (summary, sources) = kar::verify_with_sources(archive_path)?; - if summary.source_digest != identity.derived_digest() - || summary.source_bytes != identity.derived_bytes() - || summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes()) - || sources.len() != identity.tensor_count() - { - return Err("KAR header differs from derived F32 source identity".into()); - } + require_derived_header(&identity, &summary, sources.len())?; for (number, record) in sources.iter().enumerate() { - let tensor = identity.tensor(number); - let record_bytes = record - .dimensions - .iter() - .try_fold(4u64, |size, dim| size.checked_mul(*dim)) - .ok_or("KAR tensor source byte count overflow")?; - if record.name != tensor.name - || record.dtype != 0 - || &record.digest != tensor.f32_digest - || record.offset != tensor.offset - || record_bytes != tensor.bytes - { - return Err(format!( - "{}: KAR tensor source identity mismatch", - tensor.name - )); - } + require_derived_source(&identity, number, record)?; } let archive_digest = hash_file(archive_path)?; - let provenance = provenance_path(archive_path)?; - let file = File::open(provenance).map_err(|error| error.to_string())?; - let recorded: serde_json::Value = - serde_json::from_reader(file).map_err(|error| error.to_string())?; + let recorded = read_recorded_provenance(archive_path)?; if recorded != provenance_value(&identity, archive_digest) { return Err("derived preview provenance differs from source or archive".into()); } diff --git a/control-plane/src/prepare_preview/verify_sharded_parts.rs b/control-plane/src/prepare_preview/verify_sharded_parts.rs new file mode 100644 index 00000000..78f1e6d9 --- /dev/null +++ b/control-plane/src/prepare_preview/verify_sharded_parts.rs @@ -0,0 +1,132 @@ +//! Stages of the sharded archive verification (STRA-338 size-fn). + +#[allow(unused_imports)] +use super::*; + +type Parts = [Vec]; + +/// The streamed-preparation policy a sharded archive is verified against. +#[derive(Clone, Copy)] +pub(super) struct StreamPolicy { + pub(super) levels: Option, + pub(super) ple_part_elements: Option, +} + +pub(super) fn plan_verified_parts( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, + max_part_elements: u64, + ple_part_elements: Option, +) -> Result>, String> { + if let Some(limit) = ple_part_elements { + stream_parts::plan_shards_with_ple_limit(identity, source_dir, limit) + } else { + stream_parts::plan_shards_with_limit(identity, source_dir, max_part_elements) + } +} + +pub(super) fn require_sharded_header( + identity: &derived_mixed::ShardedIdentity, + archive_parts: Option<&Parts>, + summary: &kar::Summary, + source_count: usize, +) -> Result<(), String> { + let expected_count = archive_parts.map_or(identity.tensors.len(), |parts| { + parts.iter().map(Vec::len).sum() + }); + if summary.source_digest != identity.derived_sha256 + || summary.source_bytes != identity.derived_bytes + || summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes) + || source_count != expected_count + { + return Err("KAR header differs from sharded derived source".into()); + } + Ok(()) +} + +fn record_source_bytes(record: &kar::TensorSource) -> Result { + let bytes = record + .dimensions + .iter() + .try_fold(4u64, |size, dim| size.checked_mul(*dim)) + .ok_or("KAR tensor source byte count overflow")?; + Ok(bytes) +} + +pub(super) fn require_sharded_sources( + identity: &derived_mixed::ShardedIdentity, + archive_parts: Option<&Parts>, + sources: &[kar::TensorSource], +) -> Result<(), String> { + if let Some(parts) = archive_parts { + for (record, part) in sources.iter().zip(parts.iter().flatten()) { + require_part_source(record, part)?; + } + } else { + for (record, tensor) in sources.iter().zip(&identity.tensors) { + require_tensor_source(record, tensor)?; + } + } + Ok(()) +} + +fn require_part_source( + record: &kar::TensorSource, + part: &stream_parts::PartIdentity, +) -> Result<(), String> { + let record_bytes = record_source_bytes(record)?; + if record.name != part.name + || record.dimensions != part.dimensions + || record.dtype != 0 + || record.digest != part.f32_sha256 + || record.offset != part.derived_offset + || record_bytes != part.derived_bytes + { + return Err(format!("{}: sharded KAR part source mismatch", part.name)); + } + Ok(()) +} + +fn require_tensor_source( + record: &kar::TensorSource, + tensor: &derived_mixed::TensorIdentity, +) -> Result<(), String> { + let record_bytes = record_source_bytes(record)?; + if record.name != tensor.name + || record.dtype != 0 + || record.digest != tensor.f32_sha256 + || record.offset != tensor.derived_offset + || record_bytes != tensor.derived_bytes + { + return Err(format!( + "{}: sharded KAR tensor source mismatch", + tensor.name + )); + } + Ok(()) +} + +pub(super) fn require_sharded_provenance( + identity: &derived_mixed::ShardedIdentity, + archive_parts: Option<&Parts>, + archive_path: &Path, + summary: &kar::Summary, + policy: StreamPolicy, +) -> Result<(), String> { + let archive_digest = hash_file(archive_path)?; + let recorded = read_recorded_provenance(archive_path)?; + let mut expected = sharded_provenance_value(identity, archive_digest); + if let Some(levels) = policy.levels { + if summary.max_planes > levels { + return Err("KAR stream levels exceed declared preparation level".into()); + } + let parts = archive_parts.ok_or("missing streamed KAR part plan")?; + apply_stream_policy(&mut expected, levels, parts, policy.ple_part_elements); + } + if recorded != expected { + return Err( + "sharded provenance differs from source, archive, or preparation policy".into(), + ); + } + Ok(()) +}