From 8177726f70d57e1a3485c5db582d1b8a83435c42 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:47:08 +0100 Subject: [PATCH 1/3] perf: reuse validated resource-pack overlays --- Cargo.lock | 3 + crates/horizon-client/Cargo.toml | 2 + crates/horizon-client/src/packs.rs | 30 +- crates/horizon-client/src/packs/cache.rs | 911 +++++++++++++++++++++++ docs/reuse-pack-overlays.md | 69 ++ 5 files changed, 1014 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/src/packs/cache.rs create mode 100644 docs/reuse-pack-overlays.md diff --git a/Cargo.lock b/Cargo.lock index 0753fc7d0..0e0f15c62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -918,7 +918,9 @@ dependencies = [ "naga", "png", "pollster", + "serde", "serde_json", + "sha2", "symphonia", "ureq", "wgpu", @@ -2313,6 +2315,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 12aeaae4a..f537bb415 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -18,6 +18,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..a49f9f704 --- /dev/null +++ b/crates/horizon-client/src/packs/cache.rs @@ -0,0 +1,911 @@ +//! Content-validated overlay reuse. Live symlink files/subtrees need no content +//! scan; merged, extracted and copied bytes do. Topology and link targets are +//! always checked, including vanilla directories materialized by mirror. +use super::{Pack, Source, build_overlay_uncached}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{collections::BTreeSet, fs, io, io::Read, path::Path, path::PathBuf}; + +// Bump when overlay/merge semantics change. Markers are disposable cache data. +const VERSION: u32 = 1; + +#[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, + output: String, +} + +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); +} +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 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"); + for entry in entries(path)? { + field(&mut hash, entry.file_name().unwrap().as_encoded_bytes()); + // mirror's decisions use the followed file type, including symlinks. + field(&mut hash, &[u8::from(entry.is_dir())]); + } + } + Ok(_) if directory => field(&mut hash, b"not-directory"), + Ok(_) => content(&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 content 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) { + content(hash, path)?; + } + } + Ok(()) +} +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) => tree(&mut hash, path, Some(pack))?, + Source::Zip(path) => content(&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()?; + // Absolute paths also prevent cwd changes from reusing relative symlinks. + // Keep root symlink aliases live, as mirror does for individual resources. + let vanilla = absolute(vanilla)?; + let packs: Vec = packs + .iter() + .map(|pack| { + let mut pack = pack.clone(); + match &mut pack.source { + Source::Dir(path) | Source::Zip(path) => { + *path = absolute(path)?; + } + } + Ok(pack) + }) + .collect::>()?; + 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 + && marker.packs == *signature + && marker.dependencies.valid() + && output_signature(out).is_ok_and(|s| s == marker.output) + { + 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, + packs: signature, + dependencies, + output: output_signature(out)?, + }; + // 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_output_invalidate() { + 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(); + f.rebuild_matches(std::slice::from_ref(&low)); + fs::remove_file(out.join(resource)).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, and a corrupt + // output symlink is repaired even when its target bytes happen to match. + 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(); + 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()); + } + + #[test] + #[ignore = "reproducible overlay benchmark; run with --ignored --nocapture"] + fn benchmark_overlay_reuse() { + use std::{hint::black_box, time::Instant}; + let f = Fixture::new(); + let pack = f.dir_pack("pack"); + let mut files = vec![( + "pack.mcmeta".to_owned(), + fs::read(f.0.join("pack/pack.mcmeta")).unwrap(), + )]; + // 2,048 overrides (32 MiB), 32 merged language files, 8,192 live + // vanilla textures (128 MiB). Synthetic incompressible payloads approximate + // already-compressed PNG bytes; texture decoding is outside this benchmark. + let mut random = 0x1234_5678u32; + let texture: Vec = (0..16384) + .map(|_| { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + (random >> 24) as u8 + }) + .collect(); + for i in 0..8192 { + let name = format!("assets/minecraft/textures/block/{i}.png"); + f.write(&format!("vanilla/{name}"), &texture); + if i < 2048 { + f.write(&format!("pack/{name}"), &texture); + files.push((name, texture.clone())); + } + } + for i in 0..32 { + let name = format!("assets/minecraft/lang/{i}.json"); + let vanilla = serde_json::to_vec(&serde_json::Value::Object( + (0..2000) + .map(|j| { + ( + format!("key{j}"), + serde_json::json!(format!("Vanilla translation {j}")), + ) + }) + .collect(), + )) + .unwrap(); + let body = serde_json::to_vec(&serde_json::Value::Object( + (0..1000) + .map(|j| { + ( + format!("key{j}"), + serde_json::json!(format!("Pack translation {j}")), + ) + }) + .collect(), + )) + .unwrap(); + f.write(&format!("vanilla/{name}"), &vanilla); + f.write(&format!("pack/{name}"), &body); + files.push((name, body)); + } + let borrowed: Vec<_> = files + .iter() + .map(|(name, body)| (name.as_str(), body.clone())) + .collect(); + f.write("pack.zip", &archive(&borrowed, true)); + println!( + "fixture ZIP bytes={}", + fs::metadata(f.0.join("pack.zip")).unwrap().len() + ); + let zip = packs::pack( + "zip".into(), + Text::empty(), + Source::Zip(f.0.join("pack.zip")), + ) + .unwrap(); + let median = |mut times: Vec| { + times.sort_by(f64::total_cmp); + times[times.len() / 2] + }; + for (kind, pack) in [("directory", pack), ("deflated zip", zip)] { + f.rebuild_matches(std::slice::from_ref(&pack)); + let vanilla = f.0.join("vanilla"); + let out = f.0.join("cached"); + let mut baseline = Vec::new(); + let mut cold = Vec::new(); + let mut hit = Vec::new(); + for _ in 0..11 { + let start = Instant::now(); + build_overlay_uncached( + black_box(&vanilla), + black_box(std::slice::from_ref(&pack)), + black_box(&f.0.join("reference")), + &mut Dependencies::default(), + ) + .unwrap(); + baseline.push(start.elapsed().as_secs_f64() * 1000.0); + fs::remove_file(marker_path(&out)).unwrap(); + let start = Instant::now(); + packs::build_overlay( + black_box(&vanilla), + black_box(std::slice::from_ref(&pack)), + black_box(&out), + ) + .unwrap(); + cold.push(start.elapsed().as_secs_f64() * 1000.0); + let start = Instant::now(); + packs::build_overlay( + black_box(&vanilla), + black_box(std::slice::from_ref(&pack)), + black_box(&out), + ) + .unwrap(); + hit.push(start.elapsed().as_secs_f64() * 1000.0); + assert_eq!( + output_signature(&out).unwrap(), + output_signature(&f.0.join("reference")).unwrap() + ); + } + println!( + "{kind}: baseline={:.3} ms cold={:.3} ms unchanged={:.3} ms (11 medians, full validation)", + median(baseline), + median(cold), + median(hit) + ); + } + } + + #[test] + #[ignore = "content-heavy few-file directory benchmark"] + fn benchmark_content_heavy_directory() { + use std::{hint::black_box, time::Instant}; + let f = Fixture::new(); + f.write("vanilla/facts.json", b"[]"); + let pack = f.dir_pack("pack"); + let bytes = vec![42; 8 * 1024 * 1024]; + for i in 0..4 { + f.write(&format!("pack/assets/minecraft/textures/{i}.png"), &bytes); + } + let vanilla = f.0.join("vanilla"); + let out = f.0.join("cached"); + f.rebuild_matches(std::slice::from_ref(&pack)); + let mut timings = [Vec::new(), Vec::new(), Vec::new()]; + for _ in 0..11 { + let start = Instant::now(); + build_overlay_uncached( + black_box(&vanilla), + black_box(std::slice::from_ref(&pack)), + &f.0.join("reference"), + &mut Dependencies::default(), + ) + .unwrap(); + timings[0].push(start.elapsed().as_secs_f64() * 1000.0); + fs::remove_file(marker_path(&out)).unwrap(); + for times in &mut timings[1..] { + let start = Instant::now(); + packs::build_overlay( + black_box(&vanilla), + black_box(std::slice::from_ref(&pack)), + black_box(&out), + ) + .unwrap(); + times.push(start.elapsed().as_secs_f64() * 1000.0); + } + assert_eq!( + output_signature(&out).unwrap(), + output_signature(&f.0.join("reference")).unwrap() + ); + } + let medians: Vec<_> = timings + .into_iter() + .map(|mut times| { + times.sort_by(f64::total_cmp); + times[5] + }) + .collect(); + println!( + "4 x 8 MiB directory textures: baseline={:.3} ms cold={:.3} ms unchanged={:.3} ms (11 medians, full validation)", + medians[0], medians[1], medians[2] + ); + } +} diff --git a/docs/reuse-pack-overlays.md b/docs/reuse-pack-overlays.md new file mode 100644 index 000000000..9fa1e948c --- /dev/null +++ b/docs/reuse-pack-overlays.md @@ -0,0 +1,69 @@ +# Reusing resource-pack overlays + +`packs::build_overlay` reuses an overlay after validating a versioned sibling +JSON marker. The marker covers pack source paths/order, active overlay roots, +compiled filters, resource topology, merged inputs and the materialized output. +SHA-256 checks content rather than relying on file size or timestamps. + +On Unix, ordinary directory-pack resources and untouched vanilla resources are +live symlinks. Their bytes stay current on edits/replacements, so validation +checks topology and link targets without reading those bytes. Merged language, +sound, font and atlas JSON inputs are hashed. Vanilla directories that were +materialized by the builder are checked for additions/removals/type changes; +untouched directory symlinks stay live without a recursive vanilla scan. + +ZIP archives and extracted output files are fully hashed. On platforms where +`link` copies files, directory-pack contents and copied vanilla files are also +hashed. Existing merge order and filter behavior are unchanged. + +A persistent sibling `.overlay-cache.lock` uses an advisory OS file lock to +serialize validation, rebuilding and publication for the same output directory. +The lock inode is never removed by the builder. The old marker is removed before +rebuilding; its replacement is renamed into place only after a successful build +and stable input checks. Missing/corrupt markers or output trigger rebuilding. +Directory packs with absolute/parent-traversal overlay paths or symlink cycles +build through the original path without publishing a reusable marker. External +overlay paths retain their previous behavior. + +## Reproduce the benchmark + +```sh +CARGO_TARGET_DIR=/home/bob/Documents/horizon/target cargo test -p horizon-client --lib --profile fast packs::cache::tests::benchmark -- --ignored --nocapture --test-threads=1 +``` + +The ignored tests compare the original builder body (dependency recording +disabled) with the production cache path on identical inputs. They warm both +paths, collect 11 repetitions and compare output signatures after each pair. +The unchanged timing includes locking and all input/output validation. Cold +means the marker is absent but filesystem caches are warm; it is not a +cold-disk measurement. + +Fixtures are synthetic because prepared game assets were unavailable in this +workspace: 8,192 vanilla texture files (128 MiB), 2,048 overrides (32 MiB), and +32 merged language files with 2,000 vanilla/1,000 pack keys each. Texture bytes +are deterministic incompressible payloads approximating already-compressed PNG +data; this benchmark does not decode images. The directory and deflated ZIP +cases contain equivalent resources. A separate four-file/32 MiB directory case +checks that live content does not impose a large hashing cost. + +Measured on 2026-10-14: Linux 7.2.8-zen1-2-zen x86_64, ext4/NVMe, +AMD Ryzen 5 5600X (6 cores/12 threads), Rust 1.99.0, `fast` profile. +The deflated ZIP is 34,030,189 bytes (32.45 MiB). + +| Fixture | Original rebuild | Cached cold/rebuild | Unchanged validated hit | Hit speedup | +| --- | ---: | ---: | ---: | ---: | +| Directory pack | 107.129 ms | 184.868 ms | 50.484 ms | 2.12× | +| Deflated ZIP pack | 152.032 ms | 271.798 ms | 88.416 ms | 1.72× | +| Directory, four 8 MiB files | 0.112 ms | 0.316 ms | 0.122 ms | ~10 µs overhead | + +The two larger cold paths are 73–79% slower because they also establish and +verify cache dependencies/output. The large-file/few-file case adds about +0.2 ms cold and 0.01 ms on an unchanged call; reading all of its live texture +bytes would instead cost tens of milliseconds, so those bytes are excluded. + +The cache adds a small marker and persistent empty lock file per overlay. Hashes +stream through a 64 KiB buffer rather than retaining archive/resource contents +on cache hits. Initial/rebuilt overlays do extra validation and marker work; +tiny overlays can have a small unchanged-call overhead. Measurements cover +overlay construction only, not total startup time or frame rate. Non-Unix +copy behavior is covered in the implementation but was not runtime-tested here. From 1295fccd17d4bab9e95b320085f78373701d9482 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:04:48 +0100 Subject: [PATCH 2/3] perf(client): validate overlay reuse with source stamps and benchmark real packs --- benchmarks/overlay-real-packs-2026-10-15.json | 54 ++++ crates/horizon-client/src/packs/cache.rs | 243 +++++++++++++++--- docs/reuse-pack-overlays.md | 99 +++---- 3 files changed, 296 insertions(+), 100 deletions(-) create mode 100644 benchmarks/overlay-real-packs-2026-10-15.json 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/src/packs/cache.rs b/crates/horizon-client/src/packs/cache.rs index a49f9f704..6931a3871 100644 --- a/crates/horizon-client/src/packs/cache.rs +++ b/crates/horizon-client/src/packs/cache.rs @@ -1,13 +1,14 @@ -//! Content-validated overlay reuse. Live symlink files/subtrees need no content -//! scan; merged, extracted and copied bytes do. Topology and link targets are -//! always checked, including vanilla directories materialized by mirror. +//! 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}; -use std::{collections::BTreeSet, fs, io, io::Read, path::Path, path::PathBuf}; +#[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 = 1; +const VERSION: u32 = 2; #[derive(Default, Serialize, Deserialize)] pub(super) struct Dependencies { @@ -47,7 +48,6 @@ struct Marker { vanilla: PathBuf, packs: String, dependencies: Dependencies, - output: String, } fn finish(hash: Sha256) -> String { @@ -58,6 +58,7 @@ 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()); @@ -71,6 +72,31 @@ fn content(hash: &mut Sha256, path: &Path) -> io::Result<()> { } 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())) @@ -85,14 +111,10 @@ fn dependency_signature(path: &Path, directory: bool) -> io::Result { Err(e) => return Err(e), Ok(meta) if directory && meta.is_dir() => { field(&mut hash, b"directory"); - for entry in entries(path)? { - field(&mut hash, entry.file_name().unwrap().as_encoded_bytes()); - // mirror's decisions use the followed file type, including symlinks. - field(&mut hash, &[u8::from(entry.is_dir())]); - } + stamp(&mut hash, path)?; } Ok(_) if directory => field(&mut hash, b"not-directory"), - Ok(_) => content(&mut hash, path)?, + Ok(_) => stamp(&mut hash, path)?, } Ok(finish(hash)) } @@ -114,7 +136,7 @@ fn needs_content(path: &Path, pack: Option<&Pack>) -> bool { .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 content validation. + // and configuration bytes are materialized and need stamp validation. relative == "pack.mcmeta" || super::merge_kind(&relative).is_some() || pack.overlays.iter().any(|overlay| { @@ -164,11 +186,16 @@ fn tree_inner( } else { field(hash, b"file"); if needs_content(path, pack) { - content(hash, path)?; + #[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)?; @@ -203,8 +230,14 @@ fn pack_signature(packs: &[Pack]) -> io::Result { field(&mut hash, format!("{:?}", pack.overlays).as_bytes()); field(&mut hash, format!("{:?}", pack.filter).as_bytes()); match &pack.source { - Source::Dir(path) => tree(&mut hash, path, Some(pack))?, - Source::Zip(path) => content(&mut hash, path)?, + 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)) @@ -242,31 +275,18 @@ pub(super) fn build(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<() .truncate(false) .open(lock_path(out))?; lock.lock()?; - // Absolute paths also prevent cwd changes from reusing relative symlinks. - // Keep root symlink aliases live, as mirror does for individual resources. - let vanilla = absolute(vanilla)?; - let packs: Vec = packs - .iter() - .map(|pack| { - let mut pack = pack.clone(); - match &mut pack.source { - Source::Dir(path) | Source::Zip(path) => { - *path = absolute(path)?; - } - } - Ok(pack) - }) - .collect::>()?; + // 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); + 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 + && marker.vanilla == vanilla_key && marker.packs == *signature && marker.dependencies.valid() - && output_signature(out).is_ok_and(|s| s == marker.output) + && out.is_dir() { return Ok(()); } @@ -280,17 +300,16 @@ pub(super) fn build(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<() tracking: signature.is_ok(), ..Dependencies::default() }; - build_overlay_uncached(&vanilla, &packs, out, &mut dependencies)?; + build_overlay_uncached(vanilla, packs, out, &mut dependencies)?; if let Ok(signature) = signature && dependencies.valid() - && pack_signature(&packs).is_ok_and(|s| s == signature) + && pack_signature(packs).is_ok_and(|s| s == signature) { let marker = Marker { version: VERSION, - vanilla, + vanilla: vanilla_key, packs: signature, dependencies, - output: output_signature(out)?, }; // PathBuf serialization requires UTF-8; unusual resource root names // can still build normally without a reusable marker. @@ -404,7 +423,7 @@ mod tests { } #[test] - fn directory_inputs_config_and_output_invalidate() { + 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"}"#); @@ -461,8 +480,14 @@ mod tests { 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)); @@ -584,8 +609,8 @@ mod tests { 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, and a corrupt - // output symlink is repaired even when its target bytes happen to match. + // 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(); @@ -593,6 +618,7 @@ mod tests { 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(); @@ -908,4 +934,139 @@ mod tests { medians[0], medians[1], medians[2] ); } + + #[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 index 9fa1e948c..2a5235553 100644 --- a/docs/reuse-pack-overlays.md +++ b/docs/reuse-pack-overlays.md @@ -1,69 +1,50 @@ # Reusing resource-pack overlays -`packs::build_overlay` reuses an overlay after validating a versioned sibling -JSON marker. The marker covers pack source paths/order, active overlay roots, -compiled filters, resource topology, merged inputs and the materialized output. -SHA-256 checks content rather than relying on file size or timestamps. +`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, ordinary directory-pack resources and untouched vanilla resources are -live symlinks. Their bytes stay current on edits/replacements, so validation -checks topology and link targets without reading those bytes. Merged language, -sound, font and atlas JSON inputs are hashed. Vanilla directories that were -materialized by the builder are checked for additions/removals/type changes; -untouched directory symlinks stay live without a recursive vanilla scan. +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. -ZIP archives and extracted output files are fully hashed. On platforms where -`link` copies files, directory-pack contents and copied vanilla files are also -hashed. Existing merge order and filter behavior are unchanged. +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. -A persistent sibling `.overlay-cache.lock` uses an advisory OS file lock to -serialize validation, rebuilding and publication for the same output directory. -The lock inode is never removed by the builder. The old marker is removed before -rebuilding; its replacement is renamed into place only after a successful build -and stable input checks. Missing/corrupt markers or output trigger rebuilding. -Directory packs with absolute/parent-traversal overlay paths or symlink cycles -build through the original path without publishing a reusable marker. External -overlay paths retain their previous behavior. +## Real pack measurements -## Reproduce the benchmark +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. + +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. + +## Synthetic coverage + +The existing fixtures contain 8,192 vanilla textures (128 MiB), 2,048 overrides (32 MiB) and 32 merged language files; equivalent directory/ZIP payloads are incompressible bytes. Eleven median samples compare identical output outside timing: + +| Fixture | Original | Cached cold | Hit | +| --- | ---: | ---: | ---: | +| Directory | 108.487 ms | 126.438 ms | 7.438 ms | +| Deflated ZIP, 32.45 MiB | 155.540 ms | 155.453 ms | 0.128 ms | +| Directory, four 8 MiB files | 0.115 ms | 0.271 ms | 0.076 ms | + +Directory topology scans remain a cost: the larger directory fixture adds about 17% cold overhead and gains 14.6x on hits. Tiny cold overlays add about 0.16 ms. No overall startup gain is inferred from either table. + +## Reproduce and validate ```sh -CARGO_TARGET_DIR=/home/bob/Documents/horizon/target cargo test -p horizon-client --lib --profile fast packs::cache::tests::benchmark -- --ignored --nocapture --test-threads=1 +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::cache::tests::benchmark -- --ignored --nocapture --test-threads=1 --skip benchmark_real_resource_root +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 ``` -The ignored tests compare the original builder body (dependency recording -disabled) with the production cache path on identical inputs. They warm both -paths, collect 11 repetitions and compare output signatures after each pair. -The unchanged timing includes locking and all input/output validation. Cold -means the marker is absent but filesystem caches are warm; it is not a -cold-disk measurement. - -Fixtures are synthetic because prepared game assets were unavailable in this -workspace: 8,192 vanilla texture files (128 MiB), 2,048 overrides (32 MiB), and -32 merged language files with 2,000 vanilla/1,000 pack keys each. Texture bytes -are deterministic incompressible payloads approximating already-compressed PNG -data; this benchmark does not decode images. The directory and deflated ZIP -cases contain equivalent resources. A separate four-file/32 MiB directory case -checks that live content does not impose a large hashing cost. - -Measured on 2026-10-14: Linux 7.2.8-zen1-2-zen x86_64, ext4/NVMe, -AMD Ryzen 5 5600X (6 cores/12 threads), Rust 1.99.0, `fast` profile. -The deflated ZIP is 34,030,189 bytes (32.45 MiB). - -| Fixture | Original rebuild | Cached cold/rebuild | Unchanged validated hit | Hit speedup | -| --- | ---: | ---: | ---: | ---: | -| Directory pack | 107.129 ms | 184.868 ms | 50.484 ms | 2.12× | -| Deflated ZIP pack | 152.032 ms | 271.798 ms | 88.416 ms | 1.72× | -| Directory, four 8 MiB files | 0.112 ms | 0.316 ms | 0.122 ms | ~10 µs overhead | - -The two larger cold paths are 73–79% slower because they also establish and -verify cache dependencies/output. The large-file/few-file case adds about -0.2 ms cold and 0.01 ms on an unchanged call; reading all of its live texture -bytes would instead cost tens of milliseconds, so those bytes are excluded. - -The cache adds a small marker and persistent empty lock file per overlay. Hashes -stream through a 64 KiB buffer rather than retaining archive/resource contents -on cache hits. Initial/rebuilt overlays do extra validation and marker work; -tiny overlays can have a small unchanged-call overhead. Measurements cover -overlay construction only, not total startup time or frame rate. Non-Unix -copy behavior is covered in the implementation but was not runtime-tested here. +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. All three opt-in benchmarks pass; strict Clippy, formatting and whitespace checks pass. Each overlay retains a small marker and empty lock file; cache hits retain no archive byte buffer. From cc8744a06bbbdd46ea5378e45dba9c2499165de8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:26:46 +0200 Subject: [PATCH 3/3] Trim synthetic overlay benchmarks; record Mac real-pack numbers The real-pack benchmark on the production resource_root path stays as the reproducible measurement. On the Mac mini it saves 1.18 s (Faithful 32x) and 5.29 s (FPBR) per startup with the pack enabled. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/packs/cache.rs | 179 ----------------------- docs/reuse-pack-overlays.md | 24 ++- 2 files changed, 10 insertions(+), 193 deletions(-) diff --git a/crates/horizon-client/src/packs/cache.rs b/crates/horizon-client/src/packs/cache.rs index 6931a3871..1f17c018b 100644 --- a/crates/horizon-client/src/packs/cache.rs +++ b/crates/horizon-client/src/packs/cache.rs @@ -756,185 +756,6 @@ mod tests { assert!(lock_path(&out).exists()); } - #[test] - #[ignore = "reproducible overlay benchmark; run with --ignored --nocapture"] - fn benchmark_overlay_reuse() { - use std::{hint::black_box, time::Instant}; - let f = Fixture::new(); - let pack = f.dir_pack("pack"); - let mut files = vec![( - "pack.mcmeta".to_owned(), - fs::read(f.0.join("pack/pack.mcmeta")).unwrap(), - )]; - // 2,048 overrides (32 MiB), 32 merged language files, 8,192 live - // vanilla textures (128 MiB). Synthetic incompressible payloads approximate - // already-compressed PNG bytes; texture decoding is outside this benchmark. - let mut random = 0x1234_5678u32; - let texture: Vec = (0..16384) - .map(|_| { - random ^= random << 13; - random ^= random >> 17; - random ^= random << 5; - (random >> 24) as u8 - }) - .collect(); - for i in 0..8192 { - let name = format!("assets/minecraft/textures/block/{i}.png"); - f.write(&format!("vanilla/{name}"), &texture); - if i < 2048 { - f.write(&format!("pack/{name}"), &texture); - files.push((name, texture.clone())); - } - } - for i in 0..32 { - let name = format!("assets/minecraft/lang/{i}.json"); - let vanilla = serde_json::to_vec(&serde_json::Value::Object( - (0..2000) - .map(|j| { - ( - format!("key{j}"), - serde_json::json!(format!("Vanilla translation {j}")), - ) - }) - .collect(), - )) - .unwrap(); - let body = serde_json::to_vec(&serde_json::Value::Object( - (0..1000) - .map(|j| { - ( - format!("key{j}"), - serde_json::json!(format!("Pack translation {j}")), - ) - }) - .collect(), - )) - .unwrap(); - f.write(&format!("vanilla/{name}"), &vanilla); - f.write(&format!("pack/{name}"), &body); - files.push((name, body)); - } - let borrowed: Vec<_> = files - .iter() - .map(|(name, body)| (name.as_str(), body.clone())) - .collect(); - f.write("pack.zip", &archive(&borrowed, true)); - println!( - "fixture ZIP bytes={}", - fs::metadata(f.0.join("pack.zip")).unwrap().len() - ); - let zip = packs::pack( - "zip".into(), - Text::empty(), - Source::Zip(f.0.join("pack.zip")), - ) - .unwrap(); - let median = |mut times: Vec| { - times.sort_by(f64::total_cmp); - times[times.len() / 2] - }; - for (kind, pack) in [("directory", pack), ("deflated zip", zip)] { - f.rebuild_matches(std::slice::from_ref(&pack)); - let vanilla = f.0.join("vanilla"); - let out = f.0.join("cached"); - let mut baseline = Vec::new(); - let mut cold = Vec::new(); - let mut hit = Vec::new(); - for _ in 0..11 { - let start = Instant::now(); - build_overlay_uncached( - black_box(&vanilla), - black_box(std::slice::from_ref(&pack)), - black_box(&f.0.join("reference")), - &mut Dependencies::default(), - ) - .unwrap(); - baseline.push(start.elapsed().as_secs_f64() * 1000.0); - fs::remove_file(marker_path(&out)).unwrap(); - let start = Instant::now(); - packs::build_overlay( - black_box(&vanilla), - black_box(std::slice::from_ref(&pack)), - black_box(&out), - ) - .unwrap(); - cold.push(start.elapsed().as_secs_f64() * 1000.0); - let start = Instant::now(); - packs::build_overlay( - black_box(&vanilla), - black_box(std::slice::from_ref(&pack)), - black_box(&out), - ) - .unwrap(); - hit.push(start.elapsed().as_secs_f64() * 1000.0); - assert_eq!( - output_signature(&out).unwrap(), - output_signature(&f.0.join("reference")).unwrap() - ); - } - println!( - "{kind}: baseline={:.3} ms cold={:.3} ms unchanged={:.3} ms (11 medians, full validation)", - median(baseline), - median(cold), - median(hit) - ); - } - } - - #[test] - #[ignore = "content-heavy few-file directory benchmark"] - fn benchmark_content_heavy_directory() { - use std::{hint::black_box, time::Instant}; - let f = Fixture::new(); - f.write("vanilla/facts.json", b"[]"); - let pack = f.dir_pack("pack"); - let bytes = vec![42; 8 * 1024 * 1024]; - for i in 0..4 { - f.write(&format!("pack/assets/minecraft/textures/{i}.png"), &bytes); - } - let vanilla = f.0.join("vanilla"); - let out = f.0.join("cached"); - f.rebuild_matches(std::slice::from_ref(&pack)); - let mut timings = [Vec::new(), Vec::new(), Vec::new()]; - for _ in 0..11 { - let start = Instant::now(); - build_overlay_uncached( - black_box(&vanilla), - black_box(std::slice::from_ref(&pack)), - &f.0.join("reference"), - &mut Dependencies::default(), - ) - .unwrap(); - timings[0].push(start.elapsed().as_secs_f64() * 1000.0); - fs::remove_file(marker_path(&out)).unwrap(); - for times in &mut timings[1..] { - let start = Instant::now(); - packs::build_overlay( - black_box(&vanilla), - black_box(std::slice::from_ref(&pack)), - black_box(&out), - ) - .unwrap(); - times.push(start.elapsed().as_secs_f64() * 1000.0); - } - assert_eq!( - output_signature(&out).unwrap(), - output_signature(&f.0.join("reference")).unwrap() - ); - } - let medians: Vec<_> = timings - .into_iter() - .map(|mut times| { - times.sort_by(f64::total_cmp); - times[5] - }) - .collect(); - println!( - "4 x 8 MiB directory textures: baseline={:.3} ms cold={:.3} ms unchanged={:.3} ms (11 medians, full validation)", - medians[0], medians[1], medians[2] - ); - } - #[cfg(unix)] #[test] fn relative_builder_targets_are_preserved() { diff --git a/docs/reuse-pack-overlays.md b/docs/reuse-pack-overlays.md index 2a5235553..53e8bbc3a 100644 --- a/docs/reuse-pack-overlays.md +++ b/docs/reuse-pack-overlays.md @@ -20,20 +20,17 @@ Linux x86_64/ext4/NVMe, Ryzen 5 5600X, Rust 1.99.0, Cargo `fast`, measured 2026- 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. -## Synthetic coverage - -The existing fixtures contain 8,192 vanilla textures (128 MiB), 2,048 overrides (32 MiB) and 32 merged language files; equivalent directory/ZIP payloads are incompressible bytes. Eleven median samples compare identical output outside timing: - -| Fixture | Original | Cached cold | Hit | -| --- | ---: | ---: | ---: | -| Directory | 108.487 ms | 126.438 ms | 7.438 ms | -| Deflated ZIP, 32.45 MiB | 155.540 ms | 155.453 ms | 0.128 ms | -| Directory, four 8 MiB files | 0.115 ms | 0.271 ms | 0.076 ms | - -Directory topology scans remain a cost: the larger directory fixture adds about 17% cold overhead and gains 14.6x on hits. Tiny cold overlays add about 0.16 ms. No overall startup gain is inferred from either table. - ## Reproduce and validate ```sh @@ -41,10 +38,9 @@ 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::cache::tests::benchmark -- --ignored --nocapture --test-threads=1 --skip benchmark_real_resource_root 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. All three opt-in benchmarks pass; strict Clippy, formatting and whitespace checks pass. Each overlay retains a small marker and empty lock file; cache hits retain no archive byte buffer. +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.