Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add performance tracing to Firmament builds and web rebuilds
Yuechen Lifedc87292c29
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.csindex ae8f56ce..71389f9e 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs@@ -160,6 +160,7 @@ public static class BrepDisplayTessellatorvar facePatches = new List<DisplayFaceMeshPatch>();try{+ var facePhase = BuildPerfTrace.Phase("tessellation.faces");foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value)){executionBudget?.ThrowIfExpired("FaceDispatch", face.Id);@@ -178,8 +179,10 @@ public static class BrepDisplayTessellatorfacePatches.Add(faceResult.Value);accumulatedDiagnostics.AddRange(faceResult.Diagnostics);}+ facePhase.Dispose();var edgePolylines = new List<DisplayEdgePolyline>();+ var edgePhase = BuildPerfTrace.Phase("tessellation.display-edges");foreach (var edge in body.Topology.Edges.OrderBy(e => e.Id.Value)){executionBudget?.ThrowIfExpired("EdgeDispatch");@@ -195,6 +198,7 @@ public static class BrepDisplayTessellatoredgePolylines.Add(edgeResult.Value);accumulatedDiagnostics.AddRange(edgeResult.Diagnostics);}+ edgePhase.Dispose();return KernelResult<DisplayTessellationResult>.Success(new DisplayTessellationResult(facePatches, edgePolylines), accumulatedDiagnostics);}diff --git a/Aetheris.Kernel.Core/Diagnostics/BuildPerfTrace.cs b/Aetheris.Kernel.Core/Diagnostics/BuildPerfTrace.csnew file mode 100644index 00000000..ffe797a2--- /dev/null+++ b/Aetheris.Kernel.Core/Diagnostics/BuildPerfTrace.cs@@ -0,0 +1,60 @@+using System.Diagnostics;++namespace Aetheris.Kernel.Core.Diagnostics;++/// <summary>Opt-in, synchronous build-phase measurements for local qualification.</summary>+public static class BuildPerfTrace+{+ private sealed class Frame(string name, long start, long allocated, Frame? parent)+ {+ public string Name { get; } = name;+ public long Start { get; } = start;+ public long Allocated { get; } = allocated;+ public Frame? Parent { get; } = parent;+ public long ChildTicks { get; set; }+ }++ private sealed class Scope(Frame? frame) : IDisposable+ {+ public void Dispose()+ {+ if (frame is null) return;+ var ticks = Stopwatch.GetTimestamp() - frame.Start;+ var allocated = GC.GetAllocatedBytesForCurrentThread() - frame.Allocated;+ Samples.Add(new(frame.Name, ticks * 1000d / Stopwatch.Frequency,+ (ticks - frame.ChildTicks) * 1000d / Stopwatch.Frequency, allocated));+ if (frame.Parent is not null) frame.Parent.ChildTicks += ticks;+ _current = frame.Parent;+ }+ }++ public sealed record Sample(string Name, double InclusiveMilliseconds, double ExclusiveMilliseconds, long AllocatedBytes);+ public sealed record BuildPerfSnapshot(Sample[] Phases, Dictionary<string, long> Counts, int Gc0, int Gc1, int Gc2);+ private static Frame? _current;+ private static bool _enabled;+ private static readonly List<Sample> Samples = [];+ private static readonly Dictionary<string, long> Counts = new(StringComparer.Ordinal);++ public static void Start()+ {+ Samples.Clear(); Counts.Clear(); _current = null; _enabled = true;+ }++ public static void Stop() { _enabled = false; _current = null; }++ public static IDisposable Phase(string name)+ {+ if (!_enabled) return new Scope(null);+ var frame = new Frame(name, Stopwatch.GetTimestamp(), GC.GetAllocatedBytesForCurrentThread(), _current);+ _current = frame;+ return new Scope(frame);+ }++ public static void Count(string name, long value)+ {+ if (_enabled) Counts[name] = value;+ }++ public static BuildPerfSnapshot Snapshot() => new(Samples.ToArray(), Counts.ToDictionary(),+ GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2));+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 68d0a154..7f940dd5 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -3,6 +3,7 @@ using System.Security.Cryptography;using System.Text.RegularExpressions;using Aetheris.Kernel.Core.Air;using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Step242;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Verification;@@ -371,26 +372,37 @@ public static class FirmamentBuildAndExport}if (explicitSchema == FirmamentFrontendSchema.WireForm || WireFormAuthoring.IsWireFormSource(materializerSource)){+ var parsePhase = BuildPerfTrace.Phase("firmament.wire-parse-and-bind");var authored = WireFormAuthoring.Parse(materializerSource);+ parsePhase.Dispose();if (!authored.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(authored.Diagnostics);+ var buildPhase = BuildPerfTrace.Phase("firmament.wire-brep-materialize");var built = WireFormBRepMaterializer.Build(authored.Value);+ buildPhase.Dispose();if (!built.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics);+ var stepPhase = BuildPerfTrace.Phase("firmament.step-export");var step = Step242Exporter.ExportBody(built.Value.Body, new Step242ExportOptions { ProductName = authored.Value.Name });+ stepPhase.Dispose();if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);+ var importPhase = BuildPerfTrace.Phase("firmament.step-reimport");var reimport = Step242Importer.ImportBody(step.Value);+ importPhase.Dispose();if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);var manifold = reimport.Value.Topology.Edges.All(edge => reimport.Value.Topology.Coedges.Count(use => use.EdgeId == edge.Id) == 2);if (!manifold) return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,"wireform-step-reimport-not-manifold: exported WireForm did not reimport as an enclosed manifold.", "FirmamentV2.WireForm")]);var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();+ var reportPhase = BuildPerfTrace.Phase("firmament.wire-report-validation");var report = WireFormReportFactory.Create(built.Value, hash, manifold);+ reportPhase.Dispose();return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, authored.Value.Name, 0,"wire-form", "wireform", WireForm: report,EngineeringFeatures: authored.Value.Operations.Select(operation => new FirmamentEngineeringFeatureReport(operation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "Helix", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.StableId(authored.Value.Name),authored.Value.Name, "WireState", "CircularSection", operation.LengthMm, "CenterlineLength", "Add",- PolicySource: "WireFormFeatureAir", MaterializationRoute: "WireFormCenterlineAir->CircularSweepBRepPlan")).ToArray()), []);+ PolicySource: "WireFormFeatureAir", MaterializationRoute: "WireFormCenterlineAir->CircularSweepBRepPlan")).ToArray())+ { RuntimeBody = reimport.Value }, []);}if (explicitSchema == FirmamentFrontendSchema.Sweep || CircularSweepAuthoring.IsSweepSource(materializerSource)){diff --git a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs b/Aetheris.Kernel.Firmament/Materializer/WireCoils.csindex 2a859533..cf5afb64 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs@@ -1,6 +1,7 @@using System.Globalization;using System.Text.RegularExpressions;using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Geometry.Curves;using Aetheris.Kernel.Core.Geometry.Surfaces;@@ -228,7 +229,13 @@ internal static class WireCoilBRepMaterializer{try{- var stations = Stations(feature); var r = feature.WireRadiusMm; var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var points = new Dictionary<VertexId, Point3D>(); var curves = 1; var surfaces = 1;+ var stationPhase = BuildPerfTrace.Phase("coil.helix-samples-and-frames");+ var stations = Stations(feature);+ stationPhase.Dispose();+ BuildPerfTrace.Count("coil.stations", stations.Count);+ BuildPerfTrace.Count("coil.section-quadrants", 4);+ var brepPhase = BuildPerfTrace.Phase("coil.sweep-surfaces-and-topology");+ var r = feature.WireRadiusMm; var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var points = new Dictionary<VertexId, Point3D>(); var curves = 1; var surfaces = 1;var vertices = new VertexId[stations.Count, 4]; var rings = new EdgeId[stations.Count, 4]; var ringControls = new Point3D[stations.Count, 4][];for (var i = 0; i < stations.Count; i++){@@ -256,7 +263,12 @@ internal static class WireCoilBRepMaterializervar startPlane = new PlaneSurface(stations[0].Point, Direction3D.Create(stations[0].Tangent.ToVector() * -1d), stations[0].Up); var endPlane = new PlaneSurface(stations[^1].Point, stations[^1].Tangent, stations[^1].Up);var start = AddFace(builder, Enumerable.Range(0, 4).Select(q => (rings[0, 3 - q], true)).ToArray()); geometry.AddSurface(new(surfaces), SurfaceGeometry.FromPlane(startPlane)); bindings.AddFaceBinding(new(start, new(surfaces++))); faces.Add(start);var end = AddFace(builder, Enumerable.Range(0, 4).Select(q => (rings[stations.Count - 1, q], false)).ToArray()); geometry.AddSurface(new(surfaces), SurfaceGeometry.FromPlane(endPlane)); bindings.AddFaceBinding(new(end, new(surfaces++))); faces.Add(end);- var shell = builder.AddShell(faces); builder.AddBody([shell]); var body = new BrepBody(builder.Model, geometry, bindings, points); var validation = BrepBindingValidator.Validate(body, true); if (!validation.IsSuccess) return KernelResult<WireFormBuildResult>.Failure(validation.Diagnostics);+ var shell = builder.AddShell(faces); builder.AddBody([shell]); var body = new BrepBody(builder.Model, geometry, bindings, points);+ brepPhase.Dispose();+ var validationPhase = BuildPerfTrace.Phase("coil.brep-binding-validation");+ var validation = BrepBindingValidator.Validate(body, true);+ validationPhase.Dispose();+ if (!validation.IsSuccess) return KernelResult<WireFormBuildResult>.Failure(validation.Diagnostics);var samples = stations.Select(x => x.Point).ToArray(); var bounds = new[] { samples.Min(p => p.X) - r, samples.Min(p => p.Y) - r, samples.Min(p => p.Z) - r, samples.Max(p => p.X) + r, samples.Max(p => p.Y) + r, samples.Max(p => p.Z) + r };var volume = Math.PI * r * r * feature.TotalWireLengthMm; var mass = volume * 1e-9 * feature.Material.Structural!.Density.SiValue;return KernelResult<WireFormBuildResult>.Success(new(feature, body, volume, mass, bounds, ["wireform-coil-evaluable-centerline-authority", "wireform-coil-parallel-transport", "wireform-coil-non-rational-bspline-sweep", "wireform-coil-deterministic-approximation"]));diff --git a/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj b/Aetheris.Web.Perf/Aetheris.Web.Perf.csprojnew file mode 100644index 00000000..8b99fd8a--- /dev/null+++ b/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj@@ -0,0 +1,16 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>+ <EnableDefaultCompileItems>false</EnableDefaultCompileItems>+ <StartupObject>Aetheris.Web.Perf.PerfProgram</StartupObject>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />+ <Compile Include="..\Aetheris.Web.Runtime\Program.cs" Link="WebProgram.cs" />+ <Compile Include="PerfProgram.cs" />+ </ItemGroup>+</Project>diff --git a/Aetheris.Web.Perf/PerfProgram.cs b/Aetheris.Web.Perf/PerfProgram.csnew file mode 100644index 00000000..d5963778--- /dev/null+++ b/Aetheris.Web.Perf/PerfProgram.cs@@ -0,0 +1,56 @@+using System.Diagnostics;+using System.Security.Cryptography;+using System.Text.Json;++namespace Aetheris.Web.Perf;++public static class PerfProgram+{+ public static int Main(string[] args)+ {+ if (args.Length != 1) { Console.Error.WriteLine("Usage: Aetheris.Web.Perf <helix-fixture>"); return 2; }+ var source = File.ReadAllText(args[0]);+ var variants = new[] { ("helix-1", source), ("helix-2", source.Replace("Turns: 1", "Turns: 2", StringComparison.Ordinal)),+ ("helix-5", source.Replace("Turns: 1", "Turns: 5", StringComparison.Ordinal)),+ ("helix-10", source.Replace("Turns: 1", "Turns: 10", StringComparison.Ordinal)),+ ("box", "Model PerfBox { Units: mm Box Body { Size: [30mm, 20mm, 10mm] } }"),+ ("hole", "Model PerfHole { Units: mm Box Body { Size: [30mm, 20mm, 10mm] } Modify Body { Hole<Shaft> H { On: +Z Center: Point2(0mm, 0mm) Diameter: 6mm End: ThroughAll } } }") };+ foreach (var (name, text) in variants)+ {+ var runs = name == "helix-1" ? 6 : 1;+ for (var run = 0; run < runs; run++)+ {+ var request = JsonSerializer.Serialize(new { operation = "compile", source = text, sourceName = name + ".firmament", performance = true });+ var started = Stopwatch.GetTimestamp();+ var response = Aetheris.Web.Runtime.Program.Invoke(request);+ var elapsed = Stopwatch.GetElapsedTime(started).TotalMilliseconds;+ using var document = JsonDocument.Parse(response);+ var root = document.RootElement;+ if (!root.GetProperty("ok").GetBoolean()) { Console.WriteLine(JsonSerializer.Serialize(new { runtime = "Native RyuJIT", name, run, elapsed, error = root.GetProperty("error") })); return 1; }+ var result = root.GetProperty("result");+ if (!result.GetProperty("success").GetBoolean()) { Console.WriteLine(JsonSerializer.Serialize(new { runtime = "Native RyuJIT", name, run, elapsed, diagnostics = result.GetProperty("diagnostics") })); return 1; }+ var model = result.GetProperty("model");+ object? stepEvidence = null;+ if (run == 0)+ {+ using var stepResult = JsonDocument.Parse(Aetheris.Web.Runtime.Program.Invoke(JsonSerializer.Serialize(new { operation = "exportStep", sessionId = model.GetProperty("id").GetString() })));+ var bytes = Convert.FromBase64String(stepResult.RootElement.GetProperty("result").GetProperty("base64").GetString()!);+ if (name == "helix-5")+ {+ var output = Path.Combine("artifacts", "local", "web-perf", "helix-5-native.step");+ Directory.CreateDirectory(Path.GetDirectoryName(output)!);+ File.WriteAllBytes(output, bytes);+ }+ stepEvidence = new { bytes = bytes.Length, sha256 = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant() };+ }+ var definition = model.GetProperty("mesh").GetProperty("definitions")[0];+ Console.WriteLine(JsonSerializer.Serialize(new { runtime = "Native RyuJIT", name, run, elapsed, timings = model.GetProperty("timings"),+ mesh = new { definitions = model.GetProperty("mesh").GetProperty("definitions").GetArrayLength(),+ vertices = definition.GetProperty("positions").GetArrayLength() / 3, triangles = definition.GetProperty("indices").GetArrayLength() / 3,+ ranges = definition.GetProperty("ranges").GetArrayLength(), edges = definition.GetProperty("edges").GetArrayLength() }, step = stepEvidence }));+ Aetheris.Web.Runtime.Program.Invoke(JsonSerializer.Serialize(new { operation = "disposeSession", sessionId = model.GetProperty("id").GetString() }));+ }+ }+ return 0;+ }+}diff --git a/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj b/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csprojindex 7a0911b5..c398431e 100644--- a/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj+++ b/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj@@ -13,5 +13,8 @@</PropertyGroup><ItemGroup><ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />+ <!-- The JSON bridge serializes anonymous response shapes through reflection. -->+ <TrimmerRootAssembly Include="Aetheris.Web.Runtime" />+ <TrimmerRootAssembly Include="Aetheris.Kernel.Firmament" /></ItemGroup></Project>diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.csindex 0804eb1e..ab886eec 100644--- a/Aetheris.Web.Runtime/Program.cs+++ b/Aetheris.Web.Runtime/Program.cs@@ -31,6 +31,7 @@ public static partial class Program{var request = JsonSerializer.Deserialize<WebRequest>(requestJson, JsonOptions)?? throw new WebRuntimeException("invalid-request", "The runtime request was empty.");+ if (request.Performance) BuildPerfTrace.Start();object result = request.Operation switch{"info" => Info(),@@ -48,14 +49,18 @@ public static partial class Program"disposeRuntime" => DisposeRuntime(),_ => throw new WebRuntimeException("unknown-operation", $"Unknown runtime operation '{request.Operation}'.")};- return JsonSerializer.Serialize(new { ok = true, result }, JsonOptions);+ var response = JsonSerializer.Serialize(new { ok = true, result }, JsonOptions);+ BuildPerfTrace.Stop();+ return response;}catch (WebRuntimeException exception){+ BuildPerfTrace.Stop();return JsonSerializer.Serialize(new { ok = false, error = new { code = exception.Code, message = exception.Message } }, JsonOptions);}catch (Exception exception){+ BuildPerfTrace.Stop();return JsonSerializer.Serialize(new { ok = false, error = new { code = "internal-error", message = "Aetheris could not complete the operation.", details = exception.Message } }, JsonOptions);}}@@ -175,7 +180,8 @@ public static partial class Programprivate sealed record WebRequest(string Operation, string? SessionId = null, string? Source = null,string? SourceName = null, string? PropertyId = null, WebPropertyValue? Value = null,string? SourceRevision = null, int? Offset = null, string? ConstructSemanticId = null,- string? FieldId = null, FirmamentProjectedValue? FieldValue = null, int? BuildRevision = null);+ string? FieldId = null, FirmamentProjectedValue? FieldValue = null, int? BuildRevision = null,+ bool Performance = false);private sealed class WebRuntimeException(string code, string message) : Exception(message){@@ -258,7 +264,11 @@ public static partial class Programpublic WebBuildResult Rebuild(){+ using var rebuildPhase = BuildPerfTrace.Phase("web.rebuild");+ var totalWatch = System.Diagnostics.Stopwatch.StartNew();+ var inspectPhase = BuildPerfTrace.Phase("web.property-inspection");var sourceProperties = ParameterInspector.Inspect(Id, _sourceName, _source);+ inspectPhase.Dispose();var effective = ApplyOverrides(_source, sourceProperties, _overrides);var nextProperties = sourceProperties;foreach (var (propertyId, value) in _overrides)@@ -283,11 +293,17 @@ public static partial class ProgrammeshChanged = true,diagnosticsChanged = false};+ var perf = BuildPerfTrace.Snapshot();+ var timings = new { compileMilliseconds = compiled.CompileMilliseconds, meshMilliseconds = compiled.MeshMilliseconds,+ totalBeforeSnapshotMilliseconds = totalWatch.Elapsed.TotalMilliseconds,+ profile = new { phases = perf.Phases.Select(sample => new { sample.Name, sample.InclusiveMilliseconds,+ sample.ExclusiveMilliseconds, sample.AllocatedBytes }).ToArray(), counts = perf.Counts,+ gc0 = perf.Gc0, gc1 = perf.Gc1, gc2 = perf.Gc2 } };_lastSnapshot = new{id = Id, name = Name, revision = Revision, source = _source, sourceName = _sourceName,tree = compiled.Tree, properties = _properties, mesh = compiled.Mesh,- diagnostics = compiled.Diagnostics, changes, timings = compiled.Timings+ diagnostics = compiled.Diagnostics, changes, timings};return compiled with { Revision = Revision, Model = _lastSnapshot, Changes = changes, StepText = null };}@@ -295,7 +311,9 @@ public static partial class Programprivate WebBuildResult CompilePart(string effective, List<WebProperty> properties){var watch = System.Diagnostics.Stopwatch.StartNew();+ var compilePhase = BuildPerfTrace.Phase("web.compile-and-export");var build = FirmamentBuildAndExport.CompileSource(effective);+ compilePhase.Dispose();var compileMs = watch.Elapsed.TotalMilliseconds;if (!build.IsSuccess || build.Value is null)return WebBuildResult.Failed(Diagnostics(build.Diagnostics, _sourceName), compileMs);@@ -304,12 +322,15 @@ public static partial class Programif (build.Value.RuntimeBody is { } canonicalBody) displayBody = canonicalBody;else{+ var displayImportPhase = BuildPerfTrace.Phase("web.display-step-reimport");var import = Step242Importer.ImportBody(step);+ displayImportPhase.Dispose();if (!import.IsSuccess || import.Value is null)return WebBuildResult.Failed(Diagnostics(import.Diagnostics, _sourceName), compileMs);displayBody = import.Value;}watch.Restart();+ var mappingPhase = BuildPerfTrace.Phase("web.source-projection");var definitionId = "definition:" + Sha(step)[..16].ToLowerInvariant();var entityId = build.Value.RuntimeCorrespondence?.BodyStableId?? (string.IsNullOrWhiteSpace(build.Value.ExportedFeatureId) ? Id + ":body" : build.Value.ExportedFeatureId);@@ -340,8 +361,11 @@ public static partial class ProgramsemanticConstruct ??= projections.FirstOrDefault(item => item.SemanticId == entityId)?.ConstructId.Value;var featureSources = (build.Value.Features ?? []).ToDictionary(feature => feature.FeatureId,feature => CompilerSource(feature.FeatureId), StringComparer.Ordinal);+ mappingPhase.Dispose();+ var meshPhase = BuildPerfTrace.Phase("web.mesh-build");var mesh = WebMeshBuilder.Build(Name, definitionId, entityId, displayBody,build.Value.RuntimeCorrespondence, boxSource, Revision + 1, featureSources);+ meshPhase.Dispose();var meshMs = watch.Elapsed.TotalMilliseconds;var featureNodes = (build.Value.EngineeringFeatures ?? []).Select(feature => new WebTreeNode(feature.FeatureId, feature.Kind, feature.Name, entityId, [], true,projections.FirstOrDefault(item => item.SemanticId == feature.FeatureId)?.ConstructSpan is { } span@@ -476,8 +500,15 @@ internal static class WebMeshBuilder{// Browser WASM has no blocking monitor wait. Use the existing synchronous// tessellator authority; the Worker transport supplies UI responsiveness.+ var tessPhase = BuildPerfTrace.Phase("web.tessellation");var tessellation = BrepDisplayTessellator.Tessellate(body, new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64));+ tessPhase.Dispose();if (!tessellation.IsSuccess) throw new InvalidOperationException(string.Join("; ", tessellation.Diagnostics.Select(item => item.Message)));+ BuildPerfTrace.Count("brep.faces", body.Topology.Faces.Count());+ BuildPerfTrace.Count("brep.edges", body.Topology.Edges.Count());+ BuildPerfTrace.Count("display.triangles", tessellation.Value.FacePatches.Sum(face => face.TriangleIndices.Count / 3));+ BuildPerfTrace.Count("display.edge-polylines", tessellation.Value.EdgePolylines.Count);+ var mapPhase = BuildPerfTrace.Phase("web.mesh-source-map-and-arrays");var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>(); var ranges = new List<object>();var sourceMap = correspondence is null ? null : new Aetheris.Kernel.Firmament.Materializer.GeometrySourceMap(correspondence);foreach (var face in tessellation.Value.FacePatches.OrderBy(face => face.FaceId.Value))@@ -498,6 +529,7 @@ internal static class WebMeshBuilder: semanticFace.FirmamentSelector is null ? "Construction identity is known, but Firmament has no qualified source selector for this topology." : null,source = semanticFace is null ? null : faceSource, buildRevision });}+ mapPhase.Dispose();return new{schema = "aetheris/display-mesh/1",@@ -528,8 +560,8 @@ internal sealed record WebTreeNode(string Id, string Kind, string Name, string?internal sealed record WebDiagnostic(string Severity, string Code, string Message, WebSourceRef? Source = null, string? Details = null);internal sealed record WebBuildResult(bool Success, int Revision, object? Model, IReadOnlyList<WebDiagnostic> Diagnostics, bool RetainedPreviousGeometry,object? Tree = null, object? Mesh = null, IReadOnlyList<string>? EntityIds = null, object? Timings = null, object? Changes = null, string? StepText = null,- IReadOnlyList<FirmamentConstructProjection>? Projections = null)+ IReadOnlyList<FirmamentConstructProjection>? Projections = null, double CompileMilliseconds = 0, double MeshMilliseconds = 0){- public static WebBuildResult Failed(IReadOnlyList<WebDiagnostic> diagnostics, double compileMs) => new(false, 0, null, diagnostics, false, Timings: new { compileMilliseconds = compileMs });- public static WebBuildResult Passed(string step, object tree, object mesh, IReadOnlyList<string> ids, double compileMs, double meshMs) => new(true, 0, null, [], false, tree, mesh, ids, new { compileMilliseconds = compileMs, meshMilliseconds = meshMs }, StepText: step);+ public static WebBuildResult Failed(IReadOnlyList<WebDiagnostic> diagnostics, double compileMs) => new(false, 0, null, diagnostics, false, Timings: new { compileMilliseconds = compileMs }, CompileMilliseconds: compileMs);+ public static WebBuildResult Passed(string step, object tree, object mesh, IReadOnlyList<string> ids, double compileMs, double meshMs) => new(true, 0, null, [], false, tree, mesh, ids, new { compileMilliseconds = compileMs, meshMilliseconds = meshMs }, StepText: step, CompileMilliseconds: compileMs, MeshMilliseconds: meshMs);}diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.mdindex 89e759b0..d410054a 100644--- a/Aetheris.Web.Runtime/sdk/README.md+++ b/Aetheris.Web.Runtime/sdk/README.md@@ -8,7 +8,7 @@ const cad = await Aetheris.create();const { model, diagnostics } = await cad.compile(source, { sourceName: 'bracket.firmament' });```-Vite projects add `aetherisCad()` from `@aetheris/cad/vite` to `vite.config.js`. The plugin serves the runtime during development and copies it into production builds.+Vite projects add `aetherisCad()` from `@aetheris/cad/vite` to `vite.config.js`. `npm run build` builds the fast non-AOT development package. `npm run build:production` also publishes the Worker runtime with .NET browser WebAssembly AOT (`RunAOTCompilation=true`, `WasmStripILAfterAOT=false`) using the installed Microsoft `wasm-tools` workload. The production package contains both `runtime/` for page-thread language assistance and `runtime-aot/` for geometry in the Worker. A production Vite build requires that AOT package and copies both runtimes; Vite dev and a development-mode build use only the non-AOT runtime. The caller's `wasmUrl` option remains an explicit override.## Selection correspondencediff --git a/Aetheris.Web.Runtime/sdk/package.json b/Aetheris.Web.Runtime/sdk/package.jsonindex ce37e911..e5d1980c 100644--- a/Aetheris.Web.Runtime/sdk/package.json+++ b/Aetheris.Web.Runtime/sdk/package.json@@ -18,6 +18,7 @@"files": ["dist", "README.md"],"scripts": {"build": "node scripts/build.mjs",+ "build:production": "node scripts/build.mjs --production","pack:local": "npm run build && npm pack"},"engines": { "node": ">=20" },diff --git a/Aetheris.Web.Runtime/sdk/scripts/build.mjs b/Aetheris.Web.Runtime/sdk/scripts/build.mjsindex 84213c4a..d11fb052 100644--- a/Aetheris.Web.Runtime/sdk/scripts/build.mjs+++ b/Aetheris.Web.Runtime/sdk/scripts/build.mjs@@ -7,17 +7,28 @@ const here = dirname(fileURLToPath(import.meta.url));const sdk = resolve(here, '..');const runtime = resolve(sdk, '..');const repo = resolve(runtime, '..');-const result = spawnSync('dotnet', ['build', join(runtime, 'Aetheris.Web.Runtime.csproj'), '-c', 'Release', '--nologo'], { cwd: repo, stdio: 'inherit' });-if (result.status !== 0) process.exit(result.status ?? 1);+const production = process.argv.includes('--production');+const project = join(runtime, 'Aetheris.Web.Runtime.csproj');+const run = args => {+ const result = spawnSync('dotnet', args, { cwd: repo, stdio: 'inherit' });+ if (result.status !== 0) process.exit(result.status ?? 1);+};+run(['build', project, '-c', 'Release', '--nologo']);const app = join(runtime, 'bin', 'Release', 'net10.0', 'wwwroot');const dist = join(sdk, 'dist');await rm(dist, { recursive: true, force: true });await mkdir(dist, { recursive: true });await cp(join(app, '_framework'), join(dist, 'runtime', '_framework'), { recursive: true });+if (production) {+ const published = join(repo, 'artifacts', 'local', 'helios-sdk', 'aot-publish');+ run(['publish', project, '-c', 'Release', '-p:RunAOTCompilation=true', '-p:WasmStripILAfterAOT=false',+ '-o', published, '--nologo', '-m:1']);+ await cp(join(published, 'wwwroot', '_framework'), join(dist, 'runtime-aot', '_framework'), { recursive: true });+}await copyFile(join(sdk, 'src', 'index.js'), join(dist, 'index.js'));await copyFile(join(sdk, 'src', 'worker.js'), join(dist, 'worker.js'));await copyFile(join(sdk, 'src', 'runtime.js'), join(dist, 'runtime.js'));await copyFile(join(sdk, 'src', 'index.d.ts'), join(dist, 'index.d.ts'));await copyFile(join(sdk, 'src', 'vite.js'), join(dist, 'vite.js'));await copyFile(join(sdk, 'src', 'vite.d.ts'), join(dist, 'vite.d.ts'));-console.log(`Built @aetheris/cad at ${dist}`);+console.log(`Built ${production ? 'production AOT + page runtime' : 'development runtime'} @aetheris/cad at ${dist}`);diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.tsindex 51010dfc..8c7d7e15 100644--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts@@ -17,8 +17,8 @@ export interface ChangeSet { readonly changedEntityIds: readonly string[]; readoexport interface RebuildResult { readonly success: boolean; readonly revision: number; readonly diagnostics: readonly Diagnostic[]; readonly retainedPreviousGeometry: boolean; readonly changes?: ChangeSet }export interface RuntimeCapabilities { readonly compile: boolean; readonly solidModeling: boolean; readonly assembly: boolean; readonly displayMesh: boolean; readonly propertyInspection: boolean; readonly parameterRebuild: boolean; readonly stepExport: boolean; readonly sheetMetal: boolean; readonly fea: boolean; readonly externalStepImport: boolean; readonly forgeSubprocess: boolean; readonly cancellation: boolean; readonly worker: boolean }export interface RuntimeInfo { readonly packageVersion: string; readonly runtimeVersion: string; readonly contractVersion: 'aetheris/web-editor-contract/1'; readonly language: 'Firmament'; readonly capabilities: RuntimeCapabilities }-export interface WorkerTiming { readonly operation: string; readonly executionMilliseconds: number; readonly transportMilliseconds: number; readonly payloadBytes: number }-export interface OperationOptions { readonly signal?: AbortSignal; readonly sourceRevision?: string }+export interface WorkerTiming { readonly operation: string; readonly executionMilliseconds: number; readonly transportMilliseconds: number; readonly payloadBytes: number; readonly initialization?: { readonly moduleImportMilliseconds: number; readonly runtimeCreateMilliseconds: number; readonly assemblyExportsMilliseconds: number } | null }+export interface OperationOptions { readonly signal?: AbortSignal; readonly sourceRevision?: string; readonly performance?: boolean }export interface CompileOptions extends OperationOptions { readonly sourceName?: string }export interface LanguageOptions { readonly sourceName?: string; readonly sourceRevision: string }export interface LanguageField { readonly name: string; readonly type: string; readonly required: boolean; readonly meaning: string; readonly default?: string | null; readonly choices?: readonly string[] | null }@@ -49,7 +49,7 @@ export class Aetheris {export class ModelSession {readonly id: string; readonly name: string; readonly revision: number; readonly source: string; readonly sourceName: string;readonly tree: ModelTree; readonly properties: readonly EditableProperty[]; readonly mesh: DisplayMesh; readonly diagnostics: readonly Diagnostic[]; readonly changes: ChangeSet;- readonly timings?: { readonly compileMilliseconds: number; readonly meshMilliseconds?: number };+ readonly timings?: { readonly compileMilliseconds: number; readonly meshMilliseconds?: number; readonly totalBeforeSnapshotMilliseconds?: number; readonly profile?: { readonly phases: readonly { readonly name: string; readonly inclusiveMilliseconds: number; readonly exclusiveMilliseconds: number; readonly allocatedBytes: number }[]; readonly counts: Readonly<Record<string, number>>; readonly gc0: number; readonly gc1: number; readonly gc2: number } };readonly workerTiming: WorkerTiming | null;entity(id: string): ModelTreeNode | undefined;property(id: string): EditableProperty | undefined;diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.jsindex 2f521514..ad7495c9 100644--- a/Aetheris.Web.Runtime/sdk/src/index.js+++ b/Aetheris.Web.Runtime/sdk/src/index.js@@ -3,6 +3,9 @@ import { createRuntime } from './runtime.js';const defaultRuntimeBase = typeof __AETHERIS_RUNTIME_BASE__ !== 'undefined'? new URL(__AETHERIS_RUNTIME_BASE__, globalThis.location?.href): new URL('./runtime/', import.meta.url);+const workerRuntimeBase = typeof __AETHERIS_WORKER_RUNTIME_BASE__ !== 'undefined'+ ? new URL(__AETHERIS_WORKER_RUNTIME_BASE__, globalThis.location?.href)+ : defaultRuntimeBase;export class AetherisError extends Error {constructor(code, message, details) { super(message); this.name = 'AetherisError'; this.code = code; this.details = details; }@@ -30,7 +33,8 @@ class WorkerTransport {if (data.version !== 1) { pending.reject(new AetherisError('worker-protocol', `Unsupported Aetheris worker protocol ${data.version}.`)); return; }if (data.sourceRevision !== pending.sourceRevision) { pending.reject(new AetherisError('worker-revision', 'The Aetheris worker returned a mismatched source revision.')); return; }this.lastTiming = { operation: pending.operation, executionMilliseconds: data.executionMilliseconds ?? 0,- transportMilliseconds: Math.max(0, performance.now() - pending.started - (data.executionMilliseconds ?? 0)), payloadBytes: data.payloadBytes ?? 0 };+ transportMilliseconds: Math.max(0, performance.now() - pending.started - (data.executionMilliseconds ?? 0)),+ initialization: data.initialization ?? null, payloadBytes: data.payloadBytes ?? 0 };data.error ? pending.reject(new AetherisError(data.error.code, data.error.message, data.error.details)) : pending.resolve(data.result);};this.worker.onerror = event => {@@ -66,7 +70,8 @@ class WorkerTransport {export class Aetheris {static async create(options = {}) {- const runtimeBase = options.wasmUrl ? new URL(options.wasmUrl, globalThis.location?.href) : defaultRuntimeBase;+ const runtimeBase = options.wasmUrl ? new URL(options.wasmUrl, globalThis.location?.href)+ : options.worker === true ? workerRuntimeBase : defaultRuntimeBase;const transport = options.worker === true ? new WorkerTransport(runtimeBase) : new DirectTransport(runtimeBase);const cad = new Aetheris(transport, options.diagnostics);try { cad.runtimeInfo = await cad.info(); }@@ -88,7 +93,7 @@ export class Aetheris {async capabilities() { return (await this.info()).capabilities; }async compile(source, options = {}) {throwIfAborted(options.signal);- const result = await this.transport.request({ operation: 'compile', source, sourceName: options.sourceName, sourceRevision: options.sourceRevision });+ const result = await this.transport.request({ operation: 'compile', source, sourceName: options.sourceName, sourceRevision: options.sourceRevision, performance: options.performance });this.diagnostics?.(result.diagnostics);return { model: result.success ? new ModelSession(this.transport, result.model) : null, diagnostics: result.diagnostics };}@@ -144,7 +149,7 @@ export class ModelSession {}async rebuild(options = {}) {throwIfAborted(options.signal);- const result = await this.transport.request({ operation: 'rebuild', sessionId: this.id, sourceRevision: options.sourceRevision });+ const result = await this.transport.request({ operation: 'rebuild', sessionId: this.id, sourceRevision: options.sourceRevision, performance: options.performance });if (result.success) this.apply(result.model);return result;}diff --git a/Aetheris.Web.Runtime/sdk/src/runtime.js b/Aetheris.Web.Runtime/sdk/src/runtime.jsindex d7233517..77ec4761 100644--- a/Aetheris.Web.Runtime/sdk/src/runtime.js+++ b/Aetheris.Web.Runtime/sdk/src/runtime.js@@ -18,17 +18,40 @@ export function transferables(value) {export async function createRuntime(runtimeBase = new URL('./runtime/', import.meta.url)) {const dotnetUrl = new URL('_framework/dotnet.js', runtimeBase);+ const importStart = performance.now();const { dotnet } = await import(dotnetUrl.href);+ const moduleImportMilliseconds = performance.now() - importStart;+ const createStart = performance.now();const runtime = await dotnet.withApplicationArguments().create();+ const runtimeCreateMilliseconds = performance.now() - createStart;+ const exportsStart = performance.now();const exports = await runtime.getAssemblyExports('Aetheris.Web.Runtime.dll');+ const assemblyExportsMilliseconds = performance.now() - exportsStart;const invoke = exports.Aetheris.Web.Runtime.Program.Invoke;- return request => {- const envelope = JSON.parse(invoke(JSON.stringify(request)));+ const requestRuntime = request => {+ const start = performance.now();+ const requestJson = JSON.stringify(request);+ const requestMilliseconds = performance.now() - start;+ const invokeStart = performance.now();+ const responseJson = invoke(requestJson);+ const invokeMilliseconds = performance.now() - invokeStart;+ const parseStart = performance.now();+ const envelope = JSON.parse(responseJson);+ const responseParseMilliseconds = performance.now() - parseStart;if (!envelope.ok) {const error = new Error(envelope.error.message);error.name = 'AetherisError'; error.code = envelope.error.code; error.details = envelope.error.details;throw error;}- return normalizeMesh(envelope.result);+ const normalizeStart = performance.now();+ const result = normalizeMesh(envelope.result);+ const meshNormalizeMilliseconds = performance.now() - normalizeStart;+ if (request.performance && result?.model?.timings) result.model.timings.bridge = {+ requestMilliseconds, invokeMilliseconds, responseParseMilliseconds,+ meshNormalizeMilliseconds, responseBytes: responseJson.length+ };+ return result;};+ requestRuntime.initTiming = { moduleImportMilliseconds, runtimeCreateMilliseconds, assemblyExportsMilliseconds };+ return requestRuntime;}diff --git a/Aetheris.Web.Runtime/sdk/src/vite.js b/Aetheris.Web.Runtime/sdk/src/vite.jsindex 435dbc87..92a938c1 100644--- a/Aetheris.Web.Runtime/sdk/src/vite.js+++ b/Aetheris.Web.Runtime/sdk/src/vite.js@@ -4,15 +4,24 @@ import { extname, join, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';const runtimeDirectory = fileURLToPath(new URL('./runtime/', import.meta.url));+const aotRuntimeDirectory = fileURLToPath(new URL('./runtime-aot/', import.meta.url));const publicPath = '/aetheris-runtime/';+const aotPublicPath = '/aetheris-runtime-aot/';const mime = new Map([['.js', 'text/javascript'], ['.json', 'application/json'], ['.wasm', 'application/wasm'], ['.pdb', 'application/octet-stream'], ['.dat', 'application/octet-stream']]);export function aetherisCad() {- let outputDirectory;+ let outputDirectory; let production = false;return {name: 'aetheris-cad-runtime',enforce: 'pre',- config: () => ({ define: { __AETHERIS_RUNTIME_BASE__: JSON.stringify(publicPath) }, optimizeDeps: { exclude: ['@aetheris/cad'] } }),+ config: (_, environment) => {+ production = environment.command === 'build' && environment.mode === 'production';+ if (production && !existsSync(aotRuntimeDirectory))+ throw new Error('Production requires the AOT SDK package. Run npm run sdk:install:production.');+ return { define: { __AETHERIS_RUNTIME_BASE__: JSON.stringify(publicPath),+ __AETHERIS_WORKER_RUNTIME_BASE__: JSON.stringify(production ? aotPublicPath : publicPath) },+ optimizeDeps: { exclude: ['@aetheris/cad'] } };+ },configResolved: config => { outputDirectory = config.build.outDir; },configureServer(server) {server.middlewares.use(publicPath, async (request, response, next) => {@@ -25,7 +34,22 @@ export function aetherisCad() {createReadStream(path).pipe(response);});},- async writeBundle() { await cp(runtimeDirectory, join(outputDirectory, 'aetheris-runtime'), { recursive: true }); }+ configurePreviewServer(server) {+ server.middlewares.use((request, response, next) => {+ const path = (request.url ?? '').split('?')[0];+ if (path.startsWith(aotPublicPath) || path.startsWith(publicPath)) {+ // Manifest-fingerprinted runtime assets are immutable. Boot files keep+ // a short freshness window so a newly deployed manifest is observed.+ response.setHeader('Cache-Control', /\.[a-z0-9]{10,}\.(?:wasm|dll|js|dat)$/.test(path)+ ? 'public, max-age=31536000, immutable' : 'public, max-age=300');+ }+ next();+ });+ },+ async writeBundle() {+ await cp(runtimeDirectory, join(outputDirectory, 'aetheris-runtime'), { recursive: true });+ if (production) await cp(aotRuntimeDirectory, join(outputDirectory, 'aetheris-runtime-aot'), { recursive: true });+ }};}diff --git a/Aetheris.Web.Runtime/sdk/src/worker.js b/Aetheris.Web.Runtime/sdk/src/worker.jsindex a31394fa..ab8fcf6c 100644--- a/Aetheris.Web.Runtime/sdk/src/worker.js+++ b/Aetheris.Web.Runtime/sdk/src/worker.js@@ -14,10 +14,10 @@ self.addEventListener('message', async event => {if (request.operation === 'exportStep') {const binary = atob(result.base64);const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));- self.postMessage({ version, id, sourceRevision, result: { bytes }, executionMilliseconds, payloadBytes: bytes.byteLength }, { transfer: [bytes.buffer] });+ self.postMessage({ version, id, sourceRevision, result: { bytes }, executionMilliseconds, initialization: invoke.initTiming, payloadBytes: bytes.byteLength }, { transfer: [bytes.buffer] });} else {const buffers = transferables(result);- self.postMessage({ version, id, sourceRevision, result, executionMilliseconds, payloadBytes: buffers.reduce((size, buffer) => size + buffer.byteLength, 0) }, { transfer: buffers });+ self.postMessage({ version, id, sourceRevision, result, executionMilliseconds, initialization: invoke.initTiming, payloadBytes: buffers.reduce((size, buffer) => size + buffer.byteLength, 0) }, { transfer: buffers });}} catch (error) {self.postMessage({ version, id, sourceRevision, error: { name: error.name, code: error.code ?? 'internal-error', message: error.message, details: error.details } });diff --git a/fixtures/Firmament/web-perf-helix-1.firmament b/fixtures/Firmament/web-perf-helix-1.firmamentnew file mode 100644index 00000000..b11b380e--- /dev/null+++ b/fixtures/Firmament/web-perf-helix-1.firmament@@ -0,0 +1,15 @@+Model HelixWitness {+ Units: mm+ WireForm Spring {+ Diameter: 2mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm, 0mm, 0mm]; Tangent: [1, 0, 0]; Up: [0, 0, 1] }+ Helix Winding {+ Radius: 6mm+ Turns: 1+ Pitch: 5mm+ Handedness: RightHanded+ StartPhase: 0deg+ }+ }+}