Reject undersized KAR output before shard rehash

This commit is contained in:
Pavlo Ratushnyi
2026-10-03 08:08:31 +02:00
parent 4980e5afe0
commit bca18dee91
4 changed files with 75 additions and 3 deletions
+67 -2
View File
@@ -1,9 +1,13 @@
//! Fail-closed acquisition and preparation paths. The full-size stream is
//! experimental until real-model quality and Linux GPU loading are verified.
use std::{error::Error, fs, path::Path};
use std::{
error::Error,
fs, io,
path::{Component, Path},
};
use crate::{kar, model, prepare_preview, stream_parts};
use crate::{gguf, kar, model, prepare_preview, stream_parts};
pub enum PreviewOutcome {
Created(prepare_preview::PreviewSummary),
@@ -94,6 +98,7 @@ async fn ensure_sharded_streamed_with_policy(
if let Some(limit) = ple_part_elements {
stream_parts::validate_ple_limit(limit)?;
}
preflight_existing_shards(manifest, source_dir, archive, levels)?;
model::fetch(manifest, source_dir).await?;
model::verify(manifest, source_dir).await?;
match fs::symlink_metadata(archive) {
@@ -131,6 +136,66 @@ async fn ensure_sharded_streamed_with_policy(
}
}
/// 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.
fn preflight_existing_shards(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
) -> Result<(), Box<dyn Error>> {
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()),
}
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")?;
}
}
let parent = archive
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
model::require_space(parent, minimum)
.map_err(|error| format!("KAR minimum payload does not fit: {error}").into())
}
#[cfg(test)]
mod tests {
use super::*;
+1 -1
View File
@@ -21,7 +21,7 @@ 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<u64, String> {
pub(crate) fn minimum_part_payload_bytes(derived_bytes: u64, levels: u8) -> Result<u64, String> {
if !derived_bytes.is_multiple_of(4) || !(1..=8).contains(&levels) {
return Err("invalid KAR part F32 byte count or level".into());
}
+5
View File
@@ -189,3 +189,8 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- 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.
## 2026-10-03 — fast rejection before existing-shard rehash
- `model ensure-sharded-streamed` now uses the GGUF directories of already-present, size-matched shards to reject an impossible new archive before `model fetch` rehashes the source. This metadata is not treated as verified input for acceptance: if the lower bound fits, the existing SHA-256 and preparation checks still run. Missing shards retain the normal download path, and reuse of an existing archive does not require a second archive's free space.
- With both real IQ3_S shards present, a v5 level-2 request at `--ple-part-elements 100000000` failed in **0.495 s** from an already-built debug CLI. The directory-derived minimum was 44,235,975,168 bytes; the output volume had 22,671,552,512 bytes available in that run. The command returned `KAR minimum payload does not fit` before source hashing and created no v5 archive. No model bytes or new archive were written. All 91 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64.
+2
View File
@@ -27,6 +27,8 @@ For small GGUF fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR
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.
When `model ensure-sharded-streamed` sees all source shards already present and needs to create a new archive, it reads only their GGUF directories for an even earlier minimum-space rejection, before rehashing the shards. This preliminary metadata is used only to reject an impossible destination; a passing result still goes through SHA-256 source verification and the preparation-time guard. Missing shards take the normal resumable fetch path. Reusing an existing archive does not require room for a second copy.
`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.