From ed898a7d4ad373ce4d9997cd4419ed87164da06e Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 15:22:14 -0500 Subject: [PATCH 1/4] perf(metadata,python,csharp): index top-level names so reference resolution is linear Reference resolution scanned every top-level object per lookup, so load time grew with the square of the model. Each root now keeps a name index (first match wins, same errors), invalidated when its top-level nodes change, and reused by super resolution and the overlay and merge target scans. Adds per-port count-based regression tests, the scripts/bench-load benchmark, and a CHANGELOG line. No behaviour change: canonical output of a 20x model is byte-identical before and after in all three ports. --- CHANGELOG.md | 4 + scripts/bench-load/README.md | 25 +++ scripts/bench-load/csharp/LoadBench.csproj | 14 ++ scripts/bench-load/csharp/Program.cs | 29 +++ scripts/bench-load/gen-model.py | 31 +++ scripts/bench-load/py_load.py | 40 ++++ scripts/bench-load/run.sh | 75 +++++++ scripts/bench-load/ts-load.mjs | 29 +++ scripts/ci-lane-map.txt | 1 + .../TopLevelIndexTests.cs | 179 +++++++++++++++ server/csharp/MetaObjects/Meta/MetaData.cs | 37 ++++ server/csharp/MetaObjects/MetaObjects.csproj | 5 + server/csharp/MetaObjects/NamingRefs.cs | 33 ++- server/csharp/MetaObjects/Parser.cs | 25 ++- server/csharp/MetaObjects/SuperResolve.cs | 12 +- server/csharp/MetaObjects/TopLevelIndex.cs | 79 +++++++ server/python/src/metaobjects/loader/merge.py | 44 +++- .../metaobjects/loader/resolve_references.py | 6 +- .../python/src/metaobjects/meta/meta_data.py | 140 ++++++++++-- server/python/src/metaobjects/naming_refs.py | 60 +++++- .../python/src/metaobjects/top_level_index.py | 71 ++++++ .../tests/loader/test_top_level_index.py | 203 ++++++++++++++++++ .../packages/metadata/src/naming-refs.ts | 35 ++- .../packages/metadata/src/parser-core.ts | 33 ++- .../packages/metadata/src/shared/meta-data.ts | 55 ++++- .../packages/metadata/src/super-resolve.ts | 11 +- .../packages/metadata/src/top-level-index.ts | 75 +++++++ .../metadata/test/top-level-index.test.ts | 185 ++++++++++++++++ 28 files changed, 1468 insertions(+), 68 deletions(-) create mode 100644 scripts/bench-load/README.md create mode 100644 scripts/bench-load/csharp/LoadBench.csproj create mode 100644 scripts/bench-load/csharp/Program.cs create mode 100755 scripts/bench-load/gen-model.py create mode 100644 scripts/bench-load/py_load.py create mode 100755 scripts/bench-load/run.sh create mode 100644 scripts/bench-load/ts-load.mjs create mode 100644 server/csharp/MetaObjects.Conformance.Tests/TopLevelIndexTests.cs create mode 100644 server/csharp/MetaObjects/TopLevelIndex.cs create mode 100644 server/python/src/metaobjects/top_level_index.py create mode 100644 server/python/tests/loader/test_top_level_index.py create mode 100644 server/typescript/packages/metadata/src/top-level-index.ts create mode 100644 server/typescript/packages/metadata/test/top-level-index.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index bc3b11affc..4dcae4e93d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,10 @@ here.** no version, vocabulary or `metamodelVersion` changes here. See `docs/RELEASING.md`, "The vocabulary rule". +### Fixed + +- **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 diff --git a/scripts/bench-load/README.md b/scripts/bench-load/README.md new file mode 100644 index 0000000000..09259256aa --- /dev/null +++ b/scripts/bench-load/README.md @@ -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 ] [--canonical-dir ] +``` + +- `gen-model.py ` 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. diff --git a/scripts/bench-load/csharp/LoadBench.csproj b/scripts/bench-load/csharp/LoadBench.csproj new file mode 100644 index 0000000000..4477f5e223 --- /dev/null +++ b/scripts/bench-load/csharp/LoadBench.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + $(MSBuildThisFileDirectory)../../../server/csharp/MetaObjects/MetaObjects.csproj + + + + + diff --git a/scripts/bench-load/csharp/Program.cs b/scripts/bench-load/csharp/Program.cs new file mode 100644 index 0000000000..0bef06bc27 --- /dev/null +++ b/scripts/bench-load/csharp/Program.cs @@ -0,0 +1,29 @@ +// Warm-load driver for the C# loader. +// usage: LoadBench [--canonical ] +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(); +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}}}"); diff --git a/scripts/bench-load/gen-model.py b/scripts/bench-load/gen-model.py new file mode 100755 index 0000000000..5fdae15b01 --- /dev/null +++ b/scripts/bench-load/gen-model.py @@ -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 +""" +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()) diff --git a/scripts/bench-load/py_load.py b/scripts/bench-load/py_load.py new file mode 100644 index 0000000000..820c7d292b --- /dev/null +++ b/scripts/bench-load/py_load.py @@ -0,0 +1,40 @@ +"""Warm-load driver for the Python loader. + +usage: py_load.py [--canonical ] +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)})) diff --git a/scripts/bench-load/run.sh b/scripts/bench-load/run.sh new file mode 100755 index 0000000000..62df8d9fc8 --- /dev/null +++ b/scripts/bench-load/run.sh @@ -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 ] [--sizes "1 5 10 20"] [--loads 7] [--ports "typescript python csharp"] +# [--canonical-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 diff --git a/scripts/bench-load/ts-load.mjs b/scripts/bench-load/ts-load.mjs new file mode 100644 index 0000000000..0ca2645870 --- /dev/null +++ b/scripts/bench-load/ts-load.mjs @@ -0,0 +1,29 @@ +// Warm-load driver for the TypeScript loader. +// usage: node ts-load.mjs [--canonical ] +// 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) })); diff --git a/scripts/ci-lane-map.txt b/scripts/ci-lane-map.txt index 8e31bb0fef..067e095a5a 100644 --- a/scripts/ci-lane-map.txt +++ b/scripts/ci-lane-map.txt @@ -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 diff --git a/server/csharp/MetaObjects.Conformance.Tests/TopLevelIndexTests.cs b/server/csharp/MetaObjects.Conformance.Tests/TopLevelIndexTests.cs new file mode 100644 index 0000000000..1477382d39 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/TopLevelIndexTests.cs @@ -0,0 +1,179 @@ +// The per-root top-level index behind reference resolution (TopLevelIndex.cs). +// +// Two contracts: +// 1. LINEAR. Resolving a reference does not walk every top-level object. Asserted by counting +// work (ResolutionKey calls, index builds), never by wall-clock, over 1x, 5x and 10x +// generated models. +// 2. NEVER STALE. A lookup after the root's top-level nodes changed (a node added, a node +// re-keyed by a package change, a later source merged in) sees the change. + +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public class TopLevelIndexTests +{ + private static readonly string Fitness = File.ReadAllText(Path.Combine( + CorpusRoot.Path, "..", "persistence-conformance", "canonical", "meta.fitness.json")); + + /// N renamed copies of the fitness model, one source each. + private static List Sources(int copies) => + Enumerable.Range(0, copies) + .Select(i => (IMetaDataSource)new InMemoryStringSource( + ReplaceFirst(Fitness, "\"package\": \"fitness\"", $"\"package\": \"fitness_x{i:00}\""), + id: $"fitness_x{i:00}.json")) + .ToList(); + + private static string ReplaceFirst(string text, string find, string with) + { + int at = text.IndexOf(find, StringComparison.Ordinal); + return text[..at] + with + text[(at + find.Length)..]; + } + + /// Load N copies, counting every ResolutionKey call and index rebuild. + private static (int TopLevel, int KeyCalls, int Rebuilds) Measure(int copies) + { + int calls = 0; + int rebuildsBefore = TopLevelIndex.Rebuilds; + MetaData.ResolutionKeyProbe = () => calls++; + try + { + var result = new MetaDataLoader().Load(Sources(copies)); + Assert.Empty(result.Errors); + return (result.Root.Children().Count, calls, TopLevelIndex.Rebuilds - rebuildsBefore); + } + finally + { + MetaData.ResolutionKeyProbe = null; + } + } + + [Fact] + public void ResolutionKey_calls_per_top_level_node_do_not_grow_with_the_model() + { + var (n1, c1, _) = Measure(1); + var (n5, c5, _) = Measure(5); + var (n10, c10, _) = Measure(10); + double per1 = (double)c1 / n1, per5 = (double)c5 / n5, per10 = (double)c10 / n10; + + // A scan-per-reference makes this ratio grow with the model (about 10x between 1x and 10x); + // the index keeps it flat. 1.5 leaves room for fixed per-load work. + Assert.True(per5 < per1 * 1.5, $"per-node key calls grew: 1x={per1:F1} 5x={per5:F1}"); + Assert.True(per10 < per1 * 1.5, $"per-node key calls grew: 1x={per1:F1} 10x={per10:F1}"); + // And bounded in absolute terms: a handful of key builds per top-level node, not one per + // top-level node per reference. + Assert.True(per10 < 40, $"per-node key calls at 10x: {per10:F1}"); + } + + [Fact] + public void Index_rebuilds_per_load_do_not_grow_with_the_model() + { + var (_, _, r1) = Measure(1); + var (n10, _, r10) = Measure(10); + // Appends are absorbed incrementally, so a rebuild happens only when the root's keys change; + // a load must not rebuild once per top-level node. + Assert.True(r10 <= r1 + 2, $"rebuilds 1x={r1} 10x={r10}"); + Assert.True(r10 < n10 / 4, $"rebuilds {r10} for {n10} top-level nodes"); + } + + private static MetaRoot NewRoot() => new(new TypeId("metadata", "root"), ""); + + private static MetaObject Entity(string name, string? package = null) + { + var o = new MetaObject(new TypeId("object", "entity"), name); + if (package is not null) o.SetPackage(package); + return o; + } + + private static MetaData? Resolve(MetaRoot root, string reference, string referrerPkg = "") => + NamingRefs.ResolveObjectRef(root, reference, referrerPkg); + + [Fact] + public void A_node_added_after_a_lookup_is_found_by_the_next_lookup() + { + var root = NewRoot(); + var a = Entity("A"); + root.AddChild(a); + Assert.Same(a, Resolve(root, "A")); + Assert.Null(Resolve(root, "B")); + var b = Entity("B"); + root.AddChild(b); + Assert.Same(b, Resolve(root, "B")); + Assert.Same(a, Resolve(root, "A")); + } + + [Fact] + public void First_match_still_wins_when_a_later_node_has_the_same_key() + { + var root = NewRoot(); + var first = Entity("Dup"); + root.AddChild(first); + Assert.Same(first, Resolve(root, "Dup")); + root.AddChild(Entity("Dup")); + Assert.Same(first, Resolve(root, "Dup")); + } + + [Fact] + public void SetPackage_on_a_top_level_node_re_keys_it() + { + var root = NewRoot(); + var a = Entity("A", "p"); + root.AddChild(a); + Assert.Same(a, Resolve(root, "p::A")); + a.SetPackage("q"); + Assert.Null(Resolve(root, "p::A")); + Assert.Same(a, Resolve(root, "q::A")); + } + + [Fact] + public void SetFileDefaultPackage_re_keys_a_package_less_top_level_node() + { + var root = NewRoot(); + var a = Entity("A"); + root.AddChild(a); + Assert.Same(a, Resolve(root, "A")); + a.SetFileDefaultPackage("r"); + Assert.Null(Resolve(root, "A")); + Assert.Same(a, Resolve(root, "r::A")); + } + + [Fact] + public void A_change_to_the_roots_package_re_keys_its_package_less_children() + { + var root = NewRoot(); + var a = Entity("A"); + root.AddChild(a); + Assert.Same(a, Resolve(root, "A")); + root.SetPackage("rootpkg"); // a child with no package of its own falls through to it + Assert.Null(Resolve(root, "A")); + Assert.Same(a, Resolve(root, "rootpkg::A")); + } + + [Fact] + public void A_bare_reference_falls_back_from_the_referrer_package_to_the_root_level_after_a_change() + { + var root = NewRoot(); + var rootLevel = Entity("Thing"); + root.AddChild(rootLevel); + Assert.Same(rootLevel, Resolve(root, "Thing", "pkg")); + var local = Entity("Thing", "pkg"); + root.AddChild(local); + Assert.Same(local, Resolve(root, "Thing", "pkg")); + local.SetPackage("other"); + Assert.Same(rootLevel, Resolve(root, "Thing", "pkg")); + } + + [Fact] + public void A_source_merged_in_later_contributes_its_objects() + { + var sources = Sources(2); + var one = new MetaDataLoader().Load([sources[0]]); + Assert.Null(Resolve(one.Root, "fitness_x01::Program")); + var both = new MetaDataLoader().Load(Sources(2)); + Assert.Empty(both.Errors); + Assert.NotNull(Resolve(both.Root, "fitness_x01::Program")); + Assert.NotNull(Resolve(both.Root, "fitness_x00::Program")); + } +} diff --git a/server/csharp/MetaObjects/Meta/MetaData.cs b/server/csharp/MetaObjects/Meta/MetaData.cs index 8f9c086249..9ffbe5704f 100644 --- a/server/csharp/MetaObjects/Meta/MetaData.cs +++ b/server/csharp/MetaObjects/Meta/MetaData.cs @@ -133,6 +133,33 @@ public void SetCanonicalAttr(string name, object? canonical) private MetaData? _parent; private bool _frozen; + // Bumped by every change to this node's child list other than an append, and by any change to + // a package that feeds a child's resolution key. The top-level index (TopLevelIndex.cs) is valid + // only for the epoch it was built at; any NEW way to change the child list or a child's key MUST + // bump it. (An append is detected by the child count, so add-then-lookup stays linear.) + private int _structureEpoch; + private TopLevelIndexes? _topLevelIndexes; + + internal int StructureEpoch => _structureEpoch; + + /// The number of own children, without copying the list. + internal int OwnChildCount => _children.Count; + + /// The own child at (insertion order), without copying the list. + internal MetaData OwnChildAt(int index) => _children[index]; + + /// The (lazily created) holder of this node's top-level indexes; also their lock. + internal TopLevelIndexes GetTopLevelIndexes() => + _topLevelIndexes ?? Interlocked.CompareExchange(ref _topLevelIndexes, new TopLevelIndexes(), null) ?? _topLevelIndexes!; + + /// A package feeding a resolution key changed: this node's children (whose keys may + /// fall through to its package) and its parent's index of it are stale. + private void NoteKeyChange() + { + _structureEpoch++; + if (_parent is not null) _parent._structureEpoch++; + } + /// Registry-supplied coarse value type — set by the registry factory at node construction. private DataType? _dataType; @@ -203,6 +230,11 @@ public string Fqn() return Name; } + /// Test seam: called on every so a test can count the work reference + /// lookup does (a deterministic stand-in for wall-clock). Per thread, so parallel tests cannot disturb + /// each other; null, and so free, in production. + [ThreadStatic] internal static Action? ResolutionKeyProbe; + /// /// The node's package-folded qualified key: <pkg>::<name> where /// pkg is this node's own package if set, else the nearest ancestor's @@ -219,6 +251,7 @@ public string Fqn() /// public string ResolutionKey() { + ResolutionKeyProbe?.Invoke(); // Prefer the node's own package, then the file-default package captured // at PARSE time (independent of the post-merge parent chain). Only when // neither is present (e.g. programmatic construction) fall back to the @@ -250,6 +283,7 @@ public void SetFileDefaultPackage(string pkg) { AssertNotFrozen(); _fileDefaultPackage = pkg; + NoteKeyChange(); } // --------------------------------------------------------------------------- @@ -272,6 +306,7 @@ public void SetPackage(string pkg) { AssertNotFrozen(); _package = pkg; + NoteKeyChange(); } // --------------------------------------------------------------------------- @@ -461,6 +496,8 @@ public bool HasAttr(string name) public void AddChild(MetaData child) { AssertNotFrozen(); + // A child leaving another node's list is not an append there. + if (child._parent is not null && !ReferenceEquals(child._parent, this)) child._parent._structureEpoch++; child._parent = this; _children.Add(child); } diff --git a/server/csharp/MetaObjects/MetaObjects.csproj b/server/csharp/MetaObjects/MetaObjects.csproj index 9d026b5445..865570201b 100644 --- a/server/csharp/MetaObjects/MetaObjects.csproj +++ b/server/csharp/MetaObjects/MetaObjects.csproj @@ -29,4 +29,9 @@ + + + + diff --git a/server/csharp/MetaObjects/NamingRefs.cs b/server/csharp/MetaObjects/NamingRefs.cs index 3b54379d2b..12d6da14fc 100644 --- a/server/csharp/MetaObjects/NamingRefs.cs +++ b/server/csharp/MetaObjects/NamingRefs.cs @@ -119,16 +119,37 @@ public static bool RefMatchesObject(MetaData node, string reference, string refe return resolved is not null && ReferenceEquals(resolved, node); } - private static MetaData? BindOwner(IEnumerable candidates, string owner, string referrerPkg) + private static readonly System.Collections.Concurrent.ConcurrentDictionary RefViews = new(); + + /// The per-root lookup view for top-level nodes of (any type when + /// null), by resolution key. + private static TopLevelView RefView(string? type) => + RefViews.GetOrAdd(type ?? "\0*", _ => new TopLevelView( + $"ref:{type ?? "*"}", + type is null ? static _ => true : c => c.Type == type, + static c => c.ResolutionKey())); + + /// The first top-level node of whose resolution key is exactly + /// . + private static MetaData? FindByKey(MetaData root, string? type, string key) => + TopLevelIndex.FindByKey(root, RefView(type), key, () => + { + foreach (var c in TopLevelOfType(root, type)) + if (c.ResolutionKey() == key) return c; + return null; + }); + + /// Bind an owner reference among the root's top-level nodes of by + /// exact resolution key (R2). + private static MetaData? BindOwner(MetaData root, string? type, string owner, string referrerPkg) { IReadOnlyList keys; try { keys = OwnerCandidateKeys(owner, referrerPkg); } catch (RefOverDropException) { return null; } - var list = candidates as IReadOnlyList ?? candidates.ToList(); foreach (string key in keys) { - foreach (var c in list) - if (c.ResolutionKey() == key) return c; + MetaData? node = FindByKey(root, type, key); + if (node is not null) return node; } return null; } @@ -143,7 +164,7 @@ private static IEnumerable TopLevelOfType(MetaData root, string? type) /// to tell the two apart). The single object resolver. /// public static MetaData? ResolveObjectRef(MetaData root, string reference, string referrerPkg) => - BindOwner(TopLevelOfType(root, TYPE_OBJECT), reference, referrerPkg); + BindOwner(root, TYPE_OBJECT, reference, referrerPkg); /// /// Resolve a reference that may carry a dotted child tail: bind the owner among the root's @@ -155,7 +176,7 @@ public static (MetaData? Node, MetaData? Owner) ResolveRef( MetaData root, string reference, string referrerPkg, string? ownerType = null, string? lastType = null) { var (owner, tail) = SplitChildTail(reference); - MetaData? bound = BindOwner(TopLevelOfType(root, ownerType), owner, referrerPkg); + MetaData? bound = BindOwner(root, ownerType, owner, referrerPkg); if (bound is null) return (null, null); if (tail.Length == 0) return (bound, bound); string[] path = tail[CHILD_REF_SEPARATOR.Length..].Split(CHILD_REF_SEPARATOR); diff --git a/server/csharp/MetaObjects/Parser.cs b/server/csharp/MetaObjects/Parser.cs index 81c6209374..773fc2bc22 100644 --- a/server/csharp/MetaObjects/Parser.cs +++ b/server/csharp/MetaObjects/Parser.cs @@ -1177,19 +1177,28 @@ private static string OverlayNoTargetMessage(string type, string name) => private static MetaData? FindOverlayTarget( MetaData parent, string type, string name, JsonElement nodeData, string inheritedContextPkg) { - MetaData? existing = name != "" ? parent.OwnChildByTypeAndName(type, name) : null; - if (existing is not null && parent is MetaRoot) + if (parent is MetaRoot) { + if (name == "") return null; + // The first root child of this (type, name) whose resolution key is the candidate's: + // the first same-name hit when its package matches, else the first exact + // package-qualified match (several packages may declare this name). Answered from the + // root's top-level index, which stays correct as this walk appends root children. string candidateKey = RootChildResolutionKey(nodeData, inheritedContextPkg, name); - if (existing.ResolutionKey() != candidateKey) - { - existing = parent.OwnChildren().FirstOrDefault( - c => c.Type == type && c.Name == name && c.ResolutionKey() == candidateKey); - } + return TopLevelIndex.FindByKey(parent, OverlayTargetView, OverlayTargetKey(type, name, candidateKey), + () => parent.OwnChildren().FirstOrDefault( + c => c.Type == type && c.Name == name && c.ResolutionKey() == candidateKey)); } - return existing; + return name != "" ? parent.OwnChildByTypeAndName(type, name) : null; } + /// Root-level overlay targets are keyed by (type, name, resolution key). + private static string OverlayTargetKey(string type, string name, string resolutionKey) => + $"{type}\0{name}\0{resolutionKey}"; + + private static readonly TopLevelView OverlayTargetView = + new("overlay-target", static c => c.Name != "", static c => OverlayTargetKey(c.Type, c.Name, c.ResolutionKey())); + /// The declaration's own address, for the resolved envelope's referrer. private static string OverlayReferrer(PendingOverlay item) => item.Parent is MetaRoot diff --git a/server/csharp/MetaObjects/SuperResolve.cs b/server/csharp/MetaObjects/SuperResolve.cs index 8edda83465..4aac024231 100644 --- a/server/csharp/MetaObjects/SuperResolve.cs +++ b/server/csharp/MetaObjects/SuperResolve.cs @@ -37,11 +37,17 @@ internal static class SuperResolve { // ADR-0039: OwnChildren — super-resolution reads the PHYSICAL declaration layer; the // root has no super, so its own children are its children. - foreach (MetaData child in root.OwnChildren()) - if (child.Name != "" && child.ResolutionKey() == key) return child; - return null; + return TopLevelIndex.FindByKey(root, TopLevelByKeyView, key, () => + { + foreach (MetaData child in root.OwnChildren()) + if (child.Name != "" && child.ResolutionKey() == key) return child; + return null; + }); } + private static readonly TopLevelView TopLevelByKeyView = + new("super-top-level", static c => c.Name != "", static c => c.ResolutionKey()); + // ----------------------------------------------------------------------- // Reference parsing & resolution // ----------------------------------------------------------------------- diff --git a/server/csharp/MetaObjects/TopLevelIndex.cs b/server/csharp/MetaObjects/TopLevelIndex.cs new file mode 100644 index 0000000000..c0b5ab13f4 --- /dev/null +++ b/server/csharp/MetaObjects/TopLevelIndex.cs @@ -0,0 +1,79 @@ +// A per-node lookup index over a root's direct children (the top-level nodes). +// +// Reference resolution, `extends` resolution and overlay targeting all ask "which top-level node +// has this key?" once per reference. Answering by scanning the child list and building each +// candidate's key is O(N) per question and O(N^2) per model; this answers from a dictionary. +// +// Semantics are those of the scans it replaces: the FIRST match in child order wins. +// +// Never stale. An index is valid for one StructureEpoch of the root (MetaData.cs), which every +// non-append change to the child list and every change to a package feeding a resolution key +// bumps. A pure append is picked up by scanning only the new tail (the first match still wins, +// since later children only add keys), so a loop that interleaves adds and lookups stays linear. +// Only a parentless node without a super is indexed (a loader root); anything else takes the +// original scan. A frozen tree is shared across threads, so the build and the read are locked. + +using MetaObjects.Meta; + +namespace MetaObjects; + +/// What a lookup indexes: which children count and how a child is keyed. +internal sealed class TopLevelView(string id, Func includes, Func keyOf) +{ + public string Id { get; } = id; + public Func Includes { get; } = includes; + public Func KeyOf { get; } = keyOf; +} + +/// The indexes built over one node's children, by view id. Also the lock for them. +internal sealed class TopLevelIndexes +{ + internal sealed class Index(int epoch) + { + public readonly Dictionary ByKey = new(); + public int Scanned; + public int Epoch = epoch; + } + + public readonly Dictionary ByView = new(); +} + +internal static class TopLevelIndex +{ + // Per thread, so tests that load models in parallel cannot disturb each other's count. + [ThreadStatic] private static int _rebuilds; + + /// Observable for tests: how many indexes this thread (re)built from scratch. + internal static int Rebuilds => _rebuilds; + + /// + /// The first child of that includes whose key is + /// , in child order. is the original scan, used + /// when is not indexable. + /// + internal static MetaData? FindByKey(MetaData root, TopLevelView view, string key, Func linear) + { + if (root.Parent is not null || root.SuperData is not null) return linear(); + + TopLevelIndexes holder = root.GetTopLevelIndexes(); + lock (holder) + { + if (!holder.ByView.TryGetValue(view.Id, out var index) + || index.Epoch != root.StructureEpoch + || index.Scanned > root.OwnChildCount) + { + index = new TopLevelIndexes.Index(root.StructureEpoch); + holder.ByView[view.Id] = index; + _rebuilds++; + } + int count = root.OwnChildCount; + for (int i = index.Scanned; i < count; i++) + { + MetaData child = root.OwnChildAt(i); + if (view.Includes(child)) index.ByKey.TryAdd(view.KeyOf(child), child); + } + index.Scanned = count; + return index.ByKey.GetValueOrDefault(key); + } + } +} diff --git a/server/python/src/metaobjects/loader/merge.py b/server/python/src/metaobjects/loader/merge.py index bc761c60dc..5717c33f3c 100644 --- a/server/python/src/metaobjects/loader/merge.py +++ b/server/python/src/metaobjects/loader/merge.py @@ -47,6 +47,7 @@ resolved_source, ) from ..source.semantic_diff import semantic_diff +from ..top_level_index import TopLevelView, find_top_level_by_key def merge_roots( @@ -125,18 +126,43 @@ def _find_merge_match(target: MetaData, sc: MetaData) -> Optional[MetaData]: packages don't disambiguate siblings inside a node. """ is_root = target.parent is None - return next( - ( - c - for c in target.own_children() - if c.type == sc.type - and c.name == sc.name - and (not is_root or _root_child_key(c) == _root_child_key(sc)) - ), - None, + + def scan() -> Optional[MetaData]: + return next( + ( + c + for c in target.own_children() + if c.type == sc.type + and c.name == sc.name + and (not is_root or _root_child_key(c) == _root_child_key(sc)) + ), + None, + ) + + if not is_root: + return scan() + # The first root child of this (type, name) whose package-qualified key is the + # candidate's, answered from the root's top-level index, which stays correct as the + # merge appends root children. + return find_top_level_by_key( + target, _MERGE_MATCH_VIEW, _merge_match_key(sc.type, sc.name, _root_child_key(sc)), scan ) +_MERGE_SEP = "\0" + + +def _merge_match_key(type_: str, name: str, root_child_key: str) -> str: + return f"{type_}{_MERGE_SEP}{name}{_MERGE_SEP}{root_child_key}" + + +_MERGE_MATCH_VIEW = TopLevelView( + "merge-match", + lambda c: True, + lambda c: _merge_match_key(c.type, c.name, _root_child_key(c)), +) + + def _merge_child_into( target: MetaData, sc: MetaData, diff --git a/server/python/src/metaobjects/loader/resolve_references.py b/server/python/src/metaobjects/loader/resolve_references.py index f4cc5ca698..64483dde58 100644 --- a/server/python/src/metaobjects/loader/resolve_references.py +++ b/server/python/src/metaobjects/loader/resolve_references.py @@ -27,6 +27,7 @@ REF_BEARING_ATTR_NAMES, RefOverDropError, effective_package_of, + find_named_top_level, owner_candidate_keys, resolve_object_ref, spell_ref, @@ -114,11 +115,8 @@ def _resolve_extends(root: MetaData, node: MetaData) -> None: except RefOverDropError: return # an over-drop never resolved, so super_data would be unset owner_node: Optional[MetaData] = None - # ADR-0039 sanctioned own: extends targets are top-level nodes; the root has no super. for key in keys: - owner_node = next( - (c for c in root.own_children() if c.name != "" and c.resolution_key() == key), None - ) + owner_node = find_named_top_level(root, key) if owner_node is not None: break if owner_node is None: diff --git a/server/python/src/metaobjects/meta/meta_data.py b/server/python/src/metaobjects/meta/meta_data.py index 8ea1e076ca..312d7d9820 100644 --- a/server/python/src/metaobjects/meta/meta_data.py +++ b/server/python/src/metaobjects/meta/meta_data.py @@ -1,7 +1,7 @@ """Abstract node base — Python port of the typed-tree MetaData (ADR-0002).""" from __future__ import annotations -from typing import Callable, Optional, TypeVar, cast +from typing import Any, Callable, Optional, TypeVar, cast from ..attr_class_map import attr_class_for from ..shared.base_types import SUBTYPE_BASE, TYPE_ATTR @@ -12,20 +12,79 @@ T = TypeVar("T") +class _ChildList(list["MetaData"]): + """A node's child list. Every mutation other than an append tells the owner, so the + top-level index (``top_level_index.py``) knows its keys may be stale; an append is + detected by the length instead, which keeps an add-then-lookup loop linear.""" + + __slots__ = ("_owner",) + + def __init__(self, owner: "MetaData") -> None: + super().__init__() + self._owner = owner + + def _changed(self) -> None: + self._owner._structure_epoch += 1 + + def remove(self, value: "MetaData") -> None: + super().remove(value) + self._changed() + + def pop(self, index: int = -1) -> "MetaData": + value = super().pop(index) + self._changed() + return value + + def insert(self, index: int, value: "MetaData") -> None: + super().insert(index, value) + self._changed() + + def clear(self) -> None: + super().clear() + self._changed() + + def sort(self, *args: Any, **kwargs: Any) -> None: + super().sort(*args, **kwargs) + self._changed() + + def reverse(self) -> None: + super().reverse() + self._changed() + + def __setitem__(self, key: Any, value: Any) -> None: + super().__setitem__(key, value) + self._changed() + + def __delitem__(self, key: Any) -> None: + super().__delitem__(key) + self._changed() + + def __iadd__(self, other: Any) -> "_ChildList": + # An append: the length tells the index; no epoch bump needed. + return cast("_ChildList", super().__iadd__(other)) + + def __imul__(self, n: Any) -> "_ChildList": + result = cast("_ChildList", super().__imul__(n)) + self._changed() + return result + + class MetaData: def __init__(self, type_: str, sub_type: str, name: str) -> None: + # Bumped by every change to this node's child list other than an append, and by any + # change to a package that feeds a child's resolution key. The top-level index + # (``top_level_index.py``) is valid only for the epoch it was built at; any NEW way to + # change the child list or a child's key MUST bump it. + self._structure_epoch = 0 + self._parent: Optional[MetaData] = None + self._package: Optional[str] = None + self._file_default_package: Optional[str] = None + # The top-level indexes built over this node's children, by view id. + self._top_level_indexes: Optional[dict[str, Any]] = None + self._child_list: _ChildList = _ChildList(self) self.type = type_ self.sub_type = sub_type self.name = name - self.package: Optional[str] = None - # The file-default package captured at PARSE time (the package declared - # on the owning file's root). Distinct from ``package`` (which an object - # node leaves unset — the parser does not fold the file-default package - # onto an object's own package). Used by super-resolution to match a - # cross-package fully-qualified ``extends`` over the MERGED tree, where - # per-file root packages are no longer reachable via the parent chain. - # Mirrors TS ``MetaData.fileDefaultPackage`` / ``resolutionKey()``. - self.file_default_package: Optional[str] = None # The package declared by this node or its nearest enclosing node in the SAME # document, captured at parse time (None for a node built in code). Unlike the # parse context, an ``overlay: true`` node's explicit package counts, so the @@ -46,9 +105,7 @@ def __init__(self, type_: str, sub_type: str, name: str) -> None: # comparison of the merged trees could make. Mirrors TS `MetaData.isMerge`. self.is_merge = False self.is_array = False - self.parent: Optional[MetaData] = None self._attr_nodes: dict[str, MetaData] = {} # name -> MetaAttr instance - self._children: list[MetaData] = [] self._cache: dict[str, object] = {} self._frozen = False # FR5a / ADR-0009 — provenance envelope. Always populated; defaults @@ -56,6 +113,65 @@ def __init__(self, type_: str, sub_type: str, name: str) -> None: # (parser, merge) overwrite via set_source during the tree walk. self._source: ErrorSource = CodeSource.DEFAULT + # ``package``, ``file_default_package`` and ``parent`` feed a node's resolution key (and its + # parent's index of it), so a write to any of them bumps the structure epoch. + + @property + def package(self) -> Optional[str]: + return self._package + + @package.setter + def package(self, value: Optional[str]) -> None: + self._package = value + self._note_key_change() + + @property + def file_default_package(self) -> Optional[str]: + """The file-default package captured at PARSE time (the package declared on the + owning file's root). Distinct from ``package`` (which an object node leaves unset + — the parser does not fold the file-default package onto an object's own + package). Used by super-resolution to match a cross-package fully-qualified + ``extends`` over the MERGED tree, where per-file root packages are no longer + reachable via the parent chain. Mirrors TS ``MetaData.fileDefaultPackage``.""" + return self._file_default_package + + @file_default_package.setter + def file_default_package(self, value: Optional[str]) -> None: + self._file_default_package = value + self._note_key_change() + + @property + def parent(self) -> Optional["MetaData"]: + return self._parent + + @parent.setter + def parent(self, value: Optional["MetaData"]) -> None: + # Leaving a node's child list is a non-append change there. Joining one is an append + # (``add_child``), which the index detects by length. + old = self._parent + self._parent = value + if old is not None and old is not value: + old._structure_epoch += 1 + + @property + def _children(self) -> list["MetaData"]: + return self._child_list + + @_children.setter + def _children(self, value: list["MetaData"]) -> None: + # Replacing the list wholesale is a structure change; keep it tracked. + self._child_list = _ChildList(self) + self._child_list.extend(value) + self._structure_epoch += 1 + + def _note_key_change(self) -> None: + """A package that feeds a resolution key changed: this node's children (whose keys + may fall through to its package) and its parent's index of it are stale.""" + self._structure_epoch += 1 + parent = self._parent + if parent is not None: + parent._structure_epoch += 1 + @property def frozen(self) -> bool: return self._frozen diff --git a/server/python/src/metaobjects/naming_refs.py b/server/python/src/metaobjects/naming_refs.py index 03500c3709..3b9742c0cd 100644 --- a/server/python/src/metaobjects/naming_refs.py +++ b/server/python/src/metaobjects/naming_refs.py @@ -46,6 +46,7 @@ ) from .shared.base_types import TYPE_OBJECT from .shared.separators import PACKAGE_SEP +from .top_level_index import TopLevelView, find_top_level_by_key if TYPE_CHECKING: from .meta.meta_data import MetaData @@ -179,19 +180,62 @@ def _top_level_of_type(root: "MetaData", type_: Optional[str]) -> list["MetaData return kids if type_ is None else [c for c in kids if c.type == type_] +_REF_VIEWS: dict[Optional[str], TopLevelView] = {} + + +def _ref_view(type_: Optional[str]) -> TopLevelView: + """The per-root lookup view for top-level nodes of *type_* (any type when None), by + resolution key.""" + view = _REF_VIEWS.get(type_) + if view is None: + view = _REF_VIEWS[type_] = TopLevelView( + f"ref:{'*' if type_ is None else type_}", + (lambda c: True) if type_ is None else (lambda c: c.type == type_), + lambda c: c.resolution_key(), + ) + return view + + +def _find_by_key(root: "MetaData", type_: Optional[str], key: str) -> Optional["MetaData"]: + """The first top-level node of *type_* whose resolution key is exactly *key*.""" + + def scan() -> Optional["MetaData"]: + for c in _top_level_of_type(root, type_): + if c.resolution_key() == key: + return c + return None + + return find_top_level_by_key(root, _ref_view(type_), key, scan) + + +_NAMED_TOP_LEVEL_VIEW = TopLevelView("named-top-level", lambda c: c.name != "", lambda c: c.resolution_key()) + + +def find_named_top_level(root: "MetaData", key: str) -> Optional["MetaData"]: + """The first named top-level node (own children; ADR-0039: the root has no super) + whose resolution key is exactly *key*. The scan ``extends`` resolution uses.""" + + def scan() -> Optional["MetaData"]: + # ADR-0039 sanctioned own: extends targets are top-level nodes; the root has no super. + return next((c for c in root.own_children() if c.name != "" and c.resolution_key() == key), None) + + return find_top_level_by_key(root, _NAMED_TOP_LEVEL_VIEW, key, scan) + + def _bind_owner( - candidates: list["MetaData"], owner: str, referrer_pkg: str + root: "MetaData", type_: Optional[str], owner: str, referrer_pkg: str ) -> tuple[Optional["MetaData"], Optional[str]]: - """Bind an owner reference among *candidates* by exact resolution key (R2). - Returns ``(node, error)``: *error* is the over-drop message, else ``None``.""" + """Bind an owner reference among the root's top-level nodes of *type_* by exact + resolution key (R2). Returns ``(node, error)``: *error* is the over-drop message, + else ``None``.""" try: keys = owner_candidate_keys(owner, referrer_pkg) except RefOverDropError as err: return None, str(err) for key in keys: - for c in candidates: - if c.resolution_key() == key: - return c, None + node = _find_by_key(root, type_, key) + if node is not None: + return node, None return None, None @@ -200,7 +244,7 @@ def resolve_object_ref_checked( ) -> tuple[Optional["MetaData"], Optional[str]]: """Resolve a metadata OBJECT reference (no child tail) under ADR-0059 R2. Returns ``(node, error)``; *error* is set for a parent-relative over-drop.""" - return _bind_owner(_top_level_of_type(root, TYPE_OBJECT), ref, referrer_pkg) + return _bind_owner(root, TYPE_OBJECT, ref, referrer_pkg) def resolve_object_ref( @@ -234,7 +278,7 @@ def resolve_ref( effective children; the last is scoped to *last_type* when given. Returns ``(node, owner, error)``.""" owner_ref, tail = split_child_tail(ref) - bound, err = _bind_owner(_top_level_of_type(root, owner_type), owner_ref, referrer_pkg) + bound, err = _bind_owner(root, owner_type, owner_ref, referrer_pkg) if bound is None: return None, None, err if tail == "": diff --git a/server/python/src/metaobjects/top_level_index.py b/server/python/src/metaobjects/top_level_index.py new file mode 100644 index 0000000000..10cbd74d35 --- /dev/null +++ b/server/python/src/metaobjects/top_level_index.py @@ -0,0 +1,71 @@ +"""A per-node lookup index over a root's direct children (the top-level nodes). + +Reference resolution and overlay merging ask "which top-level node has this key?" once per +reference or declaration. Answering by scanning the child list and building each candidate's +key is O(N) per question and O(N^2) per model; this answers from a dict. + +Semantics are those of the scans it replaces: the FIRST match in child order wins. + +Never stale. An index is valid for one ``_structure_epoch`` of the root (``meta_data.py``), +which every non-append change to the child list and every change to a package feeding a +resolution key bumps. A pure append is picked up by scanning only the new tail (the first +match still wins, since later children only add keys), so a loop that interleaves adds and +lookups stays linear. Only a parentless node without a super is indexed (a loader root); +anything else takes the original scan. +""" +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, NamedTuple, Optional + +if TYPE_CHECKING: + from .meta.meta_data import MetaData + + +class TopLevelView(NamedTuple): + """What a lookup indexes: which children count and how a child is keyed.""" + + id: str + includes: Callable[["MetaData"], bool] + key_of: Callable[["MetaData"], str] + + +class _Index: + __slots__ = ("by_key", "scanned", "epoch") + + def __init__(self, epoch: int) -> None: + self.by_key: dict[str, "MetaData"] = {} + self.scanned = 0 + self.epoch = epoch + + +# Observable for tests: how many indexes were (re)built from scratch. +STATS = {"rebuilds": 0} + + +def find_top_level_by_key( + root: "MetaData", + view: TopLevelView, + key: str, + linear: Callable[[], Optional["MetaData"]], +) -> Optional["MetaData"]: + """The first child of *root* that *view* includes whose key is *key*, in child order. + + *linear* is the original scan, used when *root* is not indexable.""" + if root._parent is not None or root.super_data is not None: + return linear() + indexes = root._top_level_indexes + if indexes is None: + indexes = root._top_level_indexes = {} + index = indexes.get(view.id) + children = root._child_list + count = len(children) + if index is None or index.epoch != root._structure_epoch or index.scanned > count: + index = indexes[view.id] = _Index(root._structure_epoch) + STATS["rebuilds"] += 1 + by_key = index.by_key + for i in range(index.scanned, count): + child = children[i] + if view.includes(child): + by_key.setdefault(view.key_of(child), child) + index.scanned = count + return by_key.get(key) diff --git a/server/python/tests/loader/test_top_level_index.py b/server/python/tests/loader/test_top_level_index.py new file mode 100644 index 0000000000..5b1c285a63 --- /dev/null +++ b/server/python/tests/loader/test_top_level_index.py @@ -0,0 +1,203 @@ +"""The per-root top-level index behind reference resolution (``top_level_index.py``). + +Two contracts: + +1. LINEAR. Resolving a reference does not walk every top-level object. Asserted by counting + work (``resolution_key`` calls, index builds), never by wall-clock, over 1x, 5x and 10x + generated models. +2. NEVER STALE. A lookup after the root's top-level nodes changed (a node added, removed or + reordered, a node re-keyed by a package change, a later source merged in) sees the change. +""" +from __future__ import annotations + +from pathlib import Path + +from metaobjects import top_level_index +from metaobjects.loader.meta_data_loader import MetaDataLoader +from metaobjects.loader.sources import InMemoryStringSource +from metaobjects.meta.core.object.meta_object import MetaObject +from metaobjects.meta.meta_data import MetaData +from metaobjects.meta.meta_root import MetaRoot +from metaobjects.naming_refs import resolve_object_ref +from metaobjects.shared.base_types import SUBTYPE_ROOT, TYPE_METADATA, TYPE_OBJECT + +_FITNESS = ( + Path(__file__).parents[4] / "fixtures" / "persistence-conformance" / "canonical" / "meta.fitness.json" +).read_text() + + +def _sources(copies: int) -> list[InMemoryStringSource]: + """*copies* renamed copies of the fitness model, one source each.""" + return [ + InMemoryStringSource( + _FITNESS.replace('"package": "fitness"', f'"package": "fitness_x{i:02d}"', 1), + f"fitness_x{i:02d}.json", + ) + for i in range(copies) + ] + + +def _measure(copies: int, monkeypatch) -> tuple[int, int, int]: + """Load *copies* copies; return (top-level nodes, resolution_key calls, index rebuilds).""" + original = MetaData.resolution_key + calls = 0 + + def counting(self: MetaData) -> str: + nonlocal calls + calls += 1 + return original(self) + + monkeypatch.setattr(MetaData, "resolution_key", counting) + rebuilds_before = top_level_index.STATS["rebuilds"] + result = MetaDataLoader().load(_sources(copies)) + assert result.errors == [] + monkeypatch.undo() + return len(result.root.children()), calls, top_level_index.STATS["rebuilds"] - rebuilds_before + + +def test_resolution_key_calls_per_top_level_node_do_not_grow_with_the_model(monkeypatch) -> None: + n1, c1, _ = _measure(1, monkeypatch) + n5, c5, _ = _measure(5, monkeypatch) + n10, c10, _ = _measure(10, monkeypatch) + per = (c1 / n1, c5 / n5, c10 / n10) + # A scan-per-reference makes this ratio grow with the model (about 10x between 1x and 10x); + # the index keeps it flat. 1.5 leaves room for fixed per-load work. + assert per[1] < per[0] * 1.5 + assert per[2] < per[0] * 1.5 + # And bounded in absolute terms: a handful of key builds per top-level node, not one per + # top-level node per reference. + assert per[2] < 40 + + +def test_index_rebuilds_per_load_do_not_grow_with_the_model(monkeypatch) -> None: + n1, _, r1 = _measure(1, monkeypatch) + n10, _, r10 = _measure(10, monkeypatch) + # Appends are absorbed incrementally, so a rebuild happens only when the root's keys change; + # a load must not rebuild once per top-level node. + assert r10 <= r1 + 2 + assert r10 < n10 / 4 + + +def _root() -> MetaRoot: + return MetaRoot(TYPE_METADATA, SUBTYPE_ROOT, "") + + +def _entity(name: str, package: str | None = None) -> MetaObject: + node = MetaObject(TYPE_OBJECT, "entity", name) + if package is not None: + node.package = package + return node + + +def _resolve(root: MetaRoot, ref: str, referrer_pkg: str = ""): + return resolve_object_ref(root, ref, referrer_pkg) + + +def test_a_node_added_after_a_lookup_is_found_by_the_next_lookup() -> None: + root = _root() + a = _entity("A") + root.add_child(a) + assert _resolve(root, "A") is a + assert _resolve(root, "B") is None + b = _entity("B") + root.add_child(b) + assert _resolve(root, "B") is b + assert _resolve(root, "A") is a + + +def test_first_match_still_wins_when_a_later_node_has_the_same_key() -> None: + root = _root() + first = _entity("Dup") + root.add_child(first) + assert _resolve(root, "Dup") is first + root.add_child(_entity("Dup")) + assert _resolve(root, "Dup") is first + + +def test_a_removed_node_stops_resolving() -> None: + root = _root() + a, b = _entity("A"), _entity("B") + root.add_child(a) + root.add_child(b) + assert _resolve(root, "A") is a + root._children.remove(a) + assert _resolve(root, "A") is None + assert _resolve(root, "B") is b + + +def test_a_removal_then_an_append_keeping_the_length_is_not_missed() -> None: + root = _root() + a = _entity("A") + root.add_child(a) + assert _resolve(root, "A") is a + root._children.remove(a) + c = _entity("C") + root.add_child(c) # same length as when the index was built + assert _resolve(root, "A") is None + assert _resolve(root, "C") is c + + +def test_a_reorder_changes_which_duplicate_wins() -> None: + root = _root() + first, second = _entity("Dup"), _entity("Dup") + root.add_child(first) + root.add_child(second) + assert _resolve(root, "Dup") is first + root._children.reverse() + assert _resolve(root, "Dup") is second + + +def test_replacing_the_child_list_wholesale_is_seen() -> None: + root = _root() + a, b = _entity("A"), _entity("B") + root.add_child(a) + assert _resolve(root, "A") is a + root._children = [b] + assert _resolve(root, "A") is None + assert _resolve(root, "B") is b + + +def test_a_package_change_re_keys_a_top_level_node() -> None: + root = _root() + a = _entity("A", "p") + root.add_child(a) + assert _resolve(root, "p::A") is a + a.package = "q" + assert _resolve(root, "p::A") is None + assert _resolve(root, "q::A") is a + a.package = None + a.file_default_package = "r" + assert _resolve(root, "q::A") is None + assert _resolve(root, "r::A") is a + + +def test_a_change_to_the_roots_package_re_keys_its_package_less_children() -> None: + root = _root() + a = _entity("A") + root.add_child(a) + assert _resolve(root, "A") is a + root.package = "rootpkg" # a package-less child with no file package falls through to it + assert _resolve(root, "A") is None + assert _resolve(root, "rootpkg::A") is a + + +def test_a_bare_reference_falls_back_from_the_referrer_package_to_the_root_level() -> None: + root = _root() + root_level = _entity("Thing") + root.add_child(root_level) + assert _resolve(root, "Thing", "pkg") is root_level + local = _entity("Thing", "pkg") + root.add_child(local) + assert _resolve(root, "Thing", "pkg") is local + local.package = "other" + assert _resolve(root, "Thing", "pkg") is root_level + + +def test_a_source_merged_in_later_contributes_its_objects() -> None: + first, second = _sources(2) + one = MetaDataLoader().load([first]) + assert _resolve(one.root, "fitness_x01::Program") is None + both = MetaDataLoader().load([first, second]) + assert both.errors == [] + assert _resolve(both.root, "fitness_x01::Program") is not None + assert _resolve(both.root, "fitness_x00::Program") is not None diff --git a/server/typescript/packages/metadata/src/naming-refs.ts b/server/typescript/packages/metadata/src/naming-refs.ts index 94b576d4cc..87d4a083e0 100644 --- a/server/typescript/packages/metadata/src/naming-refs.ts +++ b/server/typescript/packages/metadata/src/naming-refs.ts @@ -22,6 +22,7 @@ // loader pass rewrites every reference to it, so consumers read canonical values. import type { MetaData } from "./shared/meta-data.js"; +import { findTopLevelByKey, type TopLevelView } from "./top-level-index.js"; import { PACKAGE_SEPARATOR, PACKAGE_PARENT, CHILD_REF_SEPARATOR } from "./shared/structural.js"; import { TYPE_OBJECT } from "./shared/base-types.js"; import { RELATIONSHIP_ATTR_OBJECT_REF, RELATIONSHIP_ATTR_THROUGH } from "./core/relationship/relationship-constants.js"; @@ -180,9 +181,33 @@ function topLevelOfType(root: MetaData, type: string | undefined): readonly Meta return type === undefined ? all : all.filter((c) => c.type === type); } -/** Bind an owner reference among `candidates` by exact resolution key (R2). */ +/** The per-root lookup view for top-level nodes of `type` (any type when undefined), by resolution key. */ +const refViews = new Map(); +function refView(type: string | undefined): TopLevelView { + const id = `ref:${type ?? "*"}`; + let view = refViews.get(id); + if (view === undefined) { + view = { + id, + includes: (c) => type === undefined || c.type === type, + keyOf: (c) => c.resolutionKey(), + }; + refViews.set(id, view); + } + return view; +} + +/** The first top-level node of `type` whose resolution key is exactly `key`. */ +function findByKey(root: MetaData, type: string | undefined, key: string): MetaData | undefined { + return findTopLevelByKey(root, refView(type), key, () => + topLevelOfType(root, type).find((c) => c.resolutionKey() === key), + ); +} + +/** Bind an owner reference among the root's top-level nodes of `type` by exact resolution key (R2). */ function bindOwner( - candidates: readonly MetaData[], + root: MetaData, + type: string | undefined, owner: string, referrerPkg: string, ): { node?: MetaData | undefined; error?: string | undefined } { @@ -193,7 +218,7 @@ function bindOwner( return { error: (err as Error).message }; } for (const key of keys) { - const node = candidates.find((c) => c.resolutionKey() === key); + const node = findByKey(root, type, key); if (node !== undefined) return { node }; } return {}; @@ -210,7 +235,7 @@ export function resolveObjectRef( ref: string, referrerPkg: string, ): { node?: MetaData | undefined; error?: string | undefined } { - return bindOwner(topLevelOfType(root, TYPE_OBJECT), ref, referrerPkg); + return bindOwner(root, TYPE_OBJECT, ref, referrerPkg); } /** @@ -227,7 +252,7 @@ export function resolveRef( opts?: { ownerType?: string; lastType?: string }, ): { node?: MetaData | undefined; owner?: MetaData | undefined; error?: string | undefined } { const { owner, tail } = splitChildTail(ref); - const bound = bindOwner(topLevelOfType(root, opts?.ownerType), owner, referrerPkg); + const bound = bindOwner(root, opts?.ownerType, owner, referrerPkg); if (bound.node === undefined) return bound; if (tail === "") return { node: bound.node, owner: bound.node }; const path = tail.slice(CHILD_REF_SEPARATOR.length).split(CHILD_REF_SEPARATOR); diff --git a/server/typescript/packages/metadata/src/parser-core.ts b/server/typescript/packages/metadata/src/parser-core.ts index fa9af783cc..8433f75521 100644 --- a/server/typescript/packages/metadata/src/parser-core.ts +++ b/server/typescript/packages/metadata/src/parser-core.ts @@ -40,6 +40,7 @@ import { EXTENDS_TARGET_MISMATCH_RULE, } from "./super-resolve.js"; import { RefOverDropError } from "./naming-refs.js"; +import { findTopLevelByKey, type TopLevelView } from "./top-level-index.js"; import { JsonPathBuilder, type Segment as JsonPathSegment } from "./json-path.js"; import { getYamlPosition, type YamlPosition } from "./core/yaml-positions.js"; import { @@ -1279,19 +1280,31 @@ function findOverlayTarget( nodeData: Record, inheritedContextPkg: string, ): MetaData | undefined { - let existing = name !== "" ? parent.ownChildByTypeAndName(type, name) : undefined; - if (existing !== undefined && parent instanceof MetaRoot) { + if (parent instanceof MetaRoot) { + if (name === "") return undefined; + // The first root child of this (type, name) whose resolution key is the candidate's: + // the first same-name hit when its package matches, else the first exact + // package-qualified match (several packages may declare this name). Answered from the + // root's top-level index, which stays correct as this walk appends root children. const candidateKey = rootChildResolutionKey(nodeData, inheritedContextPkg, name); - if (existing.resolutionKey() !== candidateKey) { - // The first same-name hit is a different package — scan for an exact - // package-qualified match (several packages may declare this name). - existing = parent - .ownChildren() - .find((c) => c.type === type && c.name === name && c.resolutionKey() === candidateKey); - } + return findTopLevelByKey(parent, OVERLAY_TARGET_VIEW, overlayTargetKey(type, name, candidateKey), () => + // ADR-0039: own — an overlay targets the authored layer. + parent.ownChildren().find((c) => c.type === type && c.name === name && c.resolutionKey() === candidateKey), + ); } - return existing; + return name !== "" ? parent.ownChildByTypeAndName(type, name) : undefined; +} + +/** Root-level overlay targets are keyed by (type, name, resolution key). */ +const OVERLAY_TARGET_SEP = "\u0000"; +function overlayTargetKey(type: string, name: string, resolutionKey: string): string { + return `${type}${OVERLAY_TARGET_SEP}${name}${OVERLAY_TARGET_SEP}${resolutionKey}`; } +const OVERLAY_TARGET_VIEW: TopLevelView = { + id: "overlay-target", + includes: (c) => c.name !== "", + keyOf: (c) => overlayTargetKey(c.type, c.name, c.resolutionKey()), +}; /** The one wording for a missing overlay target, shared by the defensive * in-walk path and the deferred pass, so the two cannot drift. */ diff --git a/server/typescript/packages/metadata/src/shared/meta-data.ts b/server/typescript/packages/metadata/src/shared/meta-data.ts index b28c759399..179be29e0e 100644 --- a/server/typescript/packages/metadata/src/shared/meta-data.ts +++ b/server/typescript/packages/metadata/src/shared/meta-data.ts @@ -23,7 +23,16 @@ export abstract class MetaData { readonly name: string; // Identity / packaging - package?: string; + // Accessor, not a bare field: a root child's `package` is part of its resolution key, + // so a write must tell the root its top-level index (top-level-index.ts) is stale. + get package(): string | undefined { + return this._package; + } + set package(pkg: string | undefined) { + this._package = pkg; + this._parent?._noteStructureChange(); + } + private _package: string | undefined = undefined; // Resolution-only: the file-default package (the top-level `metadata.package`) // of the FILE in which this node was declared, captured at PARSE time. This is // NOT folded into fqn() (object fqn() stays BARE for the FR5d cross-port @@ -33,7 +42,14 @@ export abstract class MetaData { // declaring file's package is known) makes resolution independent of load // order and post-merge tree shape. Mirrors Java's BaseMetaDataParser, which // folds getDefaultPackageName() into the registered name at parse time. - fileDefaultPackage?: string; + get fileDefaultPackage(): string | undefined { + return this._fileDefaultPackage; + } + set fileDefaultPackage(pkg: string | undefined) { + this._fileDefaultPackage = pkg; + this._parent?._noteStructureChange(); + } + private _fileDefaultPackage: string | undefined = undefined; superRef?: string; // super reference string; canonical after the loader's resolveReferences pass /** ADR-0059 R5 — the `extends` value exactly as authored, kept when the loader's * `resolveReferences` pass rewrites `superRef` to its canonical spelling. */ @@ -64,6 +80,12 @@ export abstract class MetaData { private _ownValue?: AttrValue; private _ownValueSet = false; private _children: MetaData[] = []; + // Bumped by every change to this node's child list OTHER than an append: a removal, + // a reorder, or a child's resolution key changing (its package or file-default package). + // An append is detected by the child count instead, so interleaved add + lookup stays + // linear. The top-level index (top-level-index.ts) is valid only for the epoch it was + // built at; any new child-list mutation MUST call `_noteStructureChange()`. + private _structureEpoch = 0; private _parent?: MetaData; private _frozen: boolean = false; @@ -421,6 +443,35 @@ export abstract class MetaData { this._children.push(child); } + /** @internal Bump the structure epoch; see `_structureEpoch`. */ + _noteStructureChange(): void { + this._structureEpoch++; + } + + /** @internal The structure epoch of this node's child list; see `_structureEpoch`. */ + get structureEpoch(): number { + return this._structureEpoch; + } + + /** + * @internal True when `children()` and `ownChildren()` are the stock ones, so the physical + * child list IS what they return. A stub or subclass that overrides either (a test double + * substituting a child, say) must be scanned through them, never through the index. + */ + get hasStockChildAccessors(): boolean { + return this.children === MetaData.prototype.children && this.ownChildren === MetaData.prototype.ownChildren; + } + + /** @internal The number of own children, without copying the list. */ + get ownChildCount(): number { + return this._children.length; + } + + /** @internal The own child at `index` (insertion order), without copying the list. */ + ownChildAt(index: number): MetaData | undefined { + return this._children[index]; + } + /** The node this node was added to as a child, or undefined for the tree root. */ get parent(): MetaData | undefined { return this._parent; diff --git a/server/typescript/packages/metadata/src/super-resolve.ts b/server/typescript/packages/metadata/src/super-resolve.ts index 78aa77874a..cb52f51741 100644 --- a/server/typescript/packages/metadata/src/super-resolve.ts +++ b/server/typescript/packages/metadata/src/super-resolve.ts @@ -15,6 +15,7 @@ import type { MetaData } from "./shared/meta-data.js"; import { PACKAGE_SEPARATOR, CHILD_REF_SEPARATOR } from "./shared/structural.js"; import { ownerCandidateKeys, RefOverDropError } from "./naming-refs.js"; +import { findTopLevelByKey, type TopLevelView } from "./top-level-index.js"; import { TYPE_IDENTITY, TYPE_OBJECT } from "./shared/base-types.js"; import { IDENTITY_SUBTYPE_PRIMARY, IDENTITY_UNIQUE_KEY_SUBTYPES } from "./core/identity/identity-constants.js"; @@ -32,9 +33,17 @@ import { IDENTITY_SUBTYPE_PRIMARY, IDENTITY_UNIQUE_KEY_SUBTYPES } from "./core/i function findTopLevel(root: MetaData, key: string): MetaData | undefined { // ADR-0039: own — super-resolution reads the PHYSICAL declaration layer; the root // has no super, so its own children are its children. - return root.ownChildren().find((c) => c.name !== "" && c.resolutionKey() === key); + return findTopLevelByKey(root, TOP_LEVEL_BY_KEY_VIEW, key, () => + root.ownChildren().find((c) => c.name !== "" && c.resolutionKey() === key), + ); } +const TOP_LEVEL_BY_KEY_VIEW: TopLevelView = { + id: "super-top-level", + includes: (c) => c.name !== "", + keyOf: (c) => c.resolutionKey(), +}; + // --------------------------------------------------------------------------- // Reference parsing & resolution // --------------------------------------------------------------------------- diff --git a/server/typescript/packages/metadata/src/top-level-index.ts b/server/typescript/packages/metadata/src/top-level-index.ts new file mode 100644 index 0000000000..2c27d96eaa --- /dev/null +++ b/server/typescript/packages/metadata/src/top-level-index.ts @@ -0,0 +1,75 @@ +// A per-node lookup index over a root's direct children (the top-level nodes). +// +// Reference resolution, `extends` resolution and overlay targeting all ask "which top-level +// node has this key?" once per reference. Answering by scanning the child list and building +// each candidate's key is O(N) per question and O(N²) per model; this answers from a map. +// +// Semantics are those of the scans it replaces: FIRST match in child order wins. +// +// Never stale. The index is valid for one `structureEpoch` of the root (shared/meta-data.ts), +// which every non-append mutation of the child list — and every change to a child's +// resolution key — bumps. A pure append is picked up by scanning only the new tail (first +// match still wins, since later children only add keys), so a loop that interleaves adds and +// lookups stays linear. A root with a super (not a loader root) takes the original scan. + +import type { MetaData } from "./shared/meta-data.js"; + +/** What a lookup indexes: which children count and how a child is keyed. */ +export interface TopLevelView { + /** Stable id: the cache key for this view's index. */ + readonly id: string; + /** Does `child` take part in this view? */ + readonly includes: (child: MetaData) => boolean; + /** The key `child` is looked up by. */ + readonly keyOf: (child: MetaData) => string; +} + +class TopLevelIndex { + readonly byKey = new Map(); + scanned = 0; + epoch: number; + constructor(epoch: number) { + this.epoch = epoch; + } +} + +const indexes = new WeakMap>(); + +/** Observable for tests: how many times an index was (re)built from scratch. */ +export const topLevelIndexStats = { rebuilds: 0, keysComputed: 0 }; + +/** The first child of `root` that `view` includes whose key is `key`, in child order. */ +export function findTopLevelByKey( + root: MetaData, + view: TopLevelView, + key: string, + linear: () => MetaData | undefined, +): MetaData | undefined { + // The index reads the physical child list; that is the effective list only when the + // node has no super (ADR-0039: a loader root has none) and its child accessors are the + // stock ones. Otherwise keep the original scan. + if (root.superData !== undefined || !root.hasStockChildAccessors) return linear(); + + let perRoot = indexes.get(root); + if (perRoot === undefined) { + perRoot = new Map(); + indexes.set(root, perRoot); + } + let index = perRoot.get(view.id); + const epoch = root.structureEpoch; + if (index === undefined || index.epoch !== epoch || index.scanned > root.ownChildCount) { + index = new TopLevelIndex(epoch); + perRoot.set(view.id, index); + topLevelIndexStats.rebuilds++; + } + const count = root.ownChildCount; + for (let i = index.scanned; i < count; i++) { + const child = root.ownChildAt(i) as MetaData; + if (!view.includes(child)) continue; + const k = view.keyOf(child); + topLevelIndexStats.keysComputed++; + if (!index.byKey.has(k)) index.byKey.set(k, child); + } + index.scanned = count; + return index.byKey.get(key); +} diff --git a/server/typescript/packages/metadata/test/top-level-index.test.ts b/server/typescript/packages/metadata/test/top-level-index.test.ts new file mode 100644 index 0000000000..27241c44b0 --- /dev/null +++ b/server/typescript/packages/metadata/test/top-level-index.test.ts @@ -0,0 +1,185 @@ +// The per-root top-level index behind reference resolution (top-level-index.ts). +// +// Two contracts: +// 1. LINEAR. Resolving a reference does not walk every top-level object. Asserted by +// counting work (resolutionKey calls, index builds), never by wall-clock, over 1x, 5x +// and 10x generated models. +// 2. NEVER STALE. A lookup after the root's top-level nodes changed — a node added, a node +// re-keyed by a package change, a later source merged in — sees the change. + +import { describe, expect, test } from "bun:test"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { MetaDataLoader } from "../src/loader/meta-data-loader.js"; +import { InMemoryStringSource } from "../src/loader/meta-data-source.js"; +import { MetaData } from "../src/shared/meta-data.js"; +import { MetaRoot } from "../src/shared/meta-root.js"; +import { resolveObjectRef } from "../src/naming-refs.js"; +import { topLevelIndexStats } from "../src/top-level-index.js"; +import { TYPE_OBJECT } from "../src/shared/base-types.js"; +import { OBJECT_SUBTYPE_ENTITY } from "../src/core/object/object-constants.js"; +import { MetaObject } from "../src/core/object/meta-object.js"; +import { TypeId } from "../src/registry.js"; +import { TYPE_METADATA } from "../src/shared/base-types.js"; + +const metaRoot = (): MetaRoot => new MetaRoot(new TypeId(TYPE_METADATA, "root"), ""); +const metaObject = (subType: string, name: string): MetaObject => new MetaObject(new TypeId(TYPE_OBJECT, subType), name); + +function repoRoot(start: string): string { + let dir = start; + while (!(existsSync(join(dir, "fixtures")) && existsSync(join(dir, "server")))) { + const parent = dirname(dir); + if (parent === dir) throw new Error("repo root not found"); + dir = parent; + } + return dir; +} + +const FITNESS = readFileSync( + join(repoRoot(import.meta.dir), "fixtures", "persistence-conformance", "canonical", "meta.fitness.json"), + "utf-8", +); + +/** `copies` renamed copies of the fitness model, one source each. */ +function sources(copies: number): InMemoryStringSource[] { + return Array.from({ length: copies }, (_, i) => { + const pkg = `fitness_x${String(i).padStart(2, "0")}`; + const text = FITNESS.replace('"package": "fitness"', `"package": "${pkg}"`); + return new InMemoryStringSource(text, { id: `${pkg}.json`, format: "json" }); + }); +} + +/** Load `copies` copies, counting every resolutionKey() call and index rebuild. */ +async function measure(copies: number): Promise<{ topLevel: number; keyCalls: number; rebuilds: number }> { + const original = MetaData.prototype.resolutionKey; + let keyCalls = 0; + MetaData.prototype.resolutionKey = function (this: MetaData): string { + keyCalls++; + return original.call(this); + }; + const rebuildsBefore = topLevelIndexStats.rebuilds; + try { + const { root, errors } = await new MetaDataLoader().load(sources(copies)); + expect(errors).toEqual([]); + return { + topLevel: root.children().length, + keyCalls, + rebuilds: topLevelIndexStats.rebuilds - rebuildsBefore, + }; + } finally { + MetaData.prototype.resolutionKey = original; + } +} + +describe("reference lookup stays linear in the number of top-level nodes", () => { + test("resolutionKey calls per top-level node do not grow with the model", async () => { + const m1 = await measure(1); + const m5 = await measure(5); + const m10 = await measure(10); + const perNode = (m: { topLevel: number; keyCalls: number }): number => m.keyCalls / m.topLevel; + + // A scan-per-reference makes this ratio grow with the model (about 10x between 1x and + // 10x); the index keeps it flat. 1.5 leaves room for fixed per-load work. + expect(perNode(m5)).toBeLessThan(perNode(m1) * 1.5); + expect(perNode(m10)).toBeLessThan(perNode(m1) * 1.5); + // And bounded in absolute terms: a handful of key builds per top-level node (each node is + // keyed once into each index it belongs to, plus a few direct reads), not one per + // top-level node per reference. + expect(perNode(m10)).toBeLessThan(40); + }); + + test("index rebuilds per load do not grow with the model", async () => { + const m1 = await measure(1); + const m10 = await measure(10); + // Appends are absorbed incrementally, so a rebuild happens only when the root's keys + // change; a load must not rebuild once per top-level node. + expect(m10.rebuilds).toBeLessThanOrEqual(m1.rebuilds + 2); + expect(m10.rebuilds).toBeLessThan(m10.topLevel / 4); + }); +}); + +describe("the top-level index is never stale", () => { + const entity = (name: string, pkg?: string) => { + const o = metaObject(OBJECT_SUBTYPE_ENTITY, name); + if (pkg !== undefined) o.setPackage(pkg); + return o; + }; + const resolve = (root: MetaRoot, ref: string, from = "") => resolveObjectRef(root, ref, from).node; + + test("a top-level node added after a lookup is found by the next lookup", () => { + const root = metaRoot(); + const a = entity("A"); + root.addChild(a); + expect(resolve(root, "A")).toBe(a); + expect(resolve(root, "B")).toBeUndefined(); + const b = entity("B"); + root.addChild(b); + expect(resolve(root, "B")).toBe(b); + expect(resolve(root, "A")).toBe(a); + }); + + test("first match still wins when a later node has the same key", () => { + const root = metaRoot(); + const first = entity("Dup"); + root.addChild(first); + expect(resolve(root, "Dup")).toBe(first); + root.addChild(entity("Dup")); + expect(resolve(root, "Dup")).toBe(first); + }); + + test("setPackage on a top-level node re-keys it: the old key stops resolving, the new one starts", () => { + const root = metaRoot(); + const a = entity("A", "p"); + root.addChild(a); + expect(resolve(root, "p::A")).toBe(a); + a.setPackage("q"); + expect(resolve(root, "p::A")).toBeUndefined(); + expect(resolve(root, "q::A")).toBe(a); + }); + + test("a direct write to package or fileDefaultPackage re-keys it too", () => { + const root = metaRoot(); + const a = entity("A", "p"); + root.addChild(a); + expect(resolve(root, "p::A")).toBe(a); + a.package = "q"; + expect(resolve(root, "p::A")).toBeUndefined(); + expect(resolve(root, "q::A")).toBe(a); + a.package = undefined; + a.fileDefaultPackage = "r"; + expect(resolve(root, "q::A")).toBeUndefined(); + expect(resolve(root, "r::A")).toBe(a); + }); + + test("a bare reference falls back from the referrer's package to the root level, after a change", () => { + const root = metaRoot(); + const rootLevel = entity("Thing"); + root.addChild(rootLevel); + expect(resolve(root, "Thing", "pkg")).toBe(rootLevel); + const local = entity("Thing", "pkg"); + root.addChild(local); + expect(resolve(root, "Thing", "pkg")).toBe(local); + local.setPackage("other"); + expect(resolve(root, "Thing", "pkg")).toBe(rootLevel); + }); + + test("a node added to a root with a built index is found by a type-scoped lookup", () => { + const root = metaRoot(); + root.addChild(entity("A")); + expect(resolveObjectRef(root, "A", "").node?.type).toBe(TYPE_OBJECT); + const later = entity("Later"); + root.addChild(later); + expect(resolveObjectRef(root, "Later", "").node).toBe(later); + }); + + test("a source merged in later contributes its objects to references resolved afterwards", async () => { + const [first, second] = sources(2) as [InMemoryStringSource, InMemoryStringSource]; + const loader = new MetaDataLoader(); + const one = await loader.load([first]); + expect(resolveObjectRef(one.root, "fitness_x01::Program", "").node).toBeUndefined(); + const both = await new MetaDataLoader().load([first, second]); + expect(both.errors).toEqual([]); + expect(resolveObjectRef(both.root, "fitness_x01::Program", "").node).toBeDefined(); + expect(resolveObjectRef(both.root, "fitness_x00::Program", "").node).toBeDefined(); + }); +}); From 56b1c75a7c8c821022100c750d6feefd11d8a9b2 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 15:32:33 -0500 Subject: [PATCH 2/4] no-mistakes(review): apply reviewer inline fixes --- server/typescript/packages/metadata/src/top-level-index.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/typescript/packages/metadata/src/top-level-index.ts b/server/typescript/packages/metadata/src/top-level-index.ts index 2c27d96eaa..9fbf6db5c4 100644 --- a/server/typescript/packages/metadata/src/top-level-index.ts +++ b/server/typescript/packages/metadata/src/top-level-index.ts @@ -36,7 +36,7 @@ class TopLevelIndex { const indexes = new WeakMap>(); /** Observable for tests: how many times an index was (re)built from scratch. */ -export const topLevelIndexStats = { rebuilds: 0, keysComputed: 0 }; +export const topLevelIndexStats = { rebuilds: 0 }; /** The first child of `root` that `view` includes whose key is `key`, in child order. */ export function findTopLevelByKey( @@ -67,7 +67,6 @@ export function findTopLevelByKey( const child = root.ownChildAt(i) as MetaData; if (!view.includes(child)) continue; const k = view.keyOf(child); - topLevelIndexStats.keysComputed++; if (!index.byKey.has(k)) index.byKey.set(k, child); } index.scanned = count; From b794fd8ab1724bfcde0b7d20f8d562192610144f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 15:35:17 -0500 Subject: [PATCH 3/4] no-mistakes(review): index C# walk-time merge lookup via FindOverlayTarget --- server/csharp/MetaObjects/Parser.cs | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/server/csharp/MetaObjects/Parser.cs b/server/csharp/MetaObjects/Parser.cs index 773fc2bc22..b758846d0c 100644 --- a/server/csharp/MetaObjects/Parser.cs +++ b/server/csharp/MetaObjects/Parser.cs @@ -1069,27 +1069,10 @@ private static string FormatAttrForMsg(object? v) // Look up an existing child with (type, name). Skip unnamed nodes — // they are always distinct (e.g. inline validators, anonymous attrs). - // - // ROOT-LEVEL lookups are PACKAGE-QUALIFIED: two files declaring the same - // (type, name) under different packages are DISTINCT root nodes, never a - // merge pair (mirrors the Java parser, which searches root children by - // "pkg::name"). Nested children stay bare-name matched — they are scoped - // by their parent, and packages don't disambiguate siblings inside a node. - MetaData? existing = name != "" - ? parent.OwnChildByTypeAndName(type, name) - : null; - if (existing is not null && parent is MetaRoot) - { - string candidateKey = RootChildResolutionKey(nodeData, inheritedContextPkg, name); - if (existing.ResolutionKey() != candidateKey) - { - // The first same-name hit is a different package — scan for an - // exact package-qualified match (several packages may declare - // this name). - existing = parent.OwnChildren().FirstOrDefault( - c => c.Type == type && c.Name == name && c.ResolutionKey() == candidateKey); - } - } + // One lookup shared with overlay targeting, so "which node does this + // declaration merge into" cannot drift between the walk and the + // deferred overlay pass. + MetaData? existing = FindOverlayTarget(parent, type, name, nodeData, inheritedContextPkg); if (isOverlayNode) { From dcd84f97c62c724257ebc237680f2fc632d4122c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 16:16:19 -0500 Subject: [PATCH 4/4] no-mistakes(test): apply changes made during test validation --- client/web/packages/runtime-web/src/meta-read.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/client/web/packages/runtime-web/src/meta-read.ts b/client/web/packages/runtime-web/src/meta-read.ts index ef3476ce4f..cee2147708 100644 --- a/client/web/packages/runtime-web/src/meta-read.ts +++ b/client/web/packages/runtime-web/src/meta-read.ts @@ -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[];