Merge pull request #680 from ludovic111/perf/mod-content-memory

🤖 Agent: merged by Ludovic's AI agent. Parity 291/291 on the head; combined with main locally: workspace clippy clean, client/world tests pass, mob_ai/save_roundtrip/spawner PASS. ATM10 registry 249 → 125 MB, vanilla 46 → 24 MB.
This commit is contained in:
Ludovic Marie
2026-10-17 19:41:47 +02:00
committed by GitHub
4 changed files with 269 additions and 14 deletions
@@ -0,0 +1,165 @@
//! Resident memory of each resource loader, in the game's start order: what a
//! larger registry (content mods, docs/modpacks.md) costs, loader by loader.
//!
//! resource_memory RESOURCES
//!
//! RESOURCES is a prepared root or a content-mod root (`.horizon-cache/mod-content`).
//! Prints, after each step, the live heap (a counting allocator: what the
//! step keeps), the heap's peak during the step (what it parsed on the way)
//! and the process RSS (what the allocator holds on to). On macOS it ends
//! with `footprint`'s physical footprint, the number the OS charges: RSS also
//! counts freed pages the allocator marked reusable.
use horizon_client::{
assets::Assets, biome::Biomes, blocks::BlockFacts, collisions, crafting::Recipes, items::Items,
light::LightTables, mesher::MeshTables, models, motion::MotionResources,
vanillagen::VanillaTerrain,
};
use std::{
alloc::{GlobalAlloc, Layout, System},
sync::atomic::{AtomicUsize, Ordering::Relaxed},
};
use std::{path::PathBuf, process::Command};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
struct Counting;
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
// SAFETY: forwards to the system allocator, only counting sizes.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let p = unsafe { System.alloc(layout) };
if !p.is_null() {
let now = LIVE.fetch_add(layout.size(), Relaxed) + layout.size();
PEAK.fetch_max(now, Relaxed);
}
p
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) };
LIVE.fetch_sub(layout.size(), Relaxed);
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new: usize) -> *mut u8 {
let p = unsafe { System.realloc(ptr, layout, new) };
if !p.is_null() {
if new >= layout.size() {
let now = LIVE.fetch_add(new - layout.size(), Relaxed) + new - layout.size();
PEAK.fetch_max(now, Relaxed);
} else {
LIVE.fetch_sub(layout.size() - new, Relaxed);
}
}
p
}
}
#[global_allocator]
static ALLOC: Counting = Counting;
const MB: f64 = 1048576.0;
fn rss_mb() -> f64 {
let out = Command::new("ps")
.args(["-o", "rss=", "-p", &std::process::id().to_string()])
.output()
.ok();
out.and_then(|o| String::from_utf8(o.stdout).ok())
.and_then(|s| s.trim().parse::<f64>().ok())
.map_or(0.0, |kb| kb / 1024.0)
}
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.ok_or("usage: resource_memory RESOURCES")?,
);
println!(
"{:<24} {:>8} {:>8} {:>10} {:>8}",
"step", "live MB", "+live", "step peak", "RSS MB"
);
let mut last = 0usize;
let mut step = |name: &str| {
let live = LIVE.load(Relaxed);
let peak = PEAK.swap(live, Relaxed);
println!(
"{name:<24} {:>8.0} {:>+8.0} {:>10.0} {:>8.0}",
live as f64 / MB,
(live as f64 - last as f64) / MB,
peak as f64 / MB,
rss_mb()
);
last = live;
};
step("start");
let registry = horizon_world::level::data::load_registry(&root)?;
step("registry alone");
drop(registry);
step("registry dropped");
let assets = Assets::load(&root)?;
step("assets");
println!(
" sprites: {} layers of {}px, {:.0} MB of pixels",
assets.texture_layers,
assets.sprite_size,
assets.pixels.len() as f64 / MB
);
// The game decodes gameplay facts once for both tables (BlockFacts::load_pair).
let (facts, behaviours) = BlockFacts::load_pair(&root, assets.registry)?;
step("block facts+behaviours");
let items = Items::load(&root, assets.registry, &facts)?;
step("items");
let recipes = Recipes::load(&root, &items)?;
step("recipes");
let biomes = Biomes::load(&root)?;
step("biomes");
let light = LightTables::load(&root, assets.registry, &facts)?;
step("light tables");
let tables = MeshTables::new(
&assets,
&facts,
models::load_visibility(&root, assets.registry)?,
)?;
step("mesh tables");
let collision = collisions::load(&root, assets.registry)?;
step("collision");
let motion = MotionResources::load(&root, &assets)?;
step("motion");
for name in [
"worldgen/blocks/block-properties.nbt",
"worldgen/blocks/cached-collision.nbt",
"worldgen/blocks/cached-support.nbt",
"cached-collision.nbt",
"occlusion.nbt",
"movement-properties.nbt",
] {
let bytes = std::fs::read(root.join(name))?;
let tree = horizon_world::nbt::read_named(&bytes, horizon_world::nbt::Limits::tables())?;
step(&format!(" tree of {name}"));
drop((tree, bytes));
step(" dropped");
}
let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, 1234)?;
step("worldgen");
println!(
"{} block states; live {:.0} MB, RSS {:.0} MB",
facts.states.len(),
LIVE.load(Relaxed) as f64 / MB,
rss_mb()
);
if let Ok(out) = Command::new("footprint")
.arg(std::process::id().to_string())
.output()
{
let text = String::from_utf8_lossy(&out.stdout);
for line in text
.lines()
.filter(|l| l.contains("Footprint") || l.contains("phys_footprint"))
{
println!(" {}", line.trim());
}
}
// Keep everything alive until the end.
drop((
terrain, behaviours, motion, collision, tables, light, biomes, recipes, items, facts,
assets,
));
Ok(())
}
+36 -9
View File
@@ -5,7 +5,8 @@ use crate::{DATA_VERSION, chunk::BlockState, compression::invalid, nbt::Tag};
pub use json::BlockStateJsonCodec;
pub(crate) use json::java_integer;
use std::{
collections::{BTreeMap, BTreeSet},
collections::{BTreeMap, BTreeSet, HashMap},
hash::{DefaultHasher, Hash, Hasher},
io,
};
@@ -14,9 +15,25 @@ pub struct BlockStateId(pub u32);
pub struct BlockRegistry {
states: Vec<BlockState>,
ids: BTreeMap<BlockState, BlockStateId>,
/// Ids by a hash of their state, checked against `states`: 12 bytes per
/// state instead of a second copy of every name and property map (about
/// 125 MB for a registry of 190,000 states).
ids: HashMap<u64, u32>,
/// States whose hash an earlier state already took (none in vanilla).
collided: BTreeMap<BlockState, BlockStateId>,
defaults: BTreeMap<String, BlockStateId>,
}
/// The hash [`BlockRegistry`] indexes states by (fixed keys: the same in
/// every process).
fn state_key(state: &BlockState) -> u64 {
let mut hasher = DefaultHasher::new();
state.name.hash(&mut hasher);
for (key, value) in &state.properties {
key.hash(&mut hasher);
value.hash(&mut hasher);
}
hasher.finish()
}
impl BlockRegistry {
pub fn from_nbt(tag: &Tag) -> io::Result<Self> {
if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) {
@@ -33,18 +50,25 @@ impl BlockRegistry {
}
let mut result = Self {
states: Vec::with_capacity(entries.len()),
ids: BTreeMap::new(),
ids: HashMap::with_capacity(entries.len()),
collided: BTreeMap::new(),
defaults: BTreeMap::new(),
};
for (i, entry) in entries.iter().enumerate() {
let state = BlockState::from_nbt(entry)?;
if result
.ids
.insert(state.clone(), BlockStateId(i as u32))
.is_some()
{
if result.id(&state).is_some() {
return Err(invalid("duplicate block registry state"));
}
match result.ids.entry(state_key(&state)) {
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(i as u32);
}
std::collections::hash_map::Entry::Occupied(_) => {
result
.collided
.insert(state.clone(), BlockStateId(i as u32));
}
}
result.states.push(state);
}
for (name, id) in defaults {
@@ -82,7 +106,10 @@ impl BlockRegistry {
self.states.get(id.0 as usize)
}
pub fn id(&self, state: &BlockState) -> Option<BlockStateId> {
self.ids.get(state).copied()
match self.ids.get(&state_key(state)) {
Some(&id) if self.states[id as usize] == *state => Some(BlockStateId(id)),
_ => self.collided.get(state).copied(),
}
}
pub fn default_state(&self, name: &str) -> Option<BlockStateId> {
self.defaults.get(name).copied()
+37
View File
@@ -586,6 +586,43 @@ the display's 144 Hz at 8 chunks; Horizon's title time includes building the con
a first start (about 5 s, cached afterwards); and the pack runs 1.21.1 against Horizon's 26.3.
A quiet rerun with more games is the next measurement.
**Where the RAM goes (2026-10-17).** RSS overstates it on macOS. `ps` counts pages the allocator
freed and marked reusable, and the content tables free a lot at load. `perf_bench.py` now also
samples the physical footprint (`footprint`, what the OS charges the process). The machine was
shared and very busy (load average 90-138 on 14 threads). RD 8, the same six mods, one or two
games per row:
| game | RSS steady MB | footprint steady MB |
|---|---:|---:|
| Horizon | 1,598-1,636 | 1,277-1,295 |
| Horizon + 6 mods | 2,996-3,052 | 1,736-1,869 |
So the six mods cost about 0.5 GB of footprint, not 1.1-1.4 GB. ATM10's 42 mods (193,762
states) take the game to 7.7 GB RSS but 3.9 GB footprint. The rest is startup garbage the
allocator keeps.
`crates/horizon-client/examples/resource_memory.rs` breaks it down per loader: the live heap
(a counting allocator), each step's peak, RSS and the footprint. Live heap after every loader,
vanilla against ATM10's 42 mods:
| loader | vanilla MB | ATM10 42 mods MB |
|---|---:|---:|
| block registry | 24 | 125 |
| assets (registry, models, sprites: 153 MB of pixels for 9,790 layers) | 94 | 657 |
| block facts and behaviours | +29 | +75 |
| items, recipes | +14 | +82 |
| light, mesh, collision, motion | +24 | +53 |
| worldgen | +79 | +182 |
| **live** / **footprint** | **240 / 551** | **1,049 / 2,724** |
The block registry kept a second copy of every state as the key of its id map; it now
indexes ids by a hash checked against the states: -22 MB live for vanilla, -124 MB for
ATM10's, -30 MB and -140 MB of footprint. The startup peaks are what is left. Each step parses
its per-state tables whole: as JSON trees, or as NBT trees of 300-600 MB each for ATM10
(`block-properties.nbt`, the collision, support, occlusion and movement tables). The peak
reaches 3.9 GB during worldgen loading, and the footprint stays near the peak. Typed, streaming
readers for those tables are the next cut.
## The working version for 2026-10-23
In scope (each is a PR or a small stack):
+31 -5
View File
@@ -44,6 +44,7 @@ import json
import math
import os
import platform
import re
import shutil
import socket
import statistics
@@ -185,19 +186,35 @@ def summary(values):
return {"n": n, "mean": rnd(mean), "stdev": sd, "min": rnd(min(values)), "max": rnd(max(values)), "ci95": ci}
def phys_footprint(pid):
"""macOS: the bytes the kernel charges the process (`footprint`), without
the freed pages the allocator marked reusable, which `ps` still counts as
resident until memory runs short. None elsewhere."""
if sys.platform != "darwin":
return None
out = subprocess.run(["footprint", "-f", "bytes", str(pid)], capture_output=True, text=True)
m = re.search(r"phys_footprint:\s*(\d+)", out.stdout)
return int(m.group(1)) if m else None
class Sampler(threading.Thread):
"""Samples a process's resident memory every quarter second (ps, so the
same reading for every game and OS)."""
same reading for every game and OS) and, on macOS, its physical footprint
every two seconds."""
def __init__(self, pid):
super().__init__(daemon=True)
self.pid, self.samples, self.stop = pid, [], threading.Event()
self.pid, self.samples, self.footprints, self.stop = pid, [], [], threading.Event()
def run(self):
tick = 0
while not self.stop.is_set():
out = subprocess.run(["ps", "-o", "rss=", "-p", str(self.pid)], capture_output=True, text=True)
if out.stdout.strip():
self.samples.append((time.time(), int(out.stdout.split()[0]) * 1024))
if tick % 8 == 0 and (fp := phys_footprint(self.pid)) is not None:
self.footprints.append((time.time(), fp))
tick += 1
self.stop.wait(0.25)
def summary(self, windows):
@@ -205,11 +222,16 @@ class Sampler(threading.Thread):
if not self.samples:
return {}
during = [rss for t, rss in self.samples if any(a <= t <= b for a, b in windows)]
return {
out = {
"rss_peak_mb": max(rss for _, rss in self.samples) / 2**20,
"rss_steady_mb": statistics.median(during) / 2**20 if during else None,
"rss_samples": len(self.samples),
}
if self.footprints:
steady = [fp for t, fp in self.footprints if any(a <= t <= b for a, b in windows)]
out["footprint_peak_mb"] = max(fp for _, fp in self.footprints) / 2**20
out["footprint_steady_mb"] = statistics.median(steady) / 2**20 if steady else None
return out
def nvidia_memory_mb(pid):
@@ -685,6 +707,8 @@ def report(args, distance, runs, app):
metric(f"memory.{name}.gpu_mb", [s.get("gpu_mb") for s in scenes])
metric("memory.rss_peak_mb", [r["memory"].get("rss_peak_mb") for r in runs])
metric("memory.rss_steady_mb", [r["memory"].get("rss_steady_mb") for r in runs])
metric("memory.footprint_peak_mb", [r["memory"].get("footprint_peak_mb") for r in runs])
metric("memory.footprint_steady_mb", [r["memory"].get("footprint_steady_mb") for r in runs])
return {"format": REPORT_FORMAT, "version": REPORT_VERSION, "kind": "game",
"created": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"app": app, "hardware": hw, "conditions": conditions, "metrics": metrics, "frames": entries,
@@ -711,7 +735,7 @@ def table(labels):
cells.append(" / ".join(cell(m.get(f"fps.{scene}.{k}")) for k in ("avg_fps", "low_1pct_fps", "low_01pct_fps")))
print(f"| {d} | {scene} | " + " | ".join(cells) + " |")
print()
print("| RD | " + " | ".join(f"{l}: title / world s, mean scene load s, RSS steady / peak MB, load avg" for l in labels) + " |")
print("| RD | " + " | ".join(f"{l}: title / world s, mean scene load s, RSS steady / peak MB, footprint steady / peak MB, load avg" for l in labels) + " |")
print("| --- |" + " --- |" * len(labels))
for d in distances:
cells = []
@@ -726,7 +750,9 @@ def table(labels):
mb = lambda k: f"{m[k]['mean']:.0f}" if k in m else "–"
cells.append(f"{sec('startup.title_ms')} / {sec('startup.world_ms')}, "
f"{statistics.mean(loads) / 1000 if loads else 0:.1f}, "
f"{mb('memory.rss_steady_mb')} / {mb('memory.rss_peak_mb')}, {r['conditions'].get('load_avg_1m')}")
f"{mb('memory.rss_steady_mb')} / {mb('memory.rss_peak_mb')}, "
f"{mb('memory.footprint_steady_mb')} / {mb('memory.footprint_peak_mb')}, "
f"{r['conditions'].get('load_avg_1m')}")
print(f"| {d} | " + " | ".join(cells) + " |")