feat(mtp-fetch): port tools/mtp_fetch.py (inventory/fetch/verify) with a local-mirror differential

Pinned 31-entry SHA-256 table, 206 + exact Content-Range, retry-once on wrong bytes, inventory re-read on a revision
change, verified.json stamps. model::http_client is now shared. Tests port test_mtp_fetch.py onto a real local HTTP
mirror; scripts/offline/diff_mtp_fetch.py runs the unmodified Python against the same mirror (10 scenarios).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 15:43:43 +02:00
co-authored by Claude Sonnet 5.5
parent 3485221865
commit 08dbe0abe0
6 changed files with 1284 additions and 7 deletions
+1
View File
@@ -31,6 +31,7 @@ pub mod metrics;
pub mod model;
pub mod model_pipeline;
pub mod models_api;
pub mod mtp_fetch;
pub mod mtp_pack;
pub mod native_model;
pub mod native_pack;
+9 -2
View File
@@ -12,7 +12,14 @@ use strata_control::{
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = env::args().skip(1).collect();
match args.as_slice() {
[command, rest @ ..] if command == "tools" && rest.first().is_some_and(|c| c != "mtp-fetch") => {
[command, sub, rest @ ..] if command == "tools" && sub == "mtp-fetch" => {
let code = strata_control::mtp_fetch::cli(rest).await?;
if code != 0 {
std::process::exit(code);
}
Ok(())
}
[command, rest @ ..] if command == "tools" => {
print!("{}", leleka_offline_tools::cli::run(rest)?);
Ok(())
}
@@ -815,7 +822,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
print!("{}", include_str!("../third_party/ggml/LICENSE"));
Ok(())
}
_ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model pre-tokenize-batch|model tokenize-batch TOKENIZER_DIR [--special]|model detokenize-batch TOKENIZER_DIR|model detokenize TOKENIZER_DIR IDS|tools embd-bf16-pack --model DIR --out FILE.gguf|tools ple-fp8-pack --model DIR --out FILE.gguf|tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic] [--out IDS.bin] [--stats]|tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]|tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]]".into()),
_ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model pre-tokenize-batch|model tokenize-batch TOKENIZER_DIR [--special]|model detokenize-batch TOKENIZER_DIR|model detokenize TOKENIZER_DIR IDS|tools embd-bf16-pack --model DIR --out FILE.gguf|tools ple-fp8-pack --model DIR --out FILE.gguf|tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic] [--out IDS.bin] [--stats]|tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]|tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]]".into()),
}
}
+11 -5
View File
@@ -98,16 +98,16 @@ pub async fn verify(manifest: &Manifest, output: &Path) -> Result<()> {
Ok(())
}
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
/// The HTTP client every acquisition path uses: HTTPS with the bundled root set, loopback HTTP for local mirrors and
/// tests, no redirects to other schemes or with credentials.
pub(crate) fn http_client() -> Result<Client> {
// 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
.iter()
.map(|der| reqwest::Certificate::from_der(der.as_ref()))
.collect::<std::result::Result<Vec<_>, _>>()?;
let client = Client::builder()
Ok(Client::builder()
.tls_certs_only(roots)
.connect_timeout(Duration::from_secs(30))
.read_timeout(Duration::from_secs(120))
@@ -128,7 +128,13 @@ pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
attempt.error("refusing a non-HTTPS model redirect")
}
}))
.build()?;
.build()?)
}
pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> {
fs::create_dir_all(output).await?;
preflight_space(manifest, output).await?;
let client = http_client()?;
let hub_token = match std::env::var("HF_TOKEN") {
Ok(token) if token.is_empty() => None,
Ok(token) if token.chars().any(char::is_whitespace) => {
+693
View File
@@ -0,0 +1,693 @@
//! `tools/mtp_fetch.py`: the MTP block of the BF16 checkpoint without the checkpoint.
//!
//! The GSQ-RCO GGUF ships no MTP head; the BF16 checkpoint (Qwen/Qwen3.8-Flash-Next, 131 shards) has 31 `mtp.*`
//! tensors scattered over 28 shards. Safetensors puts a JSON header (name -> dtype, shape, byte range) at the start of
//! each shard, so HTTP range requests read the headers and then only the MTP tensors.
//!
//! * `inventory --out DIR`: headers only; writes `mtp-inventory.json` and `.md`.
//! * `fetch --out DIR [--only SUBSTR]`: the tensors themselves, resumable; one raw file per tensor plus
//! `mtp-manifest.json`.
//! * `verify --out DIR`: the fetched tensors against SHA-256 (exit 3: some are missing or wrong).
//!
//! #327: a mirror or proxy that ignores the Range header answers 200 with the whole shard, and a proxy may cut that to
//! the requested length, so neither the size nor a hash of what was downloaded catches it. A range read therefore needs
//! a 206 whose Content-Range is the range asked for, and every tensor of the pinned revision is checked against the
//! SHA-256 table below.
use std::{
collections::{BTreeMap, BTreeSet},
error::Error,
fs::{self, File, OpenOptions},
io::{Read, Write},
path::{Path, PathBuf},
time::Duration,
};
use reqwest::{
Client, StatusCode,
header::{CONTENT_RANGE, RANGE, USER_AGENT},
};
use serde::Serialize;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
type Result<T> = std::result::Result<T, Box<dyn Error>>;
/// A fixed commit of the checkpoint (its `sha` on 2026-09-30), so every install reads the same tensors;
/// `STRATA_MTP_REVISION` overrides it (e.g. `main`).
pub const PINNED_REVISION: &str = "de4b8e4d43b917e7706784d8bb445c9af86a3540";
/// `verify`'s exit code: a tensor is missing or corrupt.
pub const BAD: i32 = 3;
const CHUNK: u64 = 64 << 20;
const HEADERS_ATTEMPTS: u32 = 4;
/// SHA-256 of every MTP tensor's bytes at [`PINNED_REVISION`] (verbatim from `mtp_fetch.py`).
pub const SHA256: &[(&str, &str)] = &[
(
"mtp.fc_embedding.weight",
"241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751",
),
(
"mtp.fc_hidden.weight",
"97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96",
),
(
"mtp.hyper_connection_mixer.hc_norm.weight",
"ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64",
),
(
"mtp.hyper_connection_mixer.input_mix_weight_down.weight",
"c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947",
),
(
"mtp.hyper_connection_mixer.input_mix_weight_up.weight",
"6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13",
),
(
"mtp.layers.0.attn_hyper_connection.block_inject_weight.weight",
"c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c",
),
(
"mtp.layers.0.attn_hyper_connection.hc_norm.weight",
"1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809",
),
(
"mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight",
"e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5",
),
(
"mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight",
"f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5",
),
(
"mtp.layers.0.mlp.experts.down_proj",
"539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0",
),
(
"mtp.layers.0.mlp.experts.gate_up_proj",
"839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5",
),
(
"mtp.layers.0.mlp.gate.weight",
"f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20",
),
(
"mtp.layers.0.mlp.shared_expert.down_proj.weight",
"d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8",
),
(
"mtp.layers.0.mlp.shared_expert.gate_proj.weight",
"f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c",
),
(
"mtp.layers.0.mlp.shared_expert.up_proj.weight",
"172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156",
),
(
"mtp.layers.0.mlp.shared_expert_gate.weight",
"acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e",
),
(
"mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight",
"c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6",
),
(
"mtp.layers.0.mlp_hyper_connection.hc_norm.weight",
"21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1",
),
(
"mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight",
"b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1",
),
(
"mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight",
"40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94",
),
(
"mtp.layers.0.self_attn.indexer.index_qk_proj.weight",
"2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859",
),
(
"mtp.layers.0.self_attn.indexer.k_layernorm.weight",
"2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54",
),
(
"mtp.layers.0.self_attn.indexer.q_layernorm.weight",
"afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6",
),
(
"mtp.layers.0.self_attn.k_norm.weight",
"8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd",
),
(
"mtp.layers.0.self_attn.k_proj.weight",
"1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38",
),
(
"mtp.layers.0.self_attn.o_proj.weight",
"9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219",
),
(
"mtp.layers.0.self_attn.q_norm.weight",
"57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef",
),
(
"mtp.layers.0.self_attn.q_proj.weight",
"5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d",
),
(
"mtp.layers.0.self_attn.v_proj.weight",
"39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41",
),
(
"mtp.pre_fc_norm_embedding.weight",
"04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86",
),
(
"mtp.pre_fc_norm_hidden.weight",
"b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d",
),
];
fn repo_url(revision: &str) -> String {
format!("https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/{revision}/")
}
/// One MTP tensor of the checkpoint: where its bytes are in which shard.
#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
pub struct Row {
pub name: String,
pub shard: String,
pub dtype: String,
pub shape: Vec<u64>,
pub start: u64,
pub end: u64,
pub bytes: u64,
}
#[derive(Serialize)]
struct Inventory<'a> {
repo: &'a str,
total_bytes: u64,
tensors: &'a [Row],
}
#[derive(Serialize)]
struct ManifestRow<'a> {
#[serde(flatten)]
row: &'a Row,
file: String,
sha256: String,
}
/// Python's `json.dump(..., indent=1)`.
fn json_indent1<T: Serialize>(value: &T) -> Result<Vec<u8>> {
let mut out = Vec::new();
let formatter = serde_json::ser::PrettyFormatter::with_indent(b" ");
let mut serializer = serde_json::Serializer::with_formatter(&mut out, formatter);
value.serialize(&mut serializer)?;
Ok(out)
}
pub struct Fetcher {
client: Client,
/// Where the shards are read from (ends with `/`).
repo: String,
/// The revision the hashes belong to.
pinned: String,
sha256: BTreeMap<String, String>,
backoff: fn(u32) -> Duration,
}
/// #327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`.
pub fn check_range(status: u16, content_range: Option<&str>, start: u64, end: u64) -> Result<()> {
if status != 206 {
return Err(format!(
"range request not honoured: HTTP {status} instead of 206 (a mirror or proxy that ignores the Range header sends the whole file)"
)
.into());
}
let want = format!("bytes {start}-{end}/");
if !content_range.unwrap_or("").trim().starts_with(&want) {
return Err(format!(
"range request answered with Content-Range {content_range:?}, not {want}..."
)
.into());
}
Ok(())
}
fn sha256_of(path: &Path) -> Result<String> {
let mut hasher = Sha256::new();
let mut file = File::open(path)?;
let mut buffer = vec![0u8; 1 << 24];
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
hasher.update(&buffer[..n]);
}
Ok(hex::encode(hasher.finalize()))
}
impl Fetcher {
/// The production configuration: the pinned revision, or `STRATA_MTP_REVISION`.
pub fn from_env() -> Result<Self> {
let revision = std::env::var("STRATA_MTP_REVISION")
.ok()
.filter(|r| !r.is_empty())
.unwrap_or_else(|| PINNED_REVISION.to_owned());
Self::new(repo_url(&revision), repo_url(PINNED_REVISION))
}
pub fn new(repo: String, pinned: String) -> Result<Self> {
Ok(Self {
client: crate::model::http_client()?,
repo,
pinned,
sha256: SHA256
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect(),
backoff: |attempt| Duration::from_secs(1 << attempt),
})
}
/// Replace the SHA-256 table (local mirrors and tests).
pub fn with_hashes(mut self, table: BTreeMap<String, String>) -> Self {
self.sha256 = table;
self
}
pub fn without_backoff(mut self) -> Self {
self.backoff = |_| Duration::ZERO;
self
}
pub fn repo(&self) -> &str {
&self.repo
}
/// The tensors' hashes are the pinned revision's: they apply when this run reads that revision.
pub fn pinned(&self) -> bool {
self.repo == self.pinned
}
async fn get_once(&self, url: &str, range: Option<(u64, u64)>) -> Result<Vec<u8>> {
let mut request = self.client.get(url).header(USER_AGENT, "strata-mtp-fetch");
if let Some((start, end)) = range {
request = request.header(RANGE, format!("bytes={start}-{end}"));
}
let response = request.send().await?;
let status = response.status();
match range {
Some((start, end)) => {
let content_range = response
.headers()
.get(CONTENT_RANGE)
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
check_range(status.as_u16(), content_range.as_deref(), start, end)?;
}
None if !status.is_success() => {
return Err(format!("HTTP {status} for {url}").into());
}
None => {}
}
let data = response.bytes().await?.to_vec();
if let Some((start, end)) = range
&& data.len() as u64 != end - start + 1
{
return Err(format!("short range read: {} of {}", data.len(), end - start + 1).into());
}
Ok(data)
}
/// `get`: network errors are retried (4 attempts, 1 s, 2 s, 4 s apart), then surfaced.
pub async fn get(&self, url: &str, range: Option<(u64, u64)>) -> Result<Vec<u8>> {
for attempt in 0..HEADERS_ATTEMPTS {
match self.get_once(url, range).await {
Ok(data) => return Ok(data),
Err(error) if attempt + 1 == HEADERS_ATTEMPTS => return Err(error),
Err(error) => {
tokio::time::sleep((self.backoff)(attempt)).await;
eprintln!("retry {url}: {error}");
}
}
}
unreachable!("the last attempt returns")
}
/// The pinned revision's files, or the repository's current ones when that revision is gone (a 404 on its index).
pub async fn resolve_repo(&mut self) {
let url = format!("{}model.safetensors.index.json", self.repo);
let head = self
.client
.head(&url)
.header(USER_AGENT, "strata-mtp-fetch")
.send()
.await;
if let Ok(response) = head
&& response.status() == StatusCode::NOT_FOUND
&& !self.repo.contains("/resolve/main/")
{
eprintln!("the checkpoint's pinned revision is gone: reading its current files (main)");
if let Some(at) = self.repo.rfind("/resolve/") {
self.repo = format!("{}/resolve/main/", &self.repo[..at]);
}
}
}
async fn shard_header(&self, shard: &str) -> Result<(u64, Map<String, Value>)> {
let url = format!("{}{shard}", self.repo);
let length: [u8; 8] = self
.get(&url, Some((0, 7)))
.await?
.try_into()
.map_err(|_| "short safetensors length prefix")?;
let n = u64::from_le_bytes(length);
let header = self.get(&url, Some((8, 8 + n - 1))).await?;
match serde_json::from_slice(&header)? {
Value::Object(map) => Ok((8 + n, map)),
_ => Err("safetensors header is not an object".into()),
}
}
pub async fn inventory(&self, out: &Path) -> Result<Vec<Row>> {
let index: Value = serde_json::from_slice(
&self
.get(&format!("{}model.safetensors.index.json", self.repo), None)
.await?,
)?;
let mtp: BTreeMap<String, String> = index["weight_map"]
.as_object()
.ok_or("index has no weight_map")?
.iter()
.filter(|(k, _)| k.starts_with("mtp."))
.map(|(k, v)| {
Ok((
k.clone(),
v.as_str().ok_or("shard name expected")?.to_owned(),
))
})
.collect::<Result<_>>()?;
let mut rows = Vec::new();
let mut total = 0u64;
for shard in mtp.values().collect::<BTreeSet<_>>() {
let (base, header) = self.shard_header(shard).await?;
for (name, meta) in &header {
if mtp.get(name) == Some(shard) {
let offsets = meta["data_offsets"]
.as_array()
.and_then(|o| Some((o.first()?.as_u64()?, o.get(1)?.as_u64()?)))
.ok_or("data_offsets must hold two numbers")?;
rows.push(Row {
name: name.clone(),
shard: shard.clone(),
dtype: meta["dtype"].as_str().unwrap_or_default().to_owned(),
shape: meta["shape"]
.as_array()
.map(|s| s.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default(),
start: base + offsets.0,
end: base + offsets.1 - 1,
bytes: offsets.1 - offsets.0,
});
total += offsets.1 - offsets.0;
}
}
}
let found: BTreeSet<&String> = rows.iter().map(|r| &r.name).collect();
let missing: Vec<&String> = mtp.keys().filter(|k| !found.contains(k)).collect();
if !missing.is_empty() {
return Err(format!(
"tensors named in the index but absent from their shard headers: {missing:?}"
)
.into());
}
rows.sort_by(|a, b| a.name.cmp(&b.name));
fs::create_dir_all(out)?;
fs::write(
out.join("mtp-inventory.json"),
json_indent1(&Inventory {
repo: &self.repo,
total_bytes: total,
tensors: &rows,
})?,
)?;
let mut lines = vec![
"# MTP block in the BF16 checkpoint".to_owned(),
String::new(),
format!(
"{} tensors, {:.3} GB, in {} shards.",
rows.len(),
total as f64 / 1e9,
rows.iter().map(|r| &r.shard).collect::<BTreeSet<_>>().len()
),
String::new(),
"| tensor | dtype | shape | MB |".to_owned(),
"|---|---|---|---:|".to_owned(),
];
for r in &rows {
lines.push(format!(
"| `{}` | {} | {} | {:.1} |",
r.name,
r.dtype,
r.shape
.iter()
.map(u64::to_string)
.collect::<Vec<_>>()
.join("x"),
r.bytes as f64 / 1e6
));
}
let text = lines.join("\n") + "\n";
fs::write(out.join("mtp-inventory.md"), &text)?;
print!("{text}");
Ok(rows)
}
pub async fn fetch(&self, out: &Path, only: Option<&str>) -> Result<()> {
let tensors_dir = out.join("tensors");
let stored: Option<Value> = fs::read(out.join("mtp-inventory.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok());
// The byte ranges belong to one revision: an inventory read from another repository or revision is read again,
// and a tensor fetched from there is not resumed - it is kept only when it is the pinned revision's (sha256).
let same = stored
.as_ref()
.is_some_and(|inv| inv["repo"].as_str() == Some(self.repo.as_str()));
let rows: Vec<Row> = match (&stored, same) {
(Some(inv), true) => inv["tensors"]
.as_array()
.ok_or("inventory has no tensors")?
.iter()
.map(|t| {
Ok(Row {
name: t["name"].as_str().ok_or("name")?.to_owned(),
shard: t["shard"].as_str().ok_or("shard")?.to_owned(),
dtype: t["dtype"].as_str().unwrap_or_default().to_owned(),
shape: t["shape"]
.as_array()
.map(|s| s.iter().filter_map(Value::as_u64).collect())
.unwrap_or_default(),
start: t["start"].as_u64().ok_or("start")?,
end: t["end"].as_u64().ok_or("end")?,
bytes: t["bytes"].as_u64().ok_or("bytes")?,
})
})
.collect::<Result<_>>()?,
_ => self.inventory(out).await?,
};
fs::create_dir_all(&tensors_dir)?;
let mut manifest = Vec::new();
for row in &rows {
if only.is_some_and(|o| !row.name.contains(o)) {
continue;
}
let path = tensors_dir.join(format!("{}.bin", row.name));
let want = if self.pinned() {
self.sha256.get(&row.name).cloned()
} else {
None
};
if path.exists()
&& !same
&& (want.is_none()
|| fs::metadata(&path)?.len() != row.bytes
|| Some(sha256_of(&path)?) != want)
{
fs::remove_file(&path)?;
}
let mut digest = String::new();
for attempt in 0..2 {
let mut have = fs::metadata(&path).map_or(0, |m| m.len());
if have > row.bytes {
fs::remove_file(&path)?;
have = 0;
}
let mut file = OpenOptions::new().create(true).append(true).open(&path)?;
let mut position = row.start + have;
while position <= row.end {
let end = (position + CHUNK - 1).min(row.end);
let data = self
.get(
&format!("{}{}", self.repo, row.shard),
Some((position, end)),
)
.await?;
file.write_all(&data)?;
position = end + 1;
eprintln!(
"{} {:.0}%",
row.name,
100.0 * (position - row.start) as f64 / row.bytes as f64
);
}
file.sync_all()?;
drop(file);
let size = fs::metadata(&path)?.len();
if size != row.bytes {
return Err(format!("{}: size {size} != {}", path.display(), row.bytes).into());
}
digest = sha256_of(&path)?;
if want.is_none() || want.as_deref() == Some(digest.as_str()) {
break;
}
fs::remove_file(&path)?; // wrong bytes (#327): the whole tensor again, once
if attempt > 0 {
return Err(format!(
"{}: sha256 {digest} is not the checkpoint's {} - the download source sends wrong data (a mirror that ignores Range requests?)",
row.name,
want.unwrap_or_default()
)
.into());
}
eprintln!(
"{}: wrong bytes (sha256 {}...), fetching it again",
row.name,
&digest[..12]
);
}
manifest.push((
row,
path.strip_prefix(out)?.to_string_lossy().into_owned(),
digest,
));
}
let rows: Vec<ManifestRow> = manifest
.iter()
.map(|(row, file, sha)| ManifestRow {
row,
file: file.clone(),
sha256: sha.clone(),
})
.collect();
fs::write(out.join("mtp-manifest.json"), json_indent1(&rows)?)?;
Ok(())
}
/// #327: the fetched tensors against SHA-256 -> the names that are missing or wrong. Empty when they are right, or
/// when there is nothing to check (no `tensors/`, or another revision is in use). A tensor's verdict is kept in
/// `tensors/verified.json` by size and mtime, so a later run hashes only what changed.
pub fn verify(&self, out: &Path) -> Vec<String> {
let tensors_dir = out.join("tensors");
if !self.pinned() || !tensors_dir.is_dir() {
return Vec::new();
}
let stamp_path = tensors_dir.join("verified.json");
let stamps: BTreeMap<String, Value> = fs::read(&stamp_path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default();
let (mut bad, mut good) = (Vec::new(), BTreeMap::new());
for (name, want) in &self.sha256 {
let path = tensors_dir.join(format!("{name}.bin"));
let Ok(metadata) = fs::metadata(&path) else {
bad.push(name.clone());
continue;
};
let key = serde_json::json!([metadata.len(), mtime_ns(&metadata), want]);
if stamps.get(name) != Some(&key) && sha256_of(&path).ok().as_deref() != Some(want) {
bad.push(name.clone());
continue;
}
good.insert(name.clone(), key);
}
if let Ok(bytes) = json_indent1(&good) {
let _ = fs::write(&stamp_path, bytes);
}
bad
}
}
#[cfg(unix)]
fn mtime_ns(metadata: &fs::Metadata) -> i128 {
use std::os::unix::fs::MetadataExt;
i128::from(metadata.mtime()) * 1_000_000_000 + i128::from(metadata.mtime_nsec())
}
#[cfg(not(unix))]
fn mtime_ns(metadata: &fs::Metadata) -> i128 {
metadata
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos() as i128)
}
/// `strata-next tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]`.
/// `--repo` points both the read and the pinned revision at a local mirror and `--sha256-file` (a JSON object of
/// name -> hex) replaces the pinned table; both exist for mirrors and for the differential harness. Returns the
/// process exit code.
pub async fn cli(args: &[String]) -> Result<i32> {
let [command, rest @ ..] = args else {
return Err(
"usage: tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]".into(),
);
};
let value = |name: &str| -> Result<Option<&str>> {
match rest.iter().position(|a| a == name) {
None => Ok(None),
Some(at) => rest
.get(at + 1)
.map(|v| Some(v.as_str()))
.ok_or_else(|| format!("{name} needs a value").into()),
}
};
let out = PathBuf::from(value("--out")?.ok_or("--out is required")?);
let mut fetcher = match value("--repo")? {
Some(repo) => {
let repo = if repo.ends_with('/') {
repo.to_owned()
} else {
format!("{repo}/")
};
Fetcher::new(repo.clone(), repo)?
}
None => Fetcher::from_env()?,
};
if let Some(path) = value("--sha256-file")? {
fetcher = fetcher.with_hashes(serde_json::from_slice(&fs::read(path)?)?);
}
match command.as_str() {
"verify" => {
let bad = fetcher.verify(&out);
for name in &bad {
eprintln!("MTP tensor missing or corrupt: {name}");
}
Ok(if bad.is_empty() { 0 } else { BAD })
}
"inventory" => {
fetcher.resolve_repo().await;
fetcher.inventory(&out).await?;
Ok(0)
}
"fetch" => {
fetcher.resolve_repo().await;
fetcher.fetch(&out, value("--only")?).await?;
Ok(0)
}
other => Err(format!("unknown mtp-fetch command {other}").into()),
}
}
+384
View File
@@ -0,0 +1,384 @@
//! `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<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))),
])
}
/// 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<String>,
}
struct Mirror {
url: String,
mode: Arc<Mutex<Mode>>,
ranges: Arc<Mutex<Vec<(String, u64, u64)>>>,
}
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::<u64>().unwrap(),
b.trim().parse::<u64>().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<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());
}
#[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::<Vec<_>>(),
["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);
}
+186
View File
@@ -0,0 +1,186 @@
#!/usr/bin/env python3
"""mtp_fetch differential: `strata-next tools mtp-fetch` vs the unmodified tools/mtp_fetch.py, both against the same
local HTTP mirror of a fake checkpoint (the fixture pattern of tools/test_mtp_fetch.py, here a real socket).
Scenarios: honest fetch + verify; a corrupted install re-fetched; a resumed half tensor; `--only`; a mirror that
ignores Range (both must refuse and leave no tensor); inventory-only. After each, the output directories must
match file for file (inventory json/md, manifest, every tensor, verified.json modulo mtime).
python scripts/offline/diff_mtp_fetch.py <strata-next>
"""
import hashlib
import http.server
import json
import shutil
import struct
import subprocess
import sys
import tempfile
import threading
from pathlib import Path
from unittest import mock
REPO = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / 'engine/strata/tools'))
import mtp_fetch as M # noqa: E402 (the oracle, unchanged)
def shard(tensors):
header, data = {}, b''
for name, blob in tensors:
header[name] = {'dtype': 'BF16', 'shape': [len(blob) // 2], 'data_offsets': [len(data), len(data) + len(blob)]}
data += blob
h = json.dumps(header).encode()
return struct.pack('<Q', len(h)) + h + data
A, B, X = bytes(range(64)), bytes(range(100, 164)) * 2, b'\x07' * 48
C = bytes(range(200, 256)) * 3
FILES = {'model-1.safetensors': shard([('model.x', X), ('mtp.a', A)]),
'model-2.safetensors': shard([('mtp.b', B), ('mtp.c', C)])}
INDEX = json.dumps({'weight_map': {'model.x': 'model-1.safetensors', 'mtp.a': 'model-1.safetensors',
'mtp.b': 'model-2.safetensors', 'mtp.c': 'model-2.safetensors'}}).encode()
HASHES = {n: hashlib.sha256(b).hexdigest() for n, b in (('mtp.a', A), ('mtp.b', B), ('mtp.c', C))}
STATE = {'ignore_range': False, 'cut': False}
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.0'
def log_message(self, *args):
pass
def do_HEAD(self):
self.send_response(200)
self.end_headers()
def do_GET(self):
name = self.path.lstrip('/')
body = INDEX if name == 'model.safetensors.index.json' else FILES.get(name)
if body is None:
self.send_response(404)
self.end_headers()
return
rng = self.headers.get('Range')
if rng is None:
self.send_response(200)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
return
a, b = map(int, rng.split('=')[1].split('-'))
if STATE['ignore_range']:
sent = body[:b - a + 1] if STATE['cut'] else body
self.send_response(200)
self.send_header('Content-Length', str(len(sent)))
self.end_headers()
self.wfile.write(sent)
return
part = body[a:b + 1]
self.send_response(206)
self.send_header('Content-Range', 'bytes %d-%d/%d' % (a, b, len(body)))
self.send_header('Content-Length', str(len(part)))
self.end_headers()
self.wfile.write(part)
def python_run(url, cmd, out, only=None):
"""Run the oracle in-process against `url`; returns (exit code, bad list)."""
with mock.patch.object(M, 'REPO', url), mock.patch.object(M, 'PINNED', url), \
mock.patch.object(M, 'SHA256', HASHES), mock.patch.object(M.time, 'sleep', lambda s: None):
import contextlib
import io
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
try:
if cmd == 'fetch':
M.fetch(str(out), only)
elif cmd == 'inventory':
M.inventory(str(out))
else:
return 0, M.verify(str(out))
return 0, []
except SystemExit as e:
return (e.code if isinstance(e.code, int) else 1), []
except Exception: # noqa: BLE001
return 1, []
def rust_run(binary, url, cmd, out, hashes_file, only=None):
args = [binary, 'tools', 'mtp-fetch', cmd, '--out', str(out), '--repo', url, '--sha256-file', str(hashes_file)]
if only:
args += ['--only', only]
r = subprocess.run(args, capture_output=True, text=True)
bad = [l.split(': ', 1)[1] for l in r.stderr.splitlines() if l.startswith('MTP tensor missing or corrupt: ')]
return r.returncode, bad
def compare(py, rs, label, bad):
names = lambda root: sorted(str(p.relative_to(root)) for p in Path(root).rglob('*') if p.is_file())
if names(py) != names(rs):
bad.append(f'{label}: file sets differ {names(py)} vs {names(rs)}')
return
for name in names(py):
a, b = (Path(py) / name).read_bytes(), (Path(rs) / name).read_bytes()
if name.endswith('verified.json'):
strip = lambda raw: {k: [v[0], v[2]] for k, v in json.loads(raw).items()}
a, b = strip(a), strip(b)
if a != b:
bad.append(f'{label}: {name} differs')
def main():
binary = str(Path(sys.argv[1]).resolve())
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f'http://127.0.0.1:{server.server_address[1]}/'
root = Path(tempfile.mkdtemp(prefix='strata-mtp-fetch-diff-'))
hashes_file = root / 'hashes.json'
hashes_file.write_text(json.dumps(HASHES))
bad, scenarios = [], 0
def both(label, cmd, py, rs, only=None):
nonlocal scenarios
scenarios += 1
pc, pbad = python_run(url, cmd, py, only)
rc, rbad = rust_run(binary, url, cmd, rs, hashes_file, only)
if cmd == 'verify': # the Python main() exits 3 (BAD) when verify() returns names
if pbad != rbad or rc != (3 if pbad else 0):
bad.append(f'{label}: python bad {pbad}, rust exit {rc} bad {rbad}')
elif (pc == 0) != (rc == 0):
bad.append(f'{label}: python exit {pc}, rust exit {rc}')
compare(py, rs, label, bad)
py, rs = root / 'py1', root / 'rs1'
both('fetch', 'fetch', py, rs)
both('verify', 'verify', py, rs)
for out in (py, rs): # a corrupted install, same size
(out / 'tensors/mtp.a.bin').write_bytes(bytes(len(A)))
both('verify finds the corruption', 'verify', py, rs)
both('refetch', 'fetch', py, rs)
both('verify after refetch', 'verify', py, rs)
py, rs = root / 'py2', root / 'rs2'
for out in (py, rs):
(out / 'tensors').mkdir(parents=True)
both('inventory', 'inventory', py, rs)
for out in (py, rs): # a half tensor to resume
(out / 'tensors/mtp.b.bin').write_bytes(B[:37])
both('resume', 'fetch', py, rs)
py, rs = root / 'py3', root / 'rs3'
both('--only', 'fetch', py, rs, only='mtp.c')
STATE.update(ignore_range=True, cut=False)
py, rs = root / 'py4', root / 'rs4'
both('mirror ignoring Range', 'fetch', py, rs)
STATE.update(cut=True)
py, rs = root / 'py5', root / 'rs5'
both('mirror cutting the whole file to the range', 'fetch', py, rs)
STATE.update(ignore_range=False, cut=False)
server.shutdown()
shutil.rmtree(root, ignore_errors=True)
for b in bad:
print('FAIL', b)
print(json.dumps({'scenarios': scenarios, 'failures': len(bad), 'oracle': 'tools/mtp_fetch.py (unmodified)'}))
return 1 if bad else 0
if __name__ == '__main__':
raise SystemExit(main())