//! `mtp_fetch` against a local HTTP mirror of a fake checkpoint: the behavioural spec is //! `engine/strata/tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine. use std::{ collections::{BTreeMap, HashSet}, fs, io::{Read, Write}, net::TcpListener, path::{Path, PathBuf}, sync::{Arc, Mutex}, thread, }; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use strata_control::mtp_fetch::{Fetcher, check_range}; fn shard(tensors: &[(&str, &[u8])]) -> Vec { let (mut header, mut data) = (serde_json::Map::new(), Vec::new()); for (name, blob) in tensors { header.insert( (*name).to_owned(), json!({"dtype": "BF16", "shape": [blob.len() / 2], "data_offsets": [data.len(), data.len() + blob.len()]}), ); data.extend_from_slice(blob); } let h = serde_json::to_vec(&header).unwrap(); [&(h.len() as u64).to_le_bytes()[..], &h, &data].concat() } fn payloads() -> (Vec, Vec, Vec) { let a: Vec = (0..64).collect(); let b: Vec = (100..164).chain(100..164).collect(); (a, b, vec![7u8; 48]) } fn files() -> BTreeMap> { let (a, b, x) = payloads(); BTreeMap::from([ ( "model-1.safetensors".to_owned(), shard(&[("model.x", &x), ("mtp.a", &a)]), ), ("model-2.safetensors".to_owned(), shard(&[("mtp.b", &b)])), ( "model.safetensors.index.json".to_owned(), serde_json::to_vec(&json!({"weight_map": { "model.x": "model-1.safetensors", "mtp.a": "model-1.safetensors", "mtp.b": "model-2.safetensors"}})) .unwrap(), ), ]) } fn hashes() -> BTreeMap { let (a, b, _) = payloads(); BTreeMap::from([ ("mtp.a".to_owned(), hex::encode(Sha256::digest(&a))), ("mtp.b".to_owned(), hex::encode(Sha256::digest(&b))), ]) } /// How the fake mirror misbehaves (the Python tests' `Mirror`). #[derive(Clone, Default)] struct Mode { ignore_range: bool, cut: bool, /// Ranges of these tensors are returned bit-flipped. wrong: HashSet, } struct Mirror { url: String, mode: Arc>, ranges: Arc>>, } fn span(name: &str, tensor: &str) -> Option<(u64, u64)> { let raw = files().remove(name)?; let n = u64::from_le_bytes(raw[..8].try_into().unwrap()); let header: Value = serde_json::from_slice(&raw[8..8 + n as usize]).unwrap(); let meta = header.get(tensor)?; let (a, b) = ( meta["data_offsets"][0].as_u64().unwrap(), meta["data_offsets"][1].as_u64().unwrap(), ); Some((8 + n + a, 8 + n + b - 1)) } fn serve() -> Mirror { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let url = format!("http://{}/", listener.local_addr().unwrap()); let mode = Arc::new(Mutex::new(Mode::default())); let ranges = Arc::new(Mutex::new(Vec::new())); let (m, r) = (mode.clone(), ranges.clone()); thread::spawn(move || { let files = files(); for stream in listener.incoming() { let Ok(mut stream) = stream else { continue }; let (mode, ranges, files) = (m.clone(), r.clone(), files.clone()); thread::spawn(move || { let mut request = Vec::new(); let mut buffer = [0u8; 1024]; while !request.ends_with(b"\r\n\r\n") { match stream.read(&mut buffer) { Ok(0) | Err(_) => return, Ok(n) => request.extend_from_slice(&buffer[..n]), } } let text = String::from_utf8_lossy(&request).into_owned(); let mut lines = text.lines(); let first = lines.next().unwrap_or_default(); let (method, path) = { let mut parts = first.split(' '); ( parts.next().unwrap_or_default(), parts.next().unwrap_or_default().trim_start_matches('/'), ) }; let range = text.lines().find_map(|l| { l.to_ascii_lowercase() .strip_prefix("range: bytes=") .map(|r| { let (a, b) = r.split_once('-').unwrap(); ( a.trim().parse::().unwrap(), b.trim().parse::().unwrap(), ) }) }); let Some(body) = files.get(path) else { let _ = stream.write_all( b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", ); return; }; let mode = mode.lock().unwrap().clone(); let respond = |stream: &mut std::net::TcpStream, status: &str, extra: &str, bytes: &[u8]| { let head = format!( "HTTP/1.1 {status}\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n", if method == "HEAD" { body.len() } else { bytes.len() } ); let _ = stream.write_all(head.as_bytes()); if method != "HEAD" { let _ = stream.write_all(bytes); } }; match range { None => respond(&mut stream, "200 OK", "", body), Some((a, b)) => { ranges.lock().unwrap().push((path.to_owned(), a, b)); if mode.ignore_range { let sent = if mode.cut { &body[..(b - a + 1) as usize] } else { &body[..] }; respond(&mut stream, "200 OK", "", sent); } else { let mut part = body[a as usize..=b as usize].to_vec(); if ["mtp.a", "mtp.b"] .iter() .any(|t| mode.wrong.contains(*t) && span(path, t) == Some((a, b))) { part.iter_mut().for_each(|x| *x ^= 0xff); } let header = format!("Content-Range: bytes {a}-{b}/{}\r\n", body.len()); respond(&mut stream, "206 Partial Content", &header, &part); } } } }); } }); Mirror { url, mode, ranges } } fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("mtp-fetch-{}-{name}", std::process::id())); let _ = fs::remove_dir_all(&dir); fs::create_dir_all(&dir).unwrap(); dir } fn fetcher(mirror: &Mirror) -> Fetcher { Fetcher::new(mirror.url.clone(), mirror.url.clone()) .unwrap() .with_hashes(hashes()) .without_backoff() } fn tensor(out: &Path, name: &str) -> Vec { fs::read(out.join("tensors").join(format!("{name}.bin"))).unwrap() } #[test] fn a_range_read_needs_a_206_with_the_asked_content_range() { check_range(206, Some("bytes 10-19/100"), 10, 19).unwrap(); for (status, content_range) in [ (200, None), (200, Some("bytes 10-19/100")), (206, Some("bytes 0-9/100")), (206, None), ] { assert!( check_range(status, content_range, 10, 19).is_err(), "{status} {content_range:?}" ); } } #[tokio::test] async fn a_mirror_that_ignores_range_is_refused() { for cut in [false, true] { let mirror = serve(); *mirror.mode.lock().unwrap() = Mode { ignore_range: true, cut, ..Mode::default() }; let error = fetcher(&mirror) .get(&format!("{}model-1.safetensors", mirror.url), Some((8, 15))) .await .unwrap_err() .to_string(); assert!(error.contains("not honoured"), "{error}"); } } #[tokio::test] async fn fetch_from_an_honest_mirror_then_verify() { let mirror = serve(); let out = scratch("honest"); let f = fetcher(&mirror); f.fetch(&out, None).await.unwrap(); let (a, b, _) = payloads(); assert_eq!((tensor(&out, "mtp.a"), tensor(&out, "mtp.b")), (a, b)); let manifest: Value = serde_json::from_slice(&fs::read(out.join("mtp-manifest.json")).unwrap()).unwrap(); let got: BTreeMap = manifest .as_array() .unwrap() .iter() .map(|r| { ( r["name"].as_str().unwrap().to_owned(), r["sha256"].as_str().unwrap().to_owned(), ) }) .collect(); assert_eq!(got, hashes()); assert!(f.verify(&out).is_empty()); } #[tokio::test] async fn wrong_bytes_are_fetched_again_once_then_refused() { let mirror = serve(); let out = scratch("wrong"); let f = fetcher(&mirror); f.fetch(&out, None).await.unwrap(); // an install the #327 mirror corrupted: right size, wrong bytes fs::write(out.join("tensors/mtp.a.bin"), vec![0u8; 64]).unwrap(); assert_eq!(f.verify(&out), ["mtp.a"]); f.fetch(&out, None).await.unwrap(); // setup runs fetch again: the bad one is fetched again assert_eq!(tensor(&out, "mtp.a"), payloads().0); assert!(f.verify(&out).is_empty()); fs::remove_file(out.join("tensors/mtp.b.bin")).unwrap(); mirror.mode.lock().unwrap().wrong.insert("mtp.b".to_owned()); let error = f.fetch(&out, None).await.unwrap_err().to_string(); assert!(error.contains("is not the checkpoint's"), "{error}"); assert!(!out.join("tensors/mtp.b.bin").exists()); } #[tokio::test] async fn an_inventory_from_another_revision_is_read_again() { let mirror = serve(); let out = scratch("revision"); let f = fetcher(&mirror); f.fetch(&out, None).await.unwrap(); let mut inventory: Value = serde_json::from_slice(&fs::read(out.join("mtp-inventory.json")).unwrap()).unwrap(); inventory["repo"] = json!("https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/"); for row in inventory["tensors"].as_array_mut().unwrap() { // that revision's ranges: not this one's row["start"] = json!(row["start"].as_u64().unwrap() + 1); row["end"] = json!(row["end"].as_u64().unwrap() + 1); } fs::write( out.join("mtp-inventory.json"), serde_json::to_vec(&inventory).unwrap(), ) .unwrap(); let (a, b, _) = payloads(); fs::write(out.join("tensors/mtp.b.bin"), &b[..10]).unwrap(); // half a tensor from that revision mirror.ranges.lock().unwrap().clear(); f.fetch(&out, None).await.unwrap(); let again: Value = serde_json::from_slice(&fs::read(out.join("mtp-inventory.json")).unwrap()).unwrap(); assert_eq!(again["repo"].as_str().unwrap(), mirror.url); assert_eq!( (tensor(&out, "mtp.a"), tensor(&out, "mtp.b")), (a.clone(), b.clone()) ); let fetched: Vec<_> = mirror .ranges .lock() .unwrap() .iter() .filter(|(_, s, e)| e - s + 1 == a.len() as u64 || e - s + 1 == b.len() as u64) .cloned() .collect(); let (start, end) = span("model-2.safetensors", "mtp.b").unwrap(); assert_eq!( fetched, [("model-2.safetensors".to_owned(), start, end)], "mtp.a was right and is kept; mtp.b is fetched whole" ); } #[tokio::test] async fn verify_keeps_its_verdict_and_skips_other_revisions() { let mirror = serve(); let out = scratch("verdict"); let f = fetcher(&mirror); f.fetch(&out, None).await.unwrap(); assert!(f.verify(&out).is_empty()); let stamps: Value = serde_json::from_slice(&fs::read(out.join("tensors/verified.json")).unwrap()).unwrap(); assert_eq!( stamps.as_object().unwrap().keys().collect::>(), ["mtp.a", "mtp.b"] ); // wrong bytes of the same size and mtime keep the cached verdict: nothing is hashed again let path = out.join("tensors/mtp.a.bin"); let mtime = fs::metadata(&path).unwrap().modified().unwrap(); fs::write(&path, vec![9u8; 64]).unwrap(); fs::File::options() .write(true) .open(&path) .unwrap() .set_modified(mtime) .unwrap(); assert!(f.verify(&out).is_empty()); // another revision (STRATA_MTP_REVISION): other hashes, nothing to check let other = Fetcher::new( "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/".to_owned(), mirror.url.clone(), ) .unwrap() .with_hashes(hashes()); assert!(other.verify(&out).is_empty()); // a changed mtime hashes the file again fs::write(&path, vec![9u8; 64]).unwrap(); fs::File::options() .write(true) .open(&path) .unwrap() .set_modified(mtime + std::time::Duration::from_secs(5)) .unwrap(); assert_eq!(f.verify(&out), ["mtp.a"]); assert!(f.verify(&out.join("nothing")).is_empty()); } #[test] fn the_pinned_table_has_31_sha256_hashes_for_the_pinned_revision() { assert_eq!(strata_control::mtp_fetch::SHA256.len(), 31); for (name, hash) in strata_control::mtp_fetch::SHA256 { assert!(name.starts_with("mtp.")); assert!( hash.len() == 64 && hash .bytes() .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) ); } assert_eq!(strata_control::mtp_fetch::PINNED_REVISION.len(), 40); }