diff --git a/control-plane/src/model.rs b/control-plane/src/model.rs index 8411d3ea..f5dfe93e 100644 --- a/control-plane/src/model.rs +++ b/control-plane/src/model.rs @@ -270,7 +270,7 @@ async fn preflight_space(manifest: &Manifest, output: &Path) -> Result<()> { require_space(output, needed) } -fn require_space(directory: &Path, needed: u64) -> Result<()> { +pub(crate) fn require_space(directory: &Path, needed: u64) -> Result<()> { let available = available_bytes(directory)?; if available < needed { return Err(format!( diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 49e5a5da..2a46a77e 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -12,13 +12,26 @@ use sha2::{Digest, Sha256}; use crate::{ derived_iq3, derived_mixed, gguf, gguf_f32_stream, iq3_s, kar, kar_codec, kar_sample, - kar_stream_encode, kar_writer, model::Manifest, stream_parts, + kar_stream_encode, kar_writer, + model::{self, Manifest}, + stream_parts, }; const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; const MAX_TENSORS: usize = 1000; const MAX_TENSOR_ELEMENTS: u64 = 1_000_000; +fn minimum_part_payload_bytes(derived_bytes: u64, levels: u8) -> Result { + if !derived_bytes.is_multiple_of(4) || !(1..=8).contains(&levels) { + return Err("invalid KAR part F32 byte count or level".into()); + } + let plane_bytes = (derived_bytes / 4) + .div_ceil(32) + .checked_mul(4 * u64::from(levels)) + .ok_or("KAR minimum payload size overflow")?; + Ok(plane_bytes.min(derived_bytes)) +} + #[derive(Clone, Copy)] enum PreviewKind { F32, @@ -416,6 +429,23 @@ fn prepare_sharded_streamed_with_policy( if archive_tensor_count == 0 || archive_tensor_count > 100_000 { return Err("streamed sharded tensor count exceeds KAR-2 limits".into()); } + // Every nested part stores at least `levels` four-byte plane words per + // 32 values; a RAW fallback stores four bytes per value. The smaller of + // these is a safe lower bound before section files are created. Passing + // this gate does not guarantee enough space for scales and metadata. + let minimum_payload_bytes = archive_parts + .iter() + .flat_map(|parts| parts.iter()) + .try_fold(0u64, |sum, part| { + sum.checked_add(minimum_part_payload_bytes(part.derived_bytes, levels)?) + .ok_or_else(|| "KAR minimum payload size overflow".to_string()) + })?; + let destination_parent = destination + .parent() + .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 @@ -1362,6 +1392,17 @@ fn hash_file(path: &Path) -> Result<[u8; 32], String> { #[cfg(test)] mod tests { use super::*; + + #[test] + fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { + assert_eq!( + minimum_part_payload_bytes(707_775_598_080, 2).unwrap(), + 44_235_974_880 + ); + assert!(minimum_part_payload_bytes(707_775_598_080, 2).unwrap() > 23 * (1 << 30)); + assert_eq!(minimum_part_payload_bytes(4, 8).unwrap(), 4); + assert!(minimum_part_payload_bytes(u64::MAX, 8).is_err()); + } use crate::model::ModelFile; fn string(out: &mut Vec, value: &str) { diff --git a/docs/build-validation.md b/docs/build-validation.md index 5f0d2b8f..dad2bcf5 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -184,3 +184,8 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - `model plan-kar-overlay-memory` verifies complete base and overlay archive SHA-256 values, payload CRCs, provenance, and 22 replacement mappings before calculating selected compressed residency. A synthetic v5 fixture selected six records with two overlay replacements and counted each exactly once. All 90 Rust tests and Clippy with warnings denied passed locally. - The release CLI ran against the preserved real v4 base and level-3 overlay in 421.0 seconds. Verified archive SHA-256 values were `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5` and `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`. At base level 2, overlay level 3, and a hypothetical 24,576 MiB GPU budget, 1,225 selected records (22 replacements) require **55,300,367,408 bytes** of compressed residency: 55,281,550,704 from selected base records and 18,816,704 from overlay records. That is 5,376,352 bytes more than the earlier base-only compressed plan. The largest full F32 scratch is 128,000,000,000 bytes, and two PLE records exceed the per-record full-decode budget while their one-row output bounds fit. All-selected residency plus one largest scratch is 183,300,367,408 bytes, so a 32 GB card cannot keep all selected records resident. This is verified archive metadata arithmetic, **not** measured GPU allocation, model quality, or inference throughput. - The external report is `/Users/para/.local/share/strata-next/qwen-iq3-s-selected-overlay-memory.json`, 3,586 bytes, SHA-256 `488a79973f90937429af1483bafe648441cd6e76ceb3a9f9edf9c16c7fcf376c`. The verified source shards, base archive, overlay, and this report remain outside Git. The local release build output was removed after the run. + +## 2026-10-03 — KAR preparation space guard + +- Streamed sharded preparation now checks the output volume before creating private section files. Its conservative lower bound takes the smaller of the mandatory bit-plane bytes and the F32 RAW fallback for each planned part. For the target virtual F32 size of 707,775,598,080 bytes at level 2, the aggregate bit-plane floor alone is 44,235,974,880 bytes before scales, codebooks, alignment, and provenance. The current Mac volume has about 23 GiB free and the occupied Linux host's root volume about 18 GiB free, so neither can hold a second full archive. This guard avoids starting section writes on a clearly undersized volume; source identity calculation still precedes it, and passing the bound does not guarantee a completed archive. +- All 91 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. The v5 partitioned synthetic archive still prepares and verifies under the space guard. diff --git a/docs/model-assets.md b/docs/model-assets.md index b60ba58b..4e1b005c 100644 --- a/docs/model-assets.md +++ b/docs/model-assets.md @@ -25,6 +25,8 @@ For small GGUF fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR `model prepare-kar-overlay MANIFEST --source-dir DIR --base BASE.kar --candidates CANDIDATES.json --output OVERLAY.kar` is an experimental way to re-encode selected KAR records at a higher level. Candidates may name an unsplit tensor or one partition from a v4/v5 base, such as `per_layer_token_embd.weight#strata-part-001-of-513`; the candidate's `elements` must equal that record's element count. Preparation binds the selected GGUF byte range, its physical and derived F32 digests, and the base KAR source record, verifies the resulting overlay, writes a provenance sidecar, and removes staging sections. `model compare-kar-overlay MANIFEST --source-dir DIR --base BASE.kar --overlay OVERLAY.kar --output REPORT.json` decodes every selected record from both archives against its GGUF source range, rechecks the physical and F32 digests and overlay CRCs, and records paired full-record relative L2. The base archive's earlier full verification is assumed; it is not rehashed by the comparison. No serving loader applies this overlay yet, and lower tensor error alone does not pass the model-quality gate. +Full streamed preparation checks available space on the output volume before creating section files. Its bound counts the minimum bit-plane payload for every part and accounts for a possible RAW fallback. A volume below that bound is rejected early; passing the bound does not guarantee enough room for scales, codebooks, alignment, and provenance. Keep the verified source shards and existing archive on their external volume when retrying with more space. + `model smoke-fixture --output FILE.kar` writes a deterministic 32-element KAR-2 archive named `smoke.expert` and prints its archive digest and two-level CPU decode checksum. It refuses to overwrite an existing file. This model-free artifact lets the Linux CUDA decoder be checked before the target model is available. The acquisition stage downloads GGUF files; the native tokenizer stage extracts and uses tokenizer assets. Before fetching, the CLI checks available filesystem space against the remaining bytes in all manifest shards and checks again after the server chooses resume or restart. This avoids starting a transfer that already cannot fit; filesystem quotas or concurrent writers can still cause a later write failure. The native experimental KAR-2 preparation path exists, but upstream `iq_pack.py` equivalence, compressed GPU loading, and model startup still need implementation and differential validation. See [compressed runtime contract](compressed-runtime.md) for the target `fetch` → `verify` → `prepare` → GPU decode sequence and `with-key`/`without-key` cache profiles. Model bytes belong on an external volume and never in Git or CI artifacts.