diff --git a/benchmarks/borrowed-import/README.md b/benchmarks/borrowed-import/README.md new file mode 100644 index 000000000..77d3d6b6a --- /dev/null +++ b/benchmarks/borrowed-import/README.md @@ -0,0 +1,67 @@ +# Borrowing the input during host-value import + +On M4 Rust 1.99.1, borrowing the input reduced point import from 71.7 to 59.6 µs portable and from 70.4 to 59.4 µs SIMD. Import of the larger packet took 19.5–20.8% less time. Both complete script calls beat their pre-compaction binaries. + +The input to `CallContext::import` stays alive while the iterative importer builds its result. Previously each frame held an owning reference to its source container, and fetching a child cloned its `Value` before opening the next frame. Borrowing both from the root removes 2,001 temporary Arc increment/decrement pairs when importing 500 point records. The 1,001 frame sources account for one pair each, and fetching the 1,000 non-root containers accounts for the rest. The output containers still own their contents. Buffer reservation, depth checks, key sharing and every metering operation follow the same path. + +## Measurements + +Median microseconds per call, before → after. Percentages are median paired changes, computed as 100 × (head/base − 1) at each launch position. + +| Host | Rust | Scanner | Point import | Point full call | Packet import | Packet full call | +| --- | --- | --- | ---: | ---: | ---: | ---: | +| M4 | 1.98.1 | portable | 71.8 → 56.9 (-21.0%) | 84.8 → 76.1 (-9.9%) | 741.6 → 579.6 (-21.5%) | 1,942.1 → 1,783.9 (-8.4%) | +| M4 | 1.98.1 | SIMD | 70.5 → 56.5 (-19.8%) | 87.1 → 75.7 (-12.8%) | 736.4 → 584.1 (-20.0%) | 1,922.2 → 1,762.1 (-8.4%) | +| M4 | 1.99.1 | portable | 71.7 → 59.6 (-16.2%) | 89.0 → 78.4 (-11.9%) | 739.8 → 595.3 (-19.5%) | 1,937.8 → 1,796.2 (-7.3%) | +| M4 | 1.99.1 | SIMD | 70.4 → 59.4 (-15.6%) | 88.4 → 78.9 (-11.2%) | 750.6 → 594.1 (-20.8%) | 1,929.1 → 1,772.9 (-8.2%) | +| Shannon | 1.98.1 | portable | 112.9 → 90.8 (-19.5%) | 141.6 → 120.8 (-14.5%) | 1,388.0 → 1,100.4 (-20.8%) | 2,602.4 → 2,320.1 (-10.8%) | +| Shannon | 1.98.1 | SIMD | 112.9 → 90.7 (-19.9%) | 141.2 → 120.1 (-15.1%) | 1,386.1 → 1,094.1 (-21.0%) | 2,600.0 → 2,315.4 (-11.0%) | +| Shannon | 1.99.1 | portable | 113.1 → 91.8 (-18.9%) | 142.7 → 123.2 (-13.8%) | 1,374.7 → 1,097.3 (-20.1%) | 2,593.7 → 2,364.0 (-8.8%) | +| Shannon | 1.99.1 | SIMD | 113.3 → 91.7 (-19.1%) | 142.7 → 123.0 (-13.6%) | 1,378.6 → 1,090.0 (-20.9%) | 2,599.9 → 2,362.3 (-9.1%) | + +Same-binary changes ranged from -0.8% to +1.0% across these cells. In the same stock sweep on M4 with Rust 1.99.1, point calls also beat the pre-compaction binary by 6.4% portable and 6.2% SIMD. The packet call beat it by about 5% and 6%, respectively. + +## Inside import + +The Rust 1.99.1 M4 portable probe timed construction at each frame finish. Times below are median microseconds per call. The remainder subtracts finish time from import time within each sample before taking the median. + +| Revision | Point import | Finish | Remainder | Packet import | Finish | Remainder | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Before compaction | 90.1 | 32.4 | 57.6 | 808.6 | 165.8 | 642.2 | +| Compact headers | 95.6 | 31.7 | 63.9 | 861.5 | 159.3 | 700.4 | +| Current base | 95.5 | 31.9 | 63.7 | 854.1 | 159.4 | 692.3 | +| Borrowed input | 84.0 | 30.7 | 53.4 | 718.2 | 156.2 | 561.7 | + +In the historical point regression, finishing containers got 0.7 µs faster while the rest of the traversal took 6.3 µs longer. The packet showed the same pattern. Borrowing the input recovered 10.3 µs of non-finish time on points and 130.6 µs on packets relative to the current base. The extra clocks affect absolute times. These intervals locate the loss outside final construction, but leave its exact microarchitectural cause open. + +The allocator and stack controls used the same interposer in every arm. Bumping both sizes maps 80- and 88-byte requests to the former 112- and 128-byte allocator classes. The pad is 192 bytes at source. Disassembly of both historical binaries showed the caller frame growing from 208 to 384 bytes. The table gives median positional import times in microseconds, with per-finish clocks off. + +| Fixture | Before | Compact | Compact with both sizes bumped | Before, padded | Compact, padded | +| --- | ---: | ---: | ---: | ---: | ---: | +| Point | 71.5 | 76.5 | 76.9 | 71.4 | 77.1 | +| Packet | 784.3 | 809.6 | 811.7 | 784.8 | 807.4 | + +Changing either the caller frame or the allocation sizes left the historical import gap in place for both witnesses. + +## Values and accounting + +The point call returned 500 in 5,011 steps and peaked at 124,936 bytes, with zero retained. The packet produced the exact expected string in 259,605 steps and peaked at 1,632,776 bytes, with 262,256 retained. Both builds made exactly 501 requests of 80 bytes and 500 of 88 bytes per point call. Packet calls made 1,613 and 3,226 respectively. The allocation audit subtracted 32 from 33 timed calls after the same 32 warmups on M4 Rust 1.99.1 portable. + +Both scanner modes passed all eight golden corpora. Relative to the starting revision, all 233,906 engine observations had identical step, peak and retained counts. Four replay values differed across runs, all marked varying in the existing corpus. The checked-in counter tables already differ from the starting revision on other cases. + +## Replay + +The point fixture passes an array of 500 hashes containing two-integer arrays to a script that returns the array length. The packet fixture passes a typed hash containing 1,612 nested records to `JSON.stringify`. For the construction trace only, the same typed packet goes to a script returning an empty string. This removes the extra container import performed by the builtin call. The diagnostic requires exactly one positional import and 1,001 or 4,838 finishes per traced call. + +Each executable runs through the same symlink. Every launch position shuffles binary and scanner order, and uses the same environment padding for each pair. The point fixture runs 96 calls after 32 warmups. The packet runs 12 after 12 warmups. Every launch checks the digest, encoded size and counters, and the first position checks the full decoded result against the fixture. Same-binary repeats use the base executable. The stock timings include the entire script call. Coarse diagnostic builds clock the positional import separately. Enabling `FINISH` also clocks each `Frame::finish`, which validates the completed entries, constructs the array or hash and releases the frame. The remainder includes traversal, opening frames, reserving their output buffers, and the inner timers' overhead. + +Use the release profile with Rust 1.98.1 or 1.99.1 on the path. The build script gives every source revision, compiler and probe its own target directory. The historical revisions are `9cc23027` (before compaction) and `6966adea` (first compact headers). The change under test is `93395e00` → `fa699783`. The eight historical stock binaries used on OTIS matched the SHA-256 digests recorded in [the original record comparison](../container-records/README.md). + +```sh +dir=benchmarks/borrowed-import +"$dir/build.sh" "$work" base head base-probe head-probe +python3 "$dir/measure.py" "$work" stock-199 199 stock +python3 "$dir/measure.py" "$work" phase-199 199 phase +``` + +Use `198` for the other compiler. On OTIS we included `old compact` in the build and `--historical --positions 48` in each stock run. All other experiments used 32 positions, drawn without replacement from 0 through 4,080 padding bytes in 16-byte increments with seed 255. Shannon ran the driver under `taskset -c 2`. To reproduce the detailed M4 controls, build `old-probe compact-probe` with Rust 1.99.1, then run the same driver with experiments `layout` and `trace`. Both use the portable scanner. [Raw paired samples, binary hashes and counters](samples.json.gz) diff --git a/benchmarks/borrowed-import/build.sh b/benchmarks/borrowed-import/build.sh new file mode 100755 index 000000000..4b47814b2 --- /dev/null +++ b/benchmarks/borrowed-import/build.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Build isolated release examples for measure.py with the selected compiler on PATH. +set -euo pipefail + +if [[ $# -lt 2 ]]; then + echo "usage: build.sh SCRATCH {base|head|old|compact}[-probe]..." >&2 + exit 2 +fi +here=$(cd "$(dirname "$0")" && pwd) +repo=$(git -C "$here" rev-parse --show-toplevel) +mkdir -p "$1" +root=$(cd "$1" && pwd) +shift +case "$(rustc --version | cut -d' ' -f2)" in + 1.98.1) compiler=198 ;; + 1.99.1) compiler=199 ;; + *) echo "expected Rust 1.98.1 or 1.99.1 on PATH" >&2; exit 1 ;; +esac +export TMPDIR="$root/tmp" +mkdir -p "$TMPDIR" "$root/bin" +if [[ $(uname -s) == Darwin ]]; then + clang -O2 -dynamiclib "$here/../container-records/bump.c" -o "$root/bump.dylib" +fi +for arm in "$@"; do + case "${arm%-probe}" in + old) ref=9cc23027 ;; + compact) ref=6966adea ;; + base) ref=93395e00 ;; + head) ref=fa699783 ;; + *) echo "unknown arm $arm" >&2; exit 2 ;; + esac + source_dir="$root/source-$compiler-$arm" + mkdir "$source_dir" + git -C "$repo" archive "$ref" | tar -x -C "$source_dir" + cd "$source_dir" + if [[ $arm == *-probe ]]; then + patch -p1 < "$here/probe.patch" + fi + export CARGO_TARGET_DIR="$root/target-$compiler-$arm" + for mode in portable simd; do + features="" + if [[ $mode == simd ]]; then features=simd; fi + cargo build --locked --release --example compare --no-default-features --features "$features" + cp "$CARGO_TARGET_DIR/release/examples/compare" "$root/bin/$compiler-$mode-$arm" + done +done diff --git a/benchmarks/borrowed-import/measure.py b/benchmarks/borrowed-import/measure.py new file mode 100644 index 000000000..b265383f7 --- /dev/null +++ b/benchmarks/borrowed-import/measure.py @@ -0,0 +1,137 @@ +"""Compare release builds of examples/compare at paired, shuffled launch positions.""" +import argparse +import gzip +import hashlib +import itertools +import json +import platform +import random +import statistics +import subprocess +import sys +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO / "scripts")) +import fixtures +import json_fixtures + +POINT = "array_import_point_records/unlimited" +PACKET = "json_api_stringify_256k/metered" +FIELDS = ("digest", "output_bytes", "steps", "tracked_peak_bytes", "tracked_retained_bytes") + + +def containers(value): + if isinstance(value, dict): + return 1 + sum(map(containers, value.values())) + if isinstance(value, list): + return 1 + sum(map(containers, value)) + return 0 + + +def arms(experiment): + # Each tuple selects a binary suffix and its runtime probe switches. + if experiment == "layout": + return { + "old": ("old-probe", {"BUMP": "00"}), + "compact": ("compact-probe", {"BUMP": "00"}), + "bump": ("compact-probe", {"BUMP": "11"}), + "old-pad": ("old-probe", {"BUMP": "00", "PAD": "1"}), + "compact-pad": ("compact-probe", {"BUMP": "00", "PAD": "1"}), + } + if experiment == "trace": + return {arm: (arm + "-probe", {"FINISH": "1"}) + for arm in ("old", "compact", "base", "head")} + suffix = "-probe" if experiment == "phase" else "" + return {arm: (("base" if arm == "repeat" else arm) + suffix, {}) + for arm in ("base", "repeat", "head")} + + +def main(args): + rng = random.Random(args.seed) + root = args.root.resolve() + output = root / args.run + output.mkdir() + runner = output / "compare" + point = next(c for c in fixtures.benchmark_cases() if c["name"] == POINT) + packet = next(c for c in json_fixtures.benchmark_cases() if c["name"] == PACKET) + if args.experiment == "trace": + # Calling JSON.stringify imports the builtin namespace too. Keep the typed + # argument, and require exactly one finish per container in its tree. + packet = dict(packet, name="nested_packet_import/metered", expected="", + source=packet["source"].replace("JSON.stringify(input)", '""')) + cases = [dict(point, iterations=96), dict(packet, iterations=12)] + cases_file = output / "cases.json" + cases_file.write_text(json.dumps(cases)) + frames = {c["name"]: containers(c["args"][0]) for c in cases} + goldens = dict((k, v) for k, *v in map(json.loads, gzip.open( + REPO / "tests/golden/conformance.counters.jsonl.gz", "rt"))) + scans = ["portable"] if args.experiment in ("trace", "layout") else ["portable", "simd"] + variants = arms(args.experiment) + if args.historical: + if args.experiment != "stock": + raise ValueError("--historical requires stock binaries") + variants.update({arm: (arm, {}) for arm in ("old", "compact")}) + results, hashes, counters = [], {}, {} + for index, position in enumerate(rng.sample(range(256), args.positions)): + jobs = list(itertools.product(scans, variants)) + rng.shuffle(jobs) + for scanner, arm in jobs: + suffix, switches = variants[arm] + binary = root / "bin" / f"{args.compiler}-{scanner}-{suffix}" + if binary.name not in hashes: + hashes[binary.name] = hashlib.sha256(binary.read_bytes()).hexdigest() + runner.unlink(missing_ok=True) + runner.symlink_to(binary) + env = {"P": "x" * (16 * position), **switches} + if args.experiment == "layout": + env["DYLD_INSERT_LIBRARIES"] = str(root / "bump.dylib") + for action in (["validate", "timing"] if index == 0 else ["timing"]): + rows = subprocess.check_output([runner, cases_file, "0", action], env=env) + for case, row in zip(cases, map(json.loads, rows.splitlines()), strict=True): + name = case["name"] + assert row["name"] == name + state = [row[k] for k in FIELDS] + assert state == counters.setdefault(suffix, {}).setdefault(name, state) + if suffix.startswith(("base", "head")) and name == POINT: + assert state[2:] == goldens[POINT] + if action == "validate": + assert json.loads(row["result_json"]) == case["expected"] + continue + sample = dict(position=position, scanner=scanner, arm=arm, name=name, + ns=row["ns_per_call"]) + if suffix.endswith("-probe"): + count = case["iterations"] + assert row["phase_calls"] == [count, count * frames[name] if "FINISH" in env else 0] + sample["import"], sample["finish"] = row["phase_ns"] + results.append(sample) + if len(set(hashes.values())) != len(hashes): + raise ValueError("two different compiler configurations produced identical executables") + for name in frames: + states = [records[name] for records in counters.values()] + assert all(state[:3] == states[0][:3] and state[4] == states[0][4] for state in states) + current = [records[name] for suffix, records in counters.items() if suffix.startswith(("base", "head"))] + assert all(state == current[0] for state in current) + result = dict(host=platform.machine(), kernel=platform.release(), compiler=args.compiler, + experiment=args.experiment, seed=args.seed, positions=args.positions, + sha256=hashes, counters=counters, container_counts=frames, samples=results) + with gzip.open(output / "results.json.gz", "wt") as out: + json.dump(result, out, separators=(",", ":")) + out.write("\n") + for scanner, name in itertools.product(scans, frames): + for arm in variants: + rows = [s for s in results if (s["scanner"], s["name"], s["arm"]) == (scanner, name, arm)] + print(scanner, name, arm, *(round(statistics.median(r[k] for r in rows) / 1000, 2) + for k in ("ns", "import", "finish") if k in rows[0])) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("root", type=Path) + parser.add_argument("run", help="new output directory under ROOT") + parser.add_argument("compiler", choices=("198", "199")) + parser.add_argument("experiment", choices=("stock", "phase", "trace", "layout")) + parser.add_argument("--positions", type=int, choices=range(1, 257), metavar="1..256", default=32) + parser.add_argument("--historical", action="store_true", help="include old and compact stock builds") + parser.add_argument("--seed", type=int, default=255) + main(parser.parse_args()) diff --git a/benchmarks/borrowed-import/probe.patch b/benchmarks/borrowed-import/probe.patch new file mode 100644 index 000000000..f4ab6f11f --- /dev/null +++ b/benchmarks/borrowed-import/probe.patch @@ -0,0 +1,80 @@ +--- a/examples/compare.rs ++++ b/examples/compare.rs +@@ -67,2 +67,3 @@ + fn main() -> Result<(), Box> { ++ vibescript::import_probe::init(); + let args: Vec<_> = std::env::args().collect(); +@@ -278,2 +279,3 @@ + let start = Instant::now(); ++ vibescript::import_probe::take(); + let mut last = None; +@@ -287,2 +289,6 @@ + let elapsed = start.elapsed(); ++ let (times, counts) = vibescript::import_probe::take(); ++ assert_eq!(counts[0], n); ++ record.insert("phase_ns".into(), json!(times.map(|x| x as f64 / n as f64))); ++ record.insert("phase_calls".into(), json!(counts)); + #[cfg(feature = "allocation-stats")] +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -15,2 +15,45 @@ + ++#[doc(hidden)] ++pub mod import_probe { ++ use std::cell::Cell; ++ use std::time::Instant; ++ use crate::{CallContext, Result, Value}; ++ ++ thread_local! { ++ static NS: Cell<[u64; 2]> = const { Cell::new([0; 2]) }; ++ static CALLS: Cell<[usize; 2]> = const { Cell::new([0; 2]) }; ++ static FINISH: Cell = const { Cell::new(false) }; ++ static PAD: Cell = const { Cell::new(false) }; ++ } ++ pub fn init() { ++ FINISH.set(std::env::var_os("FINISH").is_some()); ++ PAD.set(std::env::var_os("PAD").is_some()); ++ } ++ pub(crate) fn finish_clock() -> Option { ++ FINISH.get().then(Instant::now) ++ } ++ pub(crate) fn elapsed(slot: usize, start: Instant) { ++ let ns = start.elapsed().as_nanos() as u64; ++ let mut times = NS.get(); ++ times[slot] += ns; ++ NS.set(times); ++ let mut counts = CALLS.get(); ++ counts[slot] += 1; ++ CALLS.set(counts); ++ } ++ #[inline(never)] ++ fn timed(ctx: &mut CallContext, arg: &Value) -> Result { ++ let pad = std::mem::MaybeUninit::<[u8; N]>::uninit(); ++ std::hint::black_box(&pad); ++ let start = Instant::now(); ++ let value = ctx.import(arg); ++ elapsed(0, start); ++ std::hint::black_box(&pad); ++ value ++ } ++ pub(crate) fn import(ctx: &mut CallContext, arg: &Value) -> Result { ++ if PAD.get() { timed::<192>(ctx, arg) } else { timed::<0>(ctx, arg) } ++ } ++ pub fn take() -> ([u64; 2], [usize; 2]) { (NS.take(), CALLS.take()) } ++} + mod actor; +--- a/src/value/import.rs ++++ b/src/value/import.rs +@@ -191,3 +191,5 @@ + .ok_or(crate::checked::violation("import frame expected"))?; ++ let start = crate::import_probe::finish_clock(); + produced = Some(frame.finish(self)?); ++ if let Some(start) = start { crate::import_probe::elapsed(1, start); } + } +--- a/src/vm.rs ++++ b/src/vm.rs +@@ -383,3 +383,3 @@ + for arg in args { +- let value = ctx.import(arg)?; ++ let value = crate::import_probe::import(ctx, arg)?; + crate::exports::check(ctx, &value)?; diff --git a/benchmarks/borrowed-import/samples.json.gz b/benchmarks/borrowed-import/samples.json.gz new file mode 100644 index 000000000..7deb4dd27 Binary files /dev/null and b/benchmarks/borrowed-import/samples.json.gz differ diff --git a/src/value/import.rs b/src/value/import.rs index 3c7a76564..111a22272 100644 --- a/src/value/import.rs +++ b/src/value/import.rs @@ -14,27 +14,26 @@ use crate::{ hash::Hash, range::Range, }; -use std::sync::Arc; -enum Frame { +enum Frame<'a> { Array { - source: Arc>, + source: &'a Heap, out: Buffer, }, Hash { - source: Arc, + source: &'a Hash, out: Buffer<(Value, Value)>, key: Option, }, } -impl Frame { - fn next_child(&self) -> Option { +impl<'a> Frame<'a> { + fn next_child(&self) -> Option<&'a Value> { match self { - Self::Array { source, out } => source.buffer.data.get(out.data.len()).cloned(), + Self::Array { source, out } => source.buffer.data.get(out.data.len()), Self::Hash { source, out, key } => { let (k, v) = source.buffer.data.get(out.data.len())?; - Some(if key.is_none() { k } else { v }.clone()) + Some(if key.is_none() { k } else { v }) } } } @@ -179,9 +178,9 @@ impl CallContext { Some(child) => { self.charge(1)?; if key { - produced = Some(keys.import(self, &child)?); + produced = Some(keys.import(self, child)?); } else { - produced = self.open(&child, rooted, &mut frames)?; + produced = self.open(child, rooted, &mut frames)?; } } None => { @@ -202,11 +201,11 @@ impl CallContext { } /// Imports a leaf, shares a container already charged to this call, or opens a frame. - fn open( + fn open<'a>( &mut self, - value: &Value, + value: &'a Value, rooted: bool, - frames: &mut Buffer, + frames: &mut Buffer>, ) -> Result> { match &value.0 { Kind::Array(heap) => { @@ -214,13 +213,7 @@ impl CallContext { return Ok(Some(value.clone())); } let out = Buffer::with_capacity(self, heap.buffer.data.len())?; - frames.push( - self, - Frame::Array { - source: heap.clone(), - out, - }, - )?; + frames.push(self, Frame::Array { source: heap, out })?; Ok(None) } Kind::Hash(hash) => { @@ -231,7 +224,7 @@ impl CallContext { frames.push( self, Frame::Hash { - source: hash.clone(), + source: hash, out, key: None, }, @@ -297,6 +290,7 @@ impl CallContext { mod tests { use super::*; use crate::{CallOptions, Capability, Engine, HostMethod}; + use std::sync::Arc; fn object_data_keys() -> Value { let mut value = Value::object(vec![