Merge pull request #3010 from emmertex/upstream-pr/sam3-local-mirror

#366: SAM 3 mirrors accept a local folder; tokenizer files pinned
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 17:59:59 +01:00
commit cd4e1f63ee
3 files changed
+255 -14

No files matched your search

+116 -7
View File
@@ -51,12 +51,18 @@ const MAX_REDIRECTS: usize = 8;
/// The mirrors to try, in order: `env`'s (base URLs separated by commas, spaces or newlines), then
/// the mirrors file's (one base URL per line, `#` comments), then `defaults`; duplicates and
/// unusable URLs dropped, at most 16.
/// unusable URLs dropped, at most 16. A mirror can be `http(s)://`, `file://<absolute path>` or an
/// absolute folder path: files from a local folder are copied (then checked like a download).
pub fn mirrors(env: Option<&str>, file: Option<&Path>, defaults: &[&str]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut add = |s: &str| {
let s = s.trim().trim_end_matches('/');
if !s.is_empty() && Url::parse(s).is_ok() && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS {
let s = s.trim();
// a local folder (an absolute path) is the same as its `file://` URL
let s = if Path::new(s).is_absolute() { format!("file://{}", s.replace('%', "%25")) } else { s.to_string() };
let s = keep_root(s.trim_end_matches('/'));
let s = s.as_str();
let usable = local_path(s).is_some() || Url::parse(s).is_ok();
if !s.is_empty() && usable && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS {
out.push(s.to_string());
}
};
@@ -197,13 +203,13 @@ fn download_source(
let mut errors = Vec::new();
let mut ok = false;
'mirrors: for m in mirrors {
let url = if exact_urls { m.clone() } else { format!("{m}/{}", f.name) };
let url = if exact_urls { m.clone() } else { file_url_in(m, f.name) };
for _ in 0..opts.attempts.clamp(1, 16) {
if cancel.load(Ordering::Relaxed) {
return Err(DownloadError::Cancelled);
}
let mut report = |n: u64, announced: u64| {
let mirror = Url::parse(m).map(|u| u.display()).unwrap_or_default();
let mirror = short(m);
progress(&Progress {
file: f.name.to_string(),
done: before.saturating_add(n),
@@ -284,6 +290,9 @@ fn bearer<'a>(token: Option<&'a str>, url: &Url, origin: &str) -> Option<&'a str
/// A mirror for messages (no query string: it may hold a token).
fn short(m: &str) -> String {
if local_path(m).is_some() {
return m.to_string();
}
Url::parse(m).map(|u| u.display()).unwrap_or_else(|_| "mirror".into())
}
@@ -345,8 +354,11 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: &
}
Err(_) => 0,
};
let fetched = f.size != Some(have) || have == 0;
if fetched {
let local = local_path(url);
let fetched = local.is_some() || f.size != Some(have) || have == 0;
if let Some(src) = local {
copy_local(&src, &part, limit, f.size, cancel, report)?;
} else if fetched {
let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel };
let mut url = Url::parse(url).map_err(|e| Fail::NextMirror(e.to_string()))?;
let origin = url.host.clone();
@@ -455,6 +467,103 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: &
Ok(())
}
/// The local path of a `file://` URL (absolute only; `file:///C:/x` → `C:/x` on Windows).
/// A mirror with its trailing separators taken off, except a filesystem root's: `file:///` and `file:///D:/` stay
/// as they are (without it neither is an absolute path).
fn keep_root(s: &str) -> String {
match s {
"file:" => "file:///".to_string(),
s if s.starts_with("file://") && s.ends_with(':') => format!("{s}/"),
s => s.to_string(),
}
}
/// The URL of file `name` on mirror `m`: one separator between them (a root mirror already ends with one), and on a
/// local mirror the name's own `%` escaped, so the decoded path is that very name.
fn file_url_in(m: &str, name: &str) -> String {
let name = if local_path(m).is_some() { name.replace('%', "%25") } else { name.to_string() };
if m.ends_with('/') { format!("{m}{name}") } else { format!("{m}/{name}") }
}
fn local_path(url: &str) -> Option<PathBuf> {
let rest = url.strip_prefix("file://")?;
let rest = if rest.get(2..3) == Some(":") { rest.strip_prefix('/').unwrap_or(rest) } else { rest };
let rest = percent_decode(rest)?;
let p = PathBuf::from(&rest);
if p.is_absolute() && !rest.chars().any(char::is_control) { Some(p) } else { None }
}
/// Decode `%XX` escapes (a `file://` URL's path); `None` for a broken escape or non-UTF-8 result.
fn percent_decode(s: &str) -> Option<String> {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while let Some(&c) = b.get(i) {
if c == b'%' {
let hex = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(c);
i += 1;
}
}
String::from_utf8(out).ok()
}
/// Copy a file from a local mirror into `part` (from the start; it is checked afterwards like a download).
fn copy_local(src: &Path, part: &Path, limit: u64, size: Option<u64>, cancel: &AtomicBool, report: &mut dyn FnMut(u64, u64)) -> Result<(), Fail> {
let disk = |e: std::io::Error| Fail::Disk(format!("{}: {e}", part.display()));
let meta = std::fs::metadata(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?;
if !meta.is_file() {
return Err(Fail::NextMirror(format!("{} is not a file", src.display())));
}
if meta.len() > limit || size.is_some_and(|s| s != meta.len()) {
return Err(Fail::NextMirror(format!("{} has the wrong size ({} bytes)", src.display(), meta.len())));
}
let mut input = File::open(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?;
// (a fresh file: an old one at that name may be a hard link to the source, which truncating would empty)
let mut out = new_part(part).map_err(disk)?;
let announced = size.unwrap_or(meta.len());
let mut have = 0u64;
report(0, announced);
let mut buf = vec![0u8; 1 << 20];
loop {
if cancel.load(Ordering::Relaxed) {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::Cancelled);
}
let n = match input.read(&mut buf) {
Ok(n) => n,
Err(e) => {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::NextMirror(format!("{}: {e}", src.display())));
}
};
if n == 0 {
break;
}
if have.saturating_add(n as u64) > limit {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::NextMirror(format!("{} grew past the expected {limit} bytes", src.display())));
}
out.write_all(buf.get(..n).unwrap_or_default()).map_err(disk)?;
have = have.saturating_add(n as u64);
report(have, announced);
}
// a source rewritten (or cut short) after its size was read: what was copied is not that file, and a partial
// left behind would be resumed by the next mirror, failing its hash; so it goes, and the next mirror starts over
if have != announced {
drop(out);
let _ = std::fs::remove_file(part);
return Err(Fail::NextMirror(format!("{} changed while it was copied ({have} of {announced} bytes)", src.display())));
}
out.sync_all().map_err(disk)
}
fn http_fail(e: HttpError) -> Fail {
match e {
HttpError::Cancelled => Fail::Cancelled,
+125
View File
@@ -426,6 +426,131 @@ fn hostile_file_specs_are_rejected_before_touching_disk() {
}
}
#[test]
fn copies_from_a_local_folder_mirror_and_checks_the_hash() {
let src = tmp("local-src");
let dst = tmp("local-dst");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("model.bin"), payload()).unwrap();
// a bare absolute path and a file:// URL are both mirrors (passed as a default, which is not split on spaces
// or commas the way the environment's list is: the temp folder may hold either)
let m = mirrors(None, None, &[src.to_str().unwrap()]);
assert_eq!(m, vec![file_url(&src)]);
let (r, prog) = run(&[pinned()], &m, &dst, &AtomicBool::new(false));
r.unwrap();
assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload());
assert!(prog.last().is_some_and(|p| p.done == p.total));
// a damaged local copy is rejected and never moved into place
let bad = tmp("local-bad");
std::fs::create_dir_all(&bad).unwrap();
let mut damaged = payload();
damaged[7] ^= 1;
std::fs::write(bad.join("model.bin"), damaged).unwrap();
let dst2 = tmp("local-dst2");
let (r, _) = run(&[pinned()], &[file_url(&bad)], &dst2, &AtomicBool::new(false));
assert!(matches!(r, Err(DownloadError::AllMirrorsFailed { .. })), "{r:?}");
assert!(!dst2.join("model.bin").exists() && !dst2.join("model.bin.part").exists());
// a missing folder, a relative path and a directory in place of a file are errors, not panics
let (r, _) = run(&[pinned()], &["file:///nonexistent/model-mirror".to_string()], &dst2, &AtomicBool::new(false));
assert!(r.is_err());
assert!(mirrors(Some("file://relative/dir"), None, &[]).is_empty());
std::fs::create_dir_all(src.join("dir.bin")).unwrap();
let dir_spec = FileSpec { name: "dir.bin", size: None, sha256: None, max: 10 };
let (r, _) = run(&[dir_spec], &[file_url(&src)], &dst2, &AtomicBool::new(false));
assert!(r.is_err());
for d in [&src, &dst, &bad, &dst2] {
let _ = std::fs::remove_dir_all(d);
}
}
/// The `file://` URL of a local folder (its own `%` escaped, as [`mirrors`] does: the temp folder may hold one).
fn file_url(p: &Path) -> String {
format!("file://{}", p.display().to_string().replace('%', "%25"))
}
/// A filesystem root is a usable mirror, and a file in it is found under one separator (CodeRabbit on #3010).
#[test]
fn a_root_folder_mirror_keeps_its_separator() {
assert_eq!(keep_root("file:"), "file:///");
assert_eq!(keep_root("file:///D:"), "file:///D:/");
assert_eq!(keep_root("file:///models"), "file:///models");
assert_eq!(file_url_in("file:///", "model.bin"), "file:///model.bin");
#[cfg(unix)]
{
assert_eq!(mirrors(None, None, &["/"]), ["file:///"]);
assert_eq!(local_path("file:///model.bin"), Some(PathBuf::from("/model.bin")));
}
}
/// A file name with a literal `%20` in it is copied from a local mirror under that very name, not as a space
/// (CodeRabbit on #3010).
#[test]
fn a_local_mirror_keeps_a_file_names_percent_signs() {
let src = tmp("local-percent-src");
let dst = tmp("local-percent-dst");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("model%20.bin"), payload()).unwrap();
let p = payload();
let spec = FileSpec { name: "model%20.bin", size: Some(p.len() as u64), sha256: Some(leak(sha_hex(&p))), max: p.len() as u64 };
let (r, _) = run(&[spec], &[file_url(&src)], &dst, &AtomicBool::new(false));
r.unwrap();
assert_eq!(std::fs::read(dst.join("model%20.bin")).unwrap(), payload());
for d in [&src, &dst] {
let _ = std::fs::remove_dir_all(d);
}
}
/// A leftover `.part` that is a hard link to the local mirror's file is replaced, never truncated through: the
/// mirror's file keeps its bytes (CodeRabbit on #3010).
#[cfg(unix)]
#[test]
fn a_hard_linked_part_never_empties_the_local_source() {
let src = tmp("local-link-src");
let dst = tmp("local-link-dst");
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&dst).unwrap();
std::fs::write(src.join("model.bin"), payload()).unwrap();
std::fs::hard_link(src.join("model.bin"), dst.join("model.bin.part")).unwrap();
let (r, _) = run(&[pinned()], &[file_url(&src)], &dst, &AtomicBool::new(false));
r.unwrap();
assert_eq!(std::fs::read(src.join("model.bin")).unwrap(), payload(), "the mirror's file is untouched");
assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload());
for d in [&src, &dst] {
let _ = std::fs::remove_dir_all(d);
}
}
/// A local source whose length on reading differs from the one its metadata gave (here a /proc file, whose size
/// reads as 0: as a file rewritten after its size was checked) is not kept as a partial for the next mirror to
/// resume (CodeRabbit on #3010).
#[cfg(target_os = "linux")]
#[test]
fn a_local_copy_that_comes_out_another_length_leaves_no_partial() {
let dst = tmp("local-changed-dst");
std::fs::create_dir_all(&dst).unwrap();
let part = dst.join("status.part");
let r = copy_local(Path::new("/proc/self/status"), &part, 1 << 20, None, &AtomicBool::new(false), &mut |_, _| {});
assert!(matches!(r, Err(Fail::NextMirror(_))), "the next mirror is tried");
assert!(!part.exists(), "the partial is removed");
let _ = std::fs::remove_dir_all(&dst);
}
#[test]
fn file_urls_are_percent_decoded_but_bare_paths_keep_their_percent_signs() {
// (absolute on every platform: `/models/…` has no drive on Windows, where it is not an absolute path)
let percent = std::env::temp_dir().join("50%20off");
let bare = mirrors(None, None, &[percent.to_str().unwrap()]);
assert_eq!(bare.len(), 1);
assert_eq!(local_path(&bare[0]), Some(percent));
let spaced = std::env::temp_dir().join("my sam3");
assert_eq!(local_path(&format!("file://{}", spaced.to_str().unwrap().replace('%', "%25").replace(' ', "%20"))), Some(spaced));
for hostile in ["file:///x%", "file:///x%2", "file:///x%zz", "file:///x%ff", "file:///x%0a"] {
assert_eq!(local_path(hostile), None, "{hostile}");
}
}
#[test]
fn names_differing_only_in_case_are_one_file() {
let spec = |name| FileSpec { name, size: Some(1), sha256: None, max: 1 };
+14 -7
View File
@@ -11,14 +11,21 @@ use std::path::Path;
/// The `facebook/sam3` checkpoint files [`crate::Sam3::load`] needs.
///
/// `model.safetensors` is pinned to the official checkpoint (Hugging Face LFS SHA-256). The two
/// tokenizer files are small text files without a pinned hash yet: they are only parsed by the
/// tokenizer (never executed) and capped in size.
// TODO(maintainer): pin `vocab.json` and `merges.txt` (size + SHA-256) when the files are
// uploaded to LightCraft's CDN.
/// All three are pinned (exact size + SHA-256) to the official `facebook/sam3` checkpoint files,
/// checked against a copy of them on 2026-10-13.
pub const SAM3_FILES: &[FileSpec] = &[
FileSpec { name: "vocab.json", size: None, sha256: None, max: 4 << 20 },
FileSpec { name: "merges.txt", size: None, sha256: None, max: 4 << 20 },
FileSpec {
name: "vocab.json",
size: Some(862_328),
sha256: Some("5047b556ce86ccaf6aa22b3ffccfc52d391ea4accdab9c2f2407da5b742d4363"),
max: 4 << 20,
},
FileSpec {
name: "merges.txt",
size: Some(524_619),
sha256: Some("9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a"),
max: 4 << 20,
},
FileSpec {
name: crate::WEIGHTS_FILE,
size: Some(SAM3_WEIGHTS_SIZE),