Merge pull request #607 from rdbtCVS/perf/shared-block-json-20261017

perf: reuse decoded gameplay and behaviour facts at startup
This commit is contained in:
Ludovic Marie
2026-10-17 08:16:01 +02:00
committed by GitHub
22 changed files with 3570 additions and 58 deletions
+85
View File
@@ -0,0 +1,85 @@
# Reproducing PR #607 block-facts startup profiles
These are loader-only measurements. They include `Assets::load`, `BlockFacts`, and
`Behaviours` and exclude content root preparation, graphics, input setup, first
frame, and the rest of the client startup sequence. No full-client startup gain
has been measured. The prepared `26.3` resource root must match the revision.
## Historical release builds
From the PR branch checkout, use an absolute prepared resource-root path and a
single, explicit Cargo release profile for each detached historical worktree:
```sh
PR_ROOT="$(pwd)"
BENCH_ROOT="$(mktemp -d)"
mkdir -p "$BENCH_ROOT/bin"
CARGO_TARGET_DIR="$BENCH_ROOT/target"
export CARGO_TARGET_DIR
for entry in baseline:e422bd13 a01:a01d47f2 cf:cf837118 cd:cd61e11b; do
name="${entry%%:*}"
revision="${entry#*:}"
git worktree add --detach "$BENCH_ROOT/$name" "$revision"
done
# e422bd13 predates the profiler; add the same baseline example source used
# for the benchmark, without changing any production implementation.
cp "$PR_ROOT/tools/baseline_loader_profile.rs" \
"$BENCH_ROOT/baseline/crates/horizon-client/examples/shared_json_startup_profile.rs"
for name in baseline a01 cf cd; do
(cd "$BENCH_ROOT/$name" && \
cargo build --offline --release -p horizon-client --example shared_json_startup_profile)
cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" \
"$BENCH_ROOT/bin/$name"
done
cargo build --offline --release -p horizon-client --example shared_json_startup_profile
cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" "$BENCH_ROOT/bin/current"
python3 tools/profile_shared_json.py \
--resources /absolute/path/to/.local/horizon-client/26.3 \
--baseline-binary "$BENCH_ROOT/bin/baseline" \
--a01-binary "$BENCH_ROOT/bin/a01" \
--cf-binary "$BENCH_ROOT/bin/cf" \
--cd-binary "$BENCH_ROOT/bin/cd" \
--binary "$BENCH_ROOT/bin/current" \
--repeats 10 --output "$BENCH_ROOT/five-way.json"
```
The source tree of each historical revision is exact. The baseline profiler is
an added standalone measurement example, and therefore does not alter its
historical loader logic. Comparisons use alternating forward/reverse process
order, separate processes, Linux `wait4` CPU time and peak RSS, and saved raw
samples with 25th/75th percentiles, extrema, build hashes and system load.
Keep concurrent compilation and other CPU-intensive jobs idle if possible.
`ru_maxrss` records process peak residency and cannot establish the real game's
memory usage after rendering begins. If system load rises, preserve rather than
discard outliers and report the uncertainty.
## Decoding passes and buffer lifetime
```sh
cargo build --offline --release -p horizon-client --example gameplay_decode_profile
python3 tools/profile_gameplay_decode.py \
--resources /absolute/path/to/.local/horizon-client/26.3 \
--repeats 10 --output "$BENCH_ROOT/decode.json"
python3 tools/profile_shared_json.py \
--resources /absolute/path/to/.local/horizon-client/26.3 \
--variant released="$BENCH_ROOT/bin/current"@deferred \
--variant retained="$BENCH_ROOT/bin/current"@deferred-held \
--repeats 10 --output "$BENCH_ROOT/lifetime.json"
```
The decoder profile measures the `Validate` pass and typed `Gameplay` pass
separately, including the JSON read in `total_ms`. The primary facts loader
continues both passes to preserve JSON validation, error precedence and useful
diagnostics, including overwritten fields and raw geometry. The lifetime
comparison measures current process `VmRSS` after materialisation, plus peak
RSS across the process. An explicit `drop` releases owned Rust values, but the
allocator may retain physical pages, so immediate RSS savings are not implied.
When finished, `git worktree remove` each temporary historical worktree. Do
not `git clean` or reset the active PR working tree.
+23
View File
@@ -0,0 +1,23 @@
//! Historical baseline comparator for PR #607; one normal independent loading sequence.
use horizon_client::{assets::Assets, blocks::BlockFacts};
use horizon_world::level::Behaviours;
use std::{path::Path, time::Instant};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let root = args.next().ok_or("expected prepared resource directory")?;
if args.next().as_deref() != Some("baseline") {
return Err("expected baseline".into());
}
let root = Path::new(&root);
let total = Instant::now();
let assets = Assets::load(root)?;
let started = Instant::now();
let facts = BlockFacts::load(root, assets.registry)?;
let behaviours = Behaviours::load(assets.registry, root)?;
println!("phase_ms={:.3}", started.elapsed().as_secs_f64() * 1000.0);
println!("total_ms={:.3}", total.elapsed().as_secs_f64() * 1000.0);
println!("states={}", facts.states.len());
std::hint::black_box((facts, behaviours));
Ok(())
}
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Profile the validation and typed-deserialization passes in separate processes.
Build `cargo build --release -p horizon-client --example gameplay_decode_profile`
then run this tool with the matching prepared resources. These passes are
both currently required for exact JSON error classification/precedence.
"""
import argparse
import hashlib
import json
import os
import statistics
from pathlib import Path
from profile_shared_json import percentile, run
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path,
default=Path("target/release/examples/gameplay_decode_profile"))
parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3"))
parser.add_argument("--repeats", type=int, default=8)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.repeats < 1:
parser.error("--repeats must be positive")
binary, resources = args.binary.resolve(), args.resources.resolve()
if not binary.is_file() or not resources.is_dir():
parser.error("release example or resources missing")
modes = ("validate", "typed")
samples = {mode: [] for mode in modes}
loads = [os.getloadavg()]
for i in range(args.repeats):
for mode in (modes if i % 2 == 0 else reversed(modes)):
samples[mode].append(run(binary, resources, mode))
loads.append(os.getloadavg())
result = {
"scope": "Isolated gameplay-facts.json validation/typed decoding; includes JSON file read",
"resources": str(resources),
"repeats": args.repeats,
"load_averages_before_after": loads,
"binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
"metrics": {
mode: {
key: {"median": round(statistics.median(values), 3),
"p25": round(percentile(values, .25), 3),
"p75": round(percentile(values, .75), 3),
"min": round(min(values), 3), "max": round(max(values), 3),
"samples": [round(x, 3) for x in values]}
for key in rows[0]
for values in [[row[key] for row in rows]]
}
for mode, rows in samples.items()
},
}
data = json.dumps(result, indent=2)
print(data)
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(data + "\n")
if __name__ == "__main__":
main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Profile the asset/block-facts/behaviour loading phase in release executables.
Build `shared_json_startup_profile` with the same Cargo release profile at each
revision. With --a01-binary, --cf-binary and --cd-binary, the script compares
five versions in alternated separate processes; --baseline-binary optionally
supplies a build from the original pre-PR checkout. Without historical inputs,
legacy baseline/pr607/shared/deferred same-binary comparisons are supported.
The measurement excludes full client startup, renderer and first frame.
"""
import argparse
import hashlib
import json
import os
import statistics
import subprocess
import tempfile
from pathlib import Path
def run(binary, resources, mode):
with tempfile.TemporaryFile(mode="w+t") as output:
proc = subprocess.Popen([str(binary), str(resources), mode], stdout=output,
stderr=subprocess.PIPE)
_, status, usage = os.wait4(proc.pid, 0)
proc.returncode = os.waitstatus_to_exitcode(status)
_, stderr = proc.communicate()
if proc.returncode:
raise RuntimeError(f"{binary} {mode}: {stderr.decode(errors='replace')}")
output.seek(0)
fields = dict(line.rstrip().split("=", 1) for line in output if "=" in line)
measurements = {
"phase_ms": float(fields["phase_ms"]),
"total_ms": float(fields["total_ms"]),
"cpu_ms": (usage.ru_utime + usage.ru_stime) * 1000.0,
"peak_rss_kib": usage.ru_maxrss,
}
for field in ("behaviour_json_ms", "facts_ms", "behaviours_ms", "post_rss_kib"):
if field in fields:
measurements[field] = float(fields[field])
return measurements
def percentile(values, percent):
ordered = sorted(values)
position = (len(ordered) - 1) * percent
low = int(position)
return ordered[low] + (ordered[min(low + 1, len(ordered) - 1)] - ordered[low]) * (position - low)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, default=Path("target/release/examples/shared_json_startup_profile"))
parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3"))
parser.add_argument("--repeats", type=int, default=5)
parser.add_argument("--reference-binary", type=Path, help="Legacy comparison to cf837118")
parser.add_argument("--baseline-binary", type=Path, help="Optional original main build; expects baseline mode")
parser.add_argument("--a01-binary", type=Path, help="Release executable built at a01d47f2")
parser.add_argument("--cf-binary", type=Path, help="Release executable built at cf837118")
parser.add_argument("--cd-binary", type=Path, help="Release executable built at cd61e11b")
parser.add_argument("--variant", action="append", metavar="LABEL=PATH@MODE",
help="Compare arbitrary release variants, e.g. pool=target/...@deferred")
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.repeats < 1:
parser.error("--repeats must be positive")
binary, resources = args.binary.resolve(), args.resources.resolve()
if not resources.is_dir():
parser.error("resources directory missing")
historical = any((args.a01_binary, args.cf_binary, args.cd_binary, args.baseline_binary))
if args.variant:
if historical or args.reference_binary:
parser.error("--variant cannot be mixed with historical comparison flags")
commands = {}
for specification in args.variant:
if "=" not in specification or "@" not in specification:
parser.error("--variant must be LABEL=PATH@MODE")
name, executable_mode = specification.split("=", 1)
executable, binary_mode = executable_mode.rsplit("@", 1)
if not name or not executable or not binary_mode or name in commands:
parser.error("variant names must be unique and all fields nonempty")
commands[name] = (Path(executable).resolve(), binary_mode)
elif historical:
if not all((args.a01_binary, args.cf_binary, args.cd_binary)):
parser.error("historical comparisons require --a01-binary, --cf-binary and --cd-binary")
commands = {
"baseline": ((args.baseline_binary or args.a01_binary).resolve(), "baseline"),
"a01d47f2": (args.a01_binary.resolve(), "shared"),
"cf837118": (args.cf_binary.resolve(), "deferred"),
"cd61e11b": (args.cd_binary.resolve(), "deferred"),
"current": (binary, "deferred"),
}
elif args.reference_binary:
commands = {
"baseline": (binary, "baseline"),
"pr607": (binary, "pr607"),
"cf837118": (args.reference_binary.resolve(), "deferred"),
"current": (binary, "deferred"),
}
else:
commands = {mode: (binary, mode) for mode in ("baseline", "pr607", "shared", "deferred")}
for executable, _ in commands.values():
if not executable.is_file():
parser.error(f"release executable missing: {executable}")
modes = list(commands)
samples = {mode: [] for mode in modes}
orders = []
initial_load = os.getloadavg()
for i in range(args.repeats):
order = modes if i % 2 == 0 else list(reversed(modes))
orders.append(list(order))
for mode in order:
executable, binary_mode = commands[mode]
samples[mode].append(run(executable, resources, binary_mode))
result = {
"scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame",
"resources": str(resources),
"repeats": args.repeats,
"ordering": orders,
"load_average_before": initial_load,
"load_average_after": os.getloadavg(),
"executables": {
mode: {"path": str(executable), "mode": binary_mode,
"sha256": hashlib.sha256(executable.read_bytes()).hexdigest()}
for mode, (executable, binary_mode) in commands.items()
},
"metrics": {
mode: {
key: {
"median": round(statistics.median(values), 3),
"p25": round(percentile(values, .25), 3),
"p75": round(percentile(values, .75), 3),
"min": round(min(values), 3),
"max": round(max(values), 3),
"samples": [round(value, 3) for value in values],
}
for key in rows[0]
for values in [[row[key] for row in rows]]
}
for mode, rows in samples.items()
},
}
data = json.dumps(result, indent=2)
print(data)
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(data + "\n")
if __name__ == "__main__":
main()