Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ here.**
The load warned only for a TPH base read through a subtype column; it now warns whenever the
base differs from the pre-rc.21 derivation, naming both entities and the
`identity.primary { extends: ... }` that keeps the old one.
- **Loading a large model no longer slows down quadratically (TypeScript, Python, C#).** Reference resolution looked each name up by scanning every top-level object, so load time grew with the square of the model; each root now keeps a name index, invalidated whenever its top-level nodes change, with the same first-match-wins result. A 20x-size model loads about 5x faster in TypeScript and 1.5x to 2x faster in Python and C#; loaded trees are byte-identical.

## [1.3.0] — 2026-11-17

Expand Down
6 changes: 5 additions & 1 deletion client/web/packages/runtime-web/src/meta-read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,12 @@ export interface MetaRead {
* deliberately — see `fixtures/conformance/xpkg-collision-*`) are NOT
* disambiguated by `object()`. A caller that might see a cross-package
* collision should walk `objects()` and filter on `package` itself.
*
* `| undefined` (not just `?`): `MetaData.package` is an accessor, so a real
* `MetaObject` carries the property as required-but-possibly-undefined, and
* `exactOptionalPropertyTypes` refuses to assign that to a plain optional.
*/
readonly package?: string;
readonly package?: string | undefined;
readonly subType: string;
attr: AttrReader;
fields(): MetaFieldRead[];
Expand Down
25 changes: 25 additions & 0 deletions scripts/bench-load/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Warm-load benchmark

Measures how long each loader takes to load a model that is N times the size of the
persistence-conformance "fitness" model, so growth with model size is visible (a quadratic
lookup shows up as a 20x model costing far more than 20x the 1x model).

```
scripts/bench-load/run.sh [--sizes "1 5 10 20"] [--loads 7] [--ports "typescript python csharp"]
[--src <repo-root>] [--canonical-dir <dir>]
```

- `gen-model.py <copies> <out-dir>` writes N renamed copies of the fitness model (one package
each), so every copy adds the same references and nothing collides.
- `ts-load.mjs`, `py_load.py`, `csharp/` are the three warm-load drivers. Each does one
untimed warm-up load, then times `--loads` loads and prints the median and peak RSS.
- `run.sh` generates the models, builds the C# driver, runs the drivers and prints a table.
Scratch lives under `$DEV_SCRATCH` (else the system temp dir) and is removed on exit.
- `--src` points at another checkout (for a "before" row from a pristine copy of an older
commit). Its TypeScript `metadata` package must be built (`dist/`).
- `--canonical-dir` also writes each port's canonical serialization of the largest model, so two
runs can be compared byte for byte (`cmp`) to show a change did not alter the loaded tree.

Wall-clock is noisy on a busy machine. Compare the 20x/1x growth ratio, not absolute
milliseconds, and treat the deterministic call-count tests in each port
(`top-level-index` tests) as the regression gate; this tool is for measurement, not CI.
14 changes: 14 additions & 0 deletions scripts/bench-load/csharp/LoadBench.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Warm-load driver for the C# loader. Override the library under test with
-p:MetaObjectsProject=<path to MetaObjects.csproj> to benchmark another checkout. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<MetaObjectsProject Condition="'$(MetaObjectsProject)' == ''">$(MSBuildThisFileDirectory)../../../server/csharp/MetaObjects/MetaObjects.csproj</MetaObjectsProject>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(MetaObjectsProject)" />
</ItemGroup>
</Project>
29 changes: 29 additions & 0 deletions scripts/bench-load/csharp/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Warm-load driver for the C# loader.
// usage: LoadBench <model-dir> <timed-loads> [--canonical <out-file>]
using System.Diagnostics;
using MetaObjects;
using MetaObjects.Loader;

var dir = args[0];
var n = int.Parse(args[1]);
var canonicalOut = args.Length > 3 && args[2] == "--canonical" ? args[3] : null;

LoadResult Load()
{
var r = MetaDataLoader.FromDirectory(dir);
if (r.Errors.Count > 0) throw new InvalidOperationException($"load errors: {r.Errors[0]}");
return r;
}

var first = Load(); // warm-up
if (canonicalOut is not null) File.WriteAllText(canonicalOut, SerializerJson.CanonicalSerialize(first.Root));
var times = new List<double>();
for (var i = 0; i < n; i++)
{
var t0 = Stopwatch.GetTimestamp();
Load();
times.Add(Stopwatch.GetElapsedTime(t0).TotalMilliseconds);
}
times.Sort();
var peak = Process.GetCurrentProcess().PeakWorkingSet64 / (1024 * 1024);
Console.WriteLine($"{{\"port\":\"csharp\",\"loads\":{n},\"median_ms\":{times[n / 2]:F1},\"peak_rss_mib\":{peak}}}");
31 changes: 31 additions & 0 deletions scripts/bench-load/gen-model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Write an N-package load-benchmark model: N copies of the persistence-conformance
fitness model, each under its own root package (fitness_x00 ... fitness_xNN), one file per
copy, so a model N times the size has no name collisions and every reference still resolves.

usage: gen-model.py <copies> <out-dir>
"""
import json
import pathlib
import sys

SRC = pathlib.Path(__file__).resolve().parents[2] / "fixtures/persistence-conformance/canonical/meta.fitness.json"


def main() -> int:
if len(sys.argv) != 3:
print(__doc__, file=sys.stderr)
return 2
copies, out = int(sys.argv[1]), pathlib.Path(sys.argv[2])
out.mkdir(parents=True, exist_ok=True)
text = SRC.read_text()
for i in range(copies):
pkg = f"fitness_x{i:02d}"
body = text.replace('"package": "fitness"', f'"package": "{pkg}"', 1)
json.loads(body) # fail loudly on a bad rewrite
(out / f"meta.{pkg}.json").write_text(body)
return 0


if __name__ == "__main__":
sys.exit(main())
40 changes: 40 additions & 0 deletions scripts/bench-load/py_load.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Warm-load driver for the Python loader.

usage: py_load.py <model-dir> <timed-loads> [--canonical <out-file>]
env: MO_PY_SRC the package's src/ directory (default: this checkout's)
"""
import json
import pathlib
import resource
import os
import statistics
import sys
import time
import warnings

sys.path.insert(0, os.environ.get("MO_PY_SRC") or str(pathlib.Path(__file__).resolve().parents[2] / "server/python/src"))
from metaobjects.loader.meta_data_loader import MetaDataLoader # noqa: E402
from metaobjects.serializer_json import canonical_serialize # noqa: E402

warnings.simplefilter("ignore")
directory, n, *rest = sys.argv[1:]
canonical_out = rest[1] if rest[:1] == ["--canonical"] else None


def load():
r = MetaDataLoader.from_directory(directory)
if r.errors:
raise SystemExit(f"load errors: {r.errors[0]}")
return r


first = load() # warm-up
if canonical_out:
pathlib.Path(canonical_out).write_text(canonical_serialize(first.root))
times = []
for _ in range(int(n)):
t0 = time.perf_counter()
load()
times.append((time.perf_counter() - t0) * 1000)
print(json.dumps({"port": "python", "loads": len(times), "median_ms": round(statistics.median(times), 1),
"peak_rss_mib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024)}))
75 changes: 75 additions & 0 deletions scripts/bench-load/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Warm-load benchmark: a model N times the fitness model, loaded by each port.
#
# usage: run.sh [--src <repo-root>] [--sizes "1 5 10 20"] [--loads 7] [--ports "typescript python csharp"]
# [--canonical-dir <dir>]
#
# --src the checkout to measure (default: this one). Point it at a pristine copy of an
# older commit to get a "before" row. Its TypeScript metadata package must be
# built (dist/); the C# library is built here.
# --canonical-dir also write each port's canonical serialization of the largest model, so two
# runs can be compared byte for byte.
# Prints one JSON object per (port, size): median warm-load ms, peak RSS MiB, then a table.
# Scratch (the model, the C# build) lives under $DEV_SCRATCH (else the system temp dir).
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
src="$(cd "$here/../.." && pwd)"
sizes="1 5 10 20"
loads=7
ports="typescript python csharp"
canon=""
while [ $# -gt 0 ]; do
case "$1" in
--src) src="$(cd "$2" && pwd)"; shift 2 ;;
--sizes) sizes="$2"; shift 2 ;;
--loads) loads="$2"; shift 2 ;;
--ports) ports="$2"; shift 2 ;;
--canonical-dir) canon="$2"; mkdir -p "$canon"; shift 2 ;;
*) echo "unknown option: $1" >&2; exit 2 ;;
esac
done

