diff --git a/CHANGELOG.md b/CHANGELOG.md index 234265cdc5..8e4b248920 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,9 +39,22 @@ here.** and the crate resolves a project the way the other ports do: the `.metaobjects/config.json` reader, the four source kinds, directory discovery (symlinks followed, `_pending` skipped), the `iam` and `ai` library sources embedded in the crate, and the naming strategies, pluralizers and - collection-name collision check. It passes `yaml-conformance` 15 of 19, and the + collection-name collision check. It passes `yaml-conformance` 18 of 19, and the `source-resolution-conformance` and `naming-conformance` corpora in full. Nothing is published. +- **Cross-port stage benchmark and Rust port documentation.** `scripts/bench-load/stages.py` runs + every port (TypeScript, Python, C#, Java, Kotlin, Rust) over the same model, stage by stage: load + and validate, a no-change generation run, a full generation and a one-entity-edit regeneration, + each as the median of N runs with peak memory, into one `report.json` and one Markdown table. It + never gates on a number. The Rust generation stages read "not available yet" until `cargo meta gen` + exists and are picked up on their own once it does. `--project --out ` runs it on a + private project, copies the metadata, and refuses an output inside the repository. `load_bench` + gained `--dir` and `--json`, `gen-model.py` gained `--unique-names`, and Java has a warm-load + driver. New page `docs/ports/rust.md` says what the preview Rust port does and does not do, how + to build and test it, and the planned `cargo meta` command; the crates.io name `cargo-meta` is + held by an unrelated crate, so the CLI crate will publish under another name that installs a + `cargo-meta` binary (a plan, not a promise). Nothing is published. + ### Changed - **Release policy: vocabulary is versioned by feature, not by kind (ADR-0035 Amendment 5).** Adding diff --git a/README.md b/README.md index fcb9ee9dd4..66574809bc 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ first-week wedge plan — and `meta init` picks up from there. - Already have a codebase? → Have your coding agent run the [fit assessment](#try-it-on-your-repo--nothing-to-install) — read-only, no install; it finds the drift already in your git history. -- New here? Pick your language → [`docs/ports/`](docs/ports/) (TS / Java / Kotlin / C# / Python). +- New here? Pick your language → [`docs/ports/`](docs/ports/) (TS / Java / Kotlin / C# / Python; Rust is in [preview](docs/ports/rust.md)). - Want the metamodel feature reference? → [`docs/features/`](docs/features/). - Want the documentation index? → [`docs/README.md`](docs/README.md). - Want the design rationale? → [`spec/`](spec/) + [`docs/superpowers/specs/`](docs/superpowers/specs/). @@ -169,6 +169,7 @@ first-week wedge plan — and `meta init` picks up from there. | Kotlin | **Maven Central `8.2.0`** — codegen tier on top of Java: 17 generators (entity, Exposed table, names, relations, repository, output-parser, output-prompt, render-helper, extractor, filter-allowlist, validator, Spring config, storedProc, Spring controller, requirement-tests, api-docs, report-export); 24 / 24 persistence-conformance | [`docs/ports/kotlin.md`](docs/ports/kotlin.md) | [`server/java/codegen-kotlin/`](server/java/codegen-kotlin/) · [`server/java/metadata-ktx/`](server/java/metadata-ktx/) | | C# | **NuGet `1.2.0`** — loader + conformance + EF Core codegen + render engine + `dotnet meta` CLI all shipped | [`docs/ports/csharp.md`](docs/ports/csharp.md) | [`server/csharp/`](server/csharp/) | | Python | **PyPI `1.2.0`** — loader + conformance + render + entity-model codegen + ObjectManager runtime shipped; schema migrations are TS-owned (ADR-0015) | [`docs/ports/python.md`](docs/ports/python.md) | [`server/python/`](server/python/) | +| Rust | **Preview, unpublished** — loader (JSON + YAML), project and source resolution, naming and all 40 validation passes; 526 / 526 metamodel conformance. No codegen and no `cargo meta` yet (ADR-0065) | [`docs/ports/rust.md`](docs/ports/rust.md) | [`server/rust/`](server/rust/) | ## Capability matrix diff --git a/docs/README.md b/docs/README.md index 782ad18387..11865d7d73 100644 --- a/docs/README.md +++ b/docs/README.md @@ -57,7 +57,8 @@ docs/ ├── java.md ├── kotlin.md ├── csharp.md - └── python.md + ├── python.md + └── rust.md # the Rust port, in preview: loader and validation only, no codegen yet ``` If this list and `ls docs/features/` ever disagree, trust the directory listing — diff --git a/docs/features/language-differences.md b/docs/features/language-differences.md index 7449425db6..8c57458504 100644 --- a/docs/features/language-differences.md +++ b/docs/features/language-differences.md @@ -78,4 +78,5 @@ here changes in the same pull request. - [CLI architecture](cli.md): which commands each port's own CLI carries. - [Migrations and drift](migrations-and-drift.md): the schema workflow every port uses. - The port pages: [TypeScript](../ports/typescript.md), [C#](../ports/csharp.md), - [Java](../ports/java.md), [Kotlin](../ports/kotlin.md), [Python](../ports/python.md). + [Java](../ports/java.md), [Kotlin](../ports/kotlin.md), [Python](../ports/python.md); the + Rust port is in preview and not in this comparison yet: [Rust](../ports/rust.md). diff --git a/docs/ports/rust.md b/docs/ports/rust.md new file mode 100644 index 0000000000..6cdc43d71e --- /dev/null +++ b/docs/ports/rust.md @@ -0,0 +1,145 @@ +# Rust port (preview) + +The Rust port is **in preview** ([ADR-0065](../../spec/decisions/ADR-0065-rust-is-the-sixth-port.md)). +It reads a project, validates it and serializes it, and it is held to the same shared conformance +corpora as the other five ports. It does not generate code yet, and **nothing is published**: there +is no crate on crates.io, so there is nothing to `cargo add`. You work from a checkout of this +repository. + +This page says what runs today, what does not exist yet, and how to build and test it. For the +decisions behind the port (why Rust, the layout, the preview rules), read the ADR. + +## What works today + +One crate, `metaobjects`, in the Cargo workspace at `server/rust/`: + +| Area | What it does | +|---|---| +| Loading | Reads canonical JSON and sigil-free authoring YAML ([ADR-0006](../../spec/decisions/ADR-0006-ai-first-yaml-authoring.md)): packages, children, subtypes, attributes, `extends` and references, with a line and column on every error from a YAML file. | +| Project resolution | Reads `.metaobjects/config.json` and resolves sources the way every port does: the four source kinds, directory discovery (symlinks followed, `_pending` skipped), and the `iam` and `ai` library sources, which are embedded in the crate so a library resolves with no file on disk. See [Metadata sources](../features/metadata-sources.md). | +| Naming | The naming strategies, the pluralizers and the collection-name collision check ([ADR-0058](../../spec/decisions/ADR-0058-one-physical-naming-setting.md)). | +| Registry | The type registry and the built-in providers. It is strict and sealed after bootstrap, with the same `ERR_*` codes as the other ports. | +| Validation | All 40 validation passes the TypeScript loader runs, in the same order. The ordered list is `PASSES` in `server/rust/metaobjects/src/validate/mod.rs`. | +| Serializer | The canonical serializer. A tree it loads serializes to the same bytes the other ports write. | +| Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | +| Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | + +### Conformance + +The port runs five shared corpora. A fixture that fails and is not on the port's ledger prints a +warning and does not fail the `rust` lane while the port is in preview; a fixture that passed and +regresses still fails it, because each ledger records how many fixtures must pass (`minPassing`) and +may only shrink. + +| Corpus | Rust today | +|---|---| +| `registry-conformance` | byte-identical manifest | +| `conformance` (the metamodel corpus) | **526 of 526**, and the ledger is empty | +| `yaml-conformance` | 18 of 19. The one on the ledger, `yaml-ref-root-escape`, waits for the root-level `::` reference rules of [ADR-0059](../../spec/decisions/ADR-0059-references-resolve-once-after-the-tree.md), which are reference resolution, not a validation pass. | +| `source-resolution-conformance` | all 28 cases | +| `naming-conformance` | all of it | + +Rust is not yet a column in the [per-corpus table](../CONFORMANCE.md#per-corpus-totals); it joins +when the port leaves preview. The other corpora (render, persistence, API contract, codegen compile) +need code the port does not have yet. + +### Load benchmark + +`load_bench` (a Cargo example) times loading a 20-times model built in memory from the public +conformance fitness model, per load phase and per validation pass, with the peak memory of the +process. Its invocations, the baseline options and the committed baseline are documented in +[`scripts/bench-load/README.md`](../../scripts/bench-load/README.md#rust-load_bench). + +[`scripts/bench-load/`](../../scripts/bench-load/README.md) runs this same model through every port, +stage by stage (load and validate, a no-change generation run, a full generation, a one-entity-edit +regeneration, peak memory), so a port's speed can be tracked per feature next to the others. + +## What does not exist yet + +- **Code generation.** There is no Rust generator, no `meta gen` equivalent and no `eject`. The port + loads and checks metadata; it does not write code. +- **The `cargo meta` command.** It is planned, not built. ADR-0065 names it: a Cargo subcommand (a + `cargo-meta` binary), the way the other build-tool-hosted ports spell theirs (`dotnet meta`, + `mvn metaobjects:...`). A bare `meta` stays the Node schema CLI. +- **Drift checks.** There is no `verify` for Rust yet, so nothing compares generated Rust to the model. +- **The service tier.** No `ObjectManager`, no persistence drivers and no web adapters. +- **Templates and prompts.** No render engine, no payload value objects and no output parser. +- **Publication.** The crate sets `publish = false`. There is no crates.io release, no version policy + beyond ADR-0065 (the port starts on its own `0.x` line when it publishes, and joins the lockstep + numbers only when it leaves preview), and `Cargo.toml` is not a stable interface. + +**A note on the name `cargo-meta`.** The crates.io name `cargo-meta` is held by an unrelated crate. The +plan is to publish the CLI crate under another name that installs a `cargo-meta` binary, so the command +you type is still `cargo meta`. That is a plan, not a promise: the crate name is not chosen, and +nothing is reserved. + +The schema stays where it is for every port: migrations and database checks run in the Node `meta` +tool ([ADR-0015](../../spec/decisions/ADR-0015-single-shared-migrate-engine.md); +[What differs by language](../features/language-differences.md)). + +## Build and test + +You need `rustup`. The workspace pins its toolchain in `server/rust/rust-toolchain.toml` (1.94.1, with +`rustfmt` and `clippy`), so `cargo` picks it up on its own. + +```bash +cd server/rust +cargo build +cargo test --locked # the corpora and the unit tests, about a second once built +cargo fmt --all --check +cargo clippy --locked --all-targets -- -D warnings +``` + +The repository's one pre-PR script runs the same steps, plus the `load_bench` table (printed, never +gated on a number): + +```bash +scripts/ci-local.sh --only rust +``` + +A change under `server/rust/` selects the `rust` lane in `scripts/ci-local.sh --affected`, the PR checks +and the local CI. Raise the pinned toolchain deliberately, in its own commit. + +Use the crate from a checkout, as a path dependency: + +```toml +[dependencies] +metaobjects = { path = "/server/rust/metaobjects" } +``` + +```rust +use metaobjects::collection::resolve_collection; +use metaobjects::loader::Loader; +use metaobjects::naming::NamingRegistry; +use metaobjects::providers::default_registry; + +let registry = default_registry()?; +let collection = resolve_collection(project_dir, None, &NamingRegistry::builtin())?; +let (sources, read_errors) = collection.read_sources(); +let result = Loader::new(®istry).load_sources(&sources); +assert!(read_errors.is_empty() && result.errors.is_empty()); +``` + +The API is a preview and will change; read `server/rust/metaobjects/tests/project_load.rs` for a +working call. + +## A worked codegen exercise: `examples/tasks-axi-rust/` + +[`examples/tasks-axi-rust/`](../../examples/tasks-axi-rust/README.md) is the nearest thing to a Rust +code generator today, and it is an experiment, not a product. It reimplements the read path of an +agent-facing task tracker as a small Rust binary and **generates the Rust for its rows, enums, error +codes, argument parser, help text and dispatcher from a MetaObjects model**, with an owned TypeScript +generator (ADR-0034). The real tool is the oracle: for every implemented command and flag the two print +the same bytes and exit with the same code. + +It changes nothing in MetaObjects. Its committed generated crate is the set of golden outputs a +Rust-native generator would have to reproduce, and its README records what the model had to carry. Read +its README, not this page, for what it does and does not do. + +## See also + +- [ADR-0065: Rust is the sixth port](../../spec/decisions/ADR-0065-rust-is-the-sixth-port.md) +- [Conformance coverage](../CONFORMANCE.md): the corpora, and Rust's standing in them. +- [What differs by language](../features/language-differences.md) +- The other port pages: [TypeScript](typescript.md), [C#](csharp.md), [Java](java.md), + [Kotlin](kotlin.md), [Python](python.md). diff --git a/scripts/bench-load/README.md b/scripts/bench-load/README.md index 09259256aa..c7e3ac4304 100644 --- a/scripts/bench-load/README.md +++ b/scripts/bench-load/README.md @@ -1,6 +1,12 @@ -# Warm-load benchmark +# Cross-port benchmarks: load and generation -Measures how long each loader takes to load a model that is N times the size of the +This README owns the usage of every benchmark in this directory and of the Rust `load_bench` +example. Two tools: `run.sh` (warm load across model sizes) and `stages.py` (every stage, every +port). + +## Warm load by model size + +`run.sh` 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). @@ -20,6 +26,55 @@ scripts/bench-load/run.sh [--sizes "1 5 10 20"] [--loads 7] [--ports "typescript - `--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. +## Every port, stage by stage + +``` +python3 scripts/bench-load/stages.py [--runs 5] [--copies 20] [--ports "typescript python csharp java kotlin rust"] + [--out ] +python3 scripts/bench-load/stages.py --project --out [--metadata-dir metaobjects] +``` + +`stages.py` times four stages per port on the same model: `load` (warm load and validate), +`gen-noop` (the generation command with nothing changed), `gen-full` (from clean output) and +`gen-edit` (after one entity gains a field), each the median of `--runs` runs with the peak +resident set. It writes `report.json` and `report.md` to `--out` and never gates on a number. A +stage a port cannot run prints "not available" with the reason: the Rust generation stages read +that way until `cargo meta gen` exists, and run on their own once it does (set +`MO_BENCH_RUST_META` to use a command that is not on `PATH`, `MO_BENCH_RUST_GEN_ARGS` for its +flags). Each port generates with its own CLI and one reference generator, so a generation row +tracks a port against itself over time more than against the others. Java needs the +`metaobjects-*` artifacts of the repo version in the local Maven repository; Kotlin loads +through the Java loader, so it has generation rows only. + +The model is the fitness model repeated `--copies` times with every declaration renamed per copy +(`gen-model.py --unique-names`) so it can be generated as well as loaded. + +`--project` measures your own project: its metadata directory and, when present, its +`.metaobjects/config.json` are copied into scratch (the project is never written to), and `--out` +must be outside this repository. Only the model label is anonymized; failure reasons may quote +commands and errors, so a private run stays local and its report is never committed. The TypeScript +and Java load drivers and the Java/Kotlin generation projects pass no `libraries` option, so a +project using libraries fails those columns. + +## Rust `load_bench` + +The Rust port's load benchmark is a Cargo example, `server/rust/metaobjects/examples/load_bench.rs`. +It loads a 20-times model built in memory from the fitness model, then prints the median time of +each load phase and of each validation pass, and the peak memory of the process. + +``` +cd server/rust +cargo run --release --example load_bench # 20 copies, 15 iterations, JSON +cargo run --release --example load_bench -- 20 15 yaml # the same model as YAML +cargo run --release --example load_bench -- 20 15 project # the project-reading steps +cargo run --release --example load_bench -- --dir --json # a real project, one JSON line +``` + +`--write-baseline ` records a run and `--baseline ` compares against one. A baseline is +a record to read, never a threshold: the committed `server/rust/metaobjects/baselines/load-20x.json` +was recorded on one machine, and a delta between two machines measures the machine. Compare against +a baseline you recorded yourself, before and after a change, on the same machine. + 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/gen-model.py b/scripts/bench-load/gen-model.py index 5fdae15b01..b45b77a253 100755 --- a/scripts/bench-load/gen-model.py +++ b/scripts/bench-load/gen-model.py @@ -3,25 +3,59 @@ 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 +usage: gen-model.py [--unique-names] + +--unique-names also gives every top-level declaration (and every reference to it) a per-copy +suffix, so the copies share no entity name. The load benchmark does not need that, but a +generation run does: two copies of `Program` collide on a collection name, a shared enum and a +relation, and every generator refuses the model. Without the flag the output is unchanged. """ import json import pathlib +import re import sys SRC = pathlib.Path(__file__).resolve().parents[2] / "fixtures/persistence-conformance/canonical/meta.fitness.json" +def top_level_names(doc: dict) -> set[str]: + """The name of every declaration directly under the root.""" + names = set() + for child in doc["metadata.root"]["children"]: + for body in child.values(): + if isinstance(body, dict) and isinstance(body.get("name"), str): + names.add(body["name"]) + return names + + +def rename(node, pattern: re.Pattern, suffix: str): + """Suffix every whole-word occurrence of a top-level name in a string value, so a bare + reference ("Program") and a path into one ("Program.weeks") both follow the rename.""" + if isinstance(node, str): + return pattern.sub(lambda m: m.group(0) + suffix, node) + if isinstance(node, list): + return [rename(x, pattern, suffix) for x in node] + if isinstance(node, dict): + return {k: rename(v, pattern, suffix) for k, v in node.items()} + return node + + def main() -> int: - if len(sys.argv) != 3: + args = [a for a in sys.argv[1:] if a != "--unique-names"] + unique = len(args) != len(sys.argv) - 1 + if len(args) != 2: print(__doc__, file=sys.stderr) return 2 - copies, out = int(sys.argv[1]), pathlib.Path(sys.argv[2]) + copies, out = int(args[0]), pathlib.Path(args[1]) out.mkdir(parents=True, exist_ok=True) text = SRC.read_text() + names = top_level_names(json.loads(text)) if unique else set() + pattern = re.compile(r"\b(" + "|".join(sorted(map(re.escape, names), key=len, reverse=True)) + r")\b") if names else None for i in range(copies): pkg = f"fitness_x{i:02d}" body = text.replace('"package": "fitness"', f'"package": "{pkg}"', 1) + if unique: + body = json.dumps(rename(json.loads(body), pattern, f"X{i:02d}"), indent=2) + "\n" json.loads(body) # fail loudly on a bad rewrite (out / f"meta.{pkg}.json").write_text(body) return 0 diff --git a/scripts/bench-load/java/JavaLoad.java b/scripts/bench-load/java/JavaLoad.java new file mode 100644 index 0000000000..0a2be310a0 --- /dev/null +++ b/scripts/bench-load/java/JavaLoad.java @@ -0,0 +1,45 @@ +// Warm-load driver for the Java loader (the Kotlin facade, metadata-ktx, loads through it). +// usage: java -cp JavaLoad.java +// Prints one JSON line in the shape the other drivers print. +import com.metaobjects.loader.MetaDataLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +public class JavaLoad { + static void load(Path dir) { + MetaDataLoader loader = MetaDataLoader.fromDirectory("bench", dir); + if (!loader.getErrors().isEmpty()) { + throw new IllegalStateException("load errors: " + loader.getErrors().get(0)); + } + } + + // Peak resident set from the kernel's own high-water mark, in MiB (Linux). + static long peakRssMib() throws Exception { + for (String line : Files.readAllLines(Path.of("/proc/self/status"))) { + if (line.startsWith("VmHWM:")) { + return Long.parseLong(line.replaceAll("[^0-9]", "")) / 1024; + } + } + return -1; + } + + public static void main(String[] args) throws Exception { + Path dir = Path.of(args[0]); + int n = Integer.parseInt(args.length > 1 ? args[1] : "7"); + load(dir); // warm-up + List times = new ArrayList<>(); + for (int i = 0; i < n; i++) { + long t0 = System.nanoTime(); + load(dir); + times.add((System.nanoTime() - t0) / 1e6); + } + Collections.sort(times); + System.out.println(String.format(Locale.ROOT, + "{\"port\":\"java\",\"loads\":%d,\"median_ms\":%.1f,\"peak_rss_mib\":%d}", + times.size(), times.get(times.size() / 2), peakRssMib())); + } +} diff --git a/scripts/bench-load/stages.py b/scripts/bench-load/stages.py new file mode 100644 index 0000000000..345168d723 --- /dev/null +++ b/scripts/bench-load/stages.py @@ -0,0 +1,591 @@ +#!/usr/bin/env python3 +"""Cross-port stage benchmark: every MetaObjects port, the same model, stage by stage. + +usage: stages.py [--runs 5] [--ports "typescript python csharp java kotlin rust"] + [--copies 20] [--out ] + [--project [--metadata-dir metaobjects]] + +Stages (each is the median of --runs runs, with the peak resident set of the process): + + load warm load and validate of the model (one untimed warm-up load first) + gen-noop the generation command run again with nothing changed + gen-full the generation command from clean output and clean generation state + gen-edit the generation command after one entity gains one field + +It writes report.json (machine-readable) and report.md (one table) into --out, and never +fails on a number: a delta between two machines measures the machine, so there is no +threshold. A stage a port cannot run is reported as "not available" with the reason (the +Rust generation stages read that way until `cargo meta gen` exists, and are picked up +automatically once it does). + +Default model: the public persistence-conformance fitness model repeated --copies times, with +every declaration renamed per copy so the copies can be generated as well as loaded +(`gen-model.py --unique-names`). It is the same model `run.sh` and `load_bench` use. + +--project runs the same stages on your own project instead. Its metadata directory and, when +present, its .metaobjects/config.json are COPIED into a scratch directory (the project is never +written to) and the report is written to --out, which must be OUTSIDE this repository. Only the +model label is anonymized (counts); failure reasons may quote commands and errors, so a private +run stays local and its report is never committed. The TypeScript and Java load drivers and the +Java/Kotlin generation projects pass no libraries option, so a project using libraries still +fails those columns. + +Generation runs each port's own command with ONE reference generator chosen to exist and work +in that port (typescript: entity + names; python: entity; csharp: entity; java: dto + +value-object; kotlin: entity; rust: whatever `cargo meta gen` is configured with), so a +generation row compares a port with its earlier self and with the other ports' trend, not the +same bytes. Scratch lives under $DEV_SCRATCH (else the system temp dir) and is removed on exit. +""" +from __future__ import annotations + +import argparse +import json +import os +import platform +import re +import shutil +import statistics +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO = HERE.parents[1] +ALL_PORTS = ["typescript", "python", "csharp", "java", "kotlin", "rust"] +STAGES = ["load", "gen-noop", "gen-full", "gen-edit"] + + +class NotAvailable(Exception): + """A stage this port cannot run here, with the reason to print.""" + + +# --------------------------------------------------------------------------- processes + + +def run(cmd, cwd, env=None, check=True): + """Run one command; return (wall seconds, peak RSS KiB of it and its descendants, stdout).""" + with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err: + t0 = time.perf_counter() + p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=out, stderr=err) + _, status, usage = os.wait4(p.pid, 0) + wall = time.perf_counter() - t0 + code = os.waitstatus_to_exitcode(status) + out.seek(0) + err.seek(0) + stdout = out.read().decode(errors="replace") + stderr = err.read().decode(errors="replace") + if check and code != 0: + tail = (stderr or stdout).strip().splitlines()[-3:] + raise RuntimeError(f"`{' '.join(map(str, cmd[:3]))} ...` exited {code}: {' | '.join(tail)[:300]}") + return wall, usage.ru_maxrss, stdout + + +def have(tool): + return shutil.which(tool) is not None + + +def version(cmd): + try: + out = subprocess.run(cmd, capture_output=True, text=True, timeout=20) + return ((out.stdout or out.stderr).strip().splitlines() or [""])[0] + except Exception: # noqa: BLE001 - a missing tool is reported as unknown + return "unknown" + + +# --------------------------------------------------------------------------- the model + + +def copy_model(src: Path, dest: Path) -> None: + """Copy a metadata directory without its dotfiles or build output.""" + shutil.copytree(src, dest, ignore=shutil.ignore_patterns(".*", "node_modules", "target", "bin", "obj")) + + +def install_config(project: Path, model: Path) -> None: + """The one shared prepare step: write a port scratch project's .metaobjects/config.json from + the config the benchmark placed next to the model (the source project's own, rewritten), or + the minimal synthetic config when no project config was copied.""" + src = model.parent / ".metaobjects" / "config.json" + (project / ".metaobjects").mkdir(exist_ok=True) + if src.exists(): + shutil.copy(src, project / ".metaobjects" / "config.json") + else: + (project / ".metaobjects" / "config.json").write_text('{"schema_version": 1}\n') + + +def model_files(model: Path): + return sorted(p for p in model.rglob("*") if p.is_file() and p.suffix in (".json", ".yaml", ".yml")) + + +def apply_edit(model: Path, n: int) -> None: + """Add one field to the first entity of the first JSON file (a different name each time, + so every edit is a real change to the model).""" + for path in model_files(model): + if path.suffix != ".json": + continue + doc = json.loads(path.read_text()) + children = doc.get("metadata.root", {}).get("children", []) + for child in children: + for key, body in child.items(): + if key.startswith("object.entity") and isinstance(body, dict): + body.setdefault("children", []).append({"field.string": {"name": f"benchEdit{n}"}}) + path.write_text(json.dumps(doc, indent=2) + "\n") + return + raise NotAvailable("no JSON file with an object.entity to edit (the edit stage edits JSON only)") + + +# --------------------------------------------------------------------------- ports + + +class Port: + name = "" + clean_dirs: list[str] = [] + + def __init__(self, ctx): + self.ctx = ctx + self.project: Path | None = None + self.gen_error: str | None = None + + # -- load + def load(self, model: Path, runs: int): + raise NotAvailable("no load driver") + + # -- generation + def prepare(self, work: Path, model: Path) -> None: + raise NotAvailable("no generation project") + + def gen_command(self) -> list[str]: + raise NotAvailable("no generation command") + + def gen_env(self): + return None + + def clean(self): + for d in self.clean_dirs + [".metaobjects/.gen-state"]: + shutil.rmtree(self.project / d, ignore_errors=True) + + def gen(self): + return run(self.gen_command(), self.project, self.gen_env()) + + +def drive(cmd, env=None): + """Run a warm-load driver and parse its last JSON line.""" + out = subprocess.run(cmd, capture_output=True, text=True, env=env) + if out.returncode != 0: + raise RuntimeError((out.stderr or out.stdout).strip().splitlines()[-1][:300]) + last = [ln for ln in out.stdout.splitlines() if ln.startswith("{")][-1] + d = json.loads(last) + return d["median_ms"], d["peak_rss_mib"] + + +class TypeScript(Port): + name = "typescript" + clean_dirs = ["src/generated"] + + def _meta(self): + return ["bun", str(REPO / "server/typescript/packages/cli/bin/meta.ts")] + + def load(self, model, runs): + dist = REPO / "server/typescript/packages/metadata/dist" + if not (dist / "index.js").exists(): + raise NotAvailable("the metadata package is not built (bun run --filter '*' build)") + return drive(["node", str(HERE / "ts-load.mjs"), str(model), str(runs)], {**os.environ, "MO_TS_DIST": str(dist)}) + + def prepare(self, work, model): + if not have("bun"): + raise NotAvailable("bun is not installed") + self.project = work / "ts" + self.project.mkdir() + run(self._meta() + ["init", "--no-skills", "--quiet"], self.project) + shutil.rmtree(self.project / "metaobjects", ignore_errors=True) + copy_model(model, self.project / "metaobjects") + install_config(self.project, model) + cfg = self.project / "metaobjects.config.ts" + text = cfg.read_text() + text = text.replace( + 'import { defineConfig } from "@metaobjectsdev/cli";', + 'import { defineConfig } from "@metaobjectsdev/cli";\n' + 'import { entityFile, namesFile } from "@metaobjectsdev/codegen-ts/generators";', + ) + cfg.write_text(text.replace("generators: [],", "generators: [entityFile(), namesFile()],")) + + def gen_command(self): + return self._meta() + ["gen"] + + +class Python(Port): + name = "python" + clean_dirs = ["src/generated"] + + def load(self, model, runs): + return drive(["python3", "-I", str(HERE / "py_load.py"), str(model), str(runs)], + {**os.environ, "MO_PY_SRC": str(REPO / "server/python/src")}) + + def prepare(self, work, model): + self.project = work / "py" + self.project.mkdir() + copy_model(model, self.project / "metaobjects") + install_config(self.project, model) + (self.project / "metaobjects.config.yaml").write_text( + "metadata: metaobjects\ntargets:\n api:\n outDir: src/generated\n generators: [entity]\n") + + def gen_command(self): + src = str(REPO / "server/python/src") + return ["python3", "-I", "-c", + f"import sys; sys.path.insert(0, {src!r}); from metaobjects.cli import main; sys.argv = ['metaobjects', 'gen']; sys.exit(main())"] + + +class CSharp(Port): + name = "csharp" + clean_dirs = ["out"] + + def _cli(self): + dll = self.ctx.work / "cs-cli/MetaObjects.Cli.dll" + if not dll.exists(): + if not have("dotnet"): + raise NotAvailable("dotnet is not installed") + run(["dotnet", "build", str(REPO / "server/csharp/MetaObjects.Cli/MetaObjects.Cli.csproj"), + "-c", "Release", "-o", str(self.ctx.work / "cs-cli"), "-v", "quiet", "-nologo"], REPO) + return dll + + def load(self, model, runs): + if not have("dotnet"): + raise NotAvailable("dotnet is not installed") + drv = self.ctx.work / "cs-load" + if not (drv / "LoadBench.dll").exists(): + drv.mkdir() + shutil.copy(HERE / "csharp/LoadBench.csproj", drv) + shutil.copy(HERE / "csharp/Program.cs", drv) + run(["dotnet", "build", "LoadBench.csproj", "-c", "Release", "-o", str(drv / "out"), + f"-p:MetaObjectsProject={REPO / 'server/csharp/MetaObjects/MetaObjects.csproj'}", + "-v", "quiet", "-nologo"], drv) + return drive(["dotnet", str(drv / "out/LoadBench.dll"), str(model), str(runs)]) + + def prepare(self, work, model): + cli = self._cli() + self.project = work / "cs" + self.project.mkdir() + run(["dotnet", str(cli), "init", "--root", str(self.project)], self.project) + copy_model(model, self.project / "metaobjects") + proj = self.project / "codegen/Codegen.csproj" + proj.write_text(re.sub( + r']*/>', + f'', + proj.read_text())) + gens = self.project / "codegen/Generators.cs" + gens.write_text(gens.read_text().replace( + " [\n", " [\n new MetaObjects.Codegen.Generators.EntityGenerator(),\n", 1)) + install_config(self.project, model) + cfg = self.project / ".metaobjects/config.json" + c = json.loads(cfg.read_text()) + c["csharp"] = {"outDir": "out", "namespace": "Bench"} + cfg.write_text(json.dumps(c, indent=2)) + self._dll = cli + + def gen_command(self): + return ["dotnet", str(self._dll), "gen"] + + +class Java(Port): + name = "java" + clean_dirs = ["target"] + artifact = "metaobjects-codegen-spring" + generators = [("com.metaobjects.generator.spring.SpringDtoGenerator", "java"), + ("com.metaobjects.generator.spring.SpringValueObjectGenerator", "java")] + + def _version(self): + m = re.search(r"([^<]+)", (REPO / "server/java/pom.xml").read_text()) + return m.group(1) + + def load(self, model, runs): + if not have("mvn") or not have("java"): + raise NotAvailable("mvn and java are not installed") + v = self._version() + jl = self.ctx.work / "java-load" + if not (jl / "cp.txt").exists(): + jl.mkdir() + (jl / "pom.xml").write_text( + '4.0.0' + 'benchload1' + f'com.metaobjectsmetaobjects-metadata{v}' + '') + try: + run(["mvn", "-o", "-q", "-B", "dependency:build-classpath", f"-Dmdep.outputFile={jl / 'cp.txt'}"], jl) + except RuntimeError as e: + raise NotAvailable(f"metaobjects-metadata {v} is not in the local Maven repository (mvn install): {e}") + cp = (jl / "cp.txt").read_text().strip() + return drive(["java", "-cp", cp, str(HERE / "java/JavaLoad.java"), str(model), str(runs)]) + + def prepare(self, work, model): + if not have("mvn"): + raise NotAvailable("mvn is not installed") + v = self._version() + self.project = work / self.name + self.project.mkdir() + copy_model(model, self.project / "src/main/metaobjects") + install_config(self.project, model) + gens = "".join( + f"{c}${{project.build.directory}}/generated-sources/{d}" + f"" for c, d in self.generators) + (self.project / "pom.xml").write_text( + '4.0.0' + 'benchbench1pom' + 'com.metaobjectsmetaobjects-maven-plugin' + f'{v}com.metaobjects' + f'{self.artifact}{v}' + f'src/main/metaobjects{gens}' + '') + + def gen_command(self): + return ["mvn", "-o", "-q", "-B", "metaobjects:generate"] + + +class Kotlin(Java): + name = "kotlin" + artifact = "metaobjects-codegen-kotlin" + generators = [("com.metaobjects.generator.kotlin.KotlinEntityGenerator", "kotlin")] + + def load(self, model, runs): + raise NotAvailable("loads through the Java loader (metadata-ktx is a facade); see the java column") + + +class Rust(Port): + name = "rust" + clean_dirs = ["generated"] + + def _target(self): + return Path(os.environ.get("DEV_SCRATCH") or tempfile.gettempdir()) / "mo-bench-rust-target" + + def load(self, model, runs): + if not have("cargo"): + raise NotAvailable("cargo is not installed") + env = {**os.environ, "CARGO_TARGET_DIR": str(self._target())} + run(["cargo", "build", "--release", "--example", "load_bench"], REPO / "server/rust", env) + exe = self._target() / "release/examples/load_bench" + meta = model.parent + if not (meta / ".metaobjects/config.json").exists(): + (meta / ".metaobjects").mkdir(exist_ok=True) + (meta / ".metaobjects/config.json").write_text('{"schema_version": 1}\n') + return drive([str(exe), "--dir", str(meta), "--json", "--iterations", str(runs)]) + + def _meta_command(self): + """The `cargo meta` command, if one exists: an installed `cargo-meta`, a built one in + the workspace target directory, or MO_BENCH_RUST_META (a command line).""" + override = os.environ.get("MO_BENCH_RUST_META") + if override: + return override.split() + if have("cargo-meta"): + return ["cargo", "meta"] + for rel in ("target/release/cargo-meta", "target/debug/cargo-meta"): + exe = REPO / "server/rust" / rel + if exe.exists(): + return [str(exe)] + return None + + def prepare(self, work, model): + if self._meta_command() is None: + raise NotAvailable("not available yet: `cargo meta gen` does not exist") + self.project = work / "rs" + self.project.mkdir() + copy_model(model, self.project / "metaobjects") + install_config(self.project, model) + + def gen_command(self): + extra = os.environ.get("MO_BENCH_RUST_GEN_ARGS", "").split() + return self._meta_command() + ["gen"] + extra + + +PORT_CLASSES = {c.name: c for c in (TypeScript, Python, CSharp, Java, Kotlin, Rust)} + + +# --------------------------------------------------------------------------- stages + + +class Ctx: + def __init__(self, work: Path): + self.work = work + + +def cell(median_ms, rss_kib): + return {"status": "ok", "median_ms": round(median_ms, 1), "peak_rss_mib": round(rss_kib / 1024) if rss_kib else None} + + +def measure(fn, runs): + times, rss = [], [] + for _ in range(runs): + wall, kib, _ = fn() + times.append(wall * 1000) + rss.append(kib) + return cell(statistics.median(times), max(rss)) + + +def bench_port(port: Port, work: Path, model: Path, runs: int, log): + result = {} + # load + try: + ms, mib = port.load(model, runs) + result["load"] = {"status": "ok", "median_ms": ms, "peak_rss_mib": mib} + except NotAvailable as e: + result["load"] = {"status": "not available", "reason": str(e)} + except Exception as e: # noqa: BLE001 + result["load"] = {"status": "failed", "reason": str(e)[:300]} + log(f" {port.name} load: {result['load']}") + # generation + try: + port.prepare(work, model) + port.clean() + port.gen() # untimed priming run: builds the generation project, warms caches + stages = {} + stages["gen-noop"] = measure(port.gen, runs) + log(f" {port.name} gen-noop: {stages['gen-noop']}") + + def full(): + port.clean() + return port.gen() + + stages["gen-full"] = measure(full, runs) + log(f" {port.name} gen-full: {stages['gen-full']}") + counter = iter(range(1, 10_000)) + + def edit(): + apply_edit(port.project / port.model_dir(), next(counter)) + return port.gen() + + try: + stages["gen-edit"] = measure(edit, runs) + except NotAvailable as e: + stages["gen-edit"] = {"status": "not available", "reason": str(e)} + log(f" {port.name} gen-edit: {stages['gen-edit']}") + result.update(stages) + except NotAvailable as e: + for s in STAGES[1:]: + result[s] = {"status": "not available", "reason": str(e)} + log(f" {port.name} generation: {e}") + except Exception as e: # noqa: BLE001 + for s in STAGES[1:]: + result[s] = {"status": "failed", "reason": str(e)[:300]} + log(f" {port.name} generation failed: {e}") + return result + + +def model_dir(self): + return "src/main/metaobjects" if isinstance(self, Java) else "metaobjects" + + +Port.model_dir = model_dir + + +def render_md(report) -> str: + ports = report["ports"] + lines = [f"# Cross-port stage benchmark", "", + f"Model: {report['model']['label']}. Each cell is the median of {report['runs']} runs in ms, " + "then the peak resident set in MiB. Record only: no threshold, and a delta between two " + "machines measures the machine.", ""] + lines.append("| stage | " + " | ".join(ports) + " |") + lines.append("|---|" + "---|" * len(ports)) + for stage in STAGES: + row = [] + for p in ports: + c = report["results"][p][stage] + if c["status"] == "ok": + rss = f" / {c['peak_rss_mib']} MiB" if c.get("peak_rss_mib") else "" + row.append(f"{c['median_ms']} ms{rss}") + elif c["status"] == "not available": + row.append("not available") + else: + row.append("failed") + lines.append(f"| {stage} | " + " | ".join(row) + " |") + notes = [(p, s, c["reason"]) for p in ports for s in STAGES + for c in [report["results"][p][s]] if c["status"] != "ok"] + if notes: + lines += ["", "Notes:", ""] + seen = set() + for p, s, reason in notes: + if (p, reason) not in seen: + seen.add((p, reason)) + lines.append(f"- {p} ({s}): {reason}") + e = report["environment"] + lines += ["", f"Machine: {e['os']}, {e['cpus']} CPUs. Tools: " + ", ".join(f"{k} {v}" for k, v in e["tools"].items()) + "."] + return "\n".join(lines) + "\n" + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--runs", type=int, default=5) + ap.add_argument("--ports", default=" ".join(ALL_PORTS)) + ap.add_argument("--copies", type=int, default=20) + ap.add_argument("--out", help="where report.json and report.md are written") + ap.add_argument("--project", help="a project to measure instead of the public fixture (stays local)") + ap.add_argument("--metadata-dir", default="metaobjects", help="the project's metadata directory (default metaobjects)") + args = ap.parse_args() + + ports = args.ports.split() + for p in ports: + if p not in PORT_CLASSES: + ap.error(f"unknown port {p!r}; choose from {' '.join(ALL_PORTS)}") + + scratch = Path(os.environ.get("DEV_SCRATCH") or tempfile.gettempdir()) + out = Path(args.out).resolve() if args.out else scratch / "bench-ports-report" + if args.project: + if not args.out: + ap.error("--project needs --out, outside this repository") + if out == REPO or REPO in out.parents: + ap.error("--out must be outside this repository: a private project's report is never committed") + work = Path(tempfile.mkdtemp(prefix="bench-stages.", dir=scratch)) + try: + # The model, once, in a directory every port copies from. + if args.project: + src = Path(args.project).resolve() / args.metadata_dir + if not src.is_dir(): + ap.error(f"no metadata directory at /{args.metadata_dir}") + model = work / "model/metaobjects" + copy_model(src, model) + src_cfg = src.parent / ".metaobjects" / "config.json" + if src_cfg.exists(): + cfg = json.loads(src_cfg.read_text()) + cfg["sources"] = [{"path": "metaobjects"}] + (model.parent / ".metaobjects").mkdir() + (model.parent / ".metaobjects" / "config.json").write_text(json.dumps(cfg, indent=2) + "\n") + files = model_files(model) + label = f"a private project ({len(files)} metadata files, {sum(f.stat().st_size for f in files) // 1024} KiB)" + else: + model = work / "model/metaobjects" + subprocess.run([sys.executable, str(HERE / "gen-model.py"), str(args.copies), str(model), "--unique-names"], check=True) + label = f"{args.copies} copies of the fitness model (public fixture, per-copy names)" + print(f"model: {label}", file=sys.stderr) + + ctx = Ctx(work) + results = {} + for name in ports: + print(f"{name}:", file=sys.stderr) + results[name] = bench_port(PORT_CLASSES[name](ctx), work, model, args.runs, lambda m: print(m, file=sys.stderr)) + + commit = subprocess.run(["git", "-C", str(REPO), "rev-parse", "--short", "HEAD"], capture_output=True, text=True).stdout.strip() + report = { + "model": {"label": label, "private": bool(args.project)}, + "runs": args.runs, + "ports": ports, + "stages": STAGES, + "results": results, + "environment": { + "os": f"{platform.system()} {platform.release()}", + "cpus": os.cpu_count(), + "commit": commit, + "tools": {"node": version(["node", "--version"]), "bun": version(["bun", "--version"]), + "python": platform.python_version(), "dotnet": version(["dotnet", "--version"]), + "java": version(["java", "-version"]), "rustc": version(["rustc", "--version"])}, + }, + } + out.mkdir(parents=True, exist_ok=True) + (out / "report.json").write_text(json.dumps(report, indent=2) + "\n") + (out / "report.md").write_text(render_md(report)) + print((out / "report.md").read_text()) + print(f"report: {out}/report.json and report.md", file=sys.stderr) + return 1 if any(c["status"] == "failed" for r in results.values() for c in r.values()) else 0 + finally: + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/bench-load/test-stages-project.py b/scripts/bench-load/test-stages-project.py new file mode 100644 index 0000000000..b6148b1338 --- /dev/null +++ b/scripts/bench-load/test-stages-project.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Regression tests for stages.py --project: a project whose .metaobjects/config.json names a +custom metadata directory must still load and generate, and every port's scratch project must +receive the benchmark's copied (rewritten) config. + +Oracle: the --project mode's own contract ("runs the same stages on your own project") — the +rust load stage (whose loader resolves "sources" from the config and hard-errors +ERR_SOURCE_UNRESOLVED on a path that does not exist) and the python port's generation stages +(prepared through install_config) report status "ok". Before the sources rewrite in main(), +the config's "sources" entry pointed at the custom directory, which does not exist in the +scratch copy (the metadata itself is always copied to metaobjects/), so the rust load stage +reported "failed". The python load stage alone cannot catch this: its driver loads the copied +directory directly. The prepare test iterates every registered port so a future port cannot +skip the shared install_config step. Run by hand, like the rest of scripts/bench-load/ (no test +lane reads this directory; see scripts/ci-lane-map.txt). Needs cargo, bun, dotnet and mvn for +the ports it exercises; a port whose toolchain or generator is missing is skipped. + +usage: python3 scripts/bench-load/test-stages-project.py +""" +import importlib.util +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO = HERE.parents[1] +FIXTURE = REPO / "fixtures/conformance/attr-default-polymorphic/input" +CUSTOM_DIR = "model-src" + +_spec = importlib.util.spec_from_file_location("stages", HERE / "stages.py") +stages = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(stages) + +REWRITTEN = {"schema_version": 1, "sources": [{"path": "metaobjects"}], + "naming": {"columns": "literal", "tables": "literal"}} + + +class ProjectModeTest(unittest.TestCase): + def run_stages(self, project: Path, out: Path): + return subprocess.run( + [sys.executable, str(HERE / "stages.py"), "--project", str(project), + "--metadata-dir", CUSTOM_DIR, "--ports", "rust python", "--runs", "1", "--out", str(out)], + capture_output=True, text=True, timeout=1200) + + def setUp(self): + self.scratch = Path(tempfile.mkdtemp(prefix="bench-stages-test.", dir=os.environ.get("DEV_SCRATCH") or None)) + self.project = self.scratch / "proj" + (self.project / CUSTOM_DIR).mkdir(parents=True) + (self.project / ".metaobjects").mkdir() + shutil.copytree(FIXTURE, self.project / CUSTOM_DIR, dirs_exist_ok=True) + (self.project / ".metaobjects/config.json").write_text( + json.dumps({"schema_version": 1, "sources": [{"path": CUSTOM_DIR}]}) + "\n") + + def tearDown(self): + shutil.rmtree(self.scratch, ignore_errors=True) + + def test_custom_metadata_dir_loads_and_generates(self): + out = self.scratch / "out" + r = self.run_stages(self.project, out) + self.assertEqual(r.returncode, 0, r.stderr) + report = json.loads((out / "report.json").read_text()) + self.assertEqual(report["results"]["rust"]["load"]["status"], "ok", + report["results"]["rust"]["load"]) + py = report["results"]["python"] + self.assertEqual(py["load"]["status"], "ok") + for stage in ("gen-noop", "gen-full", "gen-edit"): + self.assertEqual(py[stage]["status"], "ok", py[stage]) + + def test_every_port_prepare_installs_copied_config(self): + work = self.scratch / "prep" + model = work / "model/metaobjects" + shutil.copytree(FIXTURE, model) + (work / "model/.metaobjects").mkdir(parents=True) + (work / "model/.metaobjects/config.json").write_text(json.dumps(REWRITTEN) + "\n") + ctx = stages.Ctx(work) + checked = [] + for name, cls in stages.PORT_CLASSES.items(): + port = cls(ctx) + try: + port.prepare(work, model) + except stages.NotAvailable: + continue + installed = json.loads((port.project / ".metaobjects/config.json").read_text()) + self.assertTrue(all(installed.get(k) == v for k, v in REWRITTEN.items()), + f"{name}: {installed}") + checked.append(name) + self.assertIn("python", checked) + self.assertIn("typescript", checked) + + +if __name__ == "__main__": + unittest.main() diff --git a/server/rust/metaobjects/examples/load_bench.rs b/server/rust/metaobjects/examples/load_bench.rs index 96dc5163b3..a61c1ad4f3 100644 --- a/server/rust/metaobjects/examples/load_bench.rs +++ b/server/rust/metaobjects/examples/load_bench.rs @@ -5,12 +5,15 @@ //! `fitness_x19`), so the copies never collide and every bare reference still //! resolves inside its own copy. Nothing is written to disk. //! -//! Run it in release mode: +//! Run it in release mode. Usage, flags and baselines are documented in +//! `scripts/bench-load/README.md` ("Rust `load_bench`"), which owns them. //! -//! ```text -//! cargo run --release --example load_bench [-- -//! [json|yaml|project] [--baseline ] [--write-baseline ]] -//! ``` +//! `--dir ` loads a real project instead of the built-in model: it resolves the project's +//! sources the way every port does (config, directory walk, file text) and times the whole +//! read plus load, one untimed warm-up first, so the figure is comparable with the other +//! ports' warm-load drivers in `scripts/bench-load/`. `--json` prints one machine-readable +//! line (`port`, `loads`, `median_ms`, `peak_rss_mib`, `nodes`) in the shape those drivers +//! print. //! //! The mode picks what is loaded: `json` (the default) loads the model as JSON; //! `yaml` loads the same model as sigil-free authoring YAML, so the phase table @@ -190,13 +193,63 @@ fn project_rows(sources: &[(String, String)], iterations: usize) { } } +/// Warm-load a project directory: the project read (config, walk, file text) plus the +/// load, as one figure per iteration, after one untimed warm-up. +fn dir_bench(dir: &std::path::Path, iterations: usize, json_line: bool) { + let naming = NamingRegistry::builtin(); + let registry = default_registry().expect("the built-in providers compose"); + let loader = Loader::new(®istry); + let load_once = || { + let collection = resolve_collection(dir, None, &naming).expect("the project resolves"); + let (pairs, errors) = collection.read_sources(); + assert!(errors.is_empty(), "read errors: {:?}", errors.first()); + let result = loader.load_sources(&pairs); + assert!( + result.errors.is_empty(), + "load errors: {:?}", + result.errors.first() + ); + result.tree.len() + }; + let nodes = load_once(); + let mut times = Vec::with_capacity(iterations); + for _ in 0..iterations { + let t = Instant::now(); + std::hint::black_box(load_once()); + times.push(t.elapsed()); + } + let median_ms = (ms(median(times)) * 10.0).round() / 10.0; + let rss_mib = peak_rss_kib().map(|k| (k as f64 / 1024.0).round()); + if json_line { + println!( + "{}", + json!({ "port": "rust", "loads": iterations, "median_ms": median_ms, "peak_rss_mib": rss_mib, "nodes": nodes }) + ); + } else { + println!( + "{nodes} nodes, warm load median of {iterations}: {median_ms} ms, peak {rss_mib:?} MiB" + ); + } +} + fn main() { let mut baseline_path = None; let mut write_path = None; + let mut dir = None; + let mut dir_iterations = 7; + let mut json_line = false; let mut positional = Vec::new(); let mut raw = std::env::args().skip(1); while let Some(a) = raw.next() { match a.as_str() { + "--dir" => dir = Some(raw.next().expect("--dir takes a project directory")), + "--iterations" => { + dir_iterations = raw + .next() + .and_then(|n| n.parse().ok()) + .expect("--iterations takes a number"); + } + "--json" => json_line = true, "--baseline" => baseline_path = Some(raw.next().expect("--baseline takes a file")), "--write-baseline" => { write_path = Some(raw.next().expect("--write-baseline takes a file")); @@ -204,6 +257,10 @@ fn main() { _ => positional.push(a), } } + if let Some(dir) = dir { + dir_bench(std::path::Path::new(&dir), dir_iterations, json_line); + return; + } let mut args = positional.into_iter(); let copies: usize = args .next() diff --git a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md index f11a462679..01f08492c1 100644 --- a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md +++ b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md @@ -2,7 +2,7 @@ ## Status -**Proposed** (2026-11-14). Registers no vocabulary: `metamodelVersion` is unchanged. Adds a sixth +**Accepted** (2026-11-19). Registers no vocabulary: `metamodelVersion` is unchanged. Adds a sixth language port under `server/rust/`, in preview, and a `rust` CI lane. Amends nothing. ## Context