diff --git a/crates/horizon-client/examples/save_bench.rs b/crates/horizon-client/examples/save_bench.rs new file mode 100644 index 000000000..2e3084290 --- /dev/null +++ b/crates/horizon-client/examples/save_bench.rs @@ -0,0 +1,128 @@ +//! The region writer on real chunks, without a window: how long a world's +//! chunks take to be encoded, compressed and written by `SaveDir`, against +//! the same encoding and compression done one chunk after another (what the +//! writer thread did alone before it had helpers). +//! +//! save_bench RESOURCES DIMENSION_DIR [--rounds N] +//! +//! DIMENSION_DIR is a saved dimension folder (`saves/W/dimensions/minecraft/ +//! overworld`); its chunks are read once, then each round saves them all into +//! a scratch folder with `save_later` + `flush`, and times the one-thread +//! baseline. The written chunks are checked byte for byte against the +//! baseline's compressed records. +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + save::{SaveDir, SaveTables, encode_with}, +}; +use horizon_core::position::ChunkPos; +use horizon_world::{ + compression::Compression, + nbt::Limits, + region::{ChunkRecord, RegionFile}, +}; +use std::{path::PathBuf, sync::Arc, time::Instant}; + +type Result = std::result::Result>; + +fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let usage = "usage: save_bench RESOURCES DIMENSION_DIR [--rounds N]"; + let root = PathBuf::from(args.first().ok_or(usage)?); + let dimension = PathBuf::from(args.get(1).ok_or(usage)?); + let rounds: usize = args + .iter() + .position(|a| a == "--rounds") + .and_then(|i| args.get(i + 1)) + .and_then(|v| v.parse().ok()) + .unwrap_or(5); + + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Arc::new(Biomes::load(&root)?); + let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); + let registry = assets.registry; + + let source = SaveDir::new(dimension.clone()); + let _ = source.tables.set(tables.clone()); + let mut chunks = Vec::new(); + for entry in std::fs::read_dir(dimension.join("region"))? { + let path = entry?.path(); + if path.extension().is_none_or(|e| e != "mca") { + continue; + } + let region = RegionFile::open(&path)?; + for (pos, _) in region.chunks() { + if let Some(chunk) = source.load(pos.x, pos.z, registry, &biomes) { + chunks.push(Arc::new(chunk)); + } + } + } + chunks.sort_by_key(|c| (c.x, c.z)); + println!("{} chunks from {}", chunks.len(), dimension.display()); + + let scratch = std::env::temp_dir().join(format!("save_bench_{}", std::process::id())); + // Encoding and compressing on one thread (what the writer did alone), + // then SaveDir's writer with its helpers. + let mut times = [Vec::new(), Vec::new(), Vec::new()]; + let mut written = Vec::new(); + for round in 0..rounds { + let started = Instant::now(); + let tags: Vec<_> = chunks + .iter() + .map(|c| encode_with(c, registry, &biomes, Some(&tables), true)) + .collect(); + times[0].push(started.elapsed().as_secs_f64()); + let started = Instant::now(); + let baseline: Vec = tags + .iter() + .map(|tag| ChunkRecord::from_nbt(tag, Compression::Zlib, 0, Limits::default())) + .collect::>()?; + times[1].push(started.elapsed().as_secs_f64()); + drop(tags); + + let _ = std::fs::remove_dir_all(&scratch); + let save = SaveDir::new(scratch.clone()); + let _ = save.tables.set(tables.clone()); + let started = Instant::now(); + save.save_later(&chunks, registry, &biomes)?; + save.flush(); + times[2].push(started.elapsed().as_secs_f64()); + drop(save); + + if round == 0 { + for (chunk, want) in chunks.iter().zip(&baseline) { + let path = scratch.join(format!("region/r.{}.{}.mca", chunk.x >> 5, chunk.z >> 5)); + let got = RegionFile::open(&path)? + .read(ChunkPos::new(chunk.x, chunk.z))? + .ok_or("a saved chunk is missing")?; + if got.compressed != want.compressed { + return Err(format!("chunk {} {} differs", chunk.x, chunk.z).into()); + } + } + written = baseline.iter().map(|r| r.compressed.len()).collect(); + } + } + let _ = std::fs::remove_dir_all(&scratch); + println!( + "{} KiB compressed, identical to the one-thread records", + written.iter().sum::() / 1024 + ); + let per_chunk = 1000.0 / chunks.len() as f64; + let names = [ + "one thread: encode", + "one thread: compress", + "SaveDir (encode, compress, write)", + ]; + for (name, t) in names.iter().zip(&mut times) { + t.sort_by(f64::total_cmp); + println!( + "{name}: best {:.0} ms, median {:.0} ms of {rounds} ({:.3} ms per chunk at best)", + t[0] * 1000.0, + t[t.len() / 2] * 1000.0, + t[0] * per_chunk + ); + } + Ok(()) +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 569e7ef3c..c407a7967 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1321,22 +1321,22 @@ fn cached_region( /// Write `records` into the region files of `folder` in place, as vanilla's /// `RegionFile.write` does: each chunk takes free sectors and the header /// then points to it; the region's other chunks are not touched. `None` -/// clears a chunk. The chunks are compressed before their region is locked -/// for the writes, and each region is flushed to the disk once. +/// clears a chunk. The chunks are encoded and compressed before their region +/// is locked for the writes (`compress_records`), and each region is flushed +/// to the disk once. fn write_region_records( root: &Path, cache: &RegionCache, folder: &str, - records: Vec<((i32, i32), Option>)>, + records: &[((i32, i32), &Record)], ) -> Result<()> { let timestamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs() as u32); + let compressed = compress_records(records, timestamp); let mut by_region: BTreeMap<(i32, i32), Vec<(ChunkPos, Option)>> = BTreeMap::new(); - for ((x, z), tag) in records { - let record = tag - .map(|tag| ChunkRecord::from_nbt(&tag, Compression::Zlib, timestamp, Limits::default())) - .transpose()?; + for (&((x, z), _), record) in records.iter().zip(compressed) { + let record = record?; by_region .entry((x >> 5, z >> 5)) .or_default() @@ -1367,6 +1367,57 @@ fn write_region_records( Ok(()) } +/// Fewest chunks each helper of `compress_records` takes: below this a thread +/// costs more to start than it saves. +const CHUNKS_PER_HELPER: usize = 4; +/// Each record encoded and compressed (`None` for a deletion), in the order +/// given. Vanilla's IOWorker does this one chunk after another; here a batch +/// is shared out to scoped threads, which take the next chunk as they finish +/// one. Each chunk's bytes depend only on the chunk, and the writes stay in +/// order, so the files are the same as from one thread. At most half the +/// hardware threads help, leaving the rest to the game and its workers. +fn compress_records( + records: &[((i32, i32), &Record)], + timestamp: u32, +) -> Vec>> { + let compress = |record: &Record| { + record + .tag() + .map(|tag| ChunkRecord::from_nbt(&tag, Compression::Zlib, timestamp, Limits::default())) + .transpose() + }; + let helpers = std::thread::available_parallelism() + .map_or(1, |n| n.get().div_ceil(2)) + .min(records.len() / CHUNKS_PER_HELPER); + if helpers <= 1 { + return records.iter().map(|(_, r)| compress(r)).collect(); + } + let next = std::sync::atomic::AtomicUsize::new(0); + let mut done: Vec<(usize, std::io::Result>)> = + std::thread::scope(|scope| { + let threads: Vec<_> = (0..helpers) + .map(|_| { + scope.spawn(|| { + let mut out = Vec::new(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some((_, record)) = records.get(i) else { + return out; + }; + out.push((i, compress(record))); + } + }) + }) + .collect(); + threads + .into_iter() + .flat_map(|t| t.join().unwrap_or_else(|e| std::panic::resume_unwind(e))) + .collect() + }); + done.sort_unstable_by_key(|(i, _)| *i); + done.into_iter().map(|(_, r)| r).collect() +} + fn region_path(root: &Path, folder: &str, rx: i32, rz: i32) -> PathBuf { root.join(format!("{folder}/r.{rx}.{rz}.mca")) } @@ -1582,12 +1633,12 @@ impl SaveDir { p.get(&(entities, k.0, k.1)).is_none_or(|p| p.0 <= seq) }) }; - let records = batch + let records: Vec<_> = batch .iter() .filter(|(k, _, seq)| newest(k, *seq)) - .map(|(k, r, _)| (*k, r.tag())) + .map(|(k, r, _)| (*k, r)) .collect(); - if let Err(e) = write_region_records(&root, cache, folder, records) { + if let Err(e) = write_region_records(&root, cache, folder, &records) { log::warn!("Horizon: failed to write {folder} files: {e}"); } // Readers find the files (and a fresh region cache) from here on. @@ -2905,6 +2956,43 @@ mod tests { assert_eq!(source.block_entities[0].0, (99, 0, 99)); } + #[test] + fn records_compressed_on_helpers_match_one_thread_in_order() { + use super::{Record, compress_records}; + let records: Vec<((i32, i32), Record)> = (0..53i32) + .map(|i| { + let record = if i % 7 == 3 { + Record::Delete + } else { + let payload: Vec = (0..i * 97 % 2000).map(|v| i64::from(v * i)).collect(); + Record::Tag(Arc::new(NamedTag { + name: "".into(), + tag: Tag::compound([ + ("xPos", Tag::Int(i)), + ("Data", Tag::LongArray(payload)), + ]), + })) + }; + ((i, -i), record) + }) + .collect(); + let refs: Vec<_> = records.iter().map(|(k, r)| (*k, r)).collect(); + let compressed = compress_records(&refs, 1234); + assert_eq!(compressed.len(), records.len()); + for ((_, record), got) in records.iter().zip(compressed) { + let want = record + .tag() + .map(|t| ChunkRecord::from_nbt(&t, Compression::Zlib, 1234, Limits::default())) + .transpose() + .unwrap(); + let got = got.unwrap(); + assert_eq!( + got.as_ref().map(|r| (&r.compressed, r.timestamp)), + want.as_ref().map(|r| (&r.compressed, r.timestamp)) + ); + } + } + #[test] fn older_worlds_are_upgraded_on_opening() { let dir = std::env::temp_dir().join(format!("horizon-dv-{}", std::process::id()));