work="$(mktemp -d "${DEV_SCRATCH:-${TMPDIR:-/tmp}}/bench-load.XXXXXX")"
trap 'rm -rf "$work"' EXIT
largest="${sizes##* }"

for n in $sizes; do python3 "$here/gen-model.py" "$n" "$work/model-$n"; done

if [[ " $ports " == *" csharp "* ]]; then
cp "$here/csharp/LoadBench.csproj" "$here/csharp/Program.cs" "$work/"
(cd "$work" && dotnet build LoadBench.csproj -c Release -o "$work/csharp-out" \
-p:MetaObjectsProject="$src/server/csharp/MetaObjects/MetaObjects.csproj" \
-v quiet -nologo >&2)
fi

results="$work/results.jsonl"
: > "$results"
for port in $ports; do
for n in $sizes; do
extra=()
[ -n "$canon" ] && [ "$n" = "$largest" ] && extra=(--canonical "$canon/$port.canonical.json")
case "$port" in
typescript) out=$(MO_TS_DIST="$src/server/typescript/packages/metadata/dist" node "$here/ts-load.mjs" "$work/model-$n" "$loads" "${extra[@]}") ;;
python) out=$(MO_PY_SRC="$src/server/python/src" python3 -I "$here/py_load.py" "$work/model-$n" "$loads" "${extra[@]}") ;;
csharp) out=$(dotnet "$work/csharp-out/LoadBench.dll" "$work/model-$n" "$loads" "${extra[@]}") ;;
esac
echo "$out" | python3 -c "import json,sys; d=json.load(sys.stdin); d['copies']=$n; print(json.dumps(d))" | tee -a "$results"
done
done

