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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,15 @@ here.**
While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a
warning and does not fail the lane; a fixture that passed and regresses still fails it, because
the ledger records how many fixtures must pass. Nothing is published and there is no codegen
or `cargo meta` command yet. A `rust` lane runs `cargo fmt --check`, clippy and the tests in
`scripts/ci-local.sh --only rust`, `pr-ci` and `local-ci`, selected by changes under
`server/rust/`.
or `cargo meta` command yet. Every load records how long each phase and each validation pass
took (`LoadResult::timings`; the `validate` module's ordered pass list is empty on purpose
until those passes land), and `load_bench` prints the per-phase and per-pass medians, with
`--write-baseline` / `--baseline` to record and compare a run — a baseline is a record to
read, never a threshold, and the committed 20x baseline is a machine-local reference. A
`rust` lane runs `cargo fmt --check`, clippy, the tests and the `load_bench` table (record
only, printed without a baseline delta — a cross-machine delta measures the machine, not the
change) in `scripts/ci-local.sh --only rust`, `pr-ci` and `local-ci`, selected by changes
under `server/rust/`.

### Changed

Expand Down
17 changes: 15 additions & 2 deletions scripts/ci-local.sh
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@
# # rust → the Rust port (preview): cargo fmt
# # --check, clippy -D warnings, and its
# # tests, which run the registry and
# # metamodel corpora. No docker half.
# # metamodel corpora, then the load_bench
# # table (record only). No docker half.
# # cube → the cube-model live check: a real Cube
# # (cubejs/cube, pinned) over a private
# # Postgres, both in docker (FR-044). Its
Expand Down Expand Up @@ -826,7 +827,19 @@ gate_conf_rust() {
( cd server/rust \
&& cargo fmt --all --check \
&& cargo clippy --locked --all-targets -q -- -D warnings \
&& cargo test --locked -q -- --nocapture )
&& cargo test --locked -q -- --nocapture \
&& gate_rust_load_bench )
}
# Load time per phase and per validation pass on the 20x fitness model. Record only:
# it prints a table and never fails on a number, so a slowdown is read in the log and
# named by the feature that caused it. No --baseline here: baselines/load-20x.json was
# recorded on one host, and a CI delta against it would measure the machine, not the
# change. Deltas are a same-machine workflow — record your own baseline before a
# feature lands and compare after it, from server/rust:
# cargo run --release --locked --example load_bench -- 20 15 --write-baseline <file>
# cargo run --release --locked --example load_bench -- 20 15 --baseline <file>
gate_rust_load_bench() {
cargo run --release --locked -q --example load_bench -- 20 15
}
gate_conf_kotlin() {
( cd server/java \
Expand Down
17 changes: 17 additions & 0 deletions server/rust/metaobjects/baselines/load-20x.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"note": "Record only: a reference to read, never a threshold. Regenerate with load_bench --write-baseline.",
"model": "20 copies of the fitness model",
"nodes": 7140,
"iterations": 41,
"phases": {
"json parse": 3.136,
"tree build": 8.068,
"merge": 0.502,
"super resolution": 0.138,
"validation": 0.0,
"reference resolution": 2.132,
"freeze": 0.057
},
"passes": {},
"peakRssKiB": 34400
}
153 changes: 151 additions & 2 deletions server/rust/metaobjects/examples/load_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,25 @@
//! Run it in release mode:
//!
//! ```text
//! cargo run --release --example load_bench [-- <copies> <iterations>]
//! cargo run --release --example load_bench [-- <copies> <iterations>
//! [--baseline <file>] [--write-baseline <file>]]
//! ```
//!
//! It prints one table of time per load phase and one of time per validation pass
//! (the median over the iterations), and the peak memory of the process. With
//! `--baseline` each row also shows the baseline's figure and the change; with
//! `--write-baseline` the run is saved in that file's format. A baseline is a record
//! to read: the comparison never fails the run.

use std::time::{Duration, Instant};

use serde_json::{Map, Value, json};

use metaobjects::loader::Loader;
use metaobjects::node::{NodeId, Tree};
use metaobjects::providers::default_registry;
use metaobjects::serializer::canonical_serialize;
use metaobjects::timing::{LoadTimings, ms, render_table};

const FITNESS: &str =
include_str!("../../../../fixtures/persistence-conformance/canonical/meta.fitness.json");
Expand All @@ -39,8 +49,76 @@ fn read_pass(tree: &Tree) -> usize {
n
}

/// The median of each named timing across the iterations, in first-seen order.
fn median_by_name(runs: &[Vec<(String, f64)>]) -> Vec<(String, f64)> {
let mut names: Vec<String> = Vec::new();
for run in runs {
for (n, _) in run {
if !names.contains(n) {
names.push(n.clone());
}
}
}
names
.into_iter()
.map(|n| {
let mut v: Vec<f64> = runs
.iter()
.map(|r| r.iter().find(|(m, _)| *m == n).map_or(0.0, |(_, t)| *t))
.collect();
v.sort_by(f64::total_cmp);
let mid = v[v.len() / 2];
(n, mid)
})
.collect()
}

fn rows(t: &[metaobjects::timing::Timing]) -> Vec<(String, f64)> {
t.iter()
.map(|x| (x.name.to_string(), ms(x.duration)))
.collect()
}

/// The peak resident set of this process in KiB (`VmHWM`), where the OS reports it.
fn peak_rss_kib() -> Option<u64> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
let line = status.lines().find(|l| l.starts_with("VmHWM:"))?;
line.split_whitespace().nth(1)?.parse().ok()
}

