diff --git a/Cargo.lock b/Cargo.lock index d278339d4..d2e0ea81e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1017,7 +1017,9 @@ dependencies = [ "naga", "png", "pollster", + "serde", "serde_json", + "sha2", "symphonia", "ureq", "wgpu", diff --git a/benchmarks/overlay-real-packs-2026-10-15.json b/benchmarks/overlay-real-packs-2026-10-15.json new file mode 100644 index 000000000..f664be6c4 --- /dev/null +++ b/benchmarks/overlay-real-packs-2026-10-15.json @@ -0,0 +1,54 @@ +{ + "date": "2026-10-15", + "environment": "Linux x86_64/ext4/NVMe, Ryzen5 5600X, Rust1.99.0, Cargo fast", + "scope": "actual resource_root vs original wrapper/builder; warmed storage; output equivalence outside timing", + "warmups": 2, + "median_samples": 11, + "prepared_minecraft": "26.3", + "prepared_schema": 7, + "prepared_manifest_sha256": "fd03c686302748748e132ef3978b7b0bcf42024257e802985a5cc7175cc74298", + "packs": [ + { + "project": "faithful-32x", + "version": "lDYpMiqk", + "version_name": "[26.3] Faithful 32x \u2013 September 2026 Release", + "publisher_page": "https://modrinth.com/resourcepack/faithful-32x/version/lDYpMiqk", + "download_url": "https://cdn.modrinth.com/data/w0TnApzs/versions/lDYpMiqk/Faithful%2032x%20-%2026.3.zip", + "zip_bytes": 13116019, + "zip_sha512": "e90ec63af7f239dbb99aa20c98b23d830e76898f65d3e31b7f0b53bb36db12dcd8c38d6930c743237c9c3db7bf708423fa1d1b2fd497dd6c281dbe216b779db9", + "asset_files": 5063, + "assets_uncompressed_bytes": 12524266, + "original_ms": 159.827, + "cold_ms": 162.711, + "hit_ms": 0.707 + }, + { + "project": "default-hd-128x", + "version": "rErHu3BE", + "version_name": "Default HD 128x Demo/Alpha 1.8.2.7", + "publisher_page": "https://modrinth.com/resourcepack/default-hd-128x/version/rErHu3BE", + "download_url": "https://cdn.modrinth.com/data/orfTV6nk/versions/rErHu3BE/Default%20HD%20128x%20Demo%201.8.2.7.zip", + "zip_bytes": 16876419, + "zip_sha512": "f5f9606e92b986cd9c8b8e5ff2bb52db720cc7b38e013355bdc90089e01975a08d09750ef2fd727f753d88ec3fbcd067355179b490587f667b2995f8be81640f", + "asset_files": 2318, + "assets_uncompressed_bytes": 17315416, + "original_ms": 111.501, + "cold_ms": 114.386, + "hit_ms": 0.31 + }, + { + "project": "fpbr", + "version": "dynf82xk", + "version_name": "support 1.21.9 and newer", + "publisher_page": "https://modrinth.com/resourcepack/fpbr/version/dynf82xk", + "download_url": "https://cdn.modrinth.com/data/nvEpbd8t/versions/dynf82xk/FPBR-Main-1.21.9-R1.3.zip", + "zip_bytes": 46737770, + "zip_sha512": "64f1bbd036e205118f1d9c49a79558db2c1356ee988fb939c0023db1967d78e1bd05047f341ce6d65355717ba7ddb1330af57edbb4d5b8713c96ae62987274c5", + "asset_files": 7001, + "assets_uncompressed_bytes": 56356903, + "original_ms": 347.639, + "cold_ms": 348.012, + "hit_ms": 0.448 + } + ] +} diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 0b9df5a04..47368c980 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -19,6 +19,8 @@ pollster = "0.4" bytemuck = { version = "1.24", features = ["derive"] } glam = "0.30" png = "0.18" +sha2 = "0.10.9" +serde = { version = "1", features = ["derive"] } serde_json = { version = "1.0.151", features = ["raw_value"] } cpal = "0.16" symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 2dee3206e..917bad561 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -3,6 +3,7 @@ //! and High Contrast packs, `pack.mcmeta` metadata and format compatibility, //! and an overlay resource root that layers the enabled packs over the //! vanilla resources (later packs win), so every loader sees one tree. +mod cache; pub mod pattern; use crate::text::Style; use crate::{text::Text, zip::Zip}; @@ -381,6 +382,15 @@ fn link(target: &Path, at: &Path) -> io::Result<()> { /// Build `out` as `vanilla` with the packs' files layered on top (packs in /// load order, last wins). Untouched directories are symlinks into vanilla. pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<()> { + cache::build(vanilla, packs, out) +} + +fn build_overlay_uncached( + vanilla: &Path, + packs: &[Pack], + out: &Path, + dependencies: &mut cache::Dependencies, +) -> io::Result<()> { if out.exists() { fs::remove_dir_all(out)?; } @@ -426,6 +436,7 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( let mut merged: BTreeMap> = BTreeMap::new(); for (name, stack) in &stacks { let mut layers = Vec::new(); + dependencies.file(&vanilla.join(name)); if !filters.iter().any(|f| f.blocks(name)) && let Ok(bytes) = fs::read(vanilla.join(name)) { @@ -457,6 +468,7 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( merged: &BTreeMap>, filters: &[&Filter], zips: &[Option], + dependencies: &mut cache::Dependencies, ) -> io::Result<()> { let src = if rel.is_empty() { vanilla.to_path_buf() @@ -469,6 +481,7 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( out.join(rel) }; fs::create_dir_all(&dst)?; + dependencies.directory(&src); let mut names: BTreeSet = BTreeSet::new(); if let Ok(entries) = fs::read_dir(&src) { names.extend( @@ -502,10 +515,24 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( } else if touched.contains(&child) || (vanilla.join(&child).is_dir() && !filters.is_empty()) { - mirror(&child, vanilla, out, touched, files, merged, filters, zips)?; + mirror( + &child, + vanilla, + out, + touched, + files, + merged, + filters, + zips, + dependencies, + )?; } else if filters.iter().any(|f| f.blocks(&child)) { // Hidden by a pack's filter. } else { + #[cfg(not(unix))] + if vanilla.join(&child).is_file() { + dependencies.file(&vanilla.join(&child)); + } link(&vanilla.join(&child), &out.join(&child))?; } } @@ -520,6 +547,7 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<( &merged, &filters, &zips, + dependencies, ) } /// Files vanilla loads from every pack in turn (`getResourceStack`) rather diff --git a/crates/horizon-client/src/packs/cache.rs b/crates/horizon-client/src/packs/cache.rs new file mode 100644 index 000000000..1f17c018b --- /dev/null +++ b/crates/horizon-client/src/packs/cache.rs @@ -0,0 +1,893 @@ +//! Overlay reuse validated by source topology and filesystem stamps. +//! Published output is an owned cache artifact; hits do not traverse its tree. +use super::{Pack, Source, build_overlay_uncached}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +#[cfg(any(test, not(unix)))] +use std::io::Read; +use std::{collections::BTreeSet, fs, io, path::Path, path::PathBuf}; + +// Bump when overlay/merge semantics change. Markers are disposable cache data. +const VERSION: u32 = 2; + +#[derive(Default, Serialize, Deserialize)] +pub(super) struct Dependencies { + entries: Vec<(PathBuf, bool, String)>, + #[serde(skip)] + failed: bool, + #[serde(skip)] + tracking: bool, +} +impl Dependencies { + fn record(&mut self, path: &Path, directory: bool) { + if !self.tracking { + return; + } + match dependency_signature(path, directory) { + Ok(signature) => self.entries.push((path.into(), directory, signature)), + Err(_) => self.failed = true, + } + } + pub(super) fn file(&mut self, path: &Path) { + self.record(path, false); + } + pub(super) fn directory(&mut self, path: &Path) { + self.record(path, true); + } + fn valid(&self) -> bool { + !self.failed + && self.entries.iter().all(|(path, directory, signature)| { + dependency_signature(path, *directory).is_ok_and(|s| s == *signature) + }) + } +} + +#[derive(Serialize, Deserialize)] +struct Marker { + version: u32, + vanilla: PathBuf, + packs: String, + dependencies: Dependencies, +} + +fn finish(hash: Sha256) -> String { + format!("{:x}", hash.finalize()) +} +// Length framing keeps distinct paths/configurations unambiguous. +fn field(hash: &mut Sha256, bytes: &[u8]) { + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); +} +#[cfg(any(test, not(unix)))] +fn content(hash: &mut Sha256, path: &Path) -> io::Result<()> { + let mut file = fs::File::open(path)?; + hash.update(file.metadata()?.len().to_le_bytes()); + let mut buffer = [0; 64 * 1024]; + loop { + let n = file.read(&mut buffer)?; + if n == 0 { + break; + } + hash.update(&buffer[..n]); + } + Ok(()) +} +fn stamp(hash: &mut Sha256, path: &Path) -> io::Result<()> { + let meta = fs::metadata(path)?; + hash.update(meta.len().to_le_bytes()); + field(hash, format!("{:?}", meta.modified()?).as_bytes()); + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + hash.update(meta.dev().to_le_bytes()); + hash.update(meta.ino().to_le_bytes()); + hash.update(meta.ctime().to_le_bytes()); + hash.update(meta.ctime_nsec().to_le_bytes()); + } + #[cfg(not(unix))] + { + // Portable metadata lacks a change timestamp. Preserve content-based + // validation for materialized files on those platforms. + if meta.is_file() { + return content(hash, path); + } + if let Ok(created) = meta.created() { + field(hash, format!("{created:?}").as_bytes()); + } + } + Ok(()) +} +fn entries(path: &Path) -> io::Result> { + let mut entries = fs::read_dir(path)? + .map(|e| e.map(|e| e.path())) + .collect::>>()?; + entries.sort(); + Ok(entries) +} +fn dependency_signature(path: &Path, directory: bool) -> io::Result { + let mut hash = Sha256::new(); + match fs::metadata(path) { + Err(e) if e.kind() == io::ErrorKind::NotFound => field(&mut hash, b"missing"), + Err(e) => return Err(e), + Ok(meta) if directory && meta.is_dir() => { + field(&mut hash, b"directory"); + stamp(&mut hash, path)?; + } + Ok(_) if directory => field(&mut hash, b"not-directory"), + Ok(_) => stamp(&mut hash, path)?, + } + Ok(finish(hash)) +} +fn tree(hash: &mut Sha256, path: &Path, pack: Option<&Pack>) -> io::Result<()> { + tree_inner(hash, path, pack, &mut BTreeSet::new()) +} + +fn needs_content(path: &Path, pack: Option<&Pack>) -> bool { + let Some(pack) = pack.filter(|_| cfg!(unix)) else { + return true; + }; + let Source::Dir(root) = &pack.source else { + return true; + }; + let relative = path + .strip_prefix(root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + // Ordinary folder resources are live Unix file symlinks. Rewrites and + // replacements at that path are visible without rebuilding. Merged JSON + // and configuration bytes are materialized and need stamp validation. + relative == "pack.mcmeta" + || super::merge_kind(&relative).is_some() + || pack.overlays.iter().any(|overlay| { + path.strip_prefix(root.join(overlay.trim_end_matches('/'))) + .ok() + .is_some_and(|name| { + super::merge_kind(&name.to_string_lossy().replace('\\', "/")).is_some() + }) + }) +} +fn tree_inner( + hash: &mut Sha256, + path: &Path, + pack: Option<&Pack>, + active: &mut BTreeSet, +) -> io::Result<()> { + let meta = fs::symlink_metadata(path)?; + if meta.is_symlink() { + field(hash, b"link"); + field(hash, fs::read_link(path)?.as_os_str().as_encoded_bytes()); + if pack.is_none() { + return Ok(()); + } + } + if path.is_dir() { + let canonical = if pack.is_some() { + let canonical = fs::canonicalize(path)?; + if !active.insert(canonical.clone()) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "pack symlink cycle", + )); + } + Some(canonical) + } else { + None + }; + field(hash, b"directory"); + for entry in entries(path)? { + field(hash, entry.file_name().unwrap().as_encoded_bytes()); + tree_inner(hash, &entry, pack, active)?; + } + field(hash, b"end-directory"); + if let Some(canonical) = canonical { + active.remove(&canonical); + } + } else { + field(hash, b"file"); + if needs_content(path, pack) { + #[cfg(test)] + if pack.is_none() { + return content(hash, path); + } + stamp(hash, path)?; + } + } + Ok(()) +} +#[cfg(test)] +fn output_signature(out: &Path) -> io::Result { + let mut hash = Sha256::new(); + tree(&mut hash, out, None)?; + Ok(finish(hash)) +} +fn pack_signature(packs: &[Pack]) -> io::Result { + let mut hash = Sha256::new(); + field(&mut hash, &[u8::from(cfg!(unix))]); + for pack in packs { + if matches!(pack.source, Source::Dir(_)) + && pack.overlays.iter().any(|overlay| { + Path::new(overlay).components().any(|component| { + matches!( + component, + std::path::Component::ParentDir + | std::path::Component::RootDir + | std::path::Component::Prefix(_) + ) + }) + }) + { + // The builder historically accepts external overlay roots. Preserve + // that behavior, but don't cache dependencies outside this pack tree. + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "external pack overlay", + )); + } + field(&mut hash, pack.id.as_bytes()); + // Includes source kind/path, overlay order and compiled filter settings. + field(&mut hash, format!("{:?}", pack.source).as_bytes()); + field(&mut hash, format!("{:?}", pack.overlays).as_bytes()); + field(&mut hash, format!("{:?}", pack.filter).as_bytes()); + match &pack.source { + Source::Dir(path) => { + field(&mut hash, absolute(path)?.as_os_str().as_encoded_bytes()); + tree(&mut hash, path, Some(pack))?; + } + Source::Zip(path) => { + field(&mut hash, absolute(path)?.as_os_str().as_encoded_bytes()); + stamp(&mut hash, path)?; + } + } + } + Ok(finish(hash)) +} + +pub(super) fn marker_path(out: &Path) -> PathBuf { + // Outside the resource tree: no resource-name collisions or mirror changes. + let mut name = out.as_os_str().to_os_string(); + name.push(".overlay-cache.json"); + PathBuf::from(name) +} + +fn absolute(path: &Path) -> io::Result { + if path.is_absolute() { + Ok(path.into()) + } else { + std::env::current_dir().map(|cwd| cwd.join(path)) + } +} + +fn lock_path(out: &Path) -> PathBuf { + marker_path(out).with_extension("lock") +} + +pub(super) fn build(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<()> { + if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; + } + // Keep this inode persistent: deleting it would let waiters and new callers + // acquire different locks. Closing the file releases the advisory OS lock. + let lock = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(lock_path(out))?; + lock.lock()?; + // Resolve marker identity only; preserve the builder's original link targets. + let vanilla_key = absolute(vanilla)?; + let marker_path = marker_path(out); + let signature = pack_signature(packs); + if let Ok(signature) = &signature + && let Ok(bytes) = fs::read(&marker_path) + && let Ok(marker) = serde_json::from_slice::(&bytes) + && marker.version == VERSION + && marker.vanilla == vanilla_key + && marker.packs == *signature + && marker.dependencies.valid() + && out.is_dir() + { + return Ok(()); + } + // An interrupted/failed rebuild must never leave a reusable marker. + match fs::remove_file(&marker_path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + let mut dependencies = Dependencies { + tracking: signature.is_ok(), + ..Dependencies::default() + }; + build_overlay_uncached(vanilla, packs, out, &mut dependencies)?; + if let Ok(signature) = signature + && dependencies.valid() + && pack_signature(packs).is_ok_and(|s| s == signature) + { + let marker = Marker { + version: VERSION, + vanilla: vanilla_key, + packs: signature, + dependencies, + }; + // PathBuf serialization requires UTF-8; unusual resource root names + // can still build normally without a reusable marker. + let Ok(bytes) = serde_json::to_vec(&marker) else { + return Ok(()); + }; + // Publish only a complete marker, after all output writes succeeded. + let temporary = marker_path.with_extension("tmp"); + fs::write(&temporary, bytes)?; + fs::rename(&temporary, &marker_path)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{packs, text::Text}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let path = std::env::temp_dir().join(format!( + "horizon-overlay-cache-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + fn write(&self, name: &str, bytes: &[u8]) { + let path = self.0.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, bytes).unwrap(); + } + fn dir_pack(&self, name: &str) -> Pack { + self.write( + &format!("{name}/pack.mcmeta"), + br#"{"pack":{"description":"test","pack_format":97}}"#, + ); + packs::pack(name.into(), Text::empty(), Source::Dir(self.0.join(name))).unwrap() + } + fn rebuild_matches(&self, selected: &[Pack]) { + let vanilla = self.0.join("vanilla"); + let cached = self.0.join("cached"); + packs::build_overlay(&vanilla, selected, &cached).unwrap(); + build_overlay_uncached( + &vanilla, + selected, + &self.0.join("reference"), + &mut Dependencies::default(), + ) + .unwrap(); + assert_eq!( + output_signature(&cached).unwrap(), + output_signature(&self.0.join("reference")).unwrap() + ); + } + } + impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + // Stored/deflated ZIP fixture using the production reader, no zip dependency. + fn archive(files: &[(&str, Vec)], deflate: bool) -> Vec { + let mut out = Vec::new(); + let mut central = Vec::new(); + for (name, body) in files { + let data = if deflate { + miniz_oxide::deflate::compress_to_vec(body, 6) + } else { + body.clone() + }; + let offset = out.len() as u32; + out.extend(0x0403_4b50u32.to_le_bytes()); + out.extend([20, 0, 0, 0]); + out.extend((if deflate { 8u16 } else { 0 }).to_le_bytes()); + out.extend([0; 8]); + out.extend((data.len() as u32).to_le_bytes()); + out.extend((body.len() as u32).to_le_bytes()); + out.extend((name.len() as u16).to_le_bytes()); + out.extend(0u16.to_le_bytes()); + out.extend(name.as_bytes()); + out.extend(&data); + central.extend(0x0201_4b50u32.to_le_bytes()); + central.extend([20, 0, 20, 0, 0, 0]); + central.extend((if deflate { 8u16 } else { 0 }).to_le_bytes()); + central.extend([0; 8]); + central.extend((data.len() as u32).to_le_bytes()); + central.extend((body.len() as u32).to_le_bytes()); + central.extend((name.len() as u16).to_le_bytes()); + central.extend([0; 12]); + central.extend(offset.to_le_bytes()); + central.extend(name.as_bytes()); + } + let start = out.len() as u32; + out.extend(¢ral); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend((files.len() as u16).to_le_bytes()); + out.extend((files.len() as u16).to_le_bytes()); + out.extend((central.len() as u32).to_le_bytes()); + out.extend(start.to_le_bytes()); + out.extend([0; 2]); + out + } + + #[test] + fn directory_inputs_config_and_owned_output_recovery() { + let f = Fixture::new(); + let resource = "assets/minecraft/lang/en_us.json"; + f.write(&format!("vanilla/{resource}"), br#"{"v":"a"}"#); + f.write("vanilla/assets/minecraft/textures/untouched/a", b"live"); + let mut low = f.dir_pack("low"); + let high = f.dir_pack("high"); + f.write(&format!("low/{resource}"), br#"{"p":"a"}"#); + f.write(&format!("high/{resource}"), br#"{"p":"b"}"#); + f.rebuild_matches(&[low.clone(), high.clone()]); + let out = f.0.join("cached"); + let marker = marker_path(&out); + // A hit keeps the actual merged file (and marker) in place. + let time = fs::metadata(out.join(resource)) + .unwrap() + .modified() + .unwrap(); + let marker_time = fs::metadata(&marker).unwrap().modified().unwrap(); + f.rebuild_matches(&[low.clone(), high.clone()]); + assert_eq!( + fs::metadata(out.join(resource)) + .unwrap() + .modified() + .unwrap(), + time + ); + assert_eq!( + fs::metadata(&marker).unwrap().modified().unwrap(), + marker_time + ); + // Same-length rewrites cannot hide behind file size or preserved mtime. + let path = f.0.join(format!("high/{resource}")); + let original_time = fs::metadata(&path).unwrap().modified().unwrap(); + fs::write(&path, br#"{"p":"c"}"#).unwrap(); + fs::File::open(path) + .unwrap() + .set_times(fs::FileTimes::new().set_modified(original_time)) + .unwrap(); + f.rebuild_matches(&[low.clone(), high.clone()]); + f.write(&format!("vanilla/{resource}"), br#"{"v":"b"}"#); + f.rebuild_matches(&[low.clone(), high.clone()]); + f.write("vanilla/assets/minecraft/lang/new.json", b"new"); + f.rebuild_matches(&[low.clone(), high.clone()]); + fs::remove_file(f.0.join("vanilla/assets/minecraft/lang/new.json")).unwrap(); + f.rebuild_matches(&[low.clone(), high.clone()]); + f.write("high/assets/minecraft/lang/added.json", br#"{"a":1}"#); + f.rebuild_matches(&[low.clone(), high.clone()]); + fs::remove_file(f.0.join("high/assets/minecraft/lang/added.json")).unwrap(); + f.rebuild_matches(&[low.clone(), high.clone()]); + f.rebuild_matches(&[high.clone(), low.clone()]); + f.rebuild_matches(std::slice::from_ref(&low)); + low.overlays.push("extra".into()); + f.write(&format!("low/extra/{resource}"), br#"{"p":"overlay"}"#); + f.rebuild_matches(std::slice::from_ref(&low)); + low.filter = packs::filter_of(&serde_json::json!({"filter":{"block":[{"path":"lang"}]}})); + f.rebuild_matches(std::slice::from_ref(&low)); + fs::write(out.join(resource), b"corrupt").unwrap(); + // Published output is trusted; clearing the marker explicitly repairs + // a cache tree changed outside the builder. + packs::build_overlay(&f.0.join("vanilla"), std::slice::from_ref(&low), &out).unwrap(); + assert_eq!(fs::read(out.join(resource)).unwrap(), b"corrupt"); + fs::remove_file(&marker).unwrap(); + f.rebuild_matches(std::slice::from_ref(&low)); + fs::remove_file(out.join(resource)).unwrap(); + fs::remove_file(&marker).unwrap(); + f.rebuild_matches(std::slice::from_ref(&low)); + fs::write(&marker, b"corrupt").unwrap(); + f.rebuild_matches(std::slice::from_ref(&low)); + fs::remove_file(&marker).unwrap(); + f.rebuild_matches(std::slice::from_ref(&low)); + fs::remove_dir_all(&out).unwrap(); + f.rebuild_matches(std::slice::from_ref(&low)); + #[cfg(unix)] + { + low.filter.clear(); + f.rebuild_matches(std::slice::from_ref(&low)); + // Unrelated vanilla content remains live through the directory symlink. + let before = fs::read(&marker).unwrap(); + f.write("vanilla/assets/minecraft/textures/untouched/a", b"new live"); + f.write( + "vanilla/assets/minecraft/textures/untouched/b", + b"added live", + ); + f.rebuild_matches(std::slice::from_ref(&low)); + assert_eq!(fs::read(&marker).unwrap(), before); + assert_eq!( + fs::read(out.join("assets/minecraft/textures/untouched/b")).unwrap(), + b"added live" + ); + } + // Missing selected source disables reuse; the original directory builder + // still tolerates it, and does not publish a marker for an incomplete input. + fs::remove_dir_all(f.0.join("low")).unwrap(); + f.rebuild_matches(&[low]); + assert!(!marker.exists()); + } + + #[test] + fn zip_content_and_failed_build_invalidate() { + let f = Fixture::new(); + f.write("vanilla/facts.json", b"[]"); + let name = "assets/minecraft/textures/a"; + let files = |data: &[u8]| { + vec![ + ( + "pack.mcmeta", + br#"{"pack":{"description":"test","pack_format":97}}"#.to_vec(), + ), + (name, data.to_vec()), + ] + }; + f.write("pack.zip", &archive(&files(b"aaa"), false)); + let pack = packs::pack( + "zip".into(), + Text::empty(), + Source::Zip(f.0.join("pack.zip")), + ) + .unwrap(); + f.rebuild_matches(std::slice::from_ref(&pack)); + f.rebuild_matches(std::slice::from_ref(&pack)); + f.write("pack.zip", &archive(&files(b"bbb"), false)); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!(fs::read(f.0.join("cached").join(name)).unwrap(), b"bbb"); + // The ZIP opens and enumerates, then its unsupported method fails after + // mirror has created directories. No reusable marker survives. + let mut broken = archive(&files(b"ccc"), false); + let central = broken + .windows(4) + .position(|s| s == [0x50, 0x4b, 0x01, 0x02]) + .unwrap(); + let second = central + 46 + "pack.mcmeta".len(); + broken[second + 10..second + 12].copy_from_slice(&99u16.to_le_bytes()); + f.write("pack.zip", &broken); + let out = f.0.join("cached"); + assert!( + packs::build_overlay(&f.0.join("vanilla"), std::slice::from_ref(&pack), &out).is_err() + ); + assert!(!marker_path(&out).exists()); + f.write("pack.zip", &archive(&files(b"ddd"), true)); + f.rebuild_matches(std::slice::from_ref(&pack)); + fs::remove_file(f.0.join("pack.zip")).unwrap(); + assert!(packs::build_overlay(&f.0.join("vanilla"), &[pack], &out).is_err()); + assert!(!marker_path(&out).exists()); + } + + #[cfg(unix)] + #[test] + fn unrelated_directory_pack_symlink_cycle_disables_reuse() { + let f = Fixture::new(); + f.write("vanilla/facts.json", b"[]"); + let pack = f.dir_pack("pack"); + f.write("pack/assets/minecraft/textures/a", b"pack"); + fs::create_dir_all(f.0.join("pack/docs")).unwrap(); + std::os::unix::fs::symlink(f.0.join("pack"), f.0.join("pack/docs/back")).unwrap(); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert!(!marker_path(&f.0.join("cached")).exists()); + } + + #[cfg(unix)] + #[test] + fn linked_pack_bytes_stay_live_and_topology_invalidates() { + let f = Fixture::new(); + f.write("vanilla/facts.json", b"[]"); + let pack = f.dir_pack("pack"); + let name = "assets/minecraft/textures/a"; + f.write(&format!("pack/{name}"), b"aaa"); + f.rebuild_matches(std::slice::from_ref(&pack)); + let out = f.0.join("cached"); + let marker = marker_path(&out); + let before = fs::metadata(&marker).unwrap().modified().unwrap(); + let path = f.0.join("pack").join(name); + let original_time = fs::metadata(&path).unwrap().modified().unwrap(); + fs::write(&path, b"bbb").unwrap(); + fs::File::open(&path) + .unwrap() + .set_times(fs::FileTimes::new().set_modified(original_time)) + .unwrap(); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!(fs::read(out.join(name)).unwrap(), b"bbb"); + assert_eq!(fs::metadata(&marker).unwrap().modified().unwrap(), before); + // Replacing a regular file at the same linked path is also already live. + f.write("replacement", b"ccc"); + fs::rename(f.0.join("replacement"), &path).unwrap(); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!(fs::read(out.join(name)).unwrap(), b"ccc"); + assert_eq!(fs::metadata(&marker).unwrap().modified().unwrap(), before); + // A changed source symlink identity is fingerprinted. Output is trusted + // until its marker is cleared explicitly. + fs::remove_file(&path).unwrap(); + f.write("other", b"ddd"); + std::os::unix::fs::symlink(f.0.join("other"), &path).unwrap(); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!(fs::read(out.join(name)).unwrap(), b"ddd"); + fs::remove_file(out.join(name)).unwrap(); + std::os::unix::fs::symlink(f.0.join("other"), out.join(name)).unwrap(); + fs::remove_file(&marker).unwrap(); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!(fs::read_link(out.join(name)).unwrap(), path); + fs::remove_file(&path).unwrap(); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert!(fs::symlink_metadata(out.join(name)).is_err()); + } + + #[test] + fn normalized_and_external_overlay_roots_keep_merged_bytes_current() { + let f = Fixture::new(); + let name = "assets/minecraft/lang/en_us.json"; + f.write(&format!("vanilla/{name}"), br#"{"v":1}"#); + let mut pack = f.dir_pack("pack"); + f.write(&format!("pack/extra/{name}"), br#"{"p":1}"#); + for overlay in ["extra/", "./extra", "extra/./", "extra//"] { + pack.overlays = vec![overlay.into()]; + f.rebuild_matches(std::slice::from_ref(&pack)); + let marker = marker_path(&f.0.join("cached")); + assert!(marker.exists()); + f.write(&format!("pack/extra/{name}"), br#"{"p":2}"#); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!( + fs::read(f.0.join("cached").join(name)).unwrap(), + br#"{"p":2,"v":1}"# + ); + f.write(&format!("pack/extra/{name}"), br#"{"p":1}"#); + } + f.write(&format!("outside/{name}"), br#"{"p":3}"#); + for overlay in [ + "../outside".into(), + f.0.join("outside").to_string_lossy().into_owned(), + ] { + pack.overlays = vec![overlay]; + f.rebuild_matches(std::slice::from_ref(&pack)); + assert!(!marker_path(&f.0.join("cached")).exists()); + f.write(&format!("outside/{name}"), br#"{"p":4}"#); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!( + fs::read(f.0.join("cached").join(name)).unwrap(), + br#"{"p":4,"v":1}"# + ); + f.write(&format!("outside/{name}"), br#"{"p":3}"#); + } + } + + #[cfg(unix)] + #[test] + fn root_symlink_aliases_stay_live_and_retargeted_merges_invalidate() { + let f = Fixture::new(); + let name = "assets/minecraft/lang/en_us.json"; + f.write("vanilla-a/facts.json", b"a"); + f.write("vanilla-b/facts.json", b"b"); + f.write(&format!("vanilla-a/{name}"), br#"{"v":"a"}"#); + f.write(&format!("vanilla-b/{name}"), br#"{"v":"b"}"#); + let mut pack = f.dir_pack("pack-a"); + f.dir_pack("pack-b"); + f.write("pack-a/assets/minecraft/textures/a", b"a"); + f.write("pack-b/assets/minecraft/textures/a", b"b"); + f.write(&format!("pack-a/{name}"), br#"{"p":"a"}"#); + f.write(&format!("pack-b/{name}"), br#"{"p":"b"}"#); + let vanilla = f.0.join("vanilla"); + let source = f.0.join("pack"); + std::os::unix::fs::symlink(f.0.join("vanilla-a"), &vanilla).unwrap(); + std::os::unix::fs::symlink(f.0.join("pack-a"), &source).unwrap(); + pack.source = Source::Dir(source.clone()); + f.rebuild_matches(std::slice::from_ref(&pack)); + fs::remove_file(&vanilla).unwrap(); + fs::remove_file(&source).unwrap(); + std::os::unix::fs::symlink(f.0.join("vanilla-b"), &vanilla).unwrap(); + std::os::unix::fs::symlink(f.0.join("pack-b"), &source).unwrap(); + let out = f.0.join("cached"); + assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"b"); + assert_eq!( + fs::read(out.join("assets/minecraft/textures/a")).unwrap(), + b"b" + ); + f.rebuild_matches(std::slice::from_ref(&pack)); + assert_eq!(fs::read(out.join(name)).unwrap(), br#"{"p":"b","v":"b"}"#); + } + + #[test] + fn concurrent_selections_wait_and_never_publish_mismatched_markers() { + use std::{sync::mpsc, time::Duration}; + let f = Fixture::new(); + let name = "assets/minecraft/lang/en_us.json"; + f.write(&format!("vanilla/{name}"), br#"{"v":1}"#); + let a = f.dir_pack("a"); + let b = f.dir_pack("b"); + f.write(&format!("a/{name}"), br#"{"p":"a"}"#); + f.write(&format!("b/{name}"), br#"{"p":"b"}"#); + let out = f.0.join("cached"); + let held = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(lock_path(&out)) + .unwrap(); + held.lock().unwrap(); + let (started, starts) = mpsc::channel(); + let (done, finishes) = mpsc::channel(); + std::thread::scope(|scope| { + for pack in [&a, &b] { + let started = started.clone(); + let done = done.clone(); + let vanilla = f.0.join("vanilla"); + let out = &out; + scope.spawn(move || { + started.send(()).unwrap(); + for _ in 0..20 { + packs::build_overlay(&vanilla, std::slice::from_ref(pack), out).unwrap(); + } + done.send(()).unwrap(); + }); + } + starts.recv().unwrap(); + starts.recv().unwrap(); + assert!(matches!( + finishes.recv_timeout(Duration::from_millis(50)), + Err(mpsc::RecvTimeoutError::Timeout) + )); + drop(held); + }); + finishes.recv().unwrap(); + finishes.recv().unwrap(); + for pack in [&a, &b, &a, &b] { + f.rebuild_matches(std::slice::from_ref(pack)); + let expected = if pack.id == "a" { + br#"{"p":"a","v":1}"# + } else { + br#"{"p":"b","v":1}"# + }; + assert_eq!(fs::read(out.join(name)).unwrap(), expected); + } + assert!(lock_path(&out).exists()); + } + + #[cfg(unix)] + #[test] + fn relative_builder_targets_are_preserved() { + let f = Fixture::new(); + f.write("vanilla/facts.json", b"[]"); + let mut pack = f.dir_pack("pack"); + let name = "assets/minecraft/textures/a"; + f.write(&format!("pack/{name}"), b"pack"); + let cwd = std::env::current_dir().unwrap(); + let mut relative = PathBuf::new(); + for component in cwd.components() { + if matches!(component, std::path::Component::Normal(_)) { + relative.push(".."); + } + } + relative.push(f.0.strip_prefix("/").unwrap()); + pack.source = Source::Dir(relative.join("pack")); + let vanilla = relative.join("vanilla"); + let out = f.0.join("cached"); + let reference = f.0.join("reference"); + packs::build_overlay(&vanilla, std::slice::from_ref(&pack), &out).unwrap(); + build_overlay_uncached(&vanilla, &[pack], &reference, &mut Dependencies::default()) + .unwrap(); + let expected = relative.join("pack").join(name); + assert_eq!(fs::read_link(out.join(name)).unwrap(), expected); + assert_eq!(fs::read_link(reference.join(name)).unwrap(), expected); + assert_eq!( + fs::read_link(out.join("facts.json")).unwrap(), + vanilla.join("facts.json") + ); + } + + #[test] + #[ignore = "requires prepared resources and real pack paths in environment"] + fn benchmark_real_resource_root() { + use std::{hint::black_box, time::Instant}; + let vanilla = PathBuf::from(std::env::var("HORIZON_OVERLAY_BENCH_VANILLA").unwrap()); + assert!(vanilla.join("horizon-resources.json").is_file()); + let paths: Vec = + serde_json::from_str(&std::env::var("HORIZON_OVERLAY_BENCH_PACKS").unwrap()).unwrap(); + // The original resource_root selection/cache-key path, with its original builder. + fn original(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf { + let key = packs + .iter() + .map(|p| p.id.as_str()) + .collect::>() + .join("|"); + let hash = key.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); + let out = cache.join(format!("{hash:016x}")); + build_overlay_uncached(vanilla, packs, &out, &mut Dependencies::default()).unwrap(); + out + } + let median = |mut times: Vec| { + times.sort_by(f64::total_cmp); + times[times.len() / 2] + }; + for path in paths { + let f = Fixture::new(); + let pack = packs::pack( + path.to_string_lossy().into_owned(), + Text::empty(), + Source::Zip(path.clone()), + ) + .unwrap(); + let selected = std::slice::from_ref(&pack); + let reference_cache = f.0.join("reference"); + let cached_cache = f.0.join("cached"); + fs::create_dir_all(&reference_cache).unwrap(); + let reference = original(&vanilla, selected, &reference_cache); + let out = packs::resource_root(&vanilla, selected, &cached_cache); + assert_ne!(out, vanilla, "resource_root must not fall back to vanilla"); + assert!(marker_path(&out).exists()); + let expected = output_signature(&reference).unwrap(); + assert_eq!(output_signature(&out).unwrap(), expected); + for _ in 0..2 { + original(&vanilla, selected, &reference_cache); + assert_eq!(packs::resource_root(&vanilla, selected, &cached_cache), out); + } + let mut baseline = Vec::new(); + let mut cold = Vec::new(); + let mut hit = Vec::new(); + for iteration in 0..11 { + for operation in if iteration % 2 == 0 { + [0, 1, 2] + } else { + [1, 2, 0] + } { + if operation == 1 { + fs::remove_file(marker_path(&out)).unwrap(); + } + let started = Instant::now(); + let result = if operation == 0 { + original( + black_box(&vanilla), + black_box(selected), + black_box(&reference_cache), + ) + } else { + packs::resource_root( + black_box(&vanilla), + black_box(selected), + black_box(&cached_cache), + ) + }; + black_box(&result); + let ms = started.elapsed().as_secs_f64() * 1000.0; + match operation { + 0 => baseline.push(ms), + 1 => cold.push(ms), + _ => hit.push(ms), + } + if operation != 0 { + assert_eq!(result, out); + } + } + // Verify full materialized bytes and symlink identities outside timing. + assert_eq!(output_signature(&out).unwrap(), expected); + assert_eq!(output_signature(&reference).unwrap(), expected); + } + let baseline = median(baseline); + let cold = median(cold); + let hit = median(hit); + println!( + "real pack={} ZIP={} bytes: original={baseline:.3} ms cold={cold:.3} ms hit={hit:.3} ms speedup={:.2}x saved={:.3} ms cold_overhead={:.2}% (11 medians, 2 warmups)", + path.display(), + fs::metadata(&path).unwrap().len(), + baseline / hit, + baseline - hit, + (cold / baseline - 1.0) * 100.0 + ); + } + } +} diff --git a/docs/reuse-pack-overlays.md b/docs/reuse-pack-overlays.md new file mode 100644 index 000000000..53e8bbc3a --- /dev/null +++ b/docs/reuse-pack-overlays.md @@ -0,0 +1,46 @@ +# Reusing resource-pack overlays + +`packs::build_overlay` reuses a completed overlay through a versioned sibling JSON marker and persistent OS lock. Pack sources/order, overlay roots, filters, source topology and materialized vanilla inputs determine validity. The marker is removed before rebuilding and published only after a successful build and stable input checks. + +On Unix, ZIPs and materialized inputs use length, modification time, device/inode and change-time stamps. Cache hits do not read archive bytes or traverse generated output. Directory packs still validate their topology; ordinary linked files and untouched vanilla subtrees remain live. Materialized vanilla directory stamps detect membership changes without listing them again. Only marker identity resolves paths; the builder retains the caller's original symlink targets and root aliases. + +On non-Unix platforms, materialized files retain content hashing because portable metadata lacks a change timestamp. That path was not runtime-tested. External folder overlays and symlink cycles retain uncached behavior. Missing/corrupt markers and a missing output root rebuild. Generated output is owned cache data: external edits to individual output files are deliberately not detected; delete the sibling marker or overlay directory to rebuild it. + +## Real pack measurements + +The ignored test measures the actual production `resource_root` entry point against its original selection/key/build sequence. Two warmups and 11 alternating samples use identical prepared Minecraft 26.3 resources (manifest schema 7). Complete materialized output bytes and symlink identities are compared outside timing. Cold means an absent marker with warm filesystem caches, rather than cold storage. + +Linux x86_64/ext4/NVMe, Ryzen 5 5600X, Rust 1.99.0, Cargo `fast`, measured 2026-10-15: + +| ZIP pack | Original rebuild | Cached cold | Unchanged hit | Saved per hit | +| --- | ---: | ---: | ---: | ---: | +| Faithful 32x, 26.3 September 2026 | 159.827 ms | 162.711 ms | 0.707 ms | 159.120 ms | +| Default HD 128x demo, 1.8.2.7 | 111.501 ms | 114.386 ms | 0.310 ms | 111.191 ms | +| FPBR, 1.21.9 R1.3 | 347.639 ms | 348.012 ms | 0.448 ms | 347.191 ms | + +Unchanged speedups are approximately 226x, 359x and 775x. Cold overhead on these ZIPs is 0.1–2.6%, replacing the original cache implementation's 73–79% synthetic overhead. This measures overlay assembly and cache validation, excluding scan, texture decoding, total startup and FPS. + +Mac mini (M4 Pro, APFS, Rust stable, Cargo `fast`), same harness and packs, measured 2026-10-15 during review while the machine ran other builds: + +| ZIP pack | Original rebuild | Cached cold | Unchanged hit | Saved per hit | +| --- | ---: | ---: | ---: | ---: | +| Faithful 32x, 26.3 September 2026 | 1,184.400 ms | 1,295.069 ms | 0.571 ms | 1,183.829 ms | +| FPBR, 1.21.9 R1.3 | 5,292.149 ms | 5,503.965 ms | 0.391 ms | 5,291.758 ms | + +Creating thousands of files and links costs far more on macOS than on Linux, so the saving there is seconds per startup with a pack enabled. + +Pack downloads were verified against publisher SHA-512 metadata. Exact versions, URLs, sizes, asset counts, hashes and prepared-manifest identity are recorded in `benchmarks/overlay-real-packs-2026-10-15.json`. Sources: [Faithful](https://modrinth.com/resourcepack/faithful-32x/version/lDYpMiqk), [Default HD](https://modrinth.com/resourcepack/default-hd-128x/version/rErHu3BE), [FPBR](https://modrinth.com/resourcepack/fpbr/version/dynf82xk). FPBR targets older 1.21.9 snapshots; it is measured as a large real 128x archive over prepared 26.3 resources, without claiming visual/version compatibility. Default HD is the publisher's free demo. Downloaded pack contents are not committed. + +## Reproduce and validate + +```sh +export CARGO_INCREMENTAL=0 +export HORIZON_OVERLAY_BENCH_VANILLA=/path/to/prepared/26.3 +export HORIZON_OVERLAY_BENCH_PACKS='["/path/to/Faithful.zip","/path/to/DefaultHD.zip","/path/to/FPBR.zip"]' +cargo test -p horizon-client --lib --profile fast packs::cache::tests::benchmark_real_resource_root -- --ignored --nocapture --test-threads=1 +cargo test -p horizon-client --lib --profile fast packs:: -- --nocapture +cargo clippy -p horizon-client --lib --tests --profile fast -- -D warnings +cargo fmt --all -- --check +``` + +Thirteen focused tests pass, covering source edits/replacements, Unix preserved-mtime edits, pack order/removal, overlays/filters, vanilla membership, marker/output-root recovery, failed ZIP rebuilds, symlink aliases/cycles, contention and unchanged relative link targets. The opt-in real-pack benchmark passes; strict Clippy, formatting and whitespace checks pass. Each overlay retains a small marker and empty lock file; cache hits retain no archive byte buffer.