python3 - "$results" <<'PY'
import json, sys, collections
rows = [json.loads(l) for l in open(sys.argv[1])]
by = collections.defaultdict(dict)
for r in rows:
by[r["port"]][r["copies"]] = r
sizes = sorted({r["copies"] for r in rows})
print()
print("| port | " + " | ".join(f"{s}x ms" for s in sizes) + f" | {sizes[-1]}x/{sizes[0]}x growth | peak RSS MiB at {sizes[-1]}x |")
print("|---|" + "---|" * (len(sizes) + 2))
for port, d in by.items():
cells = " | ".join(f"{d[s]['median_ms']}" for s in sizes)
growth = d[sizes[-1]]["median_ms"] / d[sizes[0]]["median_ms"]
print(f"| {port} | {cells} | {growth:.1f}x | {d[sizes[-1]]['peak_rss_mib']} |")
PY
29 changes: 29 additions & 0 deletions scripts/bench-load/ts-load.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Warm-load driver for the TypeScript loader.
// usage: node ts-load.mjs <model-dir> <timed-loads> [--canonical <out-file>]
// env: MO_TS_DIST the metadata package's built dist/ (default: this checkout's)
import { writeFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
import path from "node:path";

const dist = process.env.MO_TS_DIST ?? path.resolve(import.meta.dirname, "../../server/typescript/packages/metadata/dist");
const { MetaDataLoader, canonicalSerialize } = await import(pathToFileURL(path.join(dist, "index.js")).href);

const [dir, n = "7", ...rest] = process.argv.slice(2);
const canonicalOut = rest[0] === "--canonical" ? rest[1] : undefined;

const load = async () => {
const r = await MetaDataLoader.fromDirectory(dir);
if (r.errors.length > 0) throw new Error(`load errors: ${r.errors[0]}`);
return r;
};

const first = await load(); // warm-up
if (canonicalOut) writeFileSync(canonicalOut, canonicalSerialize(first.root));
const times = [];
for (let i = 0; i < Number(n); i++) {
const t0 = performance.now();
await load();
times.push(performance.now() - t0);
}
times.sort((a, b) => a - b);
console.log(JSON.stringify({ port: "typescript", loads: times.length, median_ms: +times[times.length >> 1].toFixed(1), peak_rss_mib: +(process.resourceUsage().maxRSS / 1024).toFixed(0) }));
1 change: 1 addition & 0 deletions scripts/ci-lane-map.txt
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ server/csharp/* | csharp | the C# port
server/rust/* | rust | the Rust port (preview, ADR-0065)
fixtures/* | ALL | shared corpora every port runs
spec/* | ALL | the metamodel spec every port implements
scripts/bench-load/* | NONE | load-benchmark drivers: run by hand, read by no test lane (the gates lane still checks them)
scripts/* | ALL | CI scripts and tooling, this map included
.github/* | ALL | the hosted workflows that call the scripts
agent-context/* | ALL | bundled into the TypeScript packages and checked by cross-port gates
Expand Down
Loading
Loading