Preflight model download disk space

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 19:59:02 +02:00
parent d44c250c12
commit 88b1a0ee47
6 changed files with 112 additions and 3 deletions
+1
View File
@@ -1592,6 +1592,7 @@ dependencies = [
"fancy-regex",
"hex",
"jsonschema",
"libc",
"reqwest",
"serde",
"serde_json",
+1
View File
@@ -15,6 +15,7 @@ axum = "0.8"
fancy-regex = "0.19"
hex = "0.4"
jsonschema = { version = "0.58.4", default-features = false }
libc = "0.2"
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+105
View File
@@ -7,6 +7,9 @@ use std::{
time::Duration,
};
#[cfg(unix)]
use std::ffi::CString;
use reqwest::{
Client, StatusCode,
header::{ACCEPT_ENCODING, CONTENT_RANGE, RANGE},
@@ -91,6 +94,7 @@ pub async fn verify(manifest: &Manifest, output: &Path) -> Result<()> {
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
// A scratch image and a standalone musl binary may have no host CA store.
// Keep certificate and hostname verification, with a root set in the binary.
let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS
@@ -169,6 +173,12 @@ async fn fetch_one(client: &Client, file: &ModelFile, output: &Path) -> Result<(
StatusCode::OK => offset = 0,
status => return Err(format!("unexpected HTTP {status} for {}", file.name).into()),
}
require_space(
destination
.parent()
.ok_or("model destination has no parent")?,
file.size - offset,
)?;
let mut hasher = Sha256::new();
if offset > 0 {
let (size, prefix_hash) = hash_file(&partial).await?;
@@ -215,6 +225,76 @@ async fn fetch_one(client: &Client, file: &ModelFile, output: &Path) -> Result<(
Ok(())
}
async fn preflight_space(manifest: &Manifest, output: &Path) -> Result<()> {
let mut needed = 0u64;
for entry in &manifest.files {
let destination = output.join(&entry.name);
reject_symlink(&destination).await?;
let remaining = match fs::metadata(&destination).await {
Ok(metadata) if metadata.len() == entry.size => 0,
Ok(_) => {
return Err(
format!("existing model file has unexpected size: {}", entry.name).into(),
);
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let partial = part_path(&destination);
reject_symlink(&partial).await?;
let offset = match fs::metadata(&partial).await {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == io::ErrorKind::NotFound => 0,
Err(error) => return Err(error.into()),
};
entry
.size
.checked_sub(offset)
.ok_or("partial file exceeds manifest size")?
}
Err(error) => return Err(error.into()),
};
needed = needed
.checked_add(remaining)
.ok_or("model disk-space requirement overflow")?;
}
require_space(output, needed)
}
fn require_space(directory: &Path, needed: u64) -> Result<()> {
let available = available_bytes(directory)?;
if available < needed {
return Err(format!(
"insufficient disk space: need {needed} additional bytes, have {available} available bytes in {}",
directory.display()
).into());
}
Ok(())
}
#[cfg(unix)]
fn available_bytes(directory: &Path) -> io::Result<u64> {
use std::{mem::MaybeUninit, os::unix::ffi::OsStrExt};
let path = CString::new(directory.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "directory contains NUL"))?;
let mut stats = MaybeUninit::<libc::statvfs>::uninit();
// SAFETY: path is NUL-terminated and stats points to writable statvfs storage.
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
// SAFETY: a successful statvfs call initialized every field of stats.
let stats = unsafe { stats.assume_init() };
(stats.f_bavail as u64)
.checked_mul(stats.f_frsize)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "available space overflow"))
}
#[cfg(not(unix))]
fn available_bytes(_directory: &Path) -> io::Result<u64> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"model fetch needs a Unix filesystem",
))
}
async fn verify_one(file: &ModelFile, path: &Path) -> Result<()> {
reject_symlink(path).await?;
let (size, hasher) = hash_file(path).await?;
@@ -271,6 +351,31 @@ mod tests {
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::{net::TcpListener, time::timeout};
#[tokio::test]
async fn insufficient_space_stops_before_network_or_partial_file() {
let root = std::env::temp_dir().join(format!(
"strata-space-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let manifest = Manifest {
schema_version: 1,
files: vec![ModelFile {
name: "huge.gguf".into(),
url: "https://example.invalid/huge.gguf".into(),
size: u64::MAX,
sha256: "0".repeat(64),
}],
};
let error = fetch(&manifest, &root).await.unwrap_err().to_string();
assert!(error.contains("insufficient disk space"));
assert!(!root.join("huge.gguf.part").exists());
fs::remove_dir_all(root).await.unwrap();
}
#[tokio::test]
async fn interrupted_download_resumes_and_verifies() {
let base = std::env::temp_dir().join(format!(
+2 -1
View File
@@ -74,4 +74,5 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- Qwen text-only prompt assembly matches eight pinned upstream golden cases byte for byte. A synthetic in-process worker receives the expected native token IDs through the HTTP Responses route and returns a completed non-streaming text response. Live streaming, reasoning output, tools, and real-model inference remain unverified.
- Added bounded KAR-2 metadata inspection, streaming CRC-32 verification of every tensor section, and optional source-manifest verification. The latter checks each shard's size and SHA-256, then hashes the shards in ascending byte-wise filename order against the archive's source digest and byte count.
- Independently generated a 1,280-byte two-tensor RAW/NESTED archive with koference `r08/code/kar_container.py` at commit `806d2398ae1daaceb2917242911e5680cbfb3608`. Its Python reader and the Rust `model verify-kar` both accepted the archive and both tensor CRCs. A two-file synthetic source manifest passed the Rust source-identity check. The temporary archive and source bytes were kept out of Git.
- Rust 1.99 formatting, Clippy with warnings denied, and 30 Rust tests pass. The full `scripts/check-local.sh` cannot reach CPU engine tests on this machine because CMake ≥3.24 is absent; Linux CI installs CMake, but the hosted workflow has not run on this repository. No model weights or GPU node were used.
- Rust 1.99 formatting, Clippy with warnings denied, and 31 Rust tests pass after adding a disk-space preflight that rejects an impossible model transfer before networking. The full `scripts/check-local.sh` cannot reach CPU engine tests on this machine because CMake ≥3.24 is absent; Linux CI installs CMake, but the hosted workflow has not run on this repository.
- Rebuilt the current CLI as a Linux/arm64 musl executable in a `scratch` image. `--version`, KAR-2 payload verification, and the optional two-shard source-identity check all ran successfully inside the image against the synthetic koference archive. This proves the current static CLI starts without a user-space loader, not that a GPU engine or real model runs. No model weights or GPU node were used.
+1 -1
View File
@@ -15,7 +15,7 @@ The profile manifest is embedded in the executable; a custom manifest path can b
The executable carries its HTTPS trust roots, so `model fetch` does not need a CA bundle installed in a minimal container. TLS certificate and hostname verification remain enabled.
The acquisition stage downloads GGUF files; the native tokenizer stage extracts and uses tokenizer assets. The upstream `iq_pack.py` format conversion, KAR-2 preparation, compressed GPU loading, and model startup still need native implementations 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.
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 upstream `iq_pack.py` format conversion, KAR-2 preparation, compressed GPU loading, and model startup still need native implementations 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.
`model inspect` reads the GGUF v3 header and tensor directory without mapping weight data. It checks metadata types, counts, alignment, duplicate keys/tensors, split numbering, and whether tensor start offsets fit the file. This is a structural check, not proof that all tensor bytes or quantization geometry are valid.
+2 -1
View File
@@ -39,8 +39,9 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f
- [x] Embed a commit-pinned IQ3_S manifest with size and SHA-256 for both GGUF shards.
- [x] Implement resumable downloads, integrity checks, and a local interrupted-transfer test.
- [x] Check free disk space for all outstanding shard bytes and again after each resume/restart response.
- [ ] Verify a complete real IQ3_S download on an external volume and record measured digests.
- [ ] Add disk-space preflight, multi-shard progress, retry policy, and authenticated Hub access where needed.
- [ ] Add multi-shard progress, retry policy, and authenticated Hub access where needed.
### P2 — native model preparation