SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 266/509: Profiler: commands, feature evaluation, io; diagnostics.profile; CLI --profile (and 3 more)
jyviko335278e3c70d
diff --git a/Cargo.lock b/Cargo.lockindex 5e7847deec..3793afab48 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4122,6 +4122,7 @@ dependencies = ["solidcraft-derive","solidcraft-geom","solidcraft-kernel",+ "solidcraft-profile","solidcraft-render","solidcraft-sketch","thiserror 2.0.21",@@ -4142,6 +4143,7 @@ dependencies = ["solidcraft-geom","solidcraft-io","solidcraft-kernel",+ "solidcraft-profile","solidcraft-render","solidcraft-sketch","thiserror 2.0.21",@@ -4198,6 +4200,7 @@ dependencies = ["solidcraft-doc","solidcraft-geom","solidcraft-kernel",+ "solidcraft-profile","thiserror 2.0.21","zip",]@@ -4212,6 +4215,7 @@ dependencies = ["serde","serde_json","solidcraft-geom",+ "solidcraft-profile","solidcraft-smlib","solidcraft-step","spade",@@ -4270,6 +4274,7 @@ dependencies = ["log","serde_json","solidcraft-geom",+ "solidcraft-profile","web-time",]@@ -4285,6 +4290,7 @@ name = "solidcraft-step"version = "0.24.0"dependencies = ["solidcraft-geom",+ "solidcraft-profile",][[package]]diff --git a/apps/solidcraft-cli/Cargo.toml b/apps/solidcraft-cli/Cargo.tomlindex 3628d387bb..258dd32f91 100644--- a/apps/solidcraft-cli/Cargo.toml+++ b/apps/solidcraft-cli/Cargo.toml@@ -20,12 +20,15 @@ name = "solvecraft-cli"path = "src/alias.rs"[features]-default = ["raytrace-cpu", "smlib"]+default = ["raytrace-cpu", "smlib", "profile"]bundled-render-library = ["solidcraft-engine/bundled-render-library"]raytrace-cpu = ["solidcraft-engine/raytrace-cpu"]# Link SMLib into the kernel (solidcraft-engine/smlib; needs scripts/fetch-smlib.sh). SMLib is the# only kernel, so without it the command line models nothing.smlib = ["solidcraft-engine/smlib"]+# The profiler, compiled in so any build can say where its time goes (`--profile`,+# SOLIDCRAFT_PROFILE=1); it records nothing until asked.+profile = ["solidcraft-engine/profile"][dependencies]solidcraft-engine = { workspace = true }diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rsindex 1f75f11056..531380d0a1 100644--- a/apps/solidcraft-cli/src/main.rs+++ b/apps/solidcraft-cli/src/main.rs@@ -36,6 +36,7 @@ mod kernel_cases;mod logger;mod oracle;mod preview;+mod profiling;mod recipe;mod render;mod spatial;@@ -58,13 +59,13 @@ struct Command {}/// `run`'s lines in the usage.-const USAGE_RUN: &str = " solidcraft-cli run <script.json|design.solidcraft|part.step> [--in design.solidcraft|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--json-out FILE] [--allow-errors]\n solidcraft-cli run --in <design.solidcraft|part.step> [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n";+const USAGE_RUN: &str = " solidcraft-cli run <script.json|design.solidcraft|part.step> [--in design.solidcraft|part.step] [--out FILE]... [--save FILE] [--quiet] [--results] [--timings] [--profile] [--profile-out trace.json] [--json-out FILE] [--allow-errors]\n solidcraft-cli run --in <design.solidcraft|part.step> [--out FILE]...\n (a timeline feature that fails fails the run and nothing is written; --allow-errors writes anyway)\n (--timings prints {timings: [{index, command, ms}], total_ms} for a script, with --results its results too;\n --profile adds each command's profile: {boolean_ms, tessellate_ms, other_ms}, the kernel's share)\n (--profile also records where the time goes, SMLib's calls, kernel operations, features, commands and import stages,\n and prints the table to stderr: count, total, self time and longest per span; --profile-out FILE writes the spans\n as a Chrome trace for chrome://tracing or ui.perfetto.dev; SOLIDCRAFT_PROFILE=1 does the same for any command)\n";/// `eval`'s lines in the usage.-const USAGE_EVAL: &str = " solidcraft-cli eval <script.json|design.solidcraft|part.step> [--in design.solidcraft|part.step] [--json-out FILE] (alias: inspect)\n solidcraft-cli eval --in <script.json|design.solidcraft|part.step> [--json-out FILE]\n (with both inputs, runs the positional script on --in before measuring; does not automatically save the modified design)\n (--json-out FILE writes the JSON that run (with --results, else the measurement) and eval print to FILE instead of stdout,\n as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark)\n";+const USAGE_EVAL: &str = " solidcraft-cli eval <script.json|design.solidcraft|part.step> [--in design.solidcraft|part.step] [--json-out FILE] [--profile] [--profile-out trace.json] (alias: inspect)\n solidcraft-cli eval --in <script.json|design.solidcraft|part.step> [--json-out FILE]\n (with both inputs, runs the positional script on --in before measuring; does not automatically save the modified design)\n (--json-out FILE writes the JSON that run (with --results, else the measurement) and eval print to FILE instead of stdout,\n as plain UTF-8: a shell's > can re-encode it, e.g. Windows PowerShell adds a byte-order mark)\n (--profile and --profile-out as for run)\n";/// `script`'s lines in the usage.const USAGE_SCRIPT: &str = " solidcraft-cli script <design.solidcraft|script.json> [--out script.json]\n (the design's history as a command script that eval and run replay)\n";/// `bench-open`'s lines in the usage.-const USAGE_BENCH_OPEN: &str = " solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] [--ops script.json]\n (--ops: after opening, run each command of the script and undo it, timing the command, the\n evaluations it caused and the view it leaves: placing and meshing what changed)\n";+const USAGE_BENCH_OPEN: &str = " solidcraft-cli bench-open <design.solidcraft | part.step> [--parse-only] [--save OUT.solidcraft] [--display LEVEL [--edit NAME EXPR]] [--ops script.json] [--profile] [--profile-out trace.json]\n (--profile and --profile-out as for run)\n (--ops: after opening, run each command of the script and undo it, timing the command, the\n evaluations it caused and the view it leaves: placing and meshing what changed)\n";/// `bench-agent`'s lines in the usage.const USAGE_BENCH_AGENT: &str = " solidcraft-cli bench-agent [--scale F] [--save design.solidcraft] [--script-out script.json]\n";/// `bench-assistant`'s lines in the usage.@@ -136,6 +137,19 @@ const COMMANDS: &[Command] = &[fn main() -> ExitCode {let mut args: Vec<String> = std::env::args().skip(1).collect();logger::init(&mut args);+ // `--profile` / `--profile-out` (run, eval, bench-open) or SOLIDCRAFT_PROFILE (any command):+ // record from here, and print the table when the command ends.+ let profiling = match args.first().map(String::as_str) {+ Some("run" | "eval" | "inspect" | "bench-open") => profiling::start(&args[1..]),+ _ => profiling::start(&[]),+ };+ let profiling = match profiling {+ Ok(p) => p,+ Err(e) => {+ eprintln!("error: {e}");+ return ExitCode::FAILURE;+ }+ };let r = match args.first().map(String::as_str) {// Asked-for help is not an error: the command's usage on stdout, exit 0. It is read// before the command runs, so `--help` never starts a run (a fuzz run, a server).@@ -202,6 +216,11 @@ fn main() -> ExitCode {}_ => Err(usage()),};+ // The table also when the command failed: where it spent its time before failing.+ let r = match (r, profiling.map(profiling::Profiling::finish)) {+ (Ok(()), Some(Err(e))) => Err(e),+ (r, _) => r,+ };match r {Ok(()) => ExitCode::SUCCESS,Err(e) => {@@ -314,6 +333,16 @@ fn positional(args: &[String]) -> Option<&String> {None}+/// Is `path` a command script (or a recipe), not a design: JSON that is no saved design.+fn is_script(path: &str) -> bool {+ let Ok(bytes) = solidcraft_engine::io::vfs::read(path, solidcraft_engine::io::MAX_DESIGN_BYTES) else { return false };+ if solidcraft_engine::io::is_design_container(&bytes) {+ return false;+ }+ serde_json::from_slice::<Value>(&bytes)+ .is_ok_and(|v| !v.get("format").and_then(Value::as_str).is_some_and(|f| solidcraft_engine::doc::format::version_of(f).is_some()))+}+/// `--json-out FILE`: where the JSON a command prints goes instead of stdout.fn json_out(args: &[String]) -> Result<Option<&str>, String> {if !args.iter().any(|a| a == "--json-out") {@@ -345,15 +374,23 @@ fn print_json(v: &Value, file: Option<&str>) -> Result<(), String> {fn cmd_run(args: &[String]) -> Result<(), String> {install_renderer();let json_out = json_out(args)?;- known_args("run", args, &["--in", "--out", "--save", "--json-out"], &["--quiet", "--results", "--timings", "--profile", "--allow-errors"], true)?;+ known_args(+ "run",+ args,+ &["--in", "--out", "--save", "--json-out", "--profile-out"],+ &["--quiet", "--results", "--timings", "--profile", "--allow-errors"],+ true,+ )?;let base = flag(args, "--in");let path = positional(args);if path.is_none() && base.is_none() {return Err(usage());}let want_results = args.iter().any(|a| a == "--results");- // `--profile` times each command and splits out its kernel time; it implies `--timings`.- let profile = args.iter().any(|a| a == "--profile");+ // `--profile` records the profiler's spans (the table goes to stderr, `profiling.rs`); for a+ // script it also times each command and splits out its kernel time, implying `--timings`.+ let script = path.is_some_and(|p| is_script(p));+ let profile = script && args.iter().any(|a| a == "--profile" || a == "--profile-out");let timings = profile || args.iter().any(|a| a == "--timings");let (mut s, results) = if want_results || timings {// Collect every command's result or time (scripts only), then process requested files too.@@ -450,7 +487,7 @@ fn timeline_ok(s: &Session) -> Result<(), String> {fn cmd_eval(args: &[String]) -> Result<(), String> {let json_out = json_out(args)?;- known_args("eval", args, &["--in", "--json-out"], &[], true)?;+ known_args("eval", args, &["--in", "--json-out", "--profile-out"], &["--profile"], true)?;let mut s = open(flag(args, "--in"), positional(args))?;let m = s.execute("inspect.measure", &json!({})).map_err(|e| e.to_string())?;let d = s.execute("document.inspect", &json!({})).map_err(|e| e.to_string())?;diff --git a/apps/solidcraft-cli/src/profiling.rs b/apps/solidcraft-cli/src/profiling.rsnew file mode 100644index 0000000000..3d0b91245e--- /dev/null+++ b/apps/solidcraft-cli/src/profiling.rs@@ -0,0 +1,50 @@+//! `--profile` and `--profile-out FILE` for `run`, `eval` and `bench-open` (and+//! `SOLIDCRAFT_PROFILE=1` for any command): record where the time goes, SMLib's calls to the+//! commands, print the table to stderr when the command ends (stdout stays the command's JSON)+//! and write the spans as a Chrome trace for chrome://tracing or Perfetto.++use solidcraft_engine::profile;++/// Rows the table prints.+const TOP: usize = 30;++/// A recording that prints its table when finished.+pub struct Profiling {+ trace: Option<String>,+}++/// Start recording when `args` (after the command) ask for it, or `SOLIDCRAFT_PROFILE` does.+pub fn start(args: &[String]) -> Result<Option<Profiling>, String> {+ let trace = match args.iter().position(|a| a == "--profile-out") {+ Some(i) => match args.get(i + 1) {+ Some(f) if !f.starts_with("--") => Some(f.clone()),+ _ => return Err("--profile-out needs a FILE".into()),+ },+ None => None,+ };+ let asked = trace.is_some() || args.iter().any(|a| a == "--profile");+ if !asked && !solidcraft_engine::timing::profile_from_env() {+ return Ok(None);+ }+ if !profile::COMPILED {+ return Err("this solidcraft-cli was built without the profiler (its `profile` feature)".into());+ }+ profile::reset();+ profile::set_enabled(true);+ Ok(Some(Profiling { trace }))+}++impl Profiling {+ /// Stop recording, print the table on stderr and write the trace.+ pub fn finish(self) -> Result<(), String> {+ profile::set_enabled(false);+ eprint!("{}", profile::report().table(TOP));+ if let Some(path) = self.trace {+ let mut bytes = Vec::new();+ profile::write_chrome_trace(&mut bytes).map_err(|e| format!("{path}: {e}"))?;+ std::fs::write(&path, bytes).map_err(|e| format!("{path}: {e}"))?;+ eprintln!("profile: trace written to {path} (open it in chrome://tracing or ui.perfetto.dev)");+ }+ Ok(())+ }+}diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.tomlindex 26782cb0e4..8faba6f93e 100644--- a/apps/solidcraft-web/Cargo.toml+++ b/apps/solidcraft-web/Cargo.toml@@ -14,12 +14,15 @@ name = "solidcraft-web"path = "src/main.rs"[features]-default = ["smlib"]+default = ["smlib", "profile"]bundled-render-library = ["solidcraft-engine/bundled-render-library"]# Link SMLib into the kernel (solidcraft-engine/smlib; needs scripts/fetch-smlib.sh# wasm32-unknown-unknown, or the sources and wasi-sdk in WASI_SDK_PATH, crates/smlib/build.rs). SMLib# is the only kernel, so without it the web app models nothing.smlib = ["solidcraft-engine/smlib"]+# The profiler, compiled in so any build can say where its time goes (the Profile operations+# preference, SOLIDCRAFT_PROFILE=1, diagnostics.profile); it records nothing until asked.+profile = ["solidcraft-engine/profile"][dependencies]solidcraft-engine = { workspace = true }diff --git a/apps/solidcraft/Cargo.toml b/apps/solidcraft/Cargo.tomlindex 8ffa40e897..6b1bd96c90 100644--- a/apps/solidcraft/Cargo.toml+++ b/apps/solidcraft/Cargo.toml@@ -8,12 +8,15 @@ publish = falsedefault-run = "solidcraft"[features]-default = ["raytrace-cpu", "bundled-render-library", "smlib"]+default = ["raytrace-cpu", "bundled-render-library", "smlib", "profile"]bundled-render-library = ["solidcraft-engine/bundled-render-library"]raytrace-cpu = ["solidcraft-engine/raytrace-cpu"]# Link SMLib into the kernel (solidcraft-engine/smlib; needs scripts/fetch-smlib.sh). SMLib is the# only kernel, so without it the app models nothing.smlib = ["solidcraft-engine/smlib"]+# The profiler, compiled in so any build can say where its time goes (the Profile operations+# preference, SOLIDCRAFT_PROFILE=1, diagnostics.profile); it records nothing until asked.+profile = ["solidcraft-engine/profile"]# The workspace lints, except unsafe_code: denied, not forbidden, so that src/open_documents.rs# (macOS file-open events), src/native_crash.rs (Windows exception filter), src/native_crash_macos.rsdiff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rsindex ba5e4c0042..c62c0cae3a 100644--- a/apps/solidcraft/src/main.rs+++ b/apps/solidcraft/src/main.rs@@ -679,6 +679,8 @@ fn main() -> eframe::Result {#[cfg(target_os = "macos")]objc2_foundation::NSProcessInfo::processInfo().setProcessName(objc2_foundation::ns_string!("SolidCraft"));mark("main");+ // SOLIDCRAFT_PROFILE=1: the profiler records from the start (diagnostics.profile reads it).+ solidcraft_engine::timing::profile_from_env();// Validate before legacy adoption, crash markers or any user preference read.let settings = settings_dir().map_err(|error| eframe::Error::AppCreation(error.into()))?;if std::env::var_os("SOLIDCRAFT_SETTINGS_DIR").is_none() {diff --git a/assets/locales/pending/profiler.json b/assets/locales/pending/profiler.jsonnew file mode 100644index 0000000000..772d5ac7a8--- /dev/null+++ b/assets/locales/pending/profiler.json@@ -0,0 +1,37 @@+{+ "en": {+ "cmd.diagnostics_profile": "Profile",+ "prefs.profile_operations": "Profile operations",+ "prefs.profile_operations_note": "Records how long SMLib calls, kernel operations, features, commands and imports take. Agents read it with diagnostics.profile."+ },+ "ar": {+ "cmd.diagnostics_profile": "التحليل الزمني",+ "prefs.profile_operations": "تحليل زمن العمليات",+ "prefs.profile_operations_note": "يسجّل المدة التي تستغرقها استدعاءات SMLib وعمليات النواة والميزات والأوامر وعمليات الاستيراد. يقرؤه الوكلاء عبر diagnostics.profile."+ },+ "de": {+ "cmd.diagnostics_profile": "Profil",+ "prefs.profile_operations": "Vorgänge profilieren",+ "prefs.profile_operations_note": "Zeichnet auf, wie lange SMLib-Aufrufe, Kernel-Vorgänge, Features, Befehle und Importe dauern. Agenten lesen es mit diagnostics.profile."+ },+ "he": {+ "cmd.diagnostics_profile": "פרופיל ביצועים",+ "prefs.profile_operations": "מדידת זמני פעולות",+ "prefs.profile_operations_note": "מתעד כמה זמן לוקחות קריאות SMLib, פעולות ליבה, תכונות, פקודות וייבוא. סוכנים קוראים זאת עם diagnostics.profile."+ },+ "ja": {+ "cmd.diagnostics_profile": "プロファイル",+ "prefs.profile_operations": "処理をプロファイル",+ "prefs.profile_operations_note": "SMLib の呼び出し、カーネル処理、フィーチャー、コマンド、インポートにかかる時間を記録します。エージェントは diagnostics.profile で読み取ります。"+ },+ "ko": {+ "cmd.diagnostics_profile": "프로파일",+ "prefs.profile_operations": "작업 프로파일링",+ "prefs.profile_operations_note": "SMLib 호출, 커널 작업, 피처, 명령, 가져오기에 걸리는 시간을 기록합니다. 에이전트는 diagnostics.profile로 읽습니다."+ },+ "zh": {+ "cmd.diagnostics_profile": "性能分析",+ "prefs.profile_operations": "分析操作耗时",+ "prefs.profile_operations_note": "记录 SMLib 调用、内核操作、特征、命令和导入所用的时间。智能体通过 diagnostics.profile 读取。"+ }+}diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.tomlindex 8960e0be1c..8093414b36 100644--- a/crates/doc/Cargo.toml+++ b/crates/doc/Cargo.toml@@ -12,6 +12,7 @@ workspace = truesolidcraft-geom = { workspace = true }solidcraft-sketch = { workspace = true }solidcraft-kernel = { workspace = true }+solidcraft-profile = { workspace = true }solidcraft-render = { workspace = true }solidcraft-derive = { workspace = true }serde = { workspace = true }diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex b068e7ea22..29caa08e7a 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -1751,6 +1751,7 @@ impl Model {/// Re-evaluate the document, reusing results up to the first changed feature.pub fn evaluate(&mut self, doc: &Document) {+ let _span = solidcraft_profile::span("doc", "evaluate");let (vals, perr) = evaluation_values(doc);self.param_errors = perr;self.frame_bodies.lock().unwrap_or_else(|e| e.into_inner()).next_generation();@@ -1877,6 +1878,8 @@ impl Model {continue;}recomputed += 1;+ // Each feature computed is a profiler span named after its kind.+ let _feature_span = solidcraft_profile::span("feature", f.kind.type_name());let before = state.clone();let t0 = now();let mut next = (*state).clone();diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.tomlindex cb20407079..61c83fed46 100644--- a/crates/engine/Cargo.toml+++ b/crates/engine/Cargo.toml@@ -19,6 +19,10 @@ smlib = ["solidcraft-kernel/smlib"]# `src/schema/record.rs`), for checking a new contract against the whole test suite.param-audit = []solver-profiling = ["solidcraft-sketch/solver-profiling"]+# Compile the profiler in (solidcraft-profile/enabled): every app turns it on by default, so any+# build can be profiled; it records only once switched on (SOLIDCRAFT_PROFILE=1, the CLI's+# --profile, the app's preference, diagnostics.profile).+profile = ["solidcraft-profile/enabled"][[example]]name = "sketch_analysis_bench"@@ -39,6 +43,7 @@ solidcraft-kernel = { workspace = true }solidcraft-doc = { workspace = true }solidcraft-io = { workspace = true }solidcraft-render = { workspace = true }+solidcraft-profile = { workspace = true }image = { workspace = true, features = ["jpeg"] }serde = { workspace = true }serde_json = { workspace = true }@@ -50,6 +55,7 @@ log = { workspace = true }web-time = { workspace = true }[dev-dependencies]+solidcraft-profile = { workspace = true, features = ["enabled"] }# Model-cache tests also run in a source tarball build (no git commit).solidcraft-io = { workspace = true, features = ["trust-unknown-source"] }# Normal CI exercises profiling assertions without enabling the production feature.diff --git a/crates/engine/src/cmd/diagnostics.rs b/crates/engine/src/cmd/diagnostics.rsindex 25a4756dcc..a918dace80 100644--- a/crates/engine/src/cmd/diagnostics.rs+++ b/crates/engine/src/cmd/diagnostics.rs@@ -1,5 +1,6 @@//! Crash reports, for agents and people (see `crate::crash` and docs/crash-reports.md): list-//! them, read one, delete them. They live on this computer and are never sent anywhere.+//! them, read one, delete them. They live on this computer and are never sent anywhere. And the+//! profiler (`solidcraft_profile`, docs/perf.md): where the time goes, SMLib's calls to commands.use serde_json::{Value, json};@@ -22,6 +23,21 @@ pub static COMMANDS: &[CommandSpec] = &[.icon("delete").noundo().params("id?: one report (default: all). Returns {deleted}"),+ CommandSpec::new("diagnostics.profile", "Profile", crate::checked!("diagnostics.profile", profile))+ .icon("bug_report")+ .noundo()+ .contract(&PROFILE_CONTRACT)+ .output(crate::schema::output_schema_for::<crate::schema::diagnostics::ProfileReport>)+ .params(+ "enabled?: bool (start or stop recording); reset?: bool (forget what was recorded); top?: rows (default 20, 0: all); \+ trace?: path (write the recorded spans as a Chrome trace-event file, for chrome://tracing or Perfetto). Returns what \+ was recorded before enabled and reset apply: {compiled, enabled, wall_ms, spans, dropped, by_category: [{category, \+ self_ms, share}], rows: [{category, name, count, total_ms, self_ms, max_ms}], rows_total, trace?}, the rows the most \+ self time first. Categories: smlib (SMLib's C API calls, timed by the C API), kernel, feature (one per feature \+ computed, by its type), doc, command, import (STEP/IGES stages), io. Self time is a span's time less the spans \+ inside it; total counts its outermost run only. Recording also starts with SOLIDCRAFT_PROFILE=1, the CLI's \+ --profile and the app's preference; off, it costs nothing measurable. Read-only",+ ),CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).icon("bug_report").noundo().enabled(crash_test_enabled).params("mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \@@ -73,3 +89,42 @@ fn crash_test(_: &mut Session, p: &Value) -> Result<Value> {_ => Err(bad(cmd, "`mode` must be panic, kernel or abort")),}}++const PROFILE_CONTRACT: crate::schema::TypedContract<crate::schema::diagnostics::ProfileParams> = crate::schema::TypedContract::new();++/// Rows `diagnostics.profile` returns at most.+const MAX_PROFILE_ROWS: u64 = 10_000;++fn profile(_: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "diagnostics.profile";+ let flag = |key: &str| match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::Bool(b)) => Ok(Some(*b)),+ Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))),+ };+ let (enabled, reset) = (flag("enabled")?, flag("reset")?);+ let top = match p.get("top") {+ None | Some(Value::Null) => 20,+ Some(v) => v.as_u64().ok_or_else(|| bad(cmd, "`top` must be a whole number of rows (0: all)"))?.min(MAX_PROFILE_ROWS) as usize,+ };+ let trace = match p.get("trace") {+ None | Some(Value::Null) => None,+ Some(_) => Some(str_(p, "trace").filter(|t| !t.trim().is_empty() && t.len() < 4096).ok_or_else(|| bad(cmd, "`trace` must be a file path"))?),+ };+ let report = solidcraft_profile::report();+ let mut out = crate::schema::diagnostics::ProfileReport::new(&report, top);+ if let Some(path) = trace {+ let mut bytes = Vec::new();+ solidcraft_profile::write_chrome_trace(&mut bytes).map_err(|e| bad(cmd, format!("trace: {e}")))?;+ solidcraft_io::vfs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ out.trace = Some(path.to_string());+ }+ if reset == Some(true) {+ solidcraft_profile::reset();+ }+ if let Some(on) = enabled {+ solidcraft_profile::set_enabled(on);+ out.enabled = solidcraft_profile::enabled();+ }+ serde_json::to_value(out).map_err(|e| EngineError::Other(format!("{cmd}: {e}")))+}diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rsindex cefc4e7b56..1b7de0a78e 100644--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@ -141,7 +141,12 @@ fn quarter_turn_x() -> solidcraft_doc::Mat {/// Add an Import feature for a STEP file to the session's design, in a new component named/// after the file (#1386).+///+/// While the profiler records, the reply's `profile` is the import's share of it (reading,+/// building the solids in SMLib, placing, meshing and evaluating them), as+/// `diagnostics.profile` reports it.fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptions) -> Result<Value> {+ let profiled = solidcraft_profile::enabled().then(solidcraft_profile::mark);let sf = read_step(path, options.names)?;let fname = name.filter(|n| !n.trim().is_empty()).unwrap_or(&sf.name).to_string();let cname = import::component_name(path, name);@@ -160,6 +165,10 @@ fn add_step(s: &mut Session, path: &str, name: Option<&str>, options: &StepOptioif let Some(turned) = turned {out["stand_up"] = json!(turned);}+ if let Some(mark) = profiled {+ let report = crate::schema::diagnostics::ProfileReport::new(&mark.report(), 20);+ out["profile"] = serde_json::to_value(report).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ }Ok(out)}@@ -835,6 +844,32 @@ mod urdf_tests;mod tests {use super::*;+ /// While the profiler records, a STEP import's reply carries its own profile: the import's+ /// stages and SMLib's calls, as diagnostics.profile reports them.+ #[cfg(feature = "smlib")]+ #[test]+ fn a_step_import_reports_its_profile_while_the_profiler_records() {+ let _serial = crate::schema::diagnostics::PROFILE_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ let dir = std::env::temp_dir().join(format!("solidcraft-import-profile-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("block.step").to_string_lossy().to_string();+ let mut s = Session::default();+ s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5})).unwrap();+ s.execute("file.export", &json!({"path": path})).unwrap();+ // The first read of the file (a second one finds it in the import cache).+ solidcraft_profile::set_enabled(true);+ let out = Session::default().execute("file.insert_step", &json!({"path": path})).unwrap();+ solidcraft_profile::set_enabled(false);+ let plain = Session::default().execute("file.insert_step", &json!({"path": path})).unwrap();+ assert!(plain.get("profile").is_none(), "nothing recorded, nothing reported: {plain}");+ let p = &out["profile"];+ let rows = p["rows"].as_array().unwrap();+ let has = |cat: &str| rows.iter().any(|r| r["category"] == cat);+ assert!(has("import") && has("smlib"), "{p}");+ assert!(p["by_category"].as_array().is_some_and(|c| !c.is_empty()) && p["wall_ms"].as_f64().is_some_and(|w| w > 0.0), "{p}");+ let _ = std::fs::remove_dir_all(&dir);+ }+/// #4747: a mesh export's `quality` follows curved faces more closely. A 3 mm hole in a/// 200 mm plate gets more triangles at fine and more again at finest, in STL and 3MF alike/// (Save As Mesh too); standard is what the export always gave; anything else is refused.diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 260cbacb17..752d861a64 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -48,6 +48,7 @@ pub use solidcraft_doc::Visibility;pub use solidcraft_geom as geom;pub use solidcraft_io as io;pub use solidcraft_kernel as kernel;+pub use solidcraft_profile as profile;pub use solidcraft_render as render;pub use solidcraft_sketch as sketch;@@ -1118,6 +1119,8 @@ impl Session {/// the model up to date before anything reads it.pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;+ // The command, the evaluation it causes and the refresh after it: one profiler span.+ let _span = solidcraft_profile::span("command", spec.id);let host_viewport = self.render_viewport.clone();let host_jobs = self.render_jobs.host.clone();let additional_jobs = self.render_jobs.additional.clone();diff --git a/crates/engine/src/schema/diagnostics.rs b/crates/engine/src/schema/diagnostics.rsnew file mode 100644index 0000000000..dd7cb1bb04--- /dev/null+++ b/crates/engine/src/schema/diagnostics.rs@@ -0,0 +1,151 @@+//! Contracts and result types for the commands in `cmd/diagnostics.rs`.++use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use serde_json::Value;++/// `true`, `false` or null, with the handler's message for anything else.+fn flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ Value::Bool(b) => Ok(Some(b)),+ _ => Err(serde::de::Error::custom("must be true or false")),+ }+}++/// A row count, with the handler's message for anything else.+fn rows<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ v => v.as_u64().map(Some).ok_or_else(|| serde::de::Error::custom("must be a whole number of rows (0: all)")),+ }+}++/// A file path, with the handler's message for anything else.+fn path<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ Value::String(s) if !s.trim().is_empty() && s.len() < 4096 => Ok(Some(s)),+ _ => Err(serde::de::Error::custom("must be a file path")),+ }+}++/// What `diagnostics.profile` should do besides reporting.+#[derive(Debug, Default, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ProfileParams {+ /// Start (`true`) or stop (`false`) recording, after the report is taken.+ #[serde(default, deserialize_with = "flag")]+ pub enabled: Option<bool>,+ /// Forget what was recorded, after the report is taken.+ #[serde(default, deserialize_with = "flag")]+ pub reset: Option<bool>,+ /// How many rows to return, the most self time first (default 20; 0: all of them).+ #[serde(default, deserialize_with = "rows")]+ pub top: Option<u64>,+ /// Write the recorded spans here as a Chrome trace-event file (chrome://tracing, Perfetto).+ #[serde(default, deserialize_with = "path")]+ pub trace: Option<String>,+}++/// One category's share of the recorded self time.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfileCategory {+ /// `smlib` (SMLib's own time, measured by its C API), `kernel`, `feature`, `doc`, `command`,+ /// `import`, `io`.+ pub category: String,+ pub self_ms: f64,+ /// Of all recorded self time, 0–1.+ pub share: f64,+}++/// One span name's aggregate.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfileRow {+ pub category: String,+ pub name: String,+ pub count: u64,+ /// Its time, counting only its outermost occurrence on each thread's stack.+ pub total_ms: f64,+ /// Its time less the time of the spans inside it.+ pub self_ms: f64,+ /// Its longest single run.+ pub max_ms: f64,+}++/// What the profiler recorded: the reply of `diagnostics.profile`, and an import's `profile`.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfileReport {+ /// The profiler is compiled into this build (the apps' `profile` feature).+ pub compiled: bool,+ /// It is recording (after this call's `enabled`).+ pub enabled: bool,+ /// Wall time the report covers.+ pub wall_ms: f64,+ /// Spans recorded.+ pub spans: u64,+ /// Spans left out of the trace (past its cap); they are in the rows.+ pub dropped: u64,+ /// Self time per category, the most first.+ pub by_category: Vec<ProfileCategory>,+ /// The span names with the most self time, the most first.+ pub rows: Vec<ProfileRow>,+ /// Span names recorded (rows lists `top` of them).+ pub rows_total: usize,+ /// Where the Chrome trace was written, when `trace` asked for one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub trace: Option<String>,+}++fn ms(d: std::time::Duration) -> f64 {+ (d.as_secs_f64() * 1e6).round() / 1e3+}++impl ProfileReport {+ /// `report` with its `top` rows of most self time (0: all of them).+ pub fn new(report: &solidcraft_profile::Report, top: usize) -> ProfileReport {+ let sorted = report.sorted();+ let all: f64 = report.rows.iter().map(|r| r.self_time.as_secs_f64()).sum();+ let by_category = report+ .by_category()+ .into_iter()+ .map(|(c, d)| ProfileCategory {+ category: c.to_string(),+ self_ms: ms(d),+ share: if all > 0.0 { (d.as_secs_f64() / all * 1000.0).round() / 1000.0 } else { 0.0 },+ })+ .collect();+ let n = if top == 0 { sorted.len() } else { top.min(sorted.len()) };+ let rows = sorted+ .iter()+ .take(n)+ .map(|r| ProfileRow {+ category: r.category.to_string(),+ name: r.name.to_string(),+ count: r.count,+ total_ms: ms(r.total),+ self_ms: ms(r.self_time),+ max_ms: ms(r.max),+ })+ .collect();+ ProfileReport {+ compiled: report.compiled,+ enabled: report.enabled,+ wall_ms: ms(report.wall),+ spans: (report.events as u64).saturating_add(report.dropped),+ dropped: report.dropped,+ by_category,+ rows,+ rows_total: sorted.len(),+ trace: None,+ }+ }+}++/// Tests that switch the process-wide profiler on, off or reset it run one at a time.+#[cfg(test)]+pub(crate) static PROFILE_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());++#[cfg(test)]+#[path = "diagnostics_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/diagnostics_tests.rs b/crates/engine/src/schema/diagnostics_tests.rsnew file mode 100644index 0000000000..df0f343bc5--- /dev/null+++ b/crates/engine/src/schema/diagnostics_tests.rs@@ -0,0 +1,57 @@+use serde_json::json;++use super::ProfileParams;+use crate::Session;+use crate::schema::input_schema_for;+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors};++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<ProfileParams>(), &["enabled", "reset", "top", "trace"]);+}++#[test]+fn strict_keeps_todays_errors() {+ assert_strict_keeps_todays_errors(&[+ ("diagnostics.profile", json!({"enabled": "yes"})),+ ("diagnostics.profile", json!({"reset": 1})),+ ("diagnostics.profile", json!({"top": -1})),+ ("diagnostics.profile", json!({"top": 2.5})),+ ("diagnostics.profile", json!({"trace": 5})),+ ]);+}++/// The profiler records commands, the features they compute and the kernel below them, and+/// reports, resets and writes a Chrome trace through the command.+#[test]+fn diagnostics_profile_reports_commands_features_and_the_kernel() {+ let _serial = super::PROFILE_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ let mut s = Session::default();+ s.execute("diagnostics.profile", &json!({"reset": true, "enabled": true})).unwrap();+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap();+ let r = s.execute("diagnostics.profile", &json!({"top": 0})).unwrap();+ assert_eq!((r["compiled"].as_bool(), r["enabled"].as_bool()), (Some(true), Some(true)), "{r}");+ let rows = r["rows"].as_array().unwrap();+ let row = |cat: &str, name: &str| rows.iter().find(|x| x["category"] == cat && x["name"] == name);+ let cmd = row("command", "solid.box").unwrap_or_else(|| panic!("{r}"));+ assert!(row("feature", "BoxFeature").is_some() && row("doc", "evaluate").is_some(), "{r}");+ assert!(row("kernel", "box_solid").is_some(), "{r}");+ assert!(cmd["self_ms"].as_f64().unwrap() <= cmd["total_ms"].as_f64().unwrap(), "{r}");+ assert_eq!(r["rows_total"].as_u64(), Some(rows.len() as u64));+ // `top` keeps the rows with the most self time.+ let one = s.execute("diagnostics.profile", &json!({"top": 1})).unwrap();+ assert_eq!(one["rows"].as_array().map(Vec::len), Some(1));+ // A trace file, then stop and forget.+ let dir = std::env::temp_dir().join(format!("solidcraft-profile-trace-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("trace.json").to_string_lossy().to_string();+ let t = s.execute("diagnostics.profile", &json!({"trace": path, "enabled": false, "reset": true})).unwrap();+ assert_eq!((t["trace"].as_str(), t["enabled"].as_bool()), (Some(path.as_str()), Some(false)));+ let trace: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert!(trace["traceEvents"].as_array().unwrap().iter().any(|e| e["ph"] == "X" && e["name"] == "solid.box"), "{trace}");+ // Only the call that reset it (its own span ends after the reset).+ let after = s.execute("diagnostics.profile", &json!({})).unwrap();+ let names: Vec<&str> = after["rows"].as_array().unwrap().iter().filter_map(|r| r["name"].as_str()).collect();+ assert_eq!(names, ["diagnostics.profile"], "{after}");+ let _ = std::fs::remove_dir_all(&dir);+}diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex f742836440..1ca4710f66 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -54,6 +54,7 @@ mod coverage_tests;mod tests;// The contracts, by command file.+pub mod diagnostics;pub mod features;pub mod inspect;diff --git a/crates/engine/src/timing.rs b/crates/engine/src/timing.rsindex a3dede46f1..d05772a205 100644--- a/crates/engine/src/timing.rs+++ b/crates/engine/src/timing.rs@@ -40,6 +40,20 @@ pub fn time<T>(profile: bool, f: impl FnOnce() -> T) -> (T, Step) {}}+/// `SOLIDCRAFT_PROFILE` asks for the profiler from the start: `1`, `true`, `on` or `yes`.+pub fn profile_env_on(value: Option<&str>) -> bool {+ value.map(|v| v.trim().to_ascii_lowercase()).is_some_and(|v| matches!(v.as_str(), "1" | "true" | "on" | "yes"))+}++/// Start the profiler when `SOLIDCRAFT_PROFILE` asks for it (the apps call this at start-up);+/// true when it is recording.+pub fn profile_from_env() -> bool {+ if profile_env_on(solidcraft_geom::env::var("PROFILE").as_deref()) {+ solidcraft_profile::set_enabled(true);+ }+ solidcraft_profile::enabled()+}+/// Milliseconds to the microsecond, so the JSON stays readable.pub fn round_ms(ms: f64) -> f64 {if ms.is_finite() { (ms * 1000.0).round() / 1000.0 } else { 0.0 }@@ -64,6 +78,16 @@ impl Step {mod tests {use super::*;+ #[test]+ fn the_profile_variable_takes_the_usual_yes_words() {+ for v in ["1", "true", " ON ", "yes"] {+ assert!(profile_env_on(Some(v)), "{v}");+ }+ for v in [None, Some(""), Some("0"), Some("off"), Some("2")] {+ assert!(!profile_env_on(v), "{v:?}");+ }+ }+#[test]fn steps_report_their_time_and_profile_only_when_asked() {let (r, step) = time(false, || 7);diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.tomlindex e9a701fe1a..5789666c63 100644--- a/crates/io/Cargo.toml+++ b/crates/io/Cargo.toml@@ -16,6 +16,7 @@ trust-unknown-source = []solidcraft-geom = { workspace = true }solidcraft-kernel = { workspace = true }solidcraft-doc = { workspace = true }+solidcraft-profile = { workspace = true }thiserror = { workspace = true }log = { workspace = true }zip = { workspace = true }diff --git a/crates/io/src/design.rs b/crates/io/src/design.rsindex a05d7e7f04..e6538d1d93 100644--- a/crates/io/src/design.rs+++ b/crates/io/src/design.rs@@ -231,6 +231,7 @@ pub fn write_design_container_with_thumbnail(geometry: Option<&solidcraft_doc::SavedModel>,thumbnail: Option<&[u8]>,) -> Result<Vec<u8>> {+ let _span = solidcraft_profile::span("io", "write_design_container_with_thumbnail");write_container(doc, compression, preview, geometry, thumbnail, MAX_DESIGN_BYTES)}@@ -654,6 +655,7 @@ pub(super) fn read(bytes: &[u8]) -> Result<Document> {/// keeps one seekable file handle instead of buffering the complete archive. JSON continues/// through the normal migrations.pub fn read_design_file(path: &str, notify: Option<impl FnOnce(DesignPreview)>) -> Result<(Document, Option<solidcraft_doc::SavedModel>)> {+ let _span = solidcraft_profile::span("io", "read_design_file");#[cfg(not(target_arch = "wasm32"))]let mut source = {crate::vfs::check(path).map_err(invalid)?;diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex f4fafebaed..245f197a5e 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -207,6 +207,7 @@ pub fn step_import_feature(bytes: &[u8], file: &str) -> Result<StepFeature> {/// [`step_import_feature`], with the bodies named after `names`.pub fn step_import_feature_named(bytes: &[u8], file: &str, names: StepNames) -> Result<StepFeature> {+ let _span = solidcraft_profile::span("import", "step_import_feature_named");if bytes.len() > MAX_STEP_BYTES {return Err(IoError::Invalid(format!("STEP file too large ({} MB, limit {} MB)", bytes.len() >> 20, MAX_STEP_BYTES >> 20)));}@@ -264,6 +265,7 @@ pub struct MeshFeature {/// feature. A glTF file's bodies are all built where they are (see [`read_gltf`] for its node/// tree), and it can't read buffers in other files.pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result<MeshFeature> {+ let _span = solidcraft_profile::span("import", "mesh_import_feature");if is_gltf_path(file) {let mut no_files = |name: &str| Err(format!("`{name}` can't be read here"));let mut g = read_gltf(bytes, file, &mut no_files)?;@@ -541,6 +543,7 @@ pub fn export_with_quality(meta: &Metadata,quality: MeshQuality,) -> Result<Vec<u8>> {+ let _span = solidcraft_profile::span("io", "export_with_quality");let sel: Vec<&solidcraft_doc::ModelBody> = state.bodies.iter().filter(|b| bodies.is_empty() || bodies.contains(&b.name)).collect();if sel.is_empty() {return Err(IoError::Empty);@@ -620,6 +623,7 @@ fn mesh_object(b: &solidcraft_doc::ModelBody, tagged: bool, quality: MeshQuality/// part, built where the file placed it) is taken into its component's frame by that offset,/// as the world placement does, so the occurrences above it place it only once.pub fn step_assembly(doc: &Document, local: &ModelState, name: &str) -> Result<Vec<u8>> {+ let _span = solidcraft_profile::span("io", "step_assembly");use solidcraft_kernel::{ExportBody, ExportProduct};let mut index: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();index.insert(0, 0);@@ -652,6 +656,7 @@ pub fn step_assembly(doc: &Document, local: &ModelState, name: &str) -> Result<V/// Read a design file's bytes.pub fn read_design(bytes: &[u8]) -> Result<Document> {+ let _span = solidcraft_profile::span("io", "read_design");if bytes.len() > MAX_DESIGN_BYTES {return Err(IoError::Invalid("design file too large".into()));}diff --git a/crates/kernel/Cargo.toml b/crates/kernel/Cargo.tomlindex e1b4e691c6..7d922123c6 100644--- a/crates/kernel/Cargo.toml+++ b/crates/kernel/Cargo.toml@@ -17,6 +17,7 @@ smlib = ["solidcraft-smlib/native"][dependencies]solidcraft-geom = { workspace = true }solidcraft-smlib = { workspace = true }+solidcraft-profile = { workspace = true }solidcraft-step = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }@@ -29,4 +30,5 @@ web-time = { workspace = true }rayon = { workspace = true }[dev-dependencies]+solidcraft-profile = { workspace = true, features = ["enabled"] }proptest = { version = "1", default-features = false, features = ["std"] }diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rsindex 862695176a..209435a3be 100644--- a/crates/kernel/src/blend.rs+++ b/crates/kernel/src/blend.rs@@ -173,6 +173,7 @@ pub(crate) fn curve_derivative(c: &Curve, t: f64) -> Option<Vec3> {/// lines the round of `radius` has (zero curvature at the contacts on planar faces), not a/// circle. A configuration SMLib cannot blend so is refused, never given a circular round.pub fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_g2");body.require_brep("G2 fillet")?;if !(radius.is_finite() && radius > 1e-6 && radius < 1e6) {return Err(KernelError::Invalid("G2 fillet size must be positive and finite".into()));@@ -208,6 +209,7 @@ fn closed(input: &Body, b: Body) -> Result<Body> {/// faces around the edges is refused with [`KernelError::TooLarge`] ([`fillet_max`] finds the/// largest that works).pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet");body.require_brep("fillet")?;crate::blend_smlib::fillet(body, edges, radius).and_then(|b| closed(body, b))}@@ -221,6 +223,7 @@ pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {/// where some edge is not rounded is refused as not supported, a setback as long as an edge at/// its corner as too large.pub fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_setback");body.require_brep("fillet")?;crate::blend_smlib::fillet_setback(body, edges, radius, setbacks).and_then(|b| closed(body, b))}@@ -229,6 +232,7 @@ pub fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec/// corners are a sphere or a Coons patch that meets the rounds tangentially, so this is refused/// rather than quietly given those corners; [`fillet`] (the default) is unchanged.pub fn fillet_g2_corners(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_g2_corners");body.require_brep("fillet")?;if !(radius.is_finite() && radius > 0.0) {return Err(KernelError::Invalid("the blend radius must be finite and positive".into()));@@ -249,6 +253,7 @@ fn radius_step(radius: f64) -> f64 {/// ([`KernelError::TooLarge`]) narrows the search: any other failure of a candidate is the/// search's error, since a smaller radius would not be the largest that fits.pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64) -> Result<Option<(f64, Body)>> {+ let _span = solidcraft_profile::span("kernel", "fillet_max");if !(radius.is_finite() && radius > 1e-6) {return Ok(None);}@@ -283,6 +288,7 @@ pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64) -> Result<Option<(f6/// up to 16 fillets, and this runs in the live preview). Any failure other than a refusal as too/// large is the error.pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Result<Option<(Vec<f64>, Body)>> {+ let _span = solidcraft_profile::span("kernel", "fillet_max_each");const MAX_GROUPS: usize = 8;const MAX_SEARCHES: usize = 2;let one = || -> Result<Option<(Vec<f64>, Body)>> { Ok(fillet_max(body, edges, radius)?.map(|(r, b)| (vec![r; edges.len()], b))) };@@ -319,6 +325,7 @@ pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Result<Optio/// The fillet of each edge at its own radius (`radii` in `edges`' order), all in one SMLib/// blend.pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_each");if radii.len() != edges.len() {return Err(KernelError::Invalid("one radius per edge".into()));}@@ -365,6 +372,7 @@ fn interacting_groups(body: &Body, pts: &[Vec3]) -> Option<Vec<Vec<usize>>> {/// Equal-distance chamfer of the edges nearest to the given points, `distance` back along each/// face, neighbouring chamfers meeting in a mitre.pub fn chamfer(body: &Body, edges: &[Vec3], distance: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "chamfer");body.require_brep("chamfer")?;if !(distance.is_finite() && distance > 1e-6 && distance < 1e6) {return Err(KernelError::Invalid("chamfer size must be positive".into()));@@ -386,6 +394,7 @@ pub enum ChamferSide {/// A chamfer with different setbacks on the two faces of each edge: `d1` along the first face/// (the one facing up most, the other with `flip`), the second side by distance or angle.pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "chamfer_sides");body.require_brep("chamfer")?;let ok = |x: f64| x.is_finite() && x > 1e-6 && x < 1e6;let valid = ok(d1)diff --git a/crates/kernel/src/blend_variable.rs b/crates/kernel/src/blend_variable.rsindex 78206dd24f..b27c91852e 100644--- a/crates/kernel/src/blend_variable.rs+++ b/crates/kernel/src/blend_variable.rs@@ -48,6 +48,7 @@ fn edge_frame(rec: &Faces, e: usize) -> Result<EdgeFrame> {/// Fillet one straight edge with radius `r0` at its end nearest `start` and `r1` at the other.pub fn fillet_variable(body: &Body, edge_at: Vec3, start: Vec3, r0: f64, r1: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_variable");fillet_variable_points(body, edge_at, start, &[(0.0, r0), (1.0, r1)], false)}@@ -182,6 +183,7 @@ impl RadiusSpline {/// positions 0 (the end nearest `start`) to 1 (the other end) and any between, the radius/// straight between them or `smooth`. One end's radius may be zero.pub fn fillet_variable_points(body: &Body, edge_at: Vec3, start: Vec3, points: &[(f64, f64)], smooth: bool) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_variable_points");if points.len() < 2 || points.len() > 100 {return Err(KernelError::Invalid("a variable radius needs 2…100 points".into()));}@@ -201,6 +203,7 @@ pub fn fillet_variable_points(body: &Body, edge_at: Vec3, start: Vec3, points: &/// `start`. One end's radius may be zero. A law whose round would leave the faces beside the/// edge is SMLib's refusal ([`KernelError::TooLarge`]).pub fn fillet_variable_spline(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_variable_spline");body.require_brep("fillet")?;spline.check()?;if !(edge_at.is_finite() && start.is_finite()) {@@ -438,6 +441,7 @@ pub fn taper(body: &Body, edge_at: Vec3, radius: f64) -> Result<Taper> {/// on alone gets a [`taper`], and the rest the constant radius. The result and the taper of each/// edge (in `edges`' order; None where the radius is constant).pub fn fillet_tapered(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body, Vec<Option<Taper>>)> {+ let _span = solidcraft_profile::span("kernel", "fillet_tapered");let why = match crate::fillet(body, edges, radius) {Err(KernelError::TooLarge(why)) => why,other => return other.map(|b| (b, vec![None; edges.len()])),@@ -473,6 +477,7 @@ pub fn fillet_tapered(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body,/// to contact at every station (SMLib's constant-chord round), its radius following the face/// angle along the edge.pub fn fillet_chord(body: &Body, edges: &[Vec3], chord: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "fillet_chord");body.require_brep("fillet")?;if !(chord.is_finite() && chord > 1e-6 && chord < 1e6) {return Err(KernelError::Invalid("the chord length must be positive".into()));diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rsindex 076ba71b09..b2e486db29 100644--- a/crates/kernel/src/body.rs+++ b/crates/kernel/src/body.rs@@ -915,7 +915,7 @@ impl Body {/// watertight wherever the B-rep is. A mesh body gives its own triangles. A face the planner/// cannot mesh is an error that names it and why.pub fn mesh(&self, t: &MeshTolerance) -> Result<Mesh> {- crate::profile::timed(crate::profile::Kind::Tessellate, || self.mesh_untimed(t))+ crate::profile::timed(crate::profile::Kind::Tessellate, "mesh", || self.mesh_untimed(t))}fn mesh_untimed(&self, t: &MeshTolerance) -> Result<Mesh> {@@ -942,7 +942,7 @@ impl Body {/// edge sampled once so faces meet exactly. For an evaluator of its own (the GPU viewport);/// [`Body::mesh_of`] gives its mesh without planning again.pub fn mesh_plan(&self, t: &MeshTolerance) -> Result<solidcraft_geom::tess::TessPlan> {- crate::profile::timed(crate::profile::Kind::Tessellate, || self.mesh_plan_untimed(t))+ crate::profile::timed(crate::profile::Kind::Tessellate, "mesh_plan", || self.mesh_plan_untimed(t))}fn mesh_plan_untimed(&self, t: &MeshTolerance) -> Result<solidcraft_geom::tess::TessPlan> {diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rsindex a6ce0bf77c..be65121947 100644--- a/crates/kernel/src/build.rs+++ b/crates/kernel/src/build.rs@@ -66,6 +66,7 @@ pub(crate) fn frame_ok(plane: &Plane) -> bool {/// Extrude each region from `start` to `end` along the plane normal (offsets in mm, `end > start`).pub fn extrude(plane: &Plane, regions: &[Region2], start: f64, end: f64) -> Result<Vec<Body>> {+ let _span = solidcraft_profile::span("kernel", "extrude");extrude_with(plane, regions, start, end, false)}@@ -75,6 +76,7 @@ pub fn extrude(plane: &Plane, regions: &[Region2], start: f64, end: f64) -> Resu/// history lists every piece under it. For the Extrude feature; other builders (sheet metal's/// flat pattern, tools) keep a face per segment.pub fn extrude_whole_sides(plane: &Plane, regions: &[Region2], start: f64, end: f64) -> Result<Vec<Body>> {+ let _span = solidcraft_profile::span("kernel", "extrude_whole_sides");extrude_with(plane, regions, start, end, true)}@@ -129,6 +131,7 @@ pub fn canonical_revolve_axis(plane: &Plane, region: &Region2, axis_origin: Vec2/// Revolve each region about the sketch axis by `angle` radians./// This legacy API preserves its historical sweep sign behavior.pub fn revolve(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result<Vec<Body>> {+ let _span = solidcraft_profile::span("kernel", "revolve");revolved(plane, regions, axis_origin, axis_dir, angle)}@@ -136,6 +139,7 @@ pub fn revolve(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir:/// face whole (#726): SMLib's revolution makes one face of each profile segment and of each/// cap, so this is [`revolve`].pub fn revolve_whole(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec2, angle: f64) -> Result<Vec<Body>> {+ let _span = solidcraft_profile::span("kernel", "revolve_whole");revolved(plane, regions, axis_origin, axis_dir, angle)}@@ -198,6 +202,7 @@ fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec/// Axis-aligned box between two corners.pub fn box_solid(a: Vec3, b: Vec3) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "box_solid");let (lo, hi) = (a.min(b), a.max(b));let s = hi - lo;if !(s.x > 1e-6 && s.y > 1e-6 && s.z > 1e-6 && s.is_finite() && s.len() < 1e7) {@@ -245,6 +250,7 @@ pub(crate) const SEAM_ANGLE: f64 = 0.6131;/// Cylinder with base centre `base`, axis direction `axis`, radius and height.pub fn cylinder(base: Vec3, axis: Vec3, radius: f64, height: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "cylinder");let plane = Plane::from_normal(base, axis).ok_or_else(|| KernelError::Invalid("cylinder axis".into()))?;let radius = finite(radius, "radius")?;if radius <= 1e-6 {@@ -260,6 +266,7 @@ pub fn cylinder(base: Vec3, axis: Vec3, radius: f64, height: f64) -> Result<Body/// Sphere: SMLib's own (smlib_make_sphere), each face swept from the arc (segment 0) of the half/// disc a sphere revolves.pub fn sphere(center: Vec3, radius: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sphere");let radius = finite(radius, "radius")?;if radius <= 1e-6 || !center.is_finite() || center.len() >= 1e7 {return Err(KernelError::Invalid("radius must be positive".into()));@@ -269,6 +276,7 @@ pub fn sphere(center: Vec3, radius: f64) -> Result<Body> {/// Torus about the Z axis through `center`.pub fn torus(center: Vec3, major: f64, minor: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "torus");let (major, minor) = (finite(major, "major radius")?, finite(minor, "minor radius")?);if !(minor > 1e-6 && major > minor) {return Err(KernelError::Invalid("torus needs major > minor > 0".into()));@@ -755,6 +763,7 @@ const MEET_SAMPLES: usize = 48;/// (radians; positive grows the profile), its sharp corners closed by `corner`/// ([`crate::draft_corners`] says what each rule gives at each corner).pub fn extrude_tapered(plane: &Plane, region: &Region2, length: f64, dir_sign: f64, taper: f64, corner: DraftCorner) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "extrude_tapered");extrude_tapered_between(plane, region, 0.0, length, 0.0, dir_sign, taper, corner)}@@ -775,6 +784,7 @@ pub fn extrude_tapered_between(taper: f64,corner: DraftCorner,) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "extrude_tapered_between");let (from, to, foot, taper) = (finite(from, "start")?, finite(to, "distance")?, finite(foot, "foot")?, finite(taper, "taper")?);if to - from <= 1e-6 {return Err(KernelError::Invalid("extrude distance is zero".into()));@@ -897,6 +907,7 @@ pub fn planar_face_record(plane: &Plane, r: &Region2) -> Result<solidcraft_geom:/// Ruled loft through two or more planar sections (outer loops only). The sections and the/// same sections in reverse order give the same body.pub fn loft(sections: &[(Plane, Loop2)]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "loft");loft_with_rails(sections, &[], RailFit::Scale)}@@ -904,6 +915,7 @@ pub fn loft(sections: &[(Plane, Loop2)]) -> Result<Body> {/// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the/// sections between. Without rails, the plain loft.pub fn loft_with_rails(sections: &[(Plane, Loop2)], rails: &[Vec<Vec3>], fit: RailFit) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "loft_with_rails");let reversed = loft_reversed(sections)?;let numbered = sections.iter().map(|(p, _)| *p).zip(numbered::number_loops(sections.iter().map(|(_, l)| l))).collect::<Vec<_>>();let loops = loft_numbered_loops(&numbered, reversed)?;@@ -920,6 +932,7 @@ pub fn loft_with_rails(sections: &[(Plane, Loop2)], rails: &[Vec<Vec3>], fit: Ra/// Holes are paired by their positions relative to the outline, independently of sketch/// curve order. A hole cannot appear or disappear partway through a loft.pub fn loft_regions(sections: &[(Plane, Region2)]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "loft_regions");if !(2..=50).contains(§ions.len()) {return Err(KernelError::Invalid("a loft needs 2…50 sections".into()));}@@ -1291,11 +1304,13 @@ pub fn path_polyline(path: &[PathSeg]) -> Result<Vec<Vec3>> {/// [`sweep`] with sweep options. The default options are exactly [`sweep`]; a twist, an end/// scale, guide rails or an orientation direction place the profile at stations along the path.pub fn sweep_with(plane: &Plane, region: &Region2, path: &[PathSeg], ctl: &crate::SweepControl) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sweep_with");smlib_sweep(plane, region, path, ctl)}/// Sweep a planar region along a chain of path segments, keeping the profile perpendicular to/// the path; at sharp corners the walls meet in mitres.pub fn sweep(plane: &Plane, region: &Region2, path: &[PathSeg]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sweep");smlib_sweep(plane, region, path, &crate::SweepControl::default())}diff --git a/crates/kernel/src/delete_face.rs b/crates/kernel/src/delete_face.rsindex db483895af..5a8461f4b3 100644--- a/crates/kernel/src/delete_face.rs+++ b/crates/kernel/src/delete_face.rs@@ -100,6 +100,7 @@ fn position(asm: &Assembly, moved: &HashMap<u32, Vec3>, v: u32) -> Result<Vec3>/// Delete faces (indices in the body's face order, as in its mesh's `tri_face`) and heal the/// gap by extending the neighbouring planes. The result's history is over `[body]`.pub fn delete_faces(body: &Body, faces: &[usize]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "delete_faces");body.require_brep("Delete Face")?;let rec = crate::native::brep_record(body)?;let n = rec.faces.len();diff --git a/crates/kernel/src/heal.rs b/crates/kernel/src/heal.rsindex 3fde7c24dc..8ff27ba462 100644--- a/crates/kernel/src/heal.rs+++ b/crates/kernel/src/heal.rs@@ -45,6 +45,7 @@ pub(crate) fn edge_points(b: &Brep, e: u32) -> Vec<Vec3> {/// result comes from those of `body` as SMLib's history says (a merged face from every face/// merged into it), over `[body]`.pub(crate) fn heal(body: &Body, keep: &[Vec<Vec3>]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "heal");let record = crate::native::brep_record(body)?;// Each edge along a split line, by the point halfway along it.let mut kept: Vec<[f64; 3]> = Vec::new();diff --git a/crates/kernel/src/helix.rs b/crates/kernel/src/helix.rsindex ce8381a593..8a18254f97 100644--- a/crates/kernel/src/helix.rs+++ b/crates/kernel/src/helix.rs@@ -15,6 +15,7 @@ fn rot(v: Vec3, k: Vec3, ang: f64) -> Vec3 {/// its attitude relative to the axis, as a screw motion does: SMLib's screw sweep, one wall per/// profile segment.pub fn sweep_helix(plane: &Plane, region: &Region2, axis_origin: Vec3, axis: Vec3, pitch: f64, turns: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sweep_helix");let (k, profile) = helix_profile(plane, region, axis_origin, axis, pitch, turns)?;crate::smlib_sweeps::screw(plane, &crate::smlib_sweeps::pieces([&profile]), axis_origin, k, pitch, turns)}@@ -32,6 +33,7 @@ pub fn sweep_helix_radial(turns: f64,law: &[(f64, f64)],) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sweep_helix_radial");if law.is_empty() {return sweep_helix(plane, region, axis_origin, axis, pitch, turns);}@@ -78,6 +80,7 @@ fn helix_profile(/// wound outward: `stations` sections per turn, flat end caps. Watertight by construction, for/// faceted booleans (modelled threads).pub fn sweep_helix_mesh(plane: &Plane, polygon: &[Vec2], axis_origin: Vec3, axis: Vec3, pitch: f64, turns: f64, stations: usize) -> Result<Mesh> {+ let _span = solidcraft_profile::span("kernel", "sweep_helix_mesh");let k = axis.normalized().ok_or_else(|| KernelError::Invalid("helix axis".into()))?;let m = polygon.len();if !(pitch.is_finite() && turns.is_finite() && turns > 0.0 && turns <= 200.0 && (3..=64).contains(&m) && (8..=720).contains(&stations)) {@@ -116,6 +119,7 @@ pub fn sweep_helix_mesh(plane: &Plane, polygon: &[Vec2], axis_origin: Vec3, axis/// A solid from a planar loop of straight segments to an apex point off its plane (a pyramid):/// SMLib's loft to a point.pub fn loft_to_point(plane: &Plane, lp: &Loop2, apex: Vec3) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "loft_to_point");if !apex.is_finite() || lp.segs.is_empty() || lp.segs.len() > 10_000 {return Err(KernelError::Invalid("loft to a point: bad section or apex".into()));}diff --git a/crates/kernel/src/iges_in.rs b/crates/kernel/src/iges_in.rsindex f9adb7aead..36715d2eed 100644--- a/crates/kernel/src/iges_in.rs+++ b/crates/kernel/src/iges_in.rs@@ -1312,6 +1312,7 @@ fn write_shell(o: &mut Out, sw: &Sewer, faces: &[FaceB], styles: &mut Vec<(u64,/// This was the one importer stage outside every panic guard, so a panic here reached the CLI/// and the wasm build, where nothing catches it.pub fn iges_to_step(text: &str) -> std::result::Result<(String, Vec<String>), String> {+ let _span = solidcraft_profile::span("import", "iges.to_step");crate::guard("IGES import", || translate(text).map_err(crate::KernelError::Invalid)).map_err(|e| match e {crate::KernelError::Invalid(m) => m,other => other.to_string(),@@ -1322,7 +1323,7 @@ fn translate(text: &str) -> std::result::Result<(String, Vec<String>), String> {if text.len() > MAX_IGES_BYTES {return Err("IGES file too large".into());}- let f = parse(text)?;+ let f = solidcraft_profile::scope("import", "iges.parse", || parse(text))?;let tol = (f.resolution * f.unit).clamp(1e-6, 0.05).max(1e-5);let mut t = Tr {f: &f,@@ -1871,6 +1872,7 @@ fn brep_edge(t: &mut Tr, sw: &mut Sewer, list: i64, ndx: i64, xf: &Xf) -> R<(usi/// Read IGES text: its solids, or its surfaces sewn into shells, as the STEP reader gives them.pub fn iges_import(text: &str) -> crate::Result<crate::StepImport> {+ let _span = solidcraft_profile::span("import", "iges.import");let (step, warnings) = iges_to_step(text).map_err(crate::KernelError::Invalid)?;let mut imp = crate::step_import(&step)?;imp.warnings.splice(0..0, warnings);diff --git a/crates/kernel/src/measure.rs b/crates/kernel/src/measure.rsindex 9cec6c3990..beecbe4830 100644--- a/crates/kernel/src/measure.rs+++ b/crates/kernel/src/measure.rs@@ -53,6 +53,7 @@ const ACCURACY: f64 = 1e-4;/// and its box is SMLib's exact box; a body SMLib cannot measure is an error. A mesh body is/// measured from its triangles, exactly.pub fn measure(b: &Body) -> Result<BodyMeasure> {+ let _span = solidcraft_profile::span("kernel", "measure");if let Some((pos, tris)) = b.triangle_mesh() {// Exact for a mesh body; topology counts are facets, sides and vertices.let m = b.mesh(&crate::MeshTolerance::chord(1.0))?;@@ -94,6 +95,7 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {/// [`measure`]'s volume, area, centre and box alone (for callers that need no topology counts,/// such as an interference check).pub fn measure_mass(b: &Body) -> Result<MassMeasure> {+ let _span = solidcraft_profile::span("kernel", "measure_mass");if b.triangle_mesh().is_some() {let m = measure(b)?;return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox, measured_by: m.measured_by, notes: m.notes });diff --git a/crates/kernel/src/meshbody.rs b/crates/kernel/src/meshbody.rsindex 071a52294c..5a6b57a555 100644--- a/crates/kernel/src/meshbody.rs+++ b/crates/kernel/src/meshbody.rs@@ -63,6 +63,7 @@ impl TriMesh {/// A mesh body from triangles (`positions` in mm). Coincident vertices are merged, degenerate/// triangles dropped, and a closed mesh with inward winding is turned outward.pub fn mesh_body(positions: &[Vec3], triangles: &[[u32; 3]]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "mesh_body");if triangles.len() > MAX_TRIANGLES {return Err(KernelError::Invalid(format!("mesh with {} triangles (limit {MAX_TRIANGLES})", triangles.len())));}diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rsindex a56a7a89a6..cef1920e42 100644--- a/crates/kernel/src/native.rs+++ b/crates/kernel/src/native.rs@@ -45,6 +45,7 @@ fn invalid(detail: impl std::fmt::Display) -> KernelError {/// body's own record and what it carries. Failure is a cache miss at the IO boundary, never a/// failed document save.pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {+ let _span = solidcraft_profile::span("kernel", "encode_native_body");guard("encode native B-rep", || {for source in body.face_sources.iter().flat_map(|s| s.iter()).flatten() {let mut at = source;@@ -81,6 +82,7 @@ pub fn encode_native_body(body: &Body) -> Result<Vec<u8>> {/// The schema 4 record of a solid body, in canonical order with its pcurves: the body itself./// Mesh bodies have none.pub fn brep_record(body: &Body) -> Result<solidcraft_geom::brep::Brep> {+ let _span = solidcraft_profile::span("kernel", "brep_record");if body.mesh.is_some() {return Err(invalid("mesh bodies are source blobs, not B-rep"));}@@ -89,12 +91,14 @@ pub fn brep_record(body: &Body) -> Result<solidcraft_geom::brep::Brep> {/// The body in SMLib (see [`Body::smlib`]), as an owned copy.pub fn smlib_body(body: &Body) -> Result<solidcraft_smlib::Brep> {+ let _span = solidcraft_profile::span("kernel", "smlib_body");body.smlib()?.try_clone().map_err(|e| KernelError::Failed(format!("SMLib: {e}")))}/// Decode bounded untrusted data. Validate indices before topology extraction./// Only a caller that has checked who produced the data may treat it as evaluated geometry.pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "decode_native_body");if bytes.len() > MAX_BYTES || bytes.get(..8) != Some(MAGIC.as_slice()) {return Err(invalid("version or size"));}@@ -124,12 +128,14 @@ pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {/// An SMLib body as a kernel body: SMLib's export mapped by `solidcraft_smlib` (canonical order,/// radians, pcurves) is the body's record, and the SMLib body is kept with it.pub fn body_from_smlib(brep: &solidcraft_smlib::Brep) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "body_from_smlib");body_from_smlib_ordered(brep).map(|(body, _)| body)}/// [`body_from_smlib`], with where each of SMLib's faces and edges is in the body's face and/// edge order ([`crate::history`]).pub(crate) fn body_from_smlib_ordered(brep: &solidcraft_smlib::Brep) -> Result<(Body, Option<solidcraft_smlib::history::Order>)> {+ let _span = solidcraft_profile::span("kernel", "body_from_smlib_ordered");let (record, order) = brep.to_native_ordered().map_err(|e| KernelError::Failed(e.to_string()))?;let handle = brep.try_clone().map_err(|e| KernelError::Failed(format!("SMLib: {e}")))?;Ok((Body::from_smlib_record(handle, record)?, Some(order)))@@ -148,6 +154,7 @@ pub(crate) fn smlib_body_ordered(body: &Body) -> Result<(solidcraft_smlib::Brep,pub(crate) fn smlib_record_ordered(record: &solidcraft_geom::brep::Brep,) -> Result<(solidcraft_smlib::Brep, Option<solidcraft_smlib::history::Order>)> {+ let _span = solidcraft_profile::span("kernel", "smlib_record_ordered");let brep = solidcraft_smlib::Brep::from_record(record, true).map_err(|e| KernelError::Failed(format!("SMLib: {e}")))?;let order = numbering(record, &brep);Ok((brep, order))diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rsindex 1f1ce9832a..fe9b33ad2d 100644--- a/crates/kernel/src/ops.rs+++ b/crates/kernel/src/ops.rs@@ -23,7 +23,7 @@ pub enum BoolOp {/// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`, from/// SMLib's own tags, or none where a body's order cannot be matched to SMLib's.pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {- crate::profile::timed(crate::profile::Kind::Boolean, || {+ crate::profile::timed(crate::profile::Kind::Boolean, "boolean", || {let r = guard("SMLib boolean", || crate::smlib_boolean::smlib_boolean(a, b, op));with_operand_roles(a, b, op, r)})@@ -36,7 +36,7 @@ pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {/// what the operands' faces stood for (their regularization protection and the planar roles on/// supports it kept).pub fn union_all(bodies: &[&Body]) -> Result<Body> {- crate::profile::timed(crate::profile::Kind::Boolean, || {+ crate::profile::timed(crate::profile::Kind::Boolean, "union_all", || {if bodies.is_empty() {return Err(KernelError::Invalid("a union of no bodies".into()));}@@ -61,7 +61,7 @@ fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result<Option<Body>>) -/// [`join_apart`]); `None` when fewer than two are given, one is a mesh, or two of them are not/// apart (their exact boxes, grown by the bodies' tolerances, overlap).pub fn union_apart(bodies: &[Body]) -> Result<Option<Body>> {- crate::profile::timed(crate::profile::Kind::Boolean, || {+ crate::profile::timed(crate::profile::Kind::Boolean, "union_apart", || {if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) {return Ok(None);}@@ -132,6 +132,7 @@ fn joined(bodies: &[Body]) -> Result<(Body, part::Part)> {/// other matrix goes through SMLib's transform. Either way the result's faces and edges are/// the body's, in its history.pub fn transform_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "transform_matrix");if m.iter().flatten().any(|x| !x.is_finite()) {return Err(KernelError::Invalid("non-finite transform".into()));}@@ -196,6 +197,7 @@ pub fn transform(body: &Body, translate: Vec3, origin: Vec3, axis: Vec3, angle:/// Split a body with a plane: the parts on the positive and the negative side of the plane/// (only the non-empty ones).pub fn split_by_plane(body: &Body, plane: &solidcraft_geom::Plane) -> Result<Vec<Body>> {+ let _span = solidcraft_profile::span("kernel", "split_by_plane");let mut out = Vec::new();for positive in [true, false] {out.extend(half_space(body, plane, positive)?.0);@@ -208,6 +210,7 @@ pub fn split_by_plane(body: &Body, plane: &solidcraft_geom::Plane) -> Result<Vec/// carries, over the body and the box. The box's face in the plane, the part's cut face, is its/// start cap on the positive side and its end cap on the negative side.pub fn half_space(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result<(Option<Body>, Body)> {+ let _span = solidcraft_profile::span("kernel", "half_space");// The box's own construction roles describe no face of the design: the cut face has none.let tool = half_box(body, plane, positive)?.with_face_sources(None);Ok((boolean(body, &tool, BoolOp::Intersect)?, tool))diff --git a/crates/kernel/src/polybool.rs b/crates/kernel/src/polybool.rsindex 6232d235e3..a722c1882b 100644--- a/crates/kernel/src/polybool.rs+++ b/crates/kernel/src/polybool.rs@@ -28,7 +28,7 @@ fn failed(what: &str) -> KernelError {/// no edges): a face of the result lies on faces of `a` or on triangles of `b`; an edge where/// `a` meets the mesh meets the triangles of the face it lies along.pub fn faceted_boolean(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result<Option<Body>> {- crate::profile::timed(crate::profile::Kind::Boolean, || faceted_boolean_untimed(a, b, op, tol))+ crate::profile::timed(crate::profile::Kind::Boolean, "faceted_boolean", || faceted_boolean_untimed(a, b, op, tol))}fn faceted_boolean_untimed(a: &Body, b: &Mesh, op: BoolOp, tol: f64) -> Result<Option<Body>> {diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rsindex 3f9766b734..5b966f9cd4 100644--- a/crates/kernel/src/polyhedron.rs+++ b/crates/kernel/src/polyhedron.rs@@ -187,12 +187,14 @@ fn polyhedron_record(hs: &[HalfSpace], verts: &[Vec3], faces: &[(usize, Vec<usiz/// Hollow a body: walls of `thickness` inside, open at the faces under `open` (SMLib's shell)./// The result's history is over `[b]`: the inner walls are offsets of the faces they line.pub fn shell(b: &Body, open: &[Vec3], thickness: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "shell");crate::offset_backend::shell(b, open, thickness)}/// Tilt the faces near `faces` by `angle` about their line on the neutral plane, so that they/// lean in (positive angle) going along `pull` (SMLib's draft).pub fn draft(b: &Body, faces: &[Vec3], neutral: &solidcraft_geom::Plane, pull: Vec3, angle: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "draft");b.require_brep("draft")?;crate::offset_backend::draft(b, faces, neutral, pull, angle)}@@ -200,6 +202,7 @@ pub fn draft(b: &Body, faces: &[Vec3], neutral: &solidcraft_geom::Plane, pull: V/// Move the faces at the given points along their outward normals by `distance` (negative: into/// the body), SMLib's offset of faces: the faces around them are extended or trimmed to meet them.pub fn offset_faces(b: &Body, at: &[Vec3], distance: f64) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "offset_faces");b.require_brep("offset faces")?;if !distance.is_finite() || distance.abs() > 1e6 {return Err(KernelError::Invalid("offset distance".into()));diff --git a/crates/kernel/src/profile.rs b/crates/kernel/src/profile.rsindex 2ea09d4c55..deb156c716 100644--- a/crates/kernel/src/profile.rs+++ b/crates/kernel/src/profile.rs@@ -74,8 +74,10 @@ pub fn credit(times: KernelTimes) {});}-/// Time `f` as `kind` when a capture is running and no timed call is.-pub(crate) fn timed<T>(kind: Kind, f: impl FnOnce() -> T) -> T {+/// Time `f` as `kind` when a capture is running and no timed call is; it is also the+/// profiler's span `name` (category `kernel`) whenever the profiler records.+pub(crate) fn timed<T>(kind: Kind, name: &'static str, f: impl FnOnce() -> T) -> T {+ let _span = solidcraft_profile::span("kernel", name);let st = STATE.with(Cell::get);if !st.on || st.busy {return f();@@ -116,7 +118,7 @@ mod tests {#[test]fn nothing_is_timed_outside_a_capture() {- timed(Kind::Boolean, || spin(2));+ timed(Kind::Boolean, "test", || spin(2));let ((), t) = capture(|| ());assert_eq!(t, KernelTimes::default());}@@ -125,11 +127,11 @@ mod tests {fn only_the_outermost_call_counts() {let started = web_time::Instant::now();let ((), t) = capture(|| {- timed(Kind::Boolean, || {+ timed(Kind::Boolean, "test", || {spin(3);- timed(Kind::Tessellate, || spin(3));+ timed(Kind::Tessellate, "test", || spin(3));});- timed(Kind::Tessellate, || spin(2));+ timed(Kind::Tessellate, "test", || spin(2));});let elapsed = started.elapsed().as_secs_f64() * 1000.0;assert!(t.boolean_ms >= 6.0 && t.tessellate_ms >= 2.0, "{t:?}");@@ -145,7 +147,7 @@ mod tests {credit(t);credit(KernelTimes { boolean_ms: f64::NAN, tessellate_ms: -3.0 });// Inside a timed call it would count twice: it is the call's time already.- timed(Kind::Boolean, || credit(t));+ timed(Kind::Boolean, "test", || credit(t));});assert_eq!((got.boolean_ms >= 4.0, got.boolean_ms < 8.0, got.tessellate_ms), (true, true, 1.0), "{got:?}");}@@ -153,9 +155,9 @@ mod tests {#[test]fn inner_captures_add_to_the_outer_one_and_a_panic_restores_it() {let ((), outer) = capture(|| {- let ((), inner) = capture(|| timed(Kind::Boolean, || spin(2)));+ let ((), inner) = capture(|| timed(Kind::Boolean, "test", || spin(2)));assert!(inner.boolean_ms >= 2.0);- let _ = std::panic::catch_unwind(|| capture(|| timed(Kind::Tessellate, || panic!("kernel"))));+ let _ = std::panic::catch_unwind(|| capture(|| timed(Kind::Tessellate, "test", || panic!("kernel"))));});assert!(outer.boolean_ms >= 2.0, "{outer:?}");let st = STATE.with(Cell::get);@@ -175,4 +177,24 @@ mod tests {assert!(!m.unwrap().triangles.is_empty());assert!(t.tessellate_ms > 0.0 && t.boolean_ms == 0.0, "{t:?}");}++ #[test]+ fn kernel_operations_are_profiler_spans_with_smlib_calls_inside() {+ use crate::{BoolOp, boolean, box_solid};+ use solidcraft_geom::Vec3;+ solidcraft_profile::set_enabled(true);+ let mark = solidcraft_profile::mark();+ let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap();+ let b = box_solid(Vec3::new(5.0, 5.0, 5.0), Vec3::new(15.0, 15.0, 15.0)).unwrap();+ let r = boolean(&a, &b, BoolOp::Cut);+ let rep = mark.report();+ let row = |cat: &str, name: &str| rep.rows.iter().find(|r| r.category == cat && r.name == name).copied();+ let k = row("kernel", "boolean").unwrap_or_else(|| panic!("{rep:?}"));+ assert!(k.count >= 1 && row("kernel", "box_solid").is_some(), "{rep:?}");+ if r.is_ok() {+ // With SMLib built, its calls are children of the boolean: their time is not its self time.+ let smlib: std::time::Duration = rep.rows.iter().filter(|r| r.category == "smlib").map(|r| r.total).sum();+ assert!(smlib > std::time::Duration::ZERO && k.self_time < k.total, "{rep:?}");+ }+ }}diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rsindex d96ada6c4e..7a7a0199cb 100644--- a/crates/kernel/src/sew.rs+++ b/crates/kernel/src/sew.rs@@ -727,6 +727,7 @@ fn arc_curve(a: Vec3, b: Vec3, mid: Vec3) -> Result<(b::Curve, [f64; 2])> {/// Sew the faces into a closed solid.pub fn sew(faces: &[FaceSpec]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sew");sew_impl(faces, false, None).map(|(body, _)| body)}@@ -737,6 +738,7 @@ pub fn sew(faces: &[FaceSpec]) -> Result<Body> {/// own; and a face whose loops meet at a vertex (a hole's corner on its face's outline) has them/// as one loop through it (see [`join_touching_loops`]).pub fn sew_touching(faces: &[FaceSpec]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sew_touching");sew_impl(faces, true, None).map(|(body, _)| body)}@@ -1329,6 +1331,7 @@ pub(crate) struct Assembled {/// shells (sheets) in the infinite region; everything in canonical order and validated./// `solid`: every shell must be closed.pub(crate) fn assemble(parts: Parts, solid: bool) -> Result<Assembled> {+ let _span = solidcraft_profile::span("kernel", "assemble");let fail = |m: String| KernelError::Invalid(format!("sew: {m}"));let Parts { vertices, edges, faces, tolerance: tol } = parts;let nf = faces.len();diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rsindex e1d79d642d..f6d8098281 100644--- a/crates/kernel/src/splitface.rs+++ b/crates/kernel/src/splitface.rs@@ -455,6 +455,7 @@ pub fn split_faces(body: &Body, faces: &[usize], tool: &SplitTool) -> Result<Bod/// Like [`split_faces`], with the body face each face of the result came from (in face order).pub fn split_faces_with_map(body: &Body, faces: &[usize], tool: &SplitTool) -> Result<(Body, Vec<usize>)> {+ let _span = solidcraft_profile::span("kernel", "split_faces_with_map");let (b, map, made) = split(body, faces, tool)?;if let Some((missed, _)) = faces.iter().zip(&made).find(|(_, m)| **m == 0) {return Err(invalid(format!("the tool does not cross face {missed}")));@@ -538,6 +539,7 @@ fn new_lines(split: &Body, h: &History) -> Result<Vec<Vec<Vec3>>> {/// face order. A body the tool misses comes back whole. Each part's history is over `[body]`:/// its faces the body's (or pieces of them), the section new.pub fn split_body(body: &Body, tool: &SplitTool) -> Result<Vec<Body>> {+ let _span = solidcraft_profile::span("kernel", "split_body");const NAME: &str = "split body";body.require_brep(NAME)?;let reach = reach_of(body);diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rsindex 2ce3f8a192..b92d8a0f2f 100644--- a/crates/kernel/src/step_in/mod.rs+++ b/crates/kernel/src/step_in/mod.rs@@ -1045,6 +1045,7 @@ pub fn step_import(text: &str) -> Result<StepImport> {}fn step_import_with_workers(text: &str, workers: usize) -> Result<StepImport> {+ let _span = solidcraft_profile::span("import", "step.import");let mut reading = StepReading::with_workers(text, workers)?;while reading.step() {}reading.finish()@@ -1071,10 +1072,12 @@ impl StepReading {}fn with_workers(text: &str, workers: usize) -> Result<StepReading> {+ let _span = solidcraft_profile::span("import", "step.read_structure");let key = text_key(text);let watch = crate::watch::current();let cancelled = || watch.as_ref().is_some_and(|w| w.cancelled());- let ex = match p21::parse(text) {+ let parsed = solidcraft_profile::scope("import", "step.parse", || p21::parse(text));+ let ex = match parsed {Ok(ex) => Arc::new(ex),Err(_) if cancelled() => return Err(crate::watch::cancelled_error("STEP import")),Err(e) => return Err(KernelError::Invalid(e)),@@ -1086,7 +1089,7 @@ impl StepReading {.filter(|e| matches!(e.name(), "MANIFOLD_SOLID_BREP" | "BREP_WITH_VOIDS" | "FACETED_BREP" | "SHELL_BASED_SURFACE_MODEL")).count();rd.watch = watch.clone();- rd.index();+ solidcraft_profile::scope("import", "step.index", || rd.index());// Roots: product definitions that are nobody's component.let child_pds: HashSet<u64> =rd.children.values().flatten().filter_map(|n| ex.get(*n).and_then(|e| e.params().get(4)).and_then(Param::as_ref_id)).collect();@@ -1128,6 +1131,7 @@ impl StepReading {/// Convert the next solid (or batch of solids); false once all are converted (or the/// watch cancelled the import).pub fn step(&mut self) -> bool {+ let _span = solidcraft_profile::span("import", "step.convert_batch");self.rd.convert_next(self.single)}@@ -1139,6 +1143,7 @@ impl StepReading {/// The import, once [`Self::step`] has converted every solid.pub fn finish(mut self) -> Result<StepImport> {while self.step() {}+ let _span = solidcraft_profile::span("import", "step.finish");let rd = &mut self.rd;// Cancelled: what was read so far is dropped here, not cached.if rd.cancelled || rd.watch.as_ref().is_some_and(|w| w.cancelled()) {diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rsindex beb2b45854..f1e6257d4f 100644--- a/crates/kernel/src/step_in/parallel.rs+++ b/crates/kernel/src/step_in/parallel.rs@@ -59,6 +59,7 @@ pub(super) fn workers() -> usize {}fn prepare(ex: &Exchange, job: &Job) -> Prepared {+ let _span = solidcraft_profile::span("import", "step.body");let (part, read) = match &job.source {Source::Oriented(part) => (part.clone(), None),Source::Item { item, units } => {@@ -66,9 +67,10 @@ fn prepare(ex: &Exchange, job: &Job) -> Prepared {(Arc::new(part), Some(read))}};- let body = placed(&part.body, &job.placement).map_err(|e| Failure { read: false, msg: e.to_string() })?;+ let body = solidcraft_profile::scope("import", "step.place", || placed(&part.body, &job.placement))+ .map_err(|e| Failure { read: false, msg: e.to_string() })?;// Counted on the part (a placement meshes the same faces).- let missing = if job.check_mesh { part.body.unmeshed_faces() } else { 0 };+ let missing = if job.check_mesh { solidcraft_profile::scope("import", "step.mesh_check", || part.body.unmeshed_faces()) } else { 0 };Ok(Made { body, missing, part, read })}@@ -85,8 +87,10 @@ fn placed(body: &Body, m: &M4) -> crate::Result<Body> {/// and brought back as a body: the part SMLib made of the file. A solid the reader or SMLib/// refuses is not imported, with the reason.pub(super) fn smlib_part(ex: &Exchange, item: u64, units: Units) -> std::result::Result<(Part, Vec<String>), Failure> {- let solid = solidcraft_step::topology::read_solid_with(ex, item, units, &solidcraft_smlib::pcurves::SmlibTrims)- .map_err(|msg| Failure { read: true, msg })?;+ let solid = solidcraft_profile::scope("import", "step.read_solid", || {+ solidcraft_step::topology::read_solid_with(ex, item, units, &solidcraft_smlib::pcurves::SmlibTrims)+ })+ .map_err(|msg| Failure { read: true, msg })?;let failed = |e: KernelError| Failure { read: false, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() };let (brep, smlib_order) = crate::native::smlib_record_ordered(&solid.brep).map_err(failed)?;let (body, body_order) = crate::native::body_from_smlib_ordered(&brep).map_err(failed)?;diff --git a/crates/kernel/src/step_out.rs b/crates/kernel/src/step_out.rsindex 33957fd335..795a0a8499 100644--- a/crates/kernel/src/step_out.rs+++ b/crates/kernel/src/step_out.rs@@ -73,6 +73,7 @@ fn rigid_frame(m: &[[f64; 4]; 4]) -> Result<([f64; 3], [f64; 3], [f64; 3])> {/// STEP text (AP242) for products with bodies and assembly placements; `root` is the top product.pub fn step_export_products(products: &[ExportProduct], root: usize, header: &StepHeader) -> Result<String> {+ let _span = solidcraft_profile::span("kernel", "step_export_products");if products.is_empty() || root >= products.len() {return Err(KernelError::Invalid("nothing to export".into()));}@@ -290,6 +291,7 @@ fn style(w: &mut Writer, item: u64, c: [f32; 3], opacity: f32) -> u64 {/// STEP text for bodies of one part (names `Body1`…).pub fn step_export_bodies(bodies: &[ExportBody], header: &StepHeader) -> Result<String> {+ let _span = solidcraft_profile::span("kernel", "step_export_bodies");let name = if header.file_name.is_empty() {"Part".to_string()} else {diff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rsindex 9c1decc66f..49d1ef8e3d 100644--- a/crates/kernel/src/sweep_path.rs+++ b/crates/kernel/src/sweep_path.rs@@ -403,11 +403,13 @@ pub(crate) fn rail_frame(along: Vec3, across: Vec3, along_to: Vec3, across_to: V/// Sweep a planar region along a 3D polyline path. The profile keeps its relation to the path/// (it need not touch it); the path should start near the profile.pub fn sweep_path(plane: &Plane, region: &Region2, path: &[Vec3]) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sweep_path");sweep_path_with(plane, region, path, &SweepControl::default())}/// [`sweep_path`] with sweep options: orientation, twist and end scale.pub fn sweep_path_with(plane: &Plane, region: &Region2, path: &[Vec3], ctl: &SweepControl) -> Result<Body> {+ let _span = solidcraft_profile::span("kernel", "sweep_path_with");ctl.check()?;smlib_sweep_points(plane, region, &crate::PointPath::polyline(path.to_vec()), ctl)}diff --git a/crates/profile/src/lib.rs b/crates/profile/src/lib.rsindex caff753f3b..6fae490090 100644--- a/crates/profile/src/lib.rs+++ b/crates/profile/src/lib.rs@@ -21,8 +21,6 @@use std::time::Duration;-use serde_json::{Value, json};-/// The profiler is compiled into this build.pub const COMPILED: bool = cfg!(any(feature = "enabled", test));@@ -124,40 +122,6 @@ impl Report {}}- /// The report as JSON, with the `top` rows of most self time (0: all of them):- /// `{compiled, enabled, wall_ms, spans, dropped, by_category: [{category, self_ms, share}],- /// rows: [{category, name, count, total_ms, self_ms, max_ms}], rows_total}`.- pub fn to_json(&self, top: usize) -> Value {- let sorted = self.sorted();- let all: f64 = self.rows.iter().map(|r| r.self_time.as_secs_f64()).sum();- let by_category: Vec<Value> = self- .by_category()- .into_iter()- .map(|(c, d)| {- let share = if all > 0.0 { (d.as_secs_f64() / all * 1000.0).round() / 1000.0 } else { 0.0 };- json!({"category": c, "self_ms": ms(d), "share": share})- })- .collect();- let n = if top == 0 { sorted.len() } else { top.min(sorted.len()) };- let rows: Vec<Value> = sorted- .iter()- .take(n)- .map(|r| {- json!({"category": r.category, "name": r.name, "count": r.count, "total_ms": ms(r.total), "self_ms": ms(r.self_time), "max_ms": ms(r.max)})- })- .collect();- json!({- "compiled": self.compiled,- "enabled": self.enabled,- "wall_ms": ms(self.wall),- "spans": self.events as u64 + self.dropped,- "dropped": self.dropped,- "by_category": by_category,- "rows": rows,- "rows_total": sorted.len(),- })- }-/// The report as a text table with the `top` rows of most self time (0: all of them).pub fn table(&self, top: usize) -> String {use std::fmt::Write as _;diff --git a/crates/profile/src/tests.rs b/crates/profile/src/tests.rsindex a3da6ae4c4..85b3b95c9f 100644--- a/crates/profile/src/tests.rs+++ b/crates/profile/src/tests.rs@@ -90,9 +90,6 @@ fn a_mark_reports_only_what_came_after_it() {let r = m.report();assert_eq!(r.rows.len(), 1, "{r:?}");assert_eq!(row(&r, "after").count, 2);- let j = r.to_json(5);- assert_eq!(j["rows"][0]["name"], "after");- assert_eq!(j["rows_total"], 1);}#[test]@@ -106,7 +103,7 @@ fn spans_on_other_threads_get_their_own_track() {set_enabled(false);let mut out = Vec::new();write_chrome_trace(&mut out).unwrap();- let v: Value = serde_json::from_slice(&out).unwrap();+ let v: serde_json::Value = serde_json::from_slice(&out).unwrap();let events = v["traceEvents"].as_array().unwrap();let tid = |name: &str| events.iter().find(|e| e["name"] == name).map(|e| e["tid"].clone()).unwrap();assert_ne!(tid("main"), tid("on_worker"));diff --git a/crates/smlib/Cargo.toml b/crates/smlib/Cargo.tomlindex 16290aa710..2647a9945b 100644--- a/crates/smlib/Cargo.toml+++ b/crates/smlib/Cargo.toml@@ -27,6 +27,7 @@ native = [][dependencies]log = { workspace = true }solidcraft-geom = { workspace = true }+solidcraft-profile = { workspace = true }[target.'cfg(target_arch = "wasm32")'.dependencies]# The clocks SMLib's C library asks for in a browser build (src/ffi.rs).@@ -36,5 +37,6 @@ web-time = { workspace = true }cc = { version = "1.2", features = ["parallel"] }[dev-dependencies]+solidcraft-profile = { workspace = true, features = ["enabled"] }flate2 = "1.1"serde_json = { workspace = true }diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rsindex 557bb7cce4..8e284d8cb1 100644--- a/crates/smlib/src/lib.rs+++ b/crates/smlib/src/lib.rs@@ -137,7 +137,25 @@ fn c_path(p: &Path) -> Result<CString> {CString::new(p.to_string_lossy().as_bytes()).map_err(|_| Error::Argument)}+/// One C API call's log line, `smlib_fn(args) -> status (1.234 ms)`: the function and the time+/// the C API measured for it (inside its lock, so waiting for another thread's call is not in it).+fn call_time(line: &str) -> Option<(&str, std::time::Duration)> {+ let name = line.get(..line.find('(')?)?;+ if !name.starts_with("smlib_") || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {+ return None;+ }+ let tail = line.strip_suffix(" ms)")?;+ let ms: f64 = tail.get(tail.rfind(" (")? + 2..)?.parse().ok()?;+ (ms.is_finite() && ms >= 0.0).then(|| (name, std::time::Duration::from_secs_f64(ms / 1000.0)))+}+fn log_line(level: i32, text: String) {+ // Every call's log line carries the C API's own timing: the profiler's SMLib spans.+ if solidcraft_profile::enabled()+ && let Some((name, took)) = call_time(&text)+ {+ solidcraft_profile::record("smlib", solidcraft_profile::intern(name), took);+ }if level == 0 {log::debug!(target: "smlib", "{text}");} else {diff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rsindex 31b9fa08a0..84f4064619 100644--- a/crates/smlib/src/tests.rs+++ b/crates/smlib/src/tests.rs@@ -68,3 +68,25 @@ fn without_native_every_call_says_so() {assert_eq!(Brep::make_box([0.0; 3], [1.0; 3]).unwrap_err(), Error::NotBuilt);assert_eq!(current_call(), None);}++#[test]+fn call_lines_give_the_function_and_the_c_api_time() {+ let (name, took) = call_time("smlib_boolean(op=1, a=#3 (12 faces), b=#4) -> 0 (12.345 ms)").unwrap();+ assert_eq!((name, took), ("smlib_boolean", std::time::Duration::from_micros(12_345)));+ assert_eq!(call_time("smlib_make_box(origin=(0,0,0)) -> -1002 (0.001 ms)").map(|c| c.0), Some("smlib_make_box"));+ for bad in ["SMLib warning at x.cpp:12: tolerance (in smlib_boolean(...))", "smlib_x() -> 0 (nan ms)", "smlib_x() -> 0 (-1 ms)", "", "smlib_x"] {+ assert_eq!(call_time(bad), None, "{bad}");+ }+}++#[cfg(feature = "native")]+#[test]+fn every_call_is_a_profiler_span_timed_by_the_c_api() {+ solidcraft_profile::set_enabled(true);+ let mark = solidcraft_profile::mark();+ let b = Brep::make_box([0.0; 3], [1.0; 3]).unwrap();+ let _ = b.volume(1e-7).unwrap();+ let r = mark.report();+ let names: Vec<&str> = r.rows.iter().filter(|r| r.category == "smlib").map(|r| r.name).collect();+ assert!(names.contains(&"smlib_make_box") && names.contains(&"smlib_brep_volume"), "{r:?}");+}diff --git a/crates/step/Cargo.toml b/crates/step/Cargo.tomlindex 72e4f7afc6..80edcb5da1 100644--- a/crates/step/Cargo.toml+++ b/crates/step/Cargo.toml@@ -10,3 +10,4 @@ workspace = true[dependencies]solidcraft-geom = { workspace = true }+solidcraft-profile = { workspace = true }diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rsindex cfbec97fb0..fa01134f13 100644--- a/crates/step/src/topology.rs+++ b/crates/step/src/topology.rs@@ -305,6 +305,8 @@ fn read_with<'a>(let p = e.params();let name = p.first().and_then(Param::as_str).unwrap_or("").to_string();let mut b = Builder::new(ex, reader, tolerance(&context), budget, trims);+ // The file's faces, edges, vertices and their geometry read into the builder.+ let topology = solidcraft_profile::span("import", "step.topology");let (shells, kind) = match e.name() {"MANIFOLD_SOLID_BREP" => (vec![b.shell(rid(p.get(1), "outer shell")?)?], Kind::Solid),"BREP_WITH_VOIDS" => {@@ -331,6 +333,7 @@ fn read_with<'a>(}n => return Err(unsupported(n)),};+ drop(topology);b.finish(item, name, shells, kind)}@@ -689,6 +692,7 @@ impl<'b, 'a> Builder<'b, 'a> {/// Pcurves, outer loops, domains and the canonical order: the finished record.fn finish(mut self, item: u64, name: String, shells: Vec<Vec<(u32, bool)>>, kind: Kind) -> R<Solid> {+ let _span = solidcraft_profile::span("import", "step.solid_record");let mut notes = Vec::new();let seams = self.add_seams()?;if seams > 0 {@@ -980,6 +984,7 @@ impl<'b, 'a> Builder<'b, 'a> {/// outer loop runs clockwise about the natural normal on a surface where that cannot be a/// face's outer boundary.fn face_pcurves(&mut self, fi: usize) -> R<(Vec<Vec<Curve2>>, [[f64; 2]; 2], bool, Option<BSurface>)> {+ let _span = solidcraft_profile::span("import", "step.face_pcurves");let face = self.faces.get(fi).ok_or("face reference")?;let label = face.surface.clone();let edge_loops: Vec<Vec<(u32, bool)>> = face@@ -1107,6 +1112,7 @@ impl Builder<'_, '_> {edge_loops: &[Vec<(u32, bool)>],exact: Vec<Vec<Option<Curve2>>>,) -> R<TrimFace<'s>> {+ let _span = solidcraft_profile::span("import", "step.trim_face");let (mut edge_at, mut vertex_at) = (HashMap::new(), HashMap::new());let (mut edges, mut vertices) = (Vec::new(), Vec::new());let mut loops = Vec::with_capacity(edge_loops.len());diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.tomlindex 6afabfdf75..4754a1212c 100644--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@ -44,7 +44,7 @@ nix = { workspace = true }winreg = "0.56"[dev-dependencies]-solidcraft-engine = { workspace = true, features = ["bundled-render-library"] }+solidcraft-engine = { workspace = true, features = ["bundled-render-library", "profile"] }# Parse the source guard structurally, including code after inline test modules.syn = { workspace = true, features = ["visit"] }# The catalog guard reads every UI source file as Rust tokens; already in the tree throughdiff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex 8f9e70e34c..b9f1c56a72 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -602,6 +602,9 @@ preference_settings! {supersampling_adaptive: bool = true, PAGE_GRAPHICS => check_tr("ui.supersampling_adaptive");/// Show the frame rate in the view's corner (the view then redraws every frame).show_frame_rate: bool = false, PAGE_GRAPHICS => check_id("ui.frame_rate");+ /// Record where the time goes (SMLib's calls, kernel operations, features, commands, imports)+ /// for `diagnostics.profile` (docs/perf.md). Off by default: nothing is recorded.+ profile_operations: bool = false, PAGE_GRAPHICS => check_tr("prefs.profile_operations");/// With the frame rate: a frame-time graph, a histogram and what the GPU drew (#2548).frame_rate_details: bool = false, PAGE_GRAPHICS;/// Draw a wider rim under finished sketch curves to improve contrast on shaded faces.@@ -830,6 +833,9 @@ pub struct PrefsWindow {snapshot: Option<Snapshot>,/// The up axis preference the view follows now (applied when it changes, and at startup).applied_up: Option<String>,+ /// The Profile operations preference the profiler last followed: applied when it changes,+ /// so `diagnostics.profile` (an agent) and SOLIDCRAFT_PROFILE can switch it in between.+ applied_profile: Option<bool>,/// The search text of the interface font list.font_filter: String,/// Search text on the Plugins page.@@ -1096,6 +1102,15 @@ fn defaults(app: &mut SolveApp, page: usize) {/// the interface scale.pub fn apply(app: &mut SolveApp, ctx: &egui::Context) {apply_network(&app.preferences);+ // The profiler records while the preference is on (switched when it changes; at start-up only+ // when on, so SOLIDCRAFT_PROFILE=1 is not undone by the default).+ let profile = app.preferences.profile_operations;+ if app.prefs_window.applied_profile != Some(profile) {+ if profile || app.prefs_window.applied_profile.is_some() {+ solidcraft_engine::profile::set_enabled(profile);+ }+ app.prefs_window.applied_profile = Some(profile);+ }// The viewport's display quality (an unknown saved value draws at Normal).solidcraft_engine::doc::display_quality::set_current(solidcraft_engine::doc::display_quality::DisplayQuality::parse(&app.preferences.display_quality).unwrap_or_default(),@@ -2389,6 +2404,24 @@ pub(crate) fn reveal_preference(h: &mut crate::scenario::Harness, handle: &str)#[cfg(test)]mod tests {+ /// Profile operations switches the profiler when it changes, and only then: an agent's+ /// diagnostics.profile in between is not undone next frame.+ #[test]+ fn the_profile_preference_switches_the_profiler_when_it_changes() {+ use serde_json::json;+ let mut h = crate::scenario::Harness::new();+ h.frames(1);+ h.call("ui.prefs", json!({"profile_operations": true}));+ h.frames(2);+ assert!(solidcraft_engine::profile::enabled());+ h.app.session.execute("diagnostics.profile", &json!({"enabled": false})).unwrap();+ h.frames(2);+ assert!(!solidcraft_engine::profile::enabled(), "the command's choice stands");+ h.call("ui.prefs", json!({"profile_operations": false}));+ h.frames(2);+ assert!(!solidcraft_engine::profile::enabled());+ }+#[test]fn the_ghost_position_defaults_round_trips_and_reads_tolerantly() {use super::SpaceMouseGhost::{LeftViewport as Current, LeftWindow as Left, RightViewport as Right};diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rsindex bc19f89f62..ecdefff899 100644--- a/crates/ui-egui/src/prefs/graphics.rs+++ b/crates/ui-egui/src/prefs/graphics.rs@@ -163,6 +163,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {ui_kit::checkbox(ui, app.tr("ui.frame_rate_details"), &mut app.preferences.frame_rate_details).on_hover_text(app.tr("settings.frame_rate_details_note"));});+ setting::profile_operations(app, left).on_hover_text(app.tr("prefs.profile_operations_note"));setting::reference_geometry_through_bodies(app, left).on_hover_text(app.tr("settings.reference_geometry_through_bodies_help"));setting::sketch_halo(app, left);}