fn to_json_rows(rows: &[(String, f64)]) -> Value {
Value::Object(
rows.iter()
.map(|(n, t)| (n.clone(), json!((t * 1000.0).round() / 1000.0)))
.collect::<Map<_, _>>(),
)
}

fn from_json_rows(v: &Value) -> Vec<(String, f64)> {
v.as_object()
.map(|m| {
m.iter()
.filter_map(|(k, v)| Some((k.clone(), v.as_f64()?)))
.collect()
})
.unwrap_or_default()
}

fn main() {
let mut args = std::env::args().skip(1);
let mut baseline_path = None;
let mut write_path = None;
let mut positional = Vec::new();
let mut raw = std::env::args().skip(1);
while let Some(a) = raw.next() {
match a.as_str() {
"--baseline" => baseline_path = Some(raw.next().expect("--baseline takes a file")),
"--write-baseline" => {
write_path = Some(raw.next().expect("--write-baseline takes a file"));
}
_ => positional.push(a),
}
}
let mut args = positional.into_iter();
let copies: usize = args
.next()
.map_or(20, |a| a.parse().expect("copies is a number"));
Expand Down Expand Up @@ -72,6 +150,8 @@ fn main() {
let mut serializes = Vec::with_capacity(iterations);
let mut cold_reads = Vec::with_capacity(iterations);
let mut warm_reads = Vec::with_capacity(iterations);
let mut phase_runs = Vec::with_capacity(iterations);
let mut pass_runs = Vec::with_capacity(iterations);
let mut nodes = 0;
for _ in 0..iterations {
let t = Instant::now();
Expand All @@ -83,6 +163,9 @@ fn main() {
result.errors.first()
);
nodes = result.tree.len();
let timings: &LoadTimings = &result.timings;
phase_runs.push(rows(&timings.phases));
pass_runs.push(rows(&timings.passes));
let t = Instant::now();
std::hint::black_box(read_pass(&result.tree));
cold_reads.push(t.elapsed());
Expand All @@ -103,6 +186,72 @@ fn main() {
"load (parse, merge, extends, references), median of {iterations}: {:?}",
median(loads)
);
let phases = median_by_name(&phase_runs);
let passes = median_by_name(&pass_runs);
let peak = peak_rss_kib();
let baseline: Option<Value> = baseline_path.as_ref().map(|p| {
serde_json::from_str(&std::fs::read_to_string(p).expect("baseline file is readable"))
.expect("baseline file is JSON")
});
println!();
print!(
"{}",
render_table(
"load phase",
&phases,
baseline
.as_ref()
.map(|b| from_json_rows(&b["phases"]))
.as_deref()
)
);
println!();
if passes.is_empty() {
println!("validation passes: none implemented yet");
} else {
print!(
"{}",
render_table(
"validation pass",
&passes,
baseline
.as_ref()
.map(|b| from_json_rows(&b["passes"]))
.as_deref()
)
);
}
println!();
match (
peak,
baseline.as_ref().and_then(|b| b["peakRssKiB"].as_u64()),
) {
(Some(now), Some(was)) => println!(
"peak memory: {} KiB (baseline {was} KiB, {:+.1}%)",
now,
(now as f64 - was as f64) / was as f64 * 100.0
),
(Some(now), None) => println!("peak memory: {now} KiB"),
(None, _) => println!("peak memory: not reported on this OS"),
}
if let Some(path) = write_path {
let doc = json!({
"note": "Record only: a reference to read, never a threshold. Regenerate with load_bench --write-baseline.",
"model": format!("{copies} copies of the fitness model"),
"nodes": nodes,
"iterations": iterations,
"phases": to_json_rows(&phases),
"passes": to_json_rows(&passes),
"peakRssKiB": peak,
});
std::fs::write(
&path,
format!("{}\n", serde_json::to_string_pretty(&doc).unwrap()),
)
.expect("baseline file is writable");
println!("baseline written to {path}");
}
println!();
println!(
"resolved reads of every node (children, attrs, is_array), first pass fills the cache, median of {iterations}: {:?}",
median(cold_reads)
Expand Down
2 changes: 2 additions & 0 deletions server/rust/metaobjects/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub mod providers;
pub mod registry;
pub mod serializer;
pub mod source;
pub mod timing;
pub mod validate;

pub use errors::MetaError;
pub use loader::{LoadResult, Loader};
Expand Down
50 changes: 41 additions & 9 deletions server/rust/metaobjects/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
//! spell every reference canonically.
//!
//! Order of passes, as in every port: parse → merge → super resolution →
//! (validation, a later step of this port) → reference resolution.
//! validation (its passes are registered as the validation features land) →
//! reference resolution.
//!
//! Built for speed from the start: each file is read once and parsed straight into
//! one arena, nothing is written to disk, and the passes walk the tree a fixed
Expand All @@ -21,6 +22,11 @@ use crate::node::{Node, NodeId, PACKAGE_SEP, Tree};
use crate::parser::{SUBTYPE_ROOT, TYPE_METADATA, TYPE_OBJECT, parse_document};
use crate::registry::TypeRegistry;
use crate::source::ErrorSource;
use crate::timing::{
LoadTimings, PHASE_FREEZE, PHASE_JSON, PHASE_MERGE, PHASE_READ, PHASE_REFS, PHASE_SUPERS,
PHASE_TREE,
};
use crate::validate::{self, Ctx, Findings};

/// The extensions a directory load picks up. YAML is a later step of this port;
/// a `.yaml` file is reported rather than silently skipped.
Expand Down Expand Up @@ -53,6 +59,8 @@ pub struct LoadResult {
pub root: NodeId,
pub errors: Vec<MetaError>,
pub warnings: Vec<MetaError>,
/// How long each phase and each validation pass took.
pub timings: LoadTimings,
}

/// Loads metadata against one registry.
Expand Down Expand Up @@ -112,6 +120,8 @@ impl<'r> Loader<'r> {
/// an `Err`; a file that cannot be read is an error in the result, and the
/// other files still load.
pub fn load_dir(&self, dir: &Path) -> std::io::Result<LoadResult> {
let mut timings = LoadTimings::default();
let read_start = std::time::Instant::now();
let files = metadata_files(dir, false)?;
let mut sources = Vec::with_capacity(files.len());
let mut unreadable = Vec::new();
Expand All @@ -126,14 +136,19 @@ impl<'r> Loader<'r> {
)),
}
}
let mut result = self.load_sources(&sources);
timings.add_phase(PHASE_READ, read_start.elapsed());
let mut result = self.load_timed(&sources, timings);
unreadable.append(&mut result.errors);
result.errors = unreadable;
Ok(result)
}

/// Load `(id, text)` pairs, each one JSON document named `id` in errors.
pub fn load_sources(&self, sources: &[(String, String)]) -> LoadResult {
self.load_timed(sources, LoadTimings::default())
}

fn load_timed(&self, sources: &[(String, String)], mut timings: LoadTimings) -> LoadResult {
let mut tree = Tree::new();
let mut errors = Vec::new();
let mut roots = Vec::new();
Expand All @@ -155,14 +170,17 @@ impl<'r> Loader<'r> {
));
continue;
}
let doc: Value = match serde_json::from_str(text) {
let doc: Result<Value, _> = timings.phase(PHASE_JSON, || serde_json::from_str(text));
let doc: Value = match doc {
Ok(v) => v,
Err(e) => {
errors.push(MetaError::at(ERR_MALFORMED_JSON, e.to_string(), envelope));
continue;
}
};
let parsed = parse_document(&doc, self.registry, &mut tree, id);
let parsed = timings.phase(PHASE_TREE, || {
parse_document(&doc, self.registry, &mut tree, id)
});
// An unknown type or subtype drops only that node, so the rest of the
// document is kept; any other parse error drops the document, as the
// TypeScript and Python loaders do.
Expand All @@ -175,24 +193,38 @@ impl<'r> Loader<'r> {
roots.push(root);
}
}
let mut warnings = Vec::new();
let root = if roots.is_empty() {
tree.add(Node::new(TYPE_METADATA, SUBTYPE_ROOT, ""))
} else {
let root = merge_roots(&mut tree, &roots, &mut errors);
let root = timings.phase(PHASE_MERGE, || merge_roots(&mut tree, &roots, &mut errors));
// Neither pass adds, removes or renames a top-level node, so one index serves both.
let top = TopLevel::build(&tree, root);
resolve_supers(&mut tree, root, &top, &mut errors);
resolve_references(&mut tree, root, &top);
timings.phase(PHASE_SUPERS, || {
resolve_supers(&mut tree, root, &top, &mut errors);
});
let mut findings = Findings::default();
let ctx = Ctx {
tree: &tree,
root,
registry: self.registry,
strict: false,
};
validate::run(&ctx, &mut findings, &mut timings);
errors.append(&mut findings.errors);
warnings.append(&mut findings.warnings);
timings.phase(PHASE_REFS, || resolve_references(&mut tree, root, &top));
root
};
// The terminal phase: the tree is complete, so it becomes read-only and its
// resolving reads memoize from here on (the other ports freeze at REGISTERED).
tree.freeze();
timings.phase(PHASE_FREEZE, || tree.freeze());
LoadResult {
tree,
root,
errors,
warnings: Vec::new(),
warnings,
timings,
}
}
}
Expand Down
Loading
Loading