Merge pull request #827 from ludovic111/perf/region-in-place

🤖 Agent: merged: chunks saved in place in their region file, as vanilla (save into a full region 80.3→7.1 ms). perf-ticks-7's four PRs together on main d85a3603: clippy, 861 client + world tests, 19 harnesses (light, lan, dedicated_server, save_roundtrip, world_reopen, disk, datafix ×6, world, server_world_gen, block_entity ×4, chunk_stage) PASS.
This commit is contained in:
Ludovic Marie
2026-10-18 09:45:19 +02:00
committed by GitHub
3 changed files with 357 additions and 89 deletions
+79 -84
View File
@@ -31,7 +31,7 @@ use horizon_world::{
compression::Compression,
heightmap::{Heightmap, HeightmapChunk, HeightmapType},
nbt::{self, Compound, JavaString, Limits, NamedTag, Tag},
region::{ChunkRecord, RegionFile, RegionWriter},
region::{ChunkRecord, RegionFile},
registry::{BlockRegistry, BlockStateId},
worldgen::terrain::TerrainBlockStates,
};
@@ -1306,94 +1306,87 @@ pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
}
type RegionCache = Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>;
/// Rewrite every region file in `folder` touched by `records`, keeping its
/// other chunks. `None` deletes a chunk.
/// The region file at `path` through the cache, which readers and the writer
/// share, so a read never sees a header older than the sectors it points to.
/// `create` makes a missing file (for a write); otherwise a missing file is
/// `None`, until a write creates it.
fn cached_region(
cache: &RegionCache,
key: (i32, i32),
path: &Path,
create: bool,
) -> Result<Option<Arc<Mutex<RegionFile>>>> {
let mut regions = cache.lock().map_err(|_| "region cache poisoned")?;
if let Some(Some(region)) = regions.get(&key) {
return Ok(Some(region.clone()));
}
if !create && regions.contains_key(&key) {
return Ok(None);
}
if create && let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
// A file this process can't write (a read-only world) is still read.
let region = match RegionFile::open_writable(path, create) {
Err(e) if !create && e.kind() == std::io::ErrorKind::PermissionDenied => {
RegionFile::open(path)
}
other => other,
};
let region = match region {
Ok(r) => Some(Arc::new(Mutex::new(r))),
Err(_) if !create => None,
Err(e) => return Err(e.into()),
};
regions.insert(key, region.clone());
Ok(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.
fn write_region_records(
root: &Path,
cache: &RegionCache,
folder: &str,
records: Vec<((i32, i32), Option<Arc<NamedTag>>)>,
) -> Result<()> {
let mut by_region: BTreeMap<(i32, i32), Vec<((i32, i32), Option<Arc<NamedTag>>)>> =
BTreeMap::new();
for (key, tag) in records {
by_region
.entry((key.0 >> 5, key.1 >> 5))
.or_default()
.push((key, tag));
}
if by_region.is_empty() {
return Ok(());
}
let staging = root.join(folder).join(".staging");
fs::create_dir_all(&staging)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as u32);
let mut by_region: BTreeMap<(i32, i32), Vec<(ChunkPos, Option<ChunkRecord>)>> = BTreeMap::new();
for ((x, z), tag) in records {
let record = tag
.map(|tag| ChunkRecord::from_nbt(&tag, Compression::Zlib, timestamp, Limits::default()))
.transpose()?;
by_region
.entry((x >> 5, z >> 5))
.or_default()
.push((ChunkPos::new(x, z), record));
}
for ((rx, rz), list) in by_region {
let path = region_path(root, folder, rx, rz);
let mut records: BTreeMap<(i32, i32), ChunkRecord> = BTreeMap::new();
let only_deletes = list.iter().all(|(_, tag)| tag.is_none());
if let Ok(mut existing) = RegionFile::open(&path) {
let positions: Vec<ChunkPos> = existing.chunks().map(|(p, _)| p).collect();
if only_deletes
&& !positions
.iter()
.any(|p| list.iter().any(|(k, _)| *k == (p.x, p.z)))
{
continue;
}
for p in positions {
if let Ok(Some(r)) = existing.read(p) {
records.insert((p.x, p.z), r);
}
}
} else if only_deletes {
// Clearing chunks of a region that doesn't exist changes nothing.
let create = list.iter().any(|(_, r)| r.is_some());
let Some(region) = cached_region(cache, (rx, rz), &path, create)? else {
continue;
}
// Deleting chunks the region doesn't hold changes nothing: leave
// the file alone (unloading empty entity chunks asks for that).
};
let mut region = region.lock().map_err(|_| "region file poisoned")?;
let mut changed = false;
for (key, tag) in list {
match tag {
Some(tag) => {
for (pos, record) in &list {
match record {
Some(record) => {
region.write(*pos, record)?;
changed = true;
records.insert(
key,
ChunkRecord::from_nbt(
&tag,
Compression::Zlib,
timestamp,
Limits::default(),
)?,
);
}
None => {
changed |= records.remove(&key).is_some();
}
None => changed |= region.clear(*pos, timestamp)?,
}
}
if !changed {
continue;
if changed {
region.sync()?;
}
if records.is_empty() {
let _ = fs::remove_file(&path);
} else {
let temporary = staging.join(format!("r.{rx}.{rz}.mca"));
let _ = fs::remove_file(&temporary);
let mut writer = RegionWriter::create(&temporary)?;
for ((x, z), r) in &records {
writer.write(ChunkPos::new(*x, *z), r)?;
}
writer.finish()?;
fs::rename(&temporary, &path)?;
}
cache
.lock()
.map_err(|_| "region cache poisoned")?
.remove(&(rx, rz));
}
let _ = fs::remove_dir(&staging);
Ok(())
}
@@ -1436,7 +1429,7 @@ impl Record {
type PendingWrites = Mutex<HashMap<(bool, i32, i32), (u64, Record)>>;
type WriteBatch = (bool, Vec<((i32, i32), Record, u64)>);
/// The background thread that encodes chunks and rewrites region files, in
/// The background thread that encodes chunks and writes them into the region files, in
/// submission order.
struct Writer {
send: mpsc::Sender<WriteBatch>,
@@ -1498,17 +1491,8 @@ impl SaveDir {
} else {
&self.entity_regions
};
let region = {
let mut regions = cache.lock().ok()?;
regions
.entry(key)
.or_insert_with(|| {
RegionFile::open(self.region_path(folder, key.0, key.1))
.ok()
.map(|r| Arc::new(Mutex::new(r)))
})
.clone()?
};
let path = self.region_path(folder, key.0, key.1);
let region = cached_region(cache, key, &path, false).ok()??;
let record = region.lock().ok()?.read(ChunkPos::new(x, z)).ok()??;
record.nbt(Limits::default()).ok()
}
@@ -1614,7 +1598,18 @@ impl SaveDir {
} else {
("region", &regions)
};
let records = batch.iter().map(|(k, r, _)| (*k, r.tag())).collect();
// IOWorker.pendingWrites: a chunk queued again since is
// written once, by its newest batch.
let newest = |k: &(i32, i32), seq: u64| {
pending.lock().map_or(true, |p| {
p.get(&(entities, k.0, k.1)).is_none_or(|p| p.0 <= seq)
})
};
let records = batch
.iter()
.filter(|(k, _, seq)| newest(k, *seq))
.map(|(k, r, _)| (*k, r.tag()))
.collect();
if let Err(e) = write_region_records(&root, cache, folder, records) {
log::warn!("Horizon: failed to write {folder} files: {e}");
}
@@ -1650,7 +1645,7 @@ impl SaveDir {
};
}
}
/// Rewrite every region touched by `chunks`, keeping their other chunks.
/// Write `chunks` into their region files and wait until they are on disk.
pub fn save(
&self,
chunks: &[Arc<Chunk>],
+160 -5
View File
@@ -1,5 +1,7 @@
//! Anvil region reading and export to a new region. Existing files are never
//! overwritten. Use a separate directory for offline edits and copied .mcc data.
//! Anvil region reading, export to a new region, and in-place chunk writes
//! as vanilla's `RegionFile` makes them (a file opened with `open_writable`).
//! Exports never overwrite a file: use a separate directory for offline
//! edits and copied .mcc data.
use crate::{
compression::{Compression, invalid},
nbt::{self, Limits, NamedTag},
@@ -54,6 +56,9 @@ pub struct RegionFile {
position: ChunkPos,
offsets: [u32; 1024],
timestamps: [u32; 1024],
/// The sectors in use (`RegionBitmap`): the header's two and every
/// chunk's.
used: Vec<bool>,
}
pub fn position_from_path(path: &Path) -> io::Result<ChunkPos> {
@@ -94,6 +99,12 @@ fn position(region: ChunkPos, index: usize) -> ChunkPos {
fn external_path(directory: &Path, chunk: ChunkPos) -> PathBuf {
directory.join(format!("c.{}.{}.mcc", chunk.x, chunk.z))
}
fn remove_if_exists(path: &Path) -> io::Result<()> {
match fs::remove_file(path) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
impl RegionFile {
pub fn position(&self) -> ChunkPos {
@@ -101,8 +112,25 @@ impl RegionFile {
}
pub fn open(path: impl AsRef<Path>) -> io::Result<Self> {
let path = path.as_ref().to_owned();
let file = File::open(&path)?;
Self::from_file(path, file)
}
/// Open for reading and in-place writes (`write`, `clear`), creating an
/// empty region with `create`.
pub fn open_writable(path: impl AsRef<Path>, create: bool) -> io::Result<Self> {
let path = path.as_ref().to_owned();
let file = OpenOptions::new()
.read(true)
.write(true)
.create(create)
.truncate(false)
.open(&path)?;
Self::from_file(path, file)
}
fn from_file(path: PathBuf, mut file: File) -> io::Result<Self> {
let position = position_from_path(&path)?;
let mut file = File::open(&path)?;
let len = file.metadata()?.len();
// RegionFile's constructor: a short header (an empty or truncated file)
// reads as far as it goes, the rest stays zero (no chunks).
@@ -134,13 +162,140 @@ impl RegionFile {
offsets[i] = 0;
}
}
Ok(Self {
let mut region = Self {
file,
path,
position,
offsets,
timestamps,
})
used: Vec::new(),
};
region.force(0, 2);
for offset in offsets.into_iter().filter(|&o| o != 0) {
region.force((offset >> 8) as usize, (offset & 255) as usize);
}
Ok(region)
}
/// `RegionBitmap.force`.
fn force(&mut self, start: usize, count: usize) {
if self.used.len() < start + count {
self.used.resize(start + count, false);
}
self.used[start..start + count].fill(true);
}
/// `RegionBitmap.free`.
fn free(&mut self, start: usize, count: usize) {
let end = (start + count).min(self.used.len());
if start < end {
self.used[start..end].fill(false);
}
}
/// `RegionBitmap.allocate`: the first run of free sectors long enough
/// (the end of the file is free).
fn allocate(&mut self, count: usize) -> usize {
let mut current = 0;
loop {
let start = (current..self.used.len())
.find(|&s| !self.used[s])
.unwrap_or(self.used.len());
let end = (start..self.used.len()).find(|&s| self.used[s]);
if end.is_none_or(|end| end - start >= count) {
self.force(start, count);
return start;
}
current = end.unwrap_or(start);
}
}
/// `RegionFile.write`: the chunk goes to the first free run of sectors
/// that holds it (an oversized one, 256 sectors or more, to its external
/// `c.X.Z.mcc` file with a one-sector stub), the header points to it,
/// and only then are its old sectors freed. The other chunks stay where
/// they are. A chunk's last sector is padded with zeros.
pub fn write(&mut self, chunk: ChunkPos, record: &ChunkRecord) -> io::Result<()> {
let i = slot(self.position, chunk)?;
if record.compressed.len() > MAX_COMPRESSED {
return Err(invalid("compressed chunk limit exceeded"));
}
let required = (record.compressed.len() + 5).div_ceil(SECTOR);
let external = required >= 256;
let sectors = if external { 1 } else { required };
let start = self.allocate(sectors);
if start + sectors > 0x100_0000 {
self.free(start, sectors);
return Err(invalid("region sector address limit exceeded"));
}
let directory = self.path.parent().unwrap_or(Path::new(".")).to_owned();
let external_file = external_path(&directory, chunk);
let mut data = Vec::with_capacity(sectors * SECTOR);
if external {
let temporary = directory.join(format!(".c.{}.{}.mcc.tmp", chunk.x, chunk.z));
let written = File::create(&temporary)
.and_then(|mut f| f.write_all(&record.compressed))
.and_then(|_| fs::rename(&temporary, &external_file));
if let Err(e) = written {
let _ = fs::remove_file(&temporary);
self.free(start, sectors);
return Err(e);
}
data.extend_from_slice(&1u32.to_be_bytes());
data.push(record.compression as u8 | 128);
} else {
data.extend_from_slice(&(record.compressed.len() as u32 + 1).to_be_bytes());
data.push(record.compression as u8);
data.extend_from_slice(&record.compressed);
}
data.resize(sectors * SECTOR, 0);
let written = self
.file
.seek(SeekFrom::Start((start * SECTOR) as u64))
.and_then(|_| self.file.write_all(&data));
if let Err(e) = written {
self.free(start, sectors);
return Err(e);
}
let old = self.offsets[i];
self.offsets[i] = (start as u32) << 8 | sectors as u32;
self.timestamps[i] = record.timestamp;
self.write_header_entry(i)?;
if !external {
remove_if_exists(&external_file)?;
}
if old != 0 {
self.free((old >> 8) as usize, (old & 255) as usize);
}
Ok(())
}
/// `RegionFile.clear`: the chunk is gone; `timestamp` marks when.
/// Returns whether the region held it.
pub fn clear(&mut self, chunk: ChunkPos, timestamp: u32) -> io::Result<bool> {
let i = slot(self.position, chunk)?;
let old = self.offsets[i];
if old == 0 {
return Ok(false);
}
self.offsets[i] = 0;
self.timestamps[i] = timestamp;
self.write_header_entry(i)?;
let directory = self.path.parent().unwrap_or(Path::new("."));
remove_if_exists(&external_path(directory, chunk))?;
self.free((old >> 8) as usize, (old & 255) as usize);
Ok(true)
}
/// Flush the writes to the disk.
pub fn sync(&self) -> io::Result<()> {
self.file.sync_data()
}
/// The header's offset and timestamp of slot `i`.
fn write_header_entry(&mut self, i: usize) -> io::Result<()> {
self.file.seek(SeekFrom::Start((i * 4) as u64))?;
self.file.write_all(&self.offsets[i].to_be_bytes())?;
self.file.seek(SeekFrom::Start((SECTOR + i * 4) as u64))?;
self.file.write_all(&self.timestamps[i].to_be_bytes())
}
pub fn chunks(&self) -> impl Iterator<Item = (ChunkPos, u32)> + '_ {
+118
View File
@@ -74,6 +74,70 @@ fn external_threshold_negative_coordinates_and_timestamps_roundtrip() {
assert!(reader.read(ChunkPos::new(0, 0)).is_err());
}
#[test]
fn in_place_writes_reuse_freed_sectors_and_keep_other_chunks() {
let dir = Directory::new();
let (a, b, c) = (
ChunkPos::new(-32, 0),
ChunkPos::new(-31, 0),
ChunkPos::new(-1, 31),
);
let mut region = RegionFile::open_writable(dir.region(), true).unwrap();
// RegionBitmap: a at sectors 2..4, b at 4.
region.write(a, &record(2 * 4096 - 5)).unwrap();
region.write(b, &record(100)).unwrap();
let sectors = |path: &Path| fs::metadata(path).unwrap().len() / 4096;
assert_eq!(sectors(&dir.region()), 5);
// a grows: it moves past b, and its two old sectors are free again.
region.write(a, &record(3 * 4096 - 5)).unwrap();
assert_eq!(sectors(&dir.region()), 8);
// c fits in a's old sectors; then an oversized c goes to its .mcc file
// (a one-sector stub, at the end: sector 8) and back inline (sector 2).
region.write(c, &record(2 * 4096 - 5)).unwrap();
assert_eq!(sectors(&dir.region()), 8);
region.write(c, &record(256 * 4096)).unwrap();
assert!(dir.0.join("c.-1.31.mcc").exists());
region.write(c, &record(10)).unwrap();
assert!(!dir.0.join("c.-1.31.mcc").exists());
assert!(region.clear(b, 7).unwrap());
assert!(!region.clear(b, 7).unwrap());
region.sync().unwrap();
drop(region);
let mut reader = RegionFile::open(dir.region()).unwrap();
assert_eq!(reader.chunks().map(|(p, _)| p).collect::<Vec<_>>(), [a, c]);
assert_eq!(
reader.read(a).unwrap().unwrap().compressed,
record(3 * 4096 - 5).compressed
);
assert_eq!(
reader.read(c).unwrap().unwrap().compressed,
record(10).compressed
);
assert!(reader.read(b).unwrap().is_none());
// Reopened, the bitmap holds the chunks' sectors: new chunks take the
// first free runs (sectors 3 and 4), not theirs.
let mut region = RegionFile::open_writable(dir.region(), false).unwrap();
region.write(b, &record(4096 - 5)).unwrap();
region
.write(ChunkPos::new(-30, 0), &record(4096 - 5))
.unwrap();
drop(region);
let mut reader = RegionFile::open(dir.region()).unwrap();
assert_eq!(
reader.read(a).unwrap().unwrap().compressed,
record(3 * 4096 - 5).compressed
);
assert_eq!(
reader.read(c).unwrap().unwrap().compressed,
record(10).compressed
);
assert_eq!(
reader.read(b).unwrap().unwrap().compressed,
record(4096 - 5).compressed
);
assert_eq!(sectors(&dir.region()), 9);
}
#[test]
fn failed_writer_cannot_commit_and_removes_its_own_external_files() {
let dir = Directory::new();
@@ -206,3 +270,57 @@ fn chunk_storage_edit_preserves_unknown_fields_and_other_blocks() {
let record = ChunkRecord::from_nbt(&root, Compression::Lz4, 17, Limits::default()).unwrap();
assert_eq!(record.nbt(Limits::default()).unwrap(), root);
}
/// Saving one chunk into a full region: the whole file rewritten (every
/// chunk read and written again, then the new file published), against
/// vanilla's in-place write. Run with --ignored --nocapture.
#[test]
#[ignore = "microbenchmark; run with --ignored --nocapture"]
fn benchmark_saving_into_a_full_region() {
let dir = Directory::new();
let chunks: Vec<ChunkPos> = (0..1024)
.map(|i| ChunkPos::new(-32 + i % 32, i / 32))
.collect();
// About what a compressed overworld chunk weighs: two sectors.
let saved = record(6000);
let mut region = RegionFile::open_writable(dir.region(), true).unwrap();
for &c in &chunks {
region.write(c, &saved).unwrap();
}
region.sync().unwrap();
drop(region);
let rounds = 100;
let start = std::time::Instant::now();
for round in 0..rounds {
let changed = chunks[round * 7 % 1024];
let mut existing = RegionFile::open(dir.region()).unwrap();
let mut records = Vec::new();
for (p, _) in existing.chunks().collect::<Vec<_>>() {
let r = if p == changed {
saved.clone()
} else {
existing.read(p).unwrap().unwrap()
};
records.push((p, r));
}
let staging = dir.0.join("staging");
fs::create_dir_all(&staging).unwrap();
let temporary = staging.join("r.-1.0.mca");
let _ = fs::remove_file(&temporary);
let mut writer = RegionWriter::create(&temporary).unwrap();
for (p, r) in &records {
writer.write(*p, r).unwrap();
}
writer.finish().unwrap();
fs::rename(&temporary, dir.region()).unwrap();
}
let rewrite = start.elapsed() / rounds as u32;
let mut region = RegionFile::open_writable(dir.region(), false).unwrap();
let start = std::time::Instant::now();
for round in 0..rounds {
region.write(chunks[round * 7 % 1024], &saved).unwrap();
region.sync().unwrap();
}
let in_place = start.elapsed() / rounds as u32;
println!("one chunk into a full region: rewrite {rewrite:?}, in place {in_place:?}");
}