Files
leleka/control-plane/tests/mtp_fetch.rs
T

278 lines
9.3 KiB
Rust

//! `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,
fs,
path::{Path, PathBuf},
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use strata_control::mtp_fetch::{Fetcher, check_range};
#[path = "mtp_fetch/mirror.rs"]
mod mirror;
use mirror::{Mirror, Mode, serve, span};
fn shard(tensors: &[(&str, &[u8])]) -> Vec<u8> {
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<u8>, Vec<u8>, Vec<u8>) {
let a: Vec<u8> = (0..64).collect();
let b: Vec<u8> = (100..164).chain(100..164).collect();
(a, b, vec![7u8; 48])
}
fn files() -> BTreeMap<String, Vec<u8>> {
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<String, String> {
let (a, b, _) = payloads();
BTreeMap::from([
("mtp.a".to_owned(), hex::encode(Sha256::digest(&a))),
("mtp.b".to_owned(), hex::encode(Sha256::digest(&b))),
])
}
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<u8> {
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<String, String> = 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());
}
fn read_json(path: &Path) -> Value {
serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
}
/// Rewrites the inventory as another revision's: its repo and ranges that are not this one's.
fn age_inventory(out: &Path) {
let mut inventory = read_json(&out.join("mtp-inventory.json"));
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();
}
/// The ranges the mirror served that were the size of a whole tensor (`a` or `b`).
fn whole_tensor_ranges(mirror: &Mirror, sizes: (usize, usize)) -> Vec<(String, u64, u64)> {
let (a, b) = (sizes.0 as u64, sizes.1 as u64);
let ranges = mirror.ranges.lock().unwrap();
let whole = ranges
.iter()
.filter(|(_, s, e)| e - s + 1 == a || e - s + 1 == b);
whole.cloned().collect()
}
#[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();
age_inventory(&out);
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 = read_json(&out.join("mtp-inventory.json"));
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 = whole_tensor_ranges(&mirror, (a.len(), b.len()));
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"
);
}
/// Replaces `mtp.a` with wrong bytes of the same size and sets its modification time to `mtime`.
fn overwrite_keeping_mtime(path: &Path, mtime: std::time::SystemTime) {
fs::write(path, vec![9u8; 64]).unwrap();
fs::File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(mtime)
.unwrap();
}
fn assert_verdicts_were_stamped(out: &Path) {
let stamps = read_json(&out.join("tensors/verified.json"));
assert_eq!(
stamps.as_object().unwrap().keys().collect::<Vec<_>>(),
["mtp.a", "mtp.b"]
);
}
/// another revision (STRATA_MTP_REVISION): other hashes, nothing to check
fn other_revision_fetcher(mirror: &Mirror) -> Fetcher {
Fetcher::new(
"https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/".to_owned(),
mirror.url.clone(),
)
.unwrap()
.with_hashes(hashes())
}
#[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());
assert_verdicts_were_stamped(&out);
// 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();
overwrite_keeping_mtime(&path, mtime);
assert!(f.verify(&out).is_empty());
assert!(other_revision_fetcher(&mirror).verify(&out).is_empty());
// a changed mtime hashes the file again
overwrite_keeping_mtime(&path, mtime + std::time::Duration::from_secs(5));
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);
}