Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Claude perf optimization M1.

Yuechen Li59d785c322ee
diff --git a/Aetheris.Kernel.Core.Tests/Brep/BrepBodyCloneTests.cs b/Aetheris.Kernel.Core.Tests/Brep/BrepBodyCloneTests.cs
new file mode 100644
index 00000000..1fe04708
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/BrepBodyCloneTests.cs
@@ -0,0 +1,34 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Tests.Brep;
+
+public sealed class BrepBodyCloneTests
+{
+ [Fact]
+ public void CloneExportsIdenticalStepAndPreservesEnumerationOrder()
+ {
+ var body = BrepPrimitives.CreateBox(4d, 6d, 8d).Value;
+ var clone = body.Clone();
+ Assert.Equal(body.Topology.Faces.Select(f => f.Id), clone.Topology.Faces.Select(f => f.Id));
+ Assert.Equal(body.Topology.Edges.Select(e => e.Id), clone.Topology.Edges.Select(e => e.Id));
+ Assert.Equal(body.Bindings.FaceBindings, clone.Bindings.FaceBindings);
+ Assert.Equal(body.Geometry.Surfaces.Select(s => s.Key), clone.Geometry.Surfaces.Select(s => s.Key));
+ Assert.Equal(Step242Exporter.ExportBody(body).Value, Step242Exporter.ExportBody(clone).Value);
+ }
+
+ [Fact]
+ public void AddingToACloneLeavesTheOriginalUnchanged()
+ {
+ var body = BrepPrimitives.CreateBox(4d, 6d, 8d).Value;
+ var vertices = body.Topology.Vertices.Count();
+ var curves = body.Geometry.Curves.Count();
+ var clone = body.Clone();
+ clone.Topology.AddVertex(new Vertex(new VertexId(1_000_000)));
+ clone.Geometry.AddCurve(new Aetheris.Kernel.Core.Geometry.CurveGeometryId(1_000_000), body.Geometry.Curves.First().Value);
+ Assert.Equal(vertices, body.Topology.Vertices.Count());
+ Assert.Equal(curves, body.Geometry.Curves.Count());
+ Assert.Equal(vertices + 1, clone.Topology.Vertices.Count());
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/BrepBindings.cs b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
index 3632b76a..5637b77c 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBindings.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
@@ -241,6 +241,18 @@ public sealed class BrepBindingModel
public IEnumerable<FaceBoundaryRoleBinding> FaceBoundaryRoleBindings => _faceBoundaryRoleBindings.Values;
public IEnumerable<VertexLoopParameterBinding> VertexLoopParameterBindings => _vertexLoopParameterBindings.Values;
+ /// <summary>An independent binding model with the same (immutable) bindings in the same order.</summary>
+ public BrepBindingModel Clone()
+ {
+ var copy = new BrepBindingModel();
+ foreach (var (id, binding) in _edgeBindings) copy._edgeBindings.Add(id, binding);
+ foreach (var (id, binding) in _faceBindings) copy._faceBindings.Add(id, binding);
+ foreach (var (id, binding) in _pcurveBindings) copy._pcurveBindings.Add(id, binding);
+ foreach (var (id, binding) in _faceBoundaryRoleBindings) copy._faceBoundaryRoleBindings.Add(id, binding);
+ foreach (var (id, binding) in _vertexLoopParameterBindings) copy._vertexLoopParameterBindings.Add(id, binding);
+ return copy;
+ }
+
public void AddEdgeBinding(EdgeGeometryBinding binding) => _edgeBindings.Add(binding.EdgeId, binding);
public void AddFaceBinding(FaceGeometryBinding binding) => _faceBindings.Add(binding.FaceId, binding);
diff --git a/Aetheris.Kernel.Core/Brep/BrepBody.cs b/Aetheris.Kernel.Core/Brep/BrepBody.cs
index 40a9bd45..a99eddbc 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBody.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBody.cs
@@ -57,6 +57,18 @@ public sealed class BrepBody
/// <summary>Source BRep evidence; display completeness is assessed separately.</summary>
public Aetheris.Kernel.Core.Import.BrepImportQualificationReport? ImportQualification { get; internal set; }
+ /// <summary>
+ /// An independent body: its topology, geometry and binding stores are copies, so adding to them
+ /// (pcurve recovery, for example) cannot affect this body. Entities, geometry objects and reports
+ /// are immutable and shared. Enumeration order is preserved, so downstream output is identical.
+ /// </summary>
+ public BrepBody Clone() => new(Topology.Clone(), Geometry.Clone(), Bindings.Clone(),
+ new Dictionary<VertexId, Point3D>(_vertexPoints), SafeBooleanComposition, ShellRepresentation, FaceOrientationReport)
+ {
+ PcurveRecoveryReport = PcurveRecoveryReport,
+ ImportQualification = ImportQualification,
+ };
+
public bool TryGetVertexPoint(VertexId vertexId, out Point3D point) => _vertexPoints.TryGetValue(vertexId, out point);
public bool TryGetEdgeCurveGeometry(EdgeId edgeId, out CurveGeometry? curve)
diff --git a/Aetheris.Kernel.Core/Brep/BrepGeometryStore.cs b/Aetheris.Kernel.Core/Brep/BrepGeometryStore.cs
index 1e921e7c..e0130032 100644
--- a/Aetheris.Kernel.Core/Brep/BrepGeometryStore.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepGeometryStore.cs
@@ -14,6 +14,15 @@ public sealed class BrepGeometryStore
public IEnumerable<KeyValuePair<SurfaceGeometryId, SurfaceGeometry>> Surfaces => _surfaces;
+ /// <summary>An independent store sharing the immutable curve and surface objects, in the same order.</summary>
+ public BrepGeometryStore Clone()
+ {
+ var copy = new BrepGeometryStore();
+ foreach (var (id, curve) in _curves) copy._curves.Add(id, curve);
+ foreach (var (id, surface) in _surfaces) copy._surfaces.Add(id, surface);
+ return copy;
+ }
+
public void AddCurve(CurveGeometryId id, CurveGeometry curve) => _curves.Add(id, curve);
public void AddSurface(SurfaceGeometryId id, SurfaceGeometry surface) => _surfaces.Add(id, surface);
diff --git a/Aetheris.Kernel.Core/Diagnostics/BuildPerfTrace.cs b/Aetheris.Kernel.Core/Diagnostics/BuildPerfTrace.cs
index ffe797a2..673dc8c7 100644
--- a/Aetheris.Kernel.Core/Diagnostics/BuildPerfTrace.cs
+++ b/Aetheris.Kernel.Core/Diagnostics/BuildPerfTrace.cs
@@ -34,10 +34,12 @@ public static class BuildPerfTrace
private static bool _enabled;
private static readonly List<Sample> Samples = [];
private static readonly Dictionary<string, long> Counts = new(StringComparer.Ordinal);
+ private static int _gc0, _gc1, _gc2;
public static void Start()
{
Samples.Clear(); Counts.Clear(); _current = null; _enabled = true;
+ _gc0 = GC.CollectionCount(0); _gc1 = GC.CollectionCount(1); _gc2 = GC.CollectionCount(2);
}
public static void Stop() { _enabled = false; _current = null; }
@@ -55,6 +57,7 @@ public static class BuildPerfTrace
if (_enabled) Counts[name] = value;
}
+ /// <summary>Phases closed so far and the collections since <see cref="Start"/>.</summary>
public static BuildPerfSnapshot Snapshot() => new(Samples.ToArray(), Counts.ToDictionary(),
- GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2));
+ GC.CollectionCount(0) - _gc0, GC.CollectionCount(1) - _gc1, GC.CollectionCount(2) - _gc2);
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index 2fbed82b..e51a47ac 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -114,6 +114,7 @@ public static class Step242Importer
public static KernelResult<BrepBody> ImportBody(string stepText, ImportPolicy? policy = null)
{
+ using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("step.import-body");
var orchestrator = ImportOrchestrator.CreateDefault();
var result = orchestrator.Import(new ImportRequest(stepText, policy));
return result.BodyResult;
diff --git a/Aetheris.Kernel.Core/Topology/TopologyModel.cs b/Aetheris.Kernel.Core/Topology/TopologyModel.cs
index 2e10b337..31033df1 100644
--- a/Aetheris.Kernel.Core/Topology/TopologyModel.cs
+++ b/Aetheris.Kernel.Core/Topology/TopologyModel.cs
@@ -18,6 +18,21 @@ public sealed class TopologyModel
public IEnumerable<Shell> Shells => _shells.Values;
public IEnumerable<Body> Bodies => _bodies.Values;
+ /// <summary>An independent model with the same entities in the same insertion order. Entities
+ /// are immutable records, so only the containers are copied.</summary>
+ public TopologyModel Clone()
+ {
+ var copy = new TopologyModel();
+ foreach (var (id, item) in _vertices) copy._vertices.Add(id, item);
+ foreach (var (id, item) in _edges) copy._edges.Add(id, item);
+ foreach (var (id, item) in _coedges) copy._coedges.Add(id, item);
+ foreach (var (id, item) in _loops) copy._loops.Add(id, item);
+ foreach (var (id, item) in _faces) copy._faces.Add(id, item);
+ foreach (var (id, item) in _shells) copy._shells.Add(id, item);
+ foreach (var (id, item) in _bodies) copy._bodies.Add(id, item);
+ return copy;
+ }
+
public void AddVertex(Vertex vertex) => _vertices.Add(vertex.Id, vertex);
public void AddEdge(Edge edge) => _edges.Add(edge.Id, edge);
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs
index 94b47dad..ae6b7675 100644
--- a/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs
@@ -45,6 +45,36 @@ public sealed class IncrementalCompilationTests
Assert.NotSame(first.Geometry!.DefinitionBodies.Values.Single(), second.Geometry.DefinitionBodies.Values.Single());
}
+ [Fact]
+ public void SessionDisplayMeshOfReusedDefinitionMatchesAFreshExport()
+ {
+ using var session = new FirmamentCompilationSession();
+ var first = Good(session.Compile(Source()));
+ var firstMesh = AssemblyDisplayMeshExporter.Serialize(session.ExportDisplayMesh(first));
+ var second = Good(session.Compile(Source()));
+ Assert.Equal(1, second.Reuse!.ReusedDefinitions);
+ var baseline = Good(new AssemblyM1Pipeline().Compile(Source()));
+ var expected = AssemblyDisplayMeshExporter.Serialize(AssemblyDisplayMeshExporter.Export(baseline));
+ Assert.Equal(expected, firstMesh);
+ Assert.Equal(expected, AssemblyDisplayMeshExporter.Serialize(session.ExportDisplayMesh(second)));
+ }
+
+ [Fact]
+ public void MutatingAReusedBodyCannotLeakIntoTheNextBuild()
+ {
+ using var session = new FirmamentCompilationSession();
+ Good(session.Compile(Source()));
+ var reused = Good(session.Compile(Source()));
+ var body = reused.Geometry!.DefinitionBodies.Values.Single();
+ body.Topology.AddVertex(new Vertex(new VertexId(1_000_000)));
+ var next = Good(session.Compile(Source()));
+ var baseline = Good(new AssemblyM1Pipeline().Compile(Source()));
+ Assert.Equal(1, next.Reuse!.ReusedDefinitions);
+ Assert.Equal(AssemblyIrAp242Exporter.Export(baseline).Value, AssemblyIrAp242Exporter.Export(next).Value);
+ Assert.Equal(baseline.Geometry!.DefinitionBodies.Values.Single().Topology.Vertices.Count(),
+ next.Geometry!.DefinitionBodies.Values.Single().Topology.Vertices.Count());
+ }
+
[Fact]
public void PlacementEditReusesGeometryButRevalidatesInterference()
{
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
index 0afc533a..d87d90a1 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -56,7 +56,12 @@ public static class AssemblyDisplayMeshExporter
}
public static AssemblyDisplayMeshDocument Export(AssemblyM1CompilationResult compilation, DisplayTessellationOptions? options = null,
- AssemblyPoseResult? pose = null)
+ AssemblyPoseResult? pose = null) => ExportCore(compilation, options, pose, (prepare, _) => prepare());
+
+ /// <summary>Export with a hook around each definition's preparation (identity → prepared mesh),
+ /// used by a compilation session to reuse unchanged definitions.</summary>
+ internal static AssemblyDisplayMeshDocument ExportCore(AssemblyM1CompilationResult compilation, DisplayTessellationOptions? options,
+ AssemblyPoseResult? pose, Func<Func<AssemblyDisplayMeshDefinition>, string, AssemblyDisplayMeshDefinition> definition)
{
if (!compilation.IsSuccess || compilation.Ir is null || compilation.Geometry is null)
throw new InvalidOperationException("assembly-mesh-invalid-compilation");
@@ -72,8 +77,8 @@ public static class AssemblyDisplayMeshExporter
{
var artifact = geometry.Artifact.Definitions.Single(d => d.DefinitionIdentity == identity);
var externalStep = artifact.Provenance.Any(p => p.Stage == "imported-step-definition");
- definitions.Add(PrepareDefinition(ids[identity], identity, body, options, externalStep) with
- { Cir = geometry.DefinitionCir.GetValueOrDefault(identity), Shader = CirShaderArtifactProvider.Resolve(geometry.DefinitionCir.GetValueOrDefault(identity)), GeometryRevision = artifact.StepSha256 });
+ definitions.Add(definition(() => PrepareDefinition(ids[identity], identity, body, options, externalStep) with
+ { Cir = geometry.DefinitionCir.GetValueOrDefault(identity), Shader = CirShaderArtifactProvider.Resolve(geometry.DefinitionCir.GetValueOrDefault(identity)), GeometryRevision = artifact.StepSha256 }, identity));
}
var occurrences = (pose?.Instances ?? compilation.Ir.Instances).OrderBy(i => i.Path.ToString(), StringComparer.Ordinal).Select(instance =>
{
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
index 8c63c08b..6f7f419f 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
@@ -10,6 +10,8 @@ namespace Aetheris.Kernel.Firmament.Assembly;
/// <summary>Bounded parser for the M0 relational assembly lane. XML-like tags are used only for product-tree containment.</summary>
public sealed class AssemblyM0Parser
{
+ /// <summary>Published-port bindings reused across a session's builds (BUILD-PERF-M1).</summary>
+ internal DerivedValueCache<PublishedPortBinding>? PortCache { get; init; }
public sealed record ParseResult(AssemblySource? Source, IReadOnlyList<AssemblyDiagnostic> Diagnostics, double ElapsedMilliseconds)
{ public bool IsSuccess => Source is not null && Diagnostics.All(x => x.Severity != AssemblyDiagnosticSeverity.Error); }
@@ -141,7 +143,7 @@ public sealed class AssemblyM0Parser
IReadOnlyList<SemanticValue> Ports(string identity)
{
if (!portCache.TryGetValue(identity, out var ports))
- portCache[identity] = ports = AssemblyPublishedPorts.BindAuthored(identity, definitionSource, sourceIdentity, diagnostics, project, portDependencies);
+ portCache[identity] = ports = AssemblyPublishedPorts.BindAuthored(identity, definitionSource, sourceIdentity, diagnostics, project, portDependencies, PortCache);
return ports;
}
var templateRanges = new List<(int Start, int Length)>();
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
index b2db70bb..968918af 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Core.Diagnostics;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Text;
@@ -29,6 +30,9 @@ public sealed record AssemblyM1CompilationResult(
AssemblyPerformanceIr? Performance = null,
AssemblyCompilationReuse? Reuse = null)
{
+ /// <summary>Input key of each definition that came from (or entered) a session's definition
+ /// cache. Values derived only from such a definition can be reused while its key is unchanged.</summary>
+ public IReadOnlyDictionary<string, string>? DefinitionInputKeys { get; init; }
public bool IsSuccess => Ir is not null && Geometry is not null && Diagnostics.All(diagnostic => diagnostic.Severity != AssemblyDiagnosticSeverity.Error);
}
@@ -57,7 +61,8 @@ internal sealed record MaterializedAssemblyDefinition(
IReadOnlyList<SemanticValue> Semantics,
AssemblyDefinitionArtifactIr Artifact,
string? CanonicalStep = null,
- FirmamentCirRetention? Cir = null);
+ FirmamentCirRetention? Cir = null,
+ string? InputKey = null);
/// <summary>
/// M1's definition seam: specialize through the ordinary Firmament compiler, then
@@ -347,13 +352,13 @@ public sealed class AssemblyM1Pipeline
internal AssemblyM1Pipeline(AssemblyDefinitionCache cache) => this.cache = cache;
public AssemblyM1CompilationResult CompileFile(string path, AssemblyPartMaterializer? domainMaterializer = null)
{
- var parsed = new AssemblyM0Parser().ParseFile(path);
+ var parsed = new AssemblyM0Parser { PortCache = cache?.PublishedPorts }.ParseFile(path);
return CompileParsed(parsed, domainMaterializer);
}
public AssemblyM1CompilationResult Compile(string source, string sourceIdentity = "<memory>", AssemblyPartMaterializer? domainMaterializer = null)
{
- var parsed = new AssemblyM0Parser().Parse(source, sourceIdentity);
+ var parsed = new AssemblyM0Parser { PortCache = cache?.PublishedPorts }.Parse(source, sourceIdentity);
return CompileParsed(parsed, domainMaterializer);
}
@@ -365,7 +370,8 @@ public sealed class AssemblyM1Pipeline
: [];
if (profile.Any(diagnostic => diagnostic.Severity == AssemblyDiagnosticSeverity.Error))
return new(null, null, profile);
- var parsed = new AssemblyM0Parser().ParseProject(project);
+ AssemblyM0Parser.ParseResult parsed;
+ using (BuildPerfTrace.Phase("assembly.parse-project")) parsed = new AssemblyM0Parser { PortCache = cache?.PublishedPorts }.ParseProject(project);
if (parsed.Source?.DefinitionSource is { } declarations &&
System.Text.RegularExpressions.Regex.IsMatch(declarations, @"\bInlineStep\b", System.Text.RegularExpressions.RegexOptions.CultureInvariant))
return new(null, null, [new AssemblyDiagnostic("assembly-profile-external-resource-unsupported",
@@ -378,25 +384,28 @@ public sealed class AssemblyM1Pipeline
if (!parsed.IsSuccess || parsed.Source is null) return new(null, null, parsed.Diagnostics);
var diagnostics = parsed.Diagnostics.ToList();
var routeWatch = Stopwatch.StartNew();
- var routeSource = AssemblyRouteBindings.Resolve(parsed.Source, diagnostics, out var routeBindings);
+ AssemblySource? routeSource; IReadOnlyList<AssemblyRouteBindingEvidence> routeBindings;
+ using (BuildPerfTrace.Phase("assembly.route-bindings")) routeSource = AssemblyRouteBindings.Resolve(parsed.Source, diagnostics, out routeBindings);
if (routeSource is null) return new(null, null, diagnostics);
parsed = parsed with { Source = routeSource };
routeWatch.Stop();
var materializationWatch = Stopwatch.StartNew();
var definitions = parsed.Source.Root.Flatten().Where(member => member.Kind == AssemblyInstanceKind.Part)
.Select(member => member.DefinitionIdentity).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)
- .Select(identity => cache is null
+ .Select(identity => { using var definitionPhase = BuildPerfTrace.Phase("assembly.definition"); return cache is null
? Materialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics, domainMaterializer, project)
: cache.Materialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics, project,
- () => Materialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics, domainMaterializer, project)))
+ () => Materialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics, domainMaterializer, project)); })
.Where(definition => definition is not null).Cast<MaterializedAssemblyDefinition>().ToDictionary(definition => definition.DefinitionIdentity, StringComparer.Ordinal);
materializationWatch.Stop();
var enriched = parsed.Source with { Root = Enrich(parsed.Source.Root, definitions) };
- var compiled = new AssemblyM0Compiler().Compile(enriched, parsed.ElapsedMilliseconds);
+ AssemblyCompilationResult compiled;
+ using (BuildPerfTrace.Phase("assembly.m0-compile")) compiled = new AssemblyM0Compiler().Compile(enriched, parsed.ElapsedMilliseconds);
diagnostics.AddRange(compiled.Diagnostics);
if (compiled.Ir is null) return new(null, null, diagnostics, compiled.Performance);
var geometryWatch = Stopwatch.StartNew();
- var geometry = Execute(compiled.Ir, definitions, diagnostics, out var validatedIr);
+ AssemblyExecutedGeometry? geometry; AssemblyIr validatedIr;
+ using (BuildPerfTrace.Phase("assembly.execute")) geometry = Execute(compiled.Ir, definitions, diagnostics, out validatedIr, cache);
geometryWatch.Stop();
var performance = compiled.Performance is null ? null : compiled.Performance with
{
@@ -404,7 +413,11 @@ public sealed class AssemblyM1Pipeline
GeometryExecutionMilliseconds = geometryWatch.Elapsed.TotalMilliseconds,
RouteBindingMilliseconds = routeWatch.Elapsed.TotalMilliseconds
};
- return new(validatedIr with { RouteBindings = routeBindings }, geometry, diagnostics, performance);
+ return new(validatedIr with { RouteBindings = routeBindings }, geometry, diagnostics, performance)
+ {
+ DefinitionInputKeys = definitions.Values.Where(definition => definition.InputKey is not null)
+ .ToDictionary(definition => definition.DefinitionIdentity, definition => definition.InputKey!, StringComparer.Ordinal)
+ };
}
private static MaterializedAssemblyDefinition? Materialize(string identity, string? declarations, string sourceIdentity,
@@ -421,6 +434,7 @@ public sealed class AssemblyM1Pipeline
AssemblyDefinitionMaterializer.Metrics(supplied.Body), supplied.Provenance);
return new(identity, supplied.SpecializationIdentity, supplied.Body, supplied.Semantics ?? [], artifact);
}
+ using var materializePhase = BuildPerfTrace.Phase("assembly.definition-materialize");
return AssemblyDefinitionMaterializer.TryMaterialize(identity, declarations, sourceIdentity, diagnostics, project);
}
@@ -440,9 +454,12 @@ public sealed class AssemblyM1Pipeline
};
}
- private static AssemblyExecutedGeometry? Execute(AssemblyIr ir, IReadOnlyDictionary<string, MaterializedAssemblyDefinition> definitions, List<AssemblyDiagnostic> diagnostics, out AssemblyIr validatedIr)
+ private static AssemblyExecutedGeometry? Execute(AssemblyIr ir, IReadOnlyDictionary<string, MaterializedAssemblyDefinition> definitions, List<AssemblyDiagnostic> diagnostics, out AssemblyIr validatedIr,
+ AssemblyDefinitionCache? cache = null)
{
var instances = new Dictionary<string, BrepBody>(StringComparer.Ordinal);
+ // A world body is determined by its definition's input key and its exact transform.
+ var worldKeys = new Dictionary<string, string>(StringComparer.Ordinal);
var instanceArtifacts = new List<AssemblyInstanceGeometryIr>();
foreach (var instance in ir.Instances.Where(item => item.Kind == AssemblyInstanceKind.Part).OrderBy(item => item.StableId, StringComparer.Ordinal))
{
@@ -455,6 +472,8 @@ public sealed class AssemblyM1Pipeline
var transform = Transform3D.FromRowMajor(instance.ResolvedTransform.Matrix);
var body = FirmasmAssemblyExecutor.TransformBody(definition.Body, transform);
instances[instance.StableId] = body;
+ if (definition.InputKey is { } inputKey)
+ worldKeys[instance.StableId] = inputKey + "|" + string.Join(',', instance.ResolvedTransform.Matrix.Select(value => BitConverter.DoubleToInt64Bits(value).ToString(System.Globalization.CultureInfo.InvariantCulture)));
instanceArtifacts.Add(new(instance.StableId, definition.Artifact.StableId, instance.ResolvedTransform, AssemblyDefinitionMaterializer.Metrics(body)));
}
if (definitions.Count == 0 || instanceArtifacts.Count == 0)
@@ -463,15 +482,17 @@ public sealed class AssemblyM1Pipeline
diagnostics.Add(new("assembly-geometry-no-materialized-definitions", "No Template-specialized part definitions were available for executable Assembly geometry."));
return null;
}
- var residuals = AssemblyWorldQuery.ValidateResiduals(ir, instances.Keys.ToHashSet(StringComparer.Ordinal));
+ IReadOnlyList<AssemblyMateResidualIr> residuals;
+ using (BuildPerfTrace.Phase("assembly.validate-residuals")) residuals = AssemblyWorldQuery.ValidateResiduals(ir, instances.Keys.ToHashSet(StringComparer.Ordinal));
var byConstraint = residuals.ToDictionary(residual => residual.ConstraintStableId, StringComparer.Ordinal);
var constraints = ir.PlacementConstraints.Select(constraint => byConstraint.TryGetValue(constraint.StableId, out var residual)
? constraint with { Residual = Math.Max(residual.PositionResidualMm, residual.AngularResidualRadians), Status = residual.Passed ? "geometry-validated" : "geometry-residual-failed" }
: constraint).ToArray();
foreach (var residual in residuals.Where(item => !item.Passed))
diagnostics.Add(new("assembly-mate-geometry-residual", $"Constraint '{residual.ConstraintStableId}' residual position={residual.PositionResidualMm:G6}mm angle={residual.AngularResidualRadians:G6}rad."));
- ValidateSolidInterference(ir, instances, diagnostics);
- var datumSeats = ValidateDatumSeats(ir, instances, diagnostics);
+ using (BuildPerfTrace.Phase("assembly.validate-interference")) ValidateSolidInterference(ir, instances, diagnostics);
+ IReadOnlyList<AssemblyDatumSeatEvidence> datumSeats;
+ using (BuildPerfTrace.Phase("assembly.validate-datum-seats")) datumSeats = ValidateDatumSeats(ir, instances, diagnostics, worldKeys, cache);
validatedIr = ir with { Schema = "aetheris/assembly-ir/m1", PlacementConstraints = constraints, Diagnostics = diagnostics };
var definitionsIr = definitions.Values.Select(definition => definition.Artifact).OrderBy(definition => definition.StableId, StringComparer.Ordinal).ToArray();
var canonical = JsonSerializer.Serialize(new { definitions = definitionsIr, instances = instanceArtifacts, residuals });
@@ -502,10 +523,15 @@ public sealed class AssemblyM1Pipeline
}
private static IReadOnlyList<AssemblyDatumSeatEvidence> ValidateDatumSeats(AssemblyIr ir,
- IReadOnlyDictionary<string, BrepBody> bodies, List<AssemblyDiagnostic> diagnostics)
+ IReadOnlyDictionary<string, BrepBody> bodies, List<AssemblyDiagnostic> diagnostics,
+ IReadOnlyDictionary<string, string>? worldKeys = null, AssemblyDefinitionCache? cache = null)
{
var evidence = new List<AssemblyDatumSeatEvidence>();
- var queries = bodies.ToDictionary(p => p.Key, p => new BrepPlanarSeatQuery(p.Value), StringComparer.Ordinal);
+ // A seat query tessellates its body lazily; an identical world body (same definition input
+ // key, same transform) reuses the query from an earlier build in this session.
+ var queries = bodies.ToDictionary(p => p.Key, p => cache is not null && worldKeys?.GetValueOrDefault(p.Key) is { } worldKey
+ ? cache.SeatQueries.GetOrAdd(worldKey, () => new BrepPlanarSeatQuery(p.Value))
+ : new BrepPlanarSeatQuery(p.Value), StringComparer.Ordinal);
var points = new List<(AssemblyInstanceIr Instance, Point3D Point, Vector3D Normal)>();
foreach (var instance in ir.Instances.Where(i => i.DatumSeat is not null))
{
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs
index 754f148b..034e57bf 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs
@@ -101,6 +101,19 @@ public static class AssemblyIrAp242Exporter
{
public static KernelResult<string> Export(AssemblyM1CompilationResult compilation)
{
+ var prepared = PrepareExport(compilation);
+ return prepared.IsSuccess ? prepared.Value() : KernelResult<string>.Failure(prepared.Diagnostics);
+ }
+
+ /// <summary>
+ /// Every structural check of <see cref="Export"/> (solved roots and child transforms,
+ /// definition-owned usages), returning the AP242 writer to run when STEP is requested.
+ /// The writer produces exactly the text <see cref="Export"/> would.
+ /// </summary>
+ public static KernelResult<Func<KernelResult<string>>> PrepareExport(AssemblyM1CompilationResult compilation)
+ {
+ static KernelResult<Func<KernelResult<string>>> Failure(string message) =>
+ KernelResult<Func<KernelResult<string>>>.Failure(AssemblyIrAp242Exporter.Failure(message).Diagnostics);
if (!compilation.IsSuccess || compilation.Ir is null || compilation.Geometry is null)
return Failure("AssemblyIR must be successfully materialized before AP242 product-structure export.");
var ir = compilation.Ir;
@@ -152,8 +165,9 @@ public static class AssemblyIrAp242Exporter
if (ir.Annotations?.Release is { } release)
foreach (var field in release.Fields.OrderBy(p => p.Key, StringComparer.Ordinal))
notes.Add(new(ir.RootInstanceStableId, new($"{release.Name}.{field.Key}", ir.Name, field.Value)));
- return Step242AssemblyExporter.Export(new(ir.Name, ir.RootInstanceStableId, definitions, occurrences,
- AssemblyPmiAuthoring.Header(ir.Annotations?.Release, ir.Name), notes));
+ var request = new Step242AssemblyExportModel(ir.Name, ir.RootInstanceStableId, definitions, occurrences,
+ AssemblyPmiAuthoring.Header(ir.Annotations?.Release, ir.Name), notes);
+ return KernelResult<Func<KernelResult<string>>>.Success(() => Step242AssemblyExporter.Export(request));
}
private static KernelResult<string> Failure(string message) => KernelResult<string>.Failure([
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs
index f7c82554..6d3aecc0 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs
@@ -14,7 +14,7 @@ internal static class AssemblyPublishedPorts
// it never materializes a body or imports STEP.
internal static IReadOnlyList<SemanticValue> BindAuthored(string identity, string declarations,
string sourceIdentity, List<AssemblyDiagnostic> diagnostics, FirmamentProjectSnapshot? project,
- List<AssemblySourceDependencyIr> dependencies)
+ List<AssemblySourceDependencyIr> dependencies, DerivedValueCache<PublishedPortBinding>? cache = null)
{
var file = Regex.Match(identity, "^(?:SectionChainFile|LoftFile)<\\\"(?<path>[^\\\"]+)\\\">$");
if (file.Success)
@@ -46,18 +46,30 @@ internal static class AssemblyPublishedPorts
.Select(d => d with { IsRoot = false }));
if (!dependencies.Any(d => d.Path == path))
dependencies.Add(new(path, Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(source))), false));
- source = FirmamentSourceSpelling.Normalize(source);
- if (!Regex.IsMatch(source, @"\bExpose\s*\{\s*Semantic\b")) return [];
- var chain = SectionChainAuthoringParser.Compile(Strip(source, diagnostics), materialize: false);
- if (!chain.IsSuccess || chain.Chain is null)
+ // Everything below is a function of the identity, the resource path and its loaded text.
+ return Memo(cache, "file\0" + identity + "\0" + path + "\0" + Hash(source), diagnostics, diagnostics =>
{
- foreach (var error in chain.Diagnostics) diagnostics.Add(new("assembly-port-section-binding-failed", error));
- return [];
- }
- var owner = Regex.Match(source, @"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{").Groups["name"].Value;
- return Read(source, owner, identity, path, diagnostics, chain.Chain);
+ source = FirmamentSourceSpelling.Normalize(source);
+ if (!Regex.IsMatch(source, @"\bExpose\s*\{\s*Semantic\b")) return [];
+ var chain = SectionChainAuthoringParser.Compile(Strip(source, diagnostics), materialize: false);
+ if (!chain.IsSuccess || chain.Chain is null)
+ {
+ foreach (var error in chain.Diagnostics) diagnostics.Add(new("assembly-port-section-binding-failed", error));
+ return [];
+ }
+ var owner = Regex.Match(source, @"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{").Groups["name"].Value;
+ return Read(source, owner, identity, path, diagnostics, chain.Chain);
+ });
}
if (!identity.Contains('<')) return [];
+ // A specialization's ports are a function of the identity, the declarations and the source name.
+ return Memo(cache, "template\0" + identity + "\0" + sourceIdentity + "\0" + Hash(declarations), diagnostics,
+ diagnostics => BindTemplate(identity, declarations, sourceIdentity, diagnostics));
+ }
+
+ private static IReadOnlyList<SemanticValue> BindTemplate(string identity, string declarations, string sourceIdentity,
+ List<AssemblyDiagnostic> diagnostics)
+ {
var templateName = identity[..identity.IndexOf('<')].Trim();
var header = Regex.Match(declarations, $@"\b(?:Struct|Model)\s+{Regex.Escape(templateName)}(?:\s*:\s*[A-Za-z_]\w*)?\s*\{{");
if (!header.Success) return [];
@@ -77,6 +89,34 @@ internal static class AssemblyPublishedPorts
}
return Read(expansion.ExpandedSource, "__AssemblyPart", identity, sourceIdentity, diagnostics);
}
+ /// <summary>Reuse a binding from an earlier build of the session when its inputs are identical,
+ /// replaying its diagnostics. Only bindings the definition cache can copy are kept, and every
+ /// reuse returns copies.</summary>
+ private static IReadOnlyList<SemanticValue> Memo(DerivedValueCache<PublishedPortBinding>? cache, string key,
+ List<AssemblyDiagnostic> diagnostics, Func<List<AssemblyDiagnostic>, IReadOnlyList<SemanticValue>> bind)
+ {
+ if (cache is null) return bind(diagnostics);
+ var computed = false;
+ var binding = cache.GetOrAdd(key, () =>
+ {
+ computed = true;
+ var reported = new List<AssemblyDiagnostic>();
+ var ports = bind(reported);
+ return new(ports, reported);
+ });
+ diagnostics.AddRange(binding.Diagnostics);
+ if (!binding.Ports.All(AssemblyDefinitionCache.CanCopy))
+ {
+ // Not shareable: keep this build's values and do not offer them to the next build.
+ if (computed) { cache.Forget(key); return binding.Ports; }
+ var reported = new List<AssemblyDiagnostic>();
+ return bind(reported);
+ }
+ return binding.Ports.Select(AssemblyDefinitionCache.Copy).ToArray();
+ }
+
+ private static string Hash(string text) => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text)));
+
internal static string Strip(string source, List<AssemblyDiagnostic> diagnostics)
{
source = FirmamentSourceSpelling.Normalize(source);
diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs
index 8d5222ed..f37fecd5 100644
--- a/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs
@@ -1,3 +1,6 @@
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Queries;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
@@ -33,6 +36,20 @@ public sealed class FirmamentCompilationSession : IDisposable
public AssemblyM1CompilationResult Compile(string source, string sourceIdentity = "<memory>") => Run(() => pipeline.Compile(source, sourceIdentity));
public AssemblyM1CompilationResult CompileProject(FirmamentProjectSnapshot project) => Run(() => pipeline.CompileProject(project));
+ /// <summary>The display mesh of a compilation from this session. Definitions whose input key is
+ /// unchanged since the previous build reuse their prepared mesh instead of tessellating again.</summary>
+ public AssemblyDisplayMeshDocument ExportDisplayMesh(AssemblyM1CompilationResult compilation)
+ {
+ lock (gate)
+ {
+ ObjectDisposedException.ThrowIf(disposed, this);
+ return AssemblyDisplayMeshExporter.ExportCore(compilation, null, null, (prepare, identity) =>
+ compilation.DefinitionInputKeys?.GetValueOrDefault(identity) is { } inputKey
+ ? cache.DisplayDefinitions.GetOrAdd(inputKey + "|" + identity, prepare)
+ : prepare());
+ }
+ }
+
public void Clear()
{
lock (gate) { ObjectDisposedException.ThrowIf(disposed, this); cache.Clear(); }
@@ -54,37 +71,61 @@ public sealed class FirmamentCompilationSession : IDisposable
}
}
+/// <summary>Values derived from cached definitions, kept for one build: entries a build does not
+/// use are dropped when the next build begins, so the working set stays bounded.</summary>
+internal sealed class DerivedValueCache<T>
+{
+ private Dictionary<string, T> current = new(StringComparer.Ordinal);
+ private Dictionary<string, T> previous = new(StringComparer.Ordinal);
+ internal void BeginBuild() { previous = current; current = new(StringComparer.Ordinal); }
+ internal void Clear() { current.Clear(); previous.Clear(); }
+ internal void Forget(string key) { current.Remove(key); previous.Remove(key); }
+ internal T GetOrAdd(string key, Func<T> create)
+ {
+ if (current.TryGetValue(key, out var value)) return value;
+ if (!previous.Remove(key, out value!)) value = create();
+ current[key] = value;
+ return value;
+ }
+}
+
+/// <summary>A published-port binding and the diagnostics it reported, replayed on reuse.</summary>
+internal sealed record PublishedPortBinding(IReadOnlyList<SemanticValue> Ports, IReadOnlyList<AssemblyDiagnostic> Diagnostics);
+
internal sealed class AssemblyDefinitionCache(int capacity)
{
- // STEP text is the immutable cache payload. A hit reimports a fresh body so
- // public mutable topology/geometry stores can never corrupt a later build.
- private sealed record Entry(string Key, string Step, MaterializedAssemblyDefinition Metadata,
+ // The materialized body is the cache payload. The cache keeps a private clone and every hit
+ // returns a fresh clone, so the public mutable topology/geometry stores can never corrupt a
+ // later build, and a rebuild sees the same body as the build that populated the cache.
+ // (BUILD-PERF-M1: previously STEP text, re-imported on every hit.)
+ private sealed record Entry(string Key, MaterializedAssemblyDefinition Metadata,
IReadOnlyList<AssemblyDiagnostic> Diagnostics);
private readonly Dictionary<string, Entry> entries = new(StringComparer.Ordinal);
private readonly Queue<string> insertionOrder = new();
internal List<AssemblyDefinitionReuse> Evidence { get; } = [];
- internal void BeginBuild() => Evidence.Clear();
- internal void Clear() { entries.Clear(); insertionOrder.Clear(); Evidence.Clear(); }
+ internal DerivedValueCache<BrepPlanarSeatQuery> SeatQueries { get; } = new();
+ internal DerivedValueCache<AssemblyDisplayMeshDefinition> DisplayDefinitions { get; } = new();
+ internal DerivedValueCache<PublishedPortBinding> PublishedPorts { get; } = new();
+ internal void BeginBuild() { Evidence.Clear(); SeatQueries.BeginBuild(); DisplayDefinitions.BeginBuild(); PublishedPorts.BeginBuild(); }
+ internal void Clear() { entries.Clear(); insertionOrder.Clear(); Evidence.Clear(); SeatQueries.Clear(); DisplayDefinitions.Clear(); PublishedPorts.Clear(); }
internal MaterializedAssemblyDefinition? Materialize(string identity, string? declarations, string sourceIdentity,
List<AssemblyDiagnostic> diagnostics, FirmamentProjectSnapshot? project,
Func<MaterializedAssemblyDefinition?> build)
{
- var key = Key(identity, declarations, sourceIdentity, project);
+ string? key;
+ using (BuildPerfTrace.Phase("assembly.cache-key")) key = Key(identity, declarations, sourceIdentity, project);
var reason = key is null ? "unsupported-resource-dependency" : "first-build-or-evicted";
if (key is not null && entries.TryGetValue(identity, out var entry))
{
reason = "definition-inputs-changed";
if (entry.Key == key)
{
- var import = Step242Importer.ImportBody(entry.Step);
- if (import.IsSuccess && import.Value is not null)
- {
- diagnostics.AddRange(entry.Diagnostics);
- Evidence.Add(new(identity, true, "unchanged-definition-inputs"));
- return CopyMetadata(entry.Metadata) with { Body = import.Value };
- }
- reason = "cached-step-reimport-failed";
+ BrepBody body;
+ using (BuildPerfTrace.Phase("assembly.cache-hit-clone")) body = entry.Metadata.Body.Clone();
+ diagnostics.AddRange(entry.Diagnostics);
+ Evidence.Add(new(identity, true, "unchanged-definition-inputs"));
+ return CopyMetadata(entry.Metadata) with { Body = body, InputKey = key };
}
}
var diagnosticStart = diagnostics.Count;
@@ -92,30 +133,30 @@ internal sealed class AssemblyDefinitionCache(int capacity)
Evidence.Add(new(identity, false, result is null ? "materialization-failed" : reason));
if (key is null || result is null || diagnostics.Skip(diagnosticStart).Any(d => d.Severity == AssemblyDiagnosticSeverity.Error))
return result;
- if (Key(identity, declarations, sourceIdentity, project) != key)
+ string? keyAfterBuild;
+ using (BuildPerfTrace.Phase("assembly.cache-key")) keyAfterBuild = Key(identity, declarations, sourceIdentity, project);
+ if (keyAfterBuild != key)
{
Evidence[^1] = new(identity, false, "resource-changed-during-build");
return result;
}
// This bounded cache only admits immutable scalar/datum semantic bindings.
// Domain materializers and geometry-valued ports stay on the uncached path.
- if (!result.Semantics.All(CanCopy) || result.CanonicalStep is not { } step)
+ if (!result.Semantics.All(CanCopy) || result.CanonicalStep is null)
{
Evidence[^1] = new(identity, false, "producer-or-semantics-not-cacheable");
return result;
}
- var metadata = CopyMetadata(result);
- // The private body is never exposed; fresh imports supply returned bodies.
- var privateImport = Step242Importer.ImportBody(step);
- if (!privateImport.IsSuccess || privateImport.Value is null) return result;
- metadata = metadata with { Body = privateImport.Value };
+ // The private body is never exposed; hits return clones of it.
+ MaterializedAssemblyDefinition metadata;
+ using (BuildPerfTrace.Phase("assembly.cache-store-clone")) metadata = CopyMetadata(result) with { Body = result.Body.Clone() };
if (!entries.ContainsKey(identity))
{
while (entries.Count >= capacity) entries.Remove(insertionOrder.Dequeue());
insertionOrder.Enqueue(identity);
}
- entries[identity] = new(key, step, metadata, diagnostics.Skip(diagnosticStart).ToArray());
- return result;
+ entries[identity] = new(key, metadata, diagnostics.Skip(diagnosticStart).ToArray());
+ return result with { InputKey = key };
}
private static string? Key(string identity, string? declarations, string sourceIdentity, FirmamentProjectSnapshot? project)
@@ -158,11 +199,11 @@ internal sealed class AssemblyDefinitionCache(int capacity)
"assembly-definition-cache-v1\0" + sourceIdentity + "\0" + identity + "\0" + inputs)));
}
- private static bool CanCopy(SemanticValue value) => value.Bindings.All(b => b is
+ internal static bool CanCopy(SemanticValue value) => value.Bindings.All(b => b is
ExactAxisBinding or ExactPlaneBinding or ExactPointBinding or ExactDatumFrameBinding or TolerancedDimensionBinding)
&& value.ExposedMembers.Values.All(CanCopy);
- private static SemanticValue Copy(SemanticValue value) => new(value.StableIdentity, value.Type,
+ internal static SemanticValue Copy(SemanticValue value) => new(value.StableIdentity, value.Type,
value.Capabilities.Values, value.Bindings, value.ExposedMembers.Values.Select(Copy), value.Provenance.ToArray(),
value.AuthoredSourceSpan, value.GeneratedSourceSpan, value.ExposedName);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 257de2c0..e67a8718 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -306,6 +306,7 @@ public static class FirmamentV2Parser
string? sourceDirectory,
FirmamentV2ForgeConceptCatalog? conceptCatalog)
{
+ using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("firmament.v2-parse");
ArgumentNullException.ThrowIfNull(sourceText);
sourceText = FirmamentSourceSpelling.Normalize(sourceText);
sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs
index 9999d82b..32db6646 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs
@@ -44,6 +44,7 @@ public static class SectionChainAuthoringParser
public static SectionChainAuthoringResult Compile(string source, bool materialize = true)
{
+ using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("sectionchain.authoring-compile");
ArgumentNullException.ThrowIfNull(source);
source = FirmamentSourceSpelling.Normalize(source);
if (LoftAuthoringParser.IsLoftSource(source))
diff --git a/Aetheris.Surfacing/BoundedPcurveBuilder.cs b/Aetheris.Surfacing/BoundedPcurveBuilder.cs
index 063138fc..e4e260ba 100644
--- a/Aetheris.Surfacing/BoundedPcurveBuilder.cs
+++ b/Aetheris.Surfacing/BoundedPcurveBuilder.cs
@@ -12,6 +12,7 @@ public static class BoundedPcurveBuilder
public static PcurveBuildResult Populate(TopologyModel topology, BrepGeometryStore geometry, BrepBindingModel bindings,
double tolerance = 1e-5, int sampleCount = 129)
{
+ using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("pcurve.bounded-build");
var result = BrepPcurveRecovery.Populate(topology, geometry, bindings, tolerance, sampleCount);
return new PcurveBuildResult(result.IsSuccess, result.Count, result.MaximumResidual,
result.Diagnostics.Select(d => new SculptDiagnostic(d.Code, d.Message, d.Entity)).ToArray());
diff --git a/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs b/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs
index 380b4e9a..34dc2675 100644
--- a/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs
+++ b/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs
@@ -19,6 +19,7 @@ internal static class SectionChainSelfIntersectionValidator
public static SectionChainSelfIntersectionValidationResult Validate(SectionChain chain, IReadOnlyList<SectionChainValidationPatch> patches)
{
+ using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("sectionchain.self-intersection-validate");
var proxies = patches.SelectMany(Triangulate).ToList();
if (chain.StartTermination == SectionTermination.Cap) proxies.AddRange(Cap(chain.Sections[0], -1, "StartTermination"));
if (chain.EndTermination == SectionTermination.Cap) proxies.AddRange(Cap(chain.Sections[^1], chain.Sections.Count - 1, "EndTermination"));
diff --git a/Aetheris.Surfacing/SectionChains.cs b/Aetheris.Surfacing/SectionChains.cs
index f3740ce7..22537947 100644
--- a/Aetheris.Surfacing/SectionChains.cs
+++ b/Aetheris.Surfacing/SectionChains.cs
@@ -213,6 +213,7 @@ public static class SectionChainMaterializer
public static SectionChainMaterializationResult Materialize(SectionChain chain)
{
+ using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("sectionchain.materialize");
ArgumentNullException.ThrowIfNull(chain);
var profileStarted = Stopwatch.GetTimestamp();
PreparedSection[] prepared;
@@ -454,6 +455,7 @@ public static class SectionChainMaterializer
IReadOnlyList<PreparedSection> sections,
IReadOnlyList<(PreparedTransition Transition, ISectionChainTransitionPatch[] Patches)> transitions)
{
+ using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("sectionchain.build-body");
var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();
var points = new Dictionary<VertexId, Point3D>(); var nextCurve = 1; var nextSurface = 1;
var vertices = new VertexId[sections.Count][]; var profileEdges = new EdgeId[sections.Count][];
diff --git a/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj b/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj
index 8b99fd8a..b16a2382 100644
--- a/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj
+++ b/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj
@@ -12,5 +12,7 @@
<ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
<Compile Include="..\Aetheris.Web.Runtime\Program.cs" Link="WebProgram.cs" />
<Compile Include="PerfProgram.cs" />
+ <Compile Include="ShowcasePerf.cs" />
+ <Compile Include="CompareStep.cs" />
</ItemGroup>
</Project>
diff --git a/Aetheris.Web.Perf/CompareStep.cs b/Aetheris.Web.Perf/CompareStep.cs
new file mode 100644
index 00000000..52657c24
--- /dev/null
+++ b/Aetheris.Web.Perf/CompareStep.cs
@@ -0,0 +1,115 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Web.Perf;
+
+/// <summary>
+/// BUILD-PERF cross-runtime determinism check: two STEP files (for example the native and the
+/// WASM export of one project) describe the same product within a tolerance. Topology counts and
+/// product structure must match exactly; volume, area, centroid and bounds within a relative
+/// tolerance. Byte identity is checked per runtime by the ratchet; this checks equivalence.
+/// </summary>
+internal static class CompareStep
+{
+ private sealed record Metrics(int Faces, int Edges, int Vertices, double Volume, double Area,
+ double[] Centroid, double[] Minimum, double[] Maximum);
+
+ public static int Run(string[] args)
+ {
+ if (args.Length < 2) return Usage();
+ var tolerance = 1e-6;
+ for (var i = 2; i < args.Length; i++)
+ {
+ if (args[i] == "--tolerance" && i + 1 < args.Length) tolerance = double.Parse(args[++i], System.Globalization.CultureInfo.InvariantCulture);
+ else return Usage();
+ }
+ var (left, leftOccurrences) = Load(args[0]);
+ var (right, rightOccurrences) = Load(args[1]);
+ var failures = new List<string>();
+ var worst = 0d;
+ foreach (var name in left.Keys.Union(right.Keys).Order(StringComparer.Ordinal))
+ {
+ if (!left.TryGetValue(name, out var a) || !right.TryGetValue(name, out var b)) { failures.Add($"{name}: present in only one file"); continue; }
+ if (a is null || b is null) { if (a is null != b is null) failures.Add($"{name}: geometry present in only one file"); continue; }
+ if ((a.Faces, a.Edges, a.Vertices) != (b.Faces, b.Edges, b.Vertices))
+ failures.Add($"{name}: topology {a.Faces}F/{a.Edges}E/{a.Vertices}V vs {b.Faces}F/{b.Edges}E/{b.Vertices}V");
+ var scale = Math.Max(1e-12, Enumerable.Range(0, 3).Max(axis => Math.Abs(a.Maximum[axis] - a.Minimum[axis])));
+ void Close(string what, double x, double y, double reference)
+ {
+ var relative = Math.Abs(x - y) / Math.Max(Math.Abs(reference), 1e-12);
+ worst = Math.Max(worst, relative);
+ if (relative > tolerance) failures.Add($"{name}: {what} {x:G12} vs {y:G12} (relative {relative:G3})");
+ }
+ Close("volume", a.Volume, b.Volume, a.Volume);
+ Close("area", a.Area, b.Area, a.Area);
+ for (var axis = 0; axis < 3; axis++)
+ {
+ Close($"centroid[{axis}]", a.Centroid[axis], b.Centroid[axis], scale);
+ Close($"minimum[{axis}]", a.Minimum[axis], b.Minimum[axis], scale);
+ Close($"maximum[{axis}]", a.Maximum[axis], b.Maximum[axis], scale);
+ }
+ }
+ if (leftOccurrences.Count != rightOccurrences.Count) failures.Add($"occurrences: {leftOccurrences.Count} vs {rightOccurrences.Count}");
+ foreach (var (path, transform) in leftOccurrences)
+ {
+ if (!rightOccurrences.TryGetValue(path, out var other)) { failures.Add($"occurrence {path}: missing"); continue; }
+ var difference = transform.Zip(other, (x, y) => Math.Abs(x - y)).DefaultIfEmpty(0).Max();
+ if (difference > tolerance) failures.Add($"occurrence {path}: transform differs by {difference:G3}");
+ }
+ Console.WriteLine($"{left.Count} definition(s), {leftOccurrences.Count} occurrence(s); worst relative difference {worst:G3}; tolerance {tolerance:G3}.");
+ foreach (var failure in failures) Console.Error.WriteLine($"DIFF {failure}");
+ Console.WriteLine(failures.Count == 0 ? "Equivalent within tolerance." : $"{failures.Count} difference(s).");
+ return failures.Count == 0 ? 0 : 1;
+ }
+
+ private static int Usage()
+ {
+ Console.Error.WriteLine("Usage: Aetheris.Web.Perf compare-step <a.step> <b.step> [--tolerance 1e-6]");
+ return 2;
+ }
+
+ private static (Dictionary<string, Metrics?> Definitions, Dictionary<string, IReadOnlyList<double>> Occurrences) Load(string path)
+ {
+ var text = File.ReadAllText(path);
+ var structure = Step242AssemblyImporter.Import(text);
+ if (structure.IsSuccess && structure.Value.Definitions.Count > 1)
+ {
+ var definitions = new Dictionary<string, Metrics?>(StringComparer.Ordinal);
+ foreach (var definition in structure.Value.Definitions)
+ definitions[Unique(definitions, definition.Name)] = definition.Geometry is { } body ? Measure(body) : null;
+ var byId = structure.Value.Definitions.ToDictionary(d => d.StableId, d => d.Name, StringComparer.Ordinal);
+ var occurrences = new Dictionary<string, IReadOnlyList<double>>(StringComparer.Ordinal);
+ var parents = structure.Value.Occurrences.ToDictionary(o => o.StableId, StringComparer.Ordinal);
+ foreach (var occurrence in structure.Value.Occurrences)
+ {
+ var segments = new List<string>();
+ for (var current = occurrence; current is not null; current = current.ParentStableId is { } parent && parents.TryGetValue(parent, out var next) ? next : null)
+ segments.Insert(0, current.Name);
+ occurrences[Unique(occurrences, string.Join('/', segments) + ":" + byId.GetValueOrDefault(occurrence.DefinitionStableId))] = occurrence.LocalTransform;
+ }
+ return (definitions, occurrences);
+ }
+ var single = Step242Importer.ImportBody(text);
+ if (!single.IsSuccess || single.Value is null) throw new InvalidOperationException($"{path}: STEP import failed.");
+ return (new(StringComparer.Ordinal) { ["body"] = Measure(single.Value) }, new(StringComparer.Ordinal));
+ }
+
+ private static string Unique<T>(Dictionary<string, T> map, string name)
+ {
+ var key = name; var index = 1;
+ while (map.ContainsKey(key)) key = $"{name}#{++index}";
+ return key;
+ }
+
+ private static Metrics Measure(BrepBody body)
+ {
+ var mass = BrepMassProperties.Evaluate(body);
+ var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : default).ToArray();
+ var minimum = points.Length == 0 ? new double[3] : new[] { points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z) };
+ var maximum = points.Length == 0 ? new double[3] : new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) };
+ var centroid = mass.Centroid is { } c ? new[] { c.X, c.Y, c.Z } : new double[3];
+ return new(body.Topology.Faces.Count(), body.Topology.Edges.Count(), body.Topology.Vertices.Count(),
+ mass.AbsoluteVolume, mass.SurfaceArea, centroid, minimum, maximum);
+ }
+}
diff --git a/Aetheris.Web.Perf/PerfProgram.cs b/Aetheris.Web.Perf/PerfProgram.cs
index d5963778..3a5e8bbc 100644
--- a/Aetheris.Web.Perf/PerfProgram.cs
+++ b/Aetheris.Web.Perf/PerfProgram.cs
@@ -8,7 +8,9 @@ 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; }
+ if (args.Length > 0 && args[0] == "showcase") return ShowcasePerf.Run(args[1..]);
+ if (args.Length > 0 && args[0] == "compare-step") return CompareStep.Run(args[1..]);
+ if (args.Length != 1) { Console.Error.WriteLine("Usage: Aetheris.Web.Perf <helix-fixture> | Aetheris.Web.Perf showcase --help | Aetheris.Web.Perf compare-step <a.step> <b.step>"); 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)),
diff --git a/Aetheris.Web.Perf/ShowcasePerf.cs b/Aetheris.Web.Perf/ShowcasePerf.cs
new file mode 100644
index 00000000..81eb4dd8
--- /dev/null
+++ b/Aetheris.Web.Perf/ShowcasePerf.cs
@@ -0,0 +1,481 @@
+using System.Diagnostics;
+using System.Reflection;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+
+namespace Aetheris.Web.Perf;
+
+/// <summary>
+/// BUILD-PERF-M0: the Helios showcase projects measured through the browser runtime's own entry
+/// point (<see cref="Aetheris.Web.Runtime.Program.Invoke"/>). Each project runs in a fresh process
+/// so its first build is a true cold build. See
+/// docs/development/milestones/general/build-perf-ladder.md.
+/// </summary>
+internal static class ShowcasePerf
+{
+ private sealed record Project(string Name, string? Directory, string Root, string? InlineSource,
+ string? LeafEditDocument = null, string? LeafEditFrom = null, string? LeafEditTo = null);
+
+ private const string BracketSource = """
+ Model WebBracket {
+ Units: mm
+ Box Plate { Size: [50mm, 40mm, 8mm] }
+ Modify Plate {
+ Hole<Shaft> CenterMount { On: +Z Center: Point2(0mm, 0mm) Diameter: 8mm End: ThroughAll }
+ }
+ }
+
+ """;
+
+ // The same sources Helios ships in fixtures/showcase (identical apart from line endings).
+ private static readonly Project[] Projects =
+ [
+ new("bracket", null, "bracket.firmament", BracketSource),
+ new("bolt", "fixtures/Thread", "hexbolt-showcase.firmament", null),
+ new("atlas", "fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas", "atlas-industrial.firmament", null),
+ new("guitar", "fixtures/Canonical/AssemblyInterfaces/GuitarX0", "guitar.firmasm", null,
+ "knob.firmament", "R:9mm,H:9mm", "R:9.5mm,H:9mm"),
+ new("house", "fixtures/Canonical/Scene/WarmModernHouse", "house.firmament", null),
+ ];
+
+ private static readonly JsonSerializerOptions Indented = new() { WriteIndented = true };
+
+ public static int Run(string[] args)
+ {
+ string? only = null, outDir = null, check = null, writeBaseline = null;
+ var runs = 1; var checkTime = false; var timeTolerance = 1.5;
+ for (var i = 0; i < args.Length; i++)
+ {
+ switch (args[i])
+ {
+ case "--project" when i + 1 < args.Length: only = args[++i]; break;
+ case "--runs" when i + 1 < args.Length: runs = int.Parse(args[++i]); break;
+ case "--out" when i + 1 < args.Length: outDir = args[++i]; break;
+ case "--check" when i + 1 < args.Length: check = args[++i]; break;
+ case "--write-baseline" when i + 1 < args.Length: writeBaseline = args[++i]; break;
+ case "--check-time": checkTime = true; break;
+ case "--time-tolerance" when i + 1 < args.Length: timeTolerance = double.Parse(args[++i], System.Globalization.CultureInfo.InvariantCulture); break;
+ default: return Usage();
+ }
+ }
+ var repo = FindRepositoryRoot();
+ if (repo is null) { Console.Error.WriteLine("Run from inside the Aetheris repository."); return 2; }
+ // A child process measures one project once; the parent fans out and aggregates.
+ if (only is not null && Environment.GetEnvironmentVariable("AETHERIS_BUILD_PERF_CHILD") == "1")
+ {
+ var project = Projects.SingleOrDefault(p => p.Name == only);
+ if (project is null) { Console.Error.WriteLine($"Unknown project '{only}'."); return 2; }
+ var report = Measure(project, repo);
+ Console.Out.Write(report.ToJsonString());
+ return 0;
+ }
+
+ outDir ??= Path.Combine(repo, "artifacts", "local", "build-perf", DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"));
+ Directory.CreateDirectory(outDir);
+ var selected = only is null ? Projects : Projects.Where(p => p.Name == only).ToArray();
+ if (selected.Length == 0) { Console.Error.WriteLine($"Unknown project '{only}'."); return 2; }
+ var results = new JsonObject
+ {
+ ["schema"] = "aetheris/build-perf/m0",
+ ["runtime"] = $"Native {RuntimeInfo()}",
+ ["machine"] = $"{Environment.MachineName} · {Environment.ProcessorCount} CPU · {Environment.OSVersion}",
+ ["commit"] = GitCommit(repo),
+ ["runs"] = runs,
+ };
+ var projects = new JsonObject();
+ foreach (var project in selected)
+ {
+ var samples = new List<JsonObject>();
+ for (var run = 0; run < runs; run++)
+ {
+ var sample = RunChild(project.Name, repo);
+ if (sample is null) return 1;
+ samples.Add(sample);
+ Console.Error.WriteLine($"{project.Name} run {run + 1}/{runs}: cold {Ms(sample, "cold", "invokeMilliseconds")} · warm {Ms(sample, "warm", "invokeMilliseconds")} · no-change {Ms(sample, "noChangeRebuild", "invokeMilliseconds")}");
+ }
+ projects[project.Name] = Summarize(samples);
+ }
+ results["projects"] = projects;
+ var reportPath = Path.Combine(outDir, "build-perf.json");
+ File.WriteAllText(reportPath, results.ToJsonString(Indented));
+ PrintTable(projects);
+ Console.WriteLine($"Report: {reportPath}");
+
+ if (writeBaseline is not null)
+ {
+ File.WriteAllText(writeBaseline, Baseline(results).ToJsonString(Indented) + "\n");
+ Console.WriteLine($"Baseline written: {writeBaseline}");
+ }
+ if (check is not null)
+ return Check(JsonNode.Parse(File.ReadAllText(check))!.AsObject(), projects, checkTime, timeTolerance) ? 0 : 1;
+ return 0;
+ }
+
+ private static int Usage()
+ {
+ Console.Error.WriteLine("""
+ Usage: Aetheris.Web.Perf showcase [--project <name>] [--runs <n>] [--out <dir>]
+ [--write-baseline <budgets.json>] [--check <budgets.json>]
+ [--check-time] [--time-tolerance <factor>]
+ Projects: bracket, bolt, atlas, guitar, house.
+ --check always gates machine-independent results (STEP hash, response size, allocations,
+ reused definitions); --check-time also gates wall time against the recorded machine.
+ """);
+ return 2;
+ }
+
+ // ---------------------------------------------------------------- measurement (child process)
+
+ private static JsonObject Measure(Project project, string repo)
+ {
+ var documents = project.InlineSource is not null
+ ? new Dictionary<string, string>(StringComparer.Ordinal) { [project.Root] = project.InlineSource }
+ : System.IO.Directory.GetFiles(Path.Combine(repo, project.Directory!))
+ .Where(path => path.EndsWith(".firmament", StringComparison.Ordinal) || path.EndsWith(".firmasm", StringComparison.Ordinal))
+ .OrderBy(path => path, StringComparer.Ordinal)
+ .ToDictionary(Path.GetFileName, path => File.ReadAllText(path).Replace("\r\n", "\n"), StringComparer.Ordinal)!;
+ var projectDocuments = documents.Count > 1 ? documents : null;
+ var report = new JsonObject { ["documents"] = documents.Count, ["root"] = project.Root };
+
+ // Cold: the first build in this process (JIT, static initialization, empty caches).
+ var (cold, session) = Compile(documents, project.Root, projectDocuments);
+ report["cold"] = cold;
+ report["determinism"] = Determinism(session, cold, project.Name);
+ Dispose(session);
+
+ // Warm: a new session in a warm process. Definition caches are per session, so this is a
+ // full build without JIT cost.
+ var (warm, warmSession) = Compile(documents, project.Root, projectDocuments);
+ report["warm"] = warm;
+
+ // Editor loop on the warm session.
+ report["noChangeRebuild"] = Rebuild(warmSession);
+ // Invariant: a rebuild that changes no geometry reproduces the cold build exactly.
+ var rebuilt = Determinism(warmSession, report["noChangeRebuild"]!.AsObject(), project.Name, dump: false);
+ report["determinism"]!["rebuildStepMatchesCold"] = rebuilt["stepDataSha256"]?.ToString() == report["determinism"]!["stepDataSha256"]?.ToString();
+ report["determinism"]!["rebuildMeshMatchesCold"] = report["noChangeRebuild"]!["meshContentSha256"]?.ToString() == cold["meshContentSha256"]?.ToString();
+ var edited = new Dictionary<string, string>(documents, StringComparer.Ordinal);
+ if (project.LeafEditDocument is { } leaf && project.LeafEditFrom is { } from && project.LeafEditTo is { } to
+ && edited.TryGetValue(leaf, out var leafText) && leafText.Contains(from, StringComparison.Ordinal))
+ {
+ edited[leaf] = leafText.Replace(from, to, StringComparison.Ordinal);
+ report["leafValueEdit"] = SetSourceAndRebuild(warmSession, edited, project.Root);
+ report["leafValueEdit"]!["edit"] = $"{leaf}: {from} -> {to}";
+ edited = new(documents, StringComparer.Ordinal);
+ SetSourceAndRebuild(warmSession, edited, project.Root);
+ }
+ var nonRoot = documents.Keys.Where(name => name != project.Root).Order(StringComparer.Ordinal).FirstOrDefault();
+ if (nonRoot is not null)
+ {
+ edited[nonRoot] += "\n// build-perf: leaf comment\n";
+ report["leafCommentEdit"] = SetSourceAndRebuild(warmSession, edited, project.Root);
+ report["leafCommentEdit"]!["edit"] = $"{nonRoot}: appended comment";
+ edited = new(documents, StringComparer.Ordinal);
+ SetSourceAndRebuild(warmSession, edited, project.Root);
+ }
+ edited[project.Root] += "\n// build-perf: root comment\n";
+ report["rootCommentEdit"] = SetSourceAndRebuild(warmSession, edited, project.Root);
+ Dispose(warmSession);
+ return report;
+ }
+
+ private static (JsonObject Sample, string SessionId) Compile(IReadOnlyDictionary<string, string> documents, string root,
+ IReadOnlyDictionary<string, string>? projectDocuments)
+ {
+ var (response, sample) = Invoke(new { operation = "compile", source = documents[root], sourceName = root, projectDocuments, performance = true });
+ var result = response["result"]!;
+ var model = result["model"] ?? throw new InvalidOperationException("Build failed: " + Truncate(result["diagnostics"]?.ToJsonString()));
+ return (Annotate(sample, result), model["id"]!.GetValue<string>());
+ }
+
+ private static JsonObject Rebuild(string sessionId)
+ {
+ var (response, sample) = Invoke(new { operation = "rebuild", sessionId, performance = true });
+ return Annotate(sample, response["result"]!);
+ }
+
+ private static JsonObject SetSourceAndRebuild(string sessionId, IReadOnlyDictionary<string, string> documents, string root)
+ {
+ Invoke(new { operation = "setSource", sessionId, source = documents[root], sourceName = root, projectDocuments = documents.Count > 1 ? documents : null });
+ return Rebuild(sessionId);
+ }
+
+ private static void Dispose(string sessionId) => Invoke(new { operation = "disposeSession", sessionId });
+
+ private static (JsonNode Response, JsonObject Sample) Invoke(object request)
+ {
+ var json = JsonSerializer.Serialize(request);
+ var allocated = GC.GetTotalAllocatedBytes(precise: true);
+ var started = Stopwatch.GetTimestamp();
+ var text = Aetheris.Web.Runtime.Program.Invoke(json);
+ var elapsed = Stopwatch.GetElapsedTime(started).TotalMilliseconds;
+ var allocatedBytes = GC.GetTotalAllocatedBytes(precise: true) - allocated;
+ var response = JsonNode.Parse(text)!;
+ if (response["ok"]?.GetValue<bool>() != true)
+ throw new InvalidOperationException("Runtime error: " + Truncate(response["error"]?.ToJsonString()));
+ return (response, new JsonObject
+ {
+ ["invokeMilliseconds"] = Round(elapsed),
+ ["responseBytes"] = Encoding.UTF8.GetByteCount(text),
+ ["allocatedBytes"] = allocatedBytes,
+ });
+ }
+
+ private static JsonObject Annotate(JsonObject sample, JsonNode result)
+ {
+ if (result["success"]?.GetValue<bool>() != true)
+ throw new InvalidOperationException("Build failed: " + Truncate(result["diagnostics"]?.ToJsonString()));
+ var timings = result["model"]?["timings"];
+ sample["rebuildMilliseconds"] = Round(timings?["totalBeforeSnapshotMilliseconds"]?.GetValue<double>() ?? 0);
+ sample["compileMilliseconds"] = Round(timings?["compileMilliseconds"]?.GetValue<double>() ?? 0);
+ sample["meshMilliseconds"] = Round(timings?["meshMilliseconds"]?.GetValue<double>() ?? 0);
+ if (timings?["reuse"]?["definitions"] is JsonArray reuse)
+ {
+ sample["definitions"] = reuse.Count;
+ sample["reusedDefinitions"] = reuse.Count(item => item?["reused"]?.GetValue<bool>() == true);
+ }
+ var profile = timings?["profile"];
+ if (profile is not null)
+ {
+ sample["gc"] = new JsonArray(profile["gc0"]!.GetValue<int>(), profile["gc1"]!.GetValue<int>(), profile["gc2"]!.GetValue<int>());
+ var phases = new JsonObject();
+ foreach (var group in profile["phases"]!.AsArray()
+ .Select(phase => (Name: phase!["name"]!.GetValue<string>(), Exclusive: phase["exclusiveMilliseconds"]!.GetValue<double>()))
+ .GroupBy(phase => phase.Name)
+ .OrderByDescending(group => group.Sum(phase => phase.Exclusive)))
+ phases[group.Key] = new JsonObject { ["count"] = group.Count(), ["exclusiveMilliseconds"] = Round(group.Sum(phase => phase.Exclusive)) };
+ sample["phases"] = phases;
+ }
+ sample["meshSha256"] = result["model"]?["mesh"] is { } mesh ? Sha256(mesh.ToJsonString()) : null;
+ // Same mesh content regardless of which build revision produced it.
+ sample["meshContentSha256"] = result["model"]?["mesh"] is { } content ? Sha256(WithoutRevisions(content.DeepClone()).ToJsonString()) : null;
+ return sample;
+ }
+
+ private static JsonObject Determinism(string sessionId, JsonObject cold, string projectName, bool dump = true)
+ {
+ var determinism = new JsonObject { ["meshSha256"] = cold["meshSha256"]?.GetValue<string>() };
+ try
+ {
+ var (response, _) = Invoke(new { operation = "exportStep", sessionId });
+ var step = Encoding.UTF8.GetString(Convert.FromBase64String(response["result"]!["base64"]!.GetValue<string>()));
+ // The STEP header carries a timestamp; the DATA section is the geometry contract.
+ var data = step.IndexOf("DATA;", StringComparison.Ordinal);
+ determinism["stepBytes"] = Encoding.UTF8.GetByteCount(step);
+ determinism["stepDataSha256"] = Sha256(data >= 0 ? step[data..] : step);
+ if (dump && Environment.GetEnvironmentVariable("AETHERIS_BUILD_PERF_DUMP_STEP") is { Length: > 0 } directory)
+ File.WriteAllText(Path.Combine(directory, $"native-{projectName}.step"), step);
+ }
+ catch (InvalidOperationException error) when (error.Message.Contains("step-export-unavailable", StringComparison.Ordinal))
+ {
+ determinism["stepDataSha256"] = null;
+ determinism["note"] = "No STEP product artifact (Scene).";
+ }
+ return determinism;
+ }
+
+ // ---------------------------------------------------------------- aggregation (parent process)
+
+ private static JsonObject? RunChild(string project, string repo)
+ {
+ var start = new ProcessStartInfo(Environment.ProcessPath!)
+ {
+ RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, WorkingDirectory = repo,
+ };
+ if (Path.GetFileNameWithoutExtension(Environment.ProcessPath!) is "dotnet") start.ArgumentList.Add(Assembly.GetEntryAssembly()!.Location);
+ foreach (var argument in new[] { "showcase", "--project", project }) start.ArgumentList.Add(argument);
+ start.Environment["AETHERIS_BUILD_PERF_CHILD"] = "1";
+ using var process = Process.Start(start)!;
+ var stdout = process.StandardOutput.ReadToEndAsync();
+ var stderr = process.StandardError.ReadToEndAsync();
+ process.WaitForExit();
+ if (process.ExitCode != 0)
+ {
+ Console.Error.WriteLine($"{project}: measurement failed (exit {process.ExitCode}).\n{Truncate(stderr.Result, 4000)}");
+ return null;
+ }
+ return JsonNode.Parse(stdout.Result)!.AsObject();
+ }
+
+ private static readonly string[] Scenarios = ["cold", "warm", "noChangeRebuild", "leafValueEdit", "leafCommentEdit", "rootCommentEdit"];
+
+ /// <summary>Median of each numeric field across runs; hashes must agree across runs.</summary>
+ private static JsonObject Summarize(IReadOnlyList<JsonObject> samples)
+ {
+ var first = samples[0];
+ var summary = new JsonObject { ["documents"] = first["documents"]!.DeepClone(), ["root"] = first["root"]!.DeepClone() };
+ var determinism = first["determinism"]!.DeepClone().AsObject();
+ var stepHashes = samples.Select(sample => sample["determinism"]?["stepDataSha256"]?.ToString()).Distinct().ToArray();
+ var meshHashes = samples.Select(sample => sample["determinism"]?["meshSha256"]?.ToString()).Distinct().ToArray();
+ determinism["stableAcrossRuns"] = stepHashes.Length == 1 && meshHashes.Length == 1;
+ determinism["rebuildStepMatchesCold"] = samples.All(sample => sample["determinism"]?["rebuildStepMatchesCold"]?.GetValue<bool>() != false);
+ determinism["rebuildMeshMatchesCold"] = samples.All(sample => sample["determinism"]?["rebuildMeshMatchesCold"]?.GetValue<bool>() != false);
+ summary["determinism"] = determinism;
+ foreach (var scenario in Scenarios)
+ {
+ var present = samples.Select(sample => sample[scenario] as JsonObject).Where(sample => sample is not null).Cast<JsonObject>().ToArray();
+ if (present.Length == 0) continue;
+ var aggregate = new JsonObject();
+ foreach (var field in new[] { "invokeMilliseconds", "rebuildMilliseconds", "compileMilliseconds", "meshMilliseconds", "responseBytes", "allocatedBytes", "definitions", "reusedDefinitions" })
+ {
+ var values = present.Select(sample => sample[field]?.GetValue<double>()).Where(value => value is not null).Select(value => value!.Value).Order().ToArray();
+ if (values.Length == 0) continue;
+ aggregate[field] = Round(values[values.Length / 2]);
+ if (field.EndsWith("Milliseconds", StringComparison.Ordinal) && values.Length > 1)
+ aggregate[field.Replace("Milliseconds", "SpreadPercent", StringComparison.Ordinal)] = Round(100 * (values[^1] - values[0]) / Math.Max(values[values.Length / 2], 1e-9));
+ }
+ if (present[0]["edit"] is { } edit) aggregate["edit"] = edit.DeepClone();
+ // Phases from the median-time run of this scenario.
+ var median = present.OrderBy(sample => sample["invokeMilliseconds"]!.GetValue<double>()).ElementAt(present.Length / 2);
+ if (median["phases"] is { } phases) aggregate["phases"] = phases.DeepClone();
+ if (median["gc"] is { } gc) aggregate["gc"] = gc.DeepClone();
+ summary[scenario] = aggregate;
+ }
+ return summary;
+ }
+
+ private static void PrintTable(JsonObject projects)
+ {
+ Console.WriteLine();
+ Console.WriteLine($"{"project",-9} {"cold",10} {"warm",10} {"no-change",10} {"leaf edit",10} {"reused",8} {"response",10} {"warm alloc",11} stable");
+ foreach (var (name, node) in projects)
+ {
+ var p = node!.AsObject();
+ var leaf = p["leafValueEdit"] ?? p["leafCommentEdit"];
+ var reused = leaf?["definitions"] is null ? "—" : $"{leaf["reusedDefinitions"]}/{leaf["definitions"]}";
+ Console.WriteLine($"{name,-9} {Ms(p, "cold", "invokeMilliseconds"),10} {Ms(p, "warm", "invokeMilliseconds"),10} {Ms(p, "noChangeRebuild", "invokeMilliseconds"),10} " +
+ $"{(leaf is null ? "—" : Format(leaf["invokeMilliseconds"]!.GetValue<double>())),10} {reused,8} {Bytes(p["warm"]?["responseBytes"]),10} {Bytes(p["warm"]?["allocatedBytes"]),11} " +
+ $"{p["determinism"]?["stableAcrossRuns"]}");
+ }
+ Console.WriteLine();
+ }
+
+ // ---------------------------------------------------------------- budgets
+
+ private static JsonObject Baseline(JsonObject results)
+ {
+ var budgets = new JsonObject
+ {
+ ["schema"] = "aetheris/build-perf-budgets/m0",
+ ["note"] = "Machine-independent fields always gate; *Milliseconds fields gate only with --check-time on the recorded machine.",
+ ["recordedOn"] = results["machine"]!.DeepClone(),
+ ["recordedCommit"] = results["commit"]!.DeepClone(),
+ };
+ var projects = new JsonObject();
+ foreach (var (name, node) in results["projects"]!.AsObject())
+ {
+ var p = node!.AsObject();
+ var budget = new JsonObject
+ {
+ ["stepDataSha256"] = p["determinism"]?["stepDataSha256"]?.DeepClone(),
+ ["meshSha256"] = p["determinism"]?["meshSha256"]?.DeepClone(),
+ ["rebuildMatchesCold"] = p["determinism"]?["rebuildStepMatchesCold"]?.GetValue<bool>() == true && p["determinism"]?["rebuildMeshMatchesCold"]?.GetValue<bool>() == true,
+ };
+ foreach (var scenario in Scenarios)
+ {
+ if (p[scenario] is not JsonObject s) continue;
+ var entry = new JsonObject
+ {
+ ["invokeMilliseconds"] = s["invokeMilliseconds"]?.DeepClone(),
+ ["responseBytes"] = s["responseBytes"]?.DeepClone(),
+ ["allocatedBytes"] = s["allocatedBytes"]?.DeepClone(),
+ };
+ if (s["reusedDefinitions"] is { } reused) entry["reusedDefinitions"] = reused.DeepClone();
+ budget[scenario] = entry;
+ }
+ projects[name] = budget;
+ }
+ budgets["projects"] = projects;
+ return budgets;
+ }
+
+ private static bool Check(JsonObject budgets, JsonObject projects, bool checkTime, double timeTolerance)
+ {
+ const double allocationTolerance = 1.10, responseTolerance = 1.01;
+ var failures = new List<string>();
+ var improvements = new List<string>();
+ foreach (var (name, budgetNode) in budgets["projects"]!.AsObject())
+ {
+ if (projects[name] is not JsonObject actual) continue;
+ var budget = budgetNode!.AsObject();
+ void Exact(string field, string? expected, string? got)
+ {
+ if (expected is not null && expected != got) failures.Add($"{name}: {field} changed ({expected[..12]} -> {got?[..Math.Min(12, got.Length)] ?? "none"}); geometry or display output differs from the baseline.");
+ }
+ Exact("STEP DATA hash", budget["stepDataSha256"]?.ToString(), actual["determinism"]?["stepDataSha256"]?.ToString());
+ Exact("display mesh hash", budget["meshSha256"]?.ToString(), actual["determinism"]?["meshSha256"]?.ToString());
+ if (actual["determinism"]?["stableAcrossRuns"]?.GetValue<bool>() == false) failures.Add($"{name}: output differs between runs.");
+ if (budget["rebuildMatchesCold"]?.GetValue<bool>() == true &&
+ (actual["determinism"]?["rebuildStepMatchesCold"]?.GetValue<bool>() == false || actual["determinism"]?["rebuildMeshMatchesCold"]?.GetValue<bool>() == false))
+ failures.Add($"{name}: a rebuild with no geometry change no longer reproduces the cold build.");
+ foreach (var scenario in Scenarios)
+ {
+ if (budget[scenario] is not JsonObject b || actual[scenario] is not JsonObject a) continue;
+ void AtMost(string field, double tolerance)
+ {
+ if (b[field] is null || a[field] is null) return;
+ double limit = b[field]!.GetValue<double>(), got = a[field]!.GetValue<double>();
+ string Show(double value) => field.EndsWith("Milliseconds", StringComparison.Ordinal) ? Format(value) : Bytes(JsonValue.Create(value));
+ if (got > limit * tolerance) failures.Add($"{name}/{scenario}: {field} {Show(got)} exceeds budget {Show(limit)} (×{tolerance}).");
+ else if (got < limit * 0.8) improvements.Add($"{name}/{scenario}: {field} {Show(got)} vs budget {Show(limit)}");
+ }
+ AtMost("responseBytes", responseTolerance);
+ AtMost("allocatedBytes", allocationTolerance);
+ if (checkTime) AtMost("invokeMilliseconds", timeTolerance);
+ if (b["reusedDefinitions"] is { } r && a["reusedDefinitions"] is { } got && got.GetValue<double>() < r.GetValue<double>())
+ failures.Add($"{name}/{scenario}: reused definitions {got} below budget {r}.");
+ }
+ }
+ foreach (var improvement in improvements) Console.WriteLine($"improved: {improvement} — consider --write-baseline");
+ foreach (var failure in failures) Console.Error.WriteLine($"FAIL {failure}");
+ Console.WriteLine(failures.Count == 0 ? "Build-perf budgets: pass." : $"Build-perf budgets: {failures.Count} failure(s).");
+ return failures.Count == 0;
+ }
+
+ // ---------------------------------------------------------------- helpers
+
+ private static JsonNode WithoutRevisions(JsonNode node)
+ {
+ if (node is JsonObject obj)
+ {
+ foreach (var key in obj.Select(pair => pair.Key).Where(key => key.Contains("evision", StringComparison.Ordinal)).ToArray()) obj.Remove(key);
+ foreach (var (_, child) in obj) if (child is not null) WithoutRevisions(child);
+ }
+ else if (node is JsonArray array) foreach (var child in array) if (child is not null) WithoutRevisions(child);
+ return node;
+ }
+
+ private static string? FindRepositoryRoot()
+ {
+ for (var dir = new DirectoryInfo(Environment.CurrentDirectory); dir is not null; dir = dir.Parent)
+ if (File.Exists(Path.Combine(dir.FullName, "Aetheris.slnx"))) return dir.FullName;
+ return null;
+ }
+
+ private static string GitCommit(string repo)
+ {
+ try
+ {
+ var head = File.ReadAllText(Path.Combine(repo, ".git", "HEAD")).Trim();
+ if (!head.StartsWith("ref: ", StringComparison.Ordinal)) return head[..12];
+ var reference = Path.Combine(repo, ".git", head[5..]);
+ return File.Exists(reference) ? File.ReadAllText(reference).Trim()[..12] : head[5..];
+ }
+ catch (IOException) { return "unknown"; }
+ }
+
+ private static string RuntimeInfo() => $"{System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription} {(Debugger.IsAttached ? "(debugger)" : "")}".Trim();
+ private static double Round(double value) => Math.Round(value, 1);
+ private static string Sha256(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant();
+ private static string Truncate(string? text, int length = 600) => text is null ? "" : text.Length <= length ? text : text[..length] + "…";
+ private static string Ms(JsonObject p, string scenario, string field) => p[scenario]?[field] is { } v ? Format(v.GetValue<double>()) : "—";
+ private static string Format(double ms) => ms >= 1000 ? $"{ms / 1000:0.00} s" : $"{ms:0} ms";
+ private static string Bytes(JsonNode? node) => node is null ? "—" : node.GetValue<double>() switch
+ {
+ >= 1 << 30 => $"{node.GetValue<double>() / (1 << 30):0.0} GB",
+ >= 1 << 20 => $"{node.GetValue<double>() / (1 << 20):0.0} MB",
+ _ => $"{node.GetValue<double>() / 1024:0} KB",
+ };
+}
diff --git a/Aetheris.Web.Perf/build-perf-budgets.json b/Aetheris.Web.Perf/build-perf-budgets.json
new file mode 100644
index 00000000..bf2c86dd
--- /dev/null
+++ b/Aetheris.Web.Perf/build-perf-budgets.json
@@ -0,0 +1,169 @@
+{
+ "schema": "aetheris/build-perf-budgets/m0",
+ "note": "Machine-independent fields always gate; *Milliseconds fields gate only with --check-time on the recorded machine.",
+ "recordedOn": "vm \u00b7 2 CPU \u00b7 Unix 6.18.44.114",
+ "recordedCommit": "2b3abbbf893a + BUILD-PERF-M0/M1 working tree",
+ "projects": {
+ "bracket": {
+ "stepDataSha256": "c3323aa5717fbd198c6148ab082623f0f5920c42487c6dd5f398da4abd2d4170",
+ "meshSha256": "b0ec1fb0d1d40af0e6b13fe9fa1ddd38167ebde5f3f3fd946eeaac4ba97509f9",
+ "rebuildMatchesCold": true,
+ "cold": {
+ "invokeMilliseconds": 679.6,
+ "responseBytes": 51765,
+ "allocatedBytes": 6383736
+ },
+ "warm": {
+ "invokeMilliseconds": 34.4,
+ "responseBytes": 51746,
+ "allocatedBytes": 3639336
+ },
+ "noChangeRebuild": {
+ "invokeMilliseconds": 32.2,
+ "responseBytes": 51668,
+ "allocatedBytes": 3538208
+ },
+ "rootCommentEdit": {
+ "invokeMilliseconds": 32.8,
+ "responseBytes": 51703,
+ "allocatedBytes": 3540192
+ }
+ },
+ "bolt": {
+ "stepDataSha256": "b29a01bd60933b8394a7cbb754c4d4894d9d537b8a56e313b80bf0263ab0349c",
+ "meshSha256": "aa9262734e2c79801a33b60f318d646b7a81aebda0b2bea9c0e711b775f835a6",
+ "rebuildMatchesCold": true,
+ "cold": {
+ "invokeMilliseconds": 6059.3,
+ "responseBytes": 13899860,
+ "allocatedBytes": 1935725472
+ },
+ "warm": {
+ "invokeMilliseconds": 3634.7,
+ "responseBytes": 13899844,
+ "allocatedBytes": 1884732616
+ },
+ "noChangeRebuild": {
+ "invokeMilliseconds": 3391.7,
+ "responseBytes": 13899795,
+ "allocatedBytes": 1882444560
+ },
+ "leafCommentEdit": {
+ "invokeMilliseconds": 3052.2,
+ "responseBytes": 13899791,
+ "allocatedBytes": 1882094152
+ },
+ "rootCommentEdit": {
+ "invokeMilliseconds": 3152.8,
+ "responseBytes": 13899824,
+ "allocatedBytes": 1882099592
+ }
+ },
+ "atlas": {
+ "stepDataSha256": "9509cba94c0b98b2a3f8ae2b037626f0bde11667c7c1297cbf5670c9f67b28af",
+ "meshSha256": "49fe7e6ef3adce069b21582e99cb1f16876aa10d8da9b13b4b4e029a8b6c2c0b",
+ "rebuildMatchesCold": true,
+ "cold": {
+ "invokeMilliseconds": 9150.4,
+ "responseBytes": 3469581,
+ "allocatedBytes": 3406553272,
+ "reusedDefinitions": 0
+ },
+ "warm": {
+ "invokeMilliseconds": 3846.3,
+ "responseBytes": 3469453,
+ "allocatedBytes": 3386982160,
+ "reusedDefinitions": 0
+ },
+ "noChangeRebuild": {
+ "invokeMilliseconds": 90,
+ "responseBytes": 3426152,
+ "allocatedBytes": 37745824,
+ "reusedDefinitions": 24
+ },
+ "leafCommentEdit": {
+ "invokeMilliseconds": 1073.6,
+ "responseBytes": 3450508,
+ "allocatedBytes": 479328584,
+ "reusedDefinitions": 2
+ },
+ "rootCommentEdit": {
+ "invokeMilliseconds": 100.1,
+ "responseBytes": 3426184,
+ "allocatedBytes": 37359912,
+ "reusedDefinitions": 24
+ }
+ },
+ "guitar": {
+ "stepDataSha256": "51c8f8fed659bfb09a64317e276cca448c30c5bfe387cccbd8687e25cdb5d3aa",
+ "meshSha256": "700ae75e20a1c49685e3d6478b4ff7e714cb28bd36491caf786c63c591a6a2c6",
+ "rebuildMatchesCold": true,
+ "cold": {
+ "invokeMilliseconds": 23141.1,
+ "responseBytes": 18058270,
+ "allocatedBytes": 9646906056,
+ "reusedDefinitions": 0
+ },
+ "warm": {
+ "invokeMilliseconds": 13030.1,
+ "responseBytes": 18057812,
+ "allocatedBytes": 9543507448,
+ "reusedDefinitions": 0
+ },
+ "noChangeRebuild": {
+ "invokeMilliseconds": 292.4,
+ "responseBytes": 17969484,
+ "allocatedBytes": 152488328,
+ "reusedDefinitions": 56
+ },
+ "leafValueEdit": {
+ "invokeMilliseconds": 3713.6,
+ "responseBytes": 18033417,
+ "allocatedBytes": 2351724208,
+ "reusedDefinitions": 4
+ },
+ "leafCommentEdit": {
+ "invokeMilliseconds": 5833,
+ "responseBytes": 17970980,
+ "allocatedBytes": 4286504152,
+ "reusedDefinitions": 55
+ },
+ "rootCommentEdit": {
+ "invokeMilliseconds": 353.2,
+ "responseBytes": 17969518,
+ "allocatedBytes": 152070432,
+ "reusedDefinitions": 56
+ }
+ },
+ "house": {
+ "stepDataSha256": null,
+ "meshSha256": "ce00e129709c10a86151b4bea6f000947cf1c51e0bb4a226b67aea8f3d54a15a",
+ "rebuildMatchesCold": true,
+ "cold": {
+ "invokeMilliseconds": 5324.4,
+ "responseBytes": 5288284,
+ "allocatedBytes": 675499016
+ },
+ "warm": {
+ "invokeMilliseconds": 3133.1,
+ "responseBytes": 5288246,
+ "allocatedBytes": 648470768
+ },
+ "noChangeRebuild": {
+ "invokeMilliseconds": 755.4,
+ "responseBytes": 5217160,
+ "allocatedBytes": 186496320
+ },
+ "leafCommentEdit": {
+ "invokeMilliseconds": 1536.3,
+ "responseBytes": 5264742,
+ "allocatedBytes": 592901384
+ },
+ "rootCommentEdit": {
+ "invokeMilliseconds": 441.6,
+ "responseBytes": 5217187,
+ "allocatedBytes": 185895752
+ }
+ }
+ }
+}
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
index 32c85cb8..2730eb4d 100644
--- a/Aetheris.Web.Runtime/Program.cs
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -204,8 +204,9 @@ public static partial class Program
private static object ExportStep(WebRequest request)
{
var session = Session(request);
- if (session.StepText is null) throw new WebRuntimeException("step-export-unavailable", "The current document has no STEP product artifact.");
- return new { mediaType = "model/step", fileName = session.Name + ".step", base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(session.StepText)), revision = session.Revision };
+ var stepText = session.StepText;
+ if (stepText is null) throw new WebRuntimeException("step-export-unavailable", "The current document has no STEP product artifact.");
+ return new { mediaType = "model/step", fileName = session.Name + ".step", base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(stepText)), revision = session.Revision };
}
private static object DisposeSession(WebRequest request)
@@ -252,7 +253,23 @@ public static partial class Program
public string Id { get; } = id;
public string Name => Path.GetFileNameWithoutExtension(_sourceName);
public int Revision { get; private set; }
- public string? StepText { get; private set; }
+ private string? _stepText;
+ private Func<string>? _stepWriter;
+ /// <summary>STEP of the current build. Assemblies write it on first request (BUILD-PERF-M1);
+ /// their structural export checks still run during the build.</summary>
+ public string? StepText
+ {
+ get
+ {
+ if (_stepText is null && _stepWriter is { } writer)
+ {
+ using var phase = BuildPerfTrace.Phase("web.assembly-step-export");
+ _stepText = writer();
+ _stepWriter = null;
+ }
+ return _stepText;
+ }
+ }
public object Snapshot => _lastSnapshot ?? throw new WebRuntimeException("model-not-built", "The model has no valid snapshot.");
public void SetSource(string nextSource, string? nextSourceName, IReadOnlyDictionary<string, string>? documents = null)
@@ -340,7 +357,8 @@ public static partial class Program
Revision++;
_properties = nextProperties;
_projections = compiled.Projections ?? [];
- StepText = compiled.StepText;
+ _stepText = compiled.StepText;
+ _stepWriter = compiled.StepWriter;
var changes = new
{
changedEntityIds = compiled.EntityIds,
@@ -361,7 +379,7 @@ public static partial class Program
tree = compiled.Tree, properties = _properties, mesh = compiled.Mesh,
diagnostics = compiled.Diagnostics, changes, timings
};
- return compiled with { Revision = Revision, Model = _lastSnapshot, Changes = changes, StepText = null };
+ return compiled with { Revision = Revision, Model = _lastSnapshot, Changes = changes, StepText = null, StepWriter = null };
}
private WebBuildResult CompilePart(string effective, List<WebProperty> properties)
@@ -442,25 +460,38 @@ public static partial class Program
// Browser projects are explicit source snapshots. Includes, ports and
// SectionChain/Loft resources must resolve through the compiler's
// project path, rather than falling through to the host filesystem.
+ var assemblyCompilePhase = BuildPerfTrace.Phase("web.assembly-compile");
var compilation = _projectDocuments is { Count: > 0 }
? _compilationSession.CompileProject(new FirmamentProjectSnapshot(_sourceName,
new Dictionary<string, string>(_projectDocuments, StringComparer.Ordinal) { [_sourceName] = effective }))
: _compilationSession.Compile(effective, _sourceName);
+ assemblyCompilePhase.Dispose();
_lastReuse = compilation.Reuse;
var compileMs = watch.Elapsed.TotalMilliseconds;
if (!compilation.IsSuccess || compilation.Ir is null || compilation.Geometry is null)
return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "warning", d.Code, d.Message, SourceRef(_sourceName, 0, effective.Length))).ToArray(), compileMs);
- var step = AssemblyIrAp242Exporter.Export(compilation);
+ var assemblyStepPhase = BuildPerfTrace.Phase("web.assembly-step-prepare");
+ var step = AssemblyIrAp242Exporter.PrepareExport(compilation);
+ assemblyStepPhase.Dispose();
if (!step.IsSuccess) return WebBuildResult.Failed(Diagnostics(step.Diagnostics, _sourceName), compileMs);
+ var writeStep = step.Value;
+ string StepWriter()
+ {
+ var written = writeStep();
+ return written.IsSuccess ? written.Value
+ : throw new WebRuntimeException("step-export-failed", string.Join("; ", written.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ }
watch.Restart();
- var mesh = AssemblyDisplayMeshExporter.Export(compilation);
+ var assemblyMeshPhase = BuildPerfTrace.Phase("web.assembly-display-mesh");
+ var mesh = _compilationSession.ExportDisplayMesh(compilation);
+ assemblyMeshPhase.Dispose();
var meshMs = watch.Elapsed.TotalMilliseconds;
var nodes = compilation.Ir.Instances.OrderBy(instance => instance.Path.Segments.Count).Select(instance =>
new WebTreeNode(instance.StableId, instance.Kind.ToString(), instance.Path.Segments.Last(), instance.ParentStableId, instance.ChildrenStableIds, true, null)).ToArray();
var children = nodes.Where(node => node.ParentId == compilation.Ir.RootInstanceStableId).Select(node => node.Id).ToArray();
var root = new WebTreeNode(compilation.Ir.RootInstanceStableId, "Assembly", compilation.Ir.Name, null, children, true, SourceRef(_sourceName, 0, effective.Length));
var tree = new { rootId = root.Id, nodes = nodes.Prepend(root).DistinctBy(node => node.Id).ToArray() };
- return WebBuildResult.Passed(step.Value, tree, mesh, nodes.Select(node => node.Id).Prepend(root.Id).Distinct().ToArray(), compileMs, meshMs);
+ return WebBuildResult.Passed(null, tree, mesh, nodes.Select(node => node.Id).Prepend(root.Id).Distinct().ToArray(), compileMs, meshMs) with { StepWriter = StepWriter };
}
private WebBuildResult CompileScene(string effective)
@@ -469,11 +500,15 @@ public static partial class Program
// A project snapshot is explicit; missing resources never fall through to browser disk.
var documents = new Dictionary<string, string>(_projectDocuments ?? new Dictionary<string, string>(), StringComparer.Ordinal)
{ [_sourceName] = effective };
+ var scenePhase = BuildPerfTrace.Phase("web.scene-compile");
var compilation = _sceneSession.CompileProject(new FirmamentProjectSnapshot(_sourceName, documents));
+ scenePhase.Dispose();
if (!compilation.IsSuccess || compilation.Scene is null)
return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic("error", d.Code, d.Message)).ToArray(), watch.Elapsed.TotalMilliseconds);
var compiledScene = compilation.Scene;
+ var sceneMeshPhase = BuildPerfTrace.Phase("web.scene-display-projection");
var mesh = DisplayProjection.Project(compiledScene);
+ sceneMeshPhase.Dispose();
var sourceNodes = compiledScene.Nodes.ToDictionary(n => n.Path, StringComparer.Ordinal);
WebSourceRef? SceneSource(string path)
{
@@ -652,6 +687,8 @@ internal sealed record WebBuildResult(bool Success, int Revision, object? Model,
object? Tree = null, object? Mesh = null, IReadOnlyList<string>? EntityIds = null, object? Timings = null, object? Changes = null, string? StepText = null,
IReadOnlyList<FirmamentConstructProjection>? Projections = null, double CompileMilliseconds = 0, double MeshMilliseconds = 0)
{
+ /// <summary>Writes the STEP text on first request; never serialized.</summary>
+ [System.Text.Json.Serialization.JsonIgnore] public Func<string>? StepWriter { get; init; }
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/docs/development/milestones/general/build-perf-ladder.md b/docs/development/milestones/general/build-perf-ladder.md
new file mode 100644
index 00000000..3b842d05
--- /dev/null
+++ b/docs/development/milestones/general/build-perf-ladder.md
@@ -0,0 +1,151 @@
+# BUILD-PERF — Firmament build performance ladder (M0–M5)
+
+## Problem
+
+Helios is an IDE for geometry. Its loop is edit → build → see. Today that loop is dominated by
+the kernel pipeline, not by WebAssembly:
+
+| Project (showcase) | Native cold (JIT) | Native warm | Response JSON | Browser, dev runtime (Windows desktop) |
+|---|---|---|---|---|
+| bracket | 0.7 s | 29 ms | 49 KB | 0.76 s |
+| bolt | 5.6 s | 3.7 s | 13.5 MB | — |
+| ATLAS | 10.0 s | 4.2 s | 3.4 MB | — |
+| house | 7.3 s | 2.2 s | 5.1 MB | — |
+| guitar | 25.8 s | 13.9 s | 17.5 MB | 870 s |
+
+Guitar rebuilds in one native `WebModelSession`:
+
+| Rebuild | Time | Definitions reused |
+|---|---|---|
+| no source change | 3.1 s | 56 / 56 |
+| one knob radius edited (`knob.firmament`) | 5.7 s | 4 / 56 |
+| comment appended to the root | 2.7 s | — |
+
+Measured 2026-10-13 through `Aetheris.Web.Runtime.Program.Invoke` (the worker's entry point),
+.NET 10 Release, commit `2b3abbb`. Native numbers are from a 2-core Linux container; the browser
+number is from the author's Windows desktop running `npm run dev` (non-AOT dev runtime).
+
+### Where guitar build time goes (sampled, native, share of the run)
+
+- `SectionChainMaterializer.Materialize` 46%: `SectionChainSelfIntersectionValidator.Validate` 23%,
+ `BoundedPcurveBuilder.Populate` 16%.
+- `Step242Importer.ImportBody` 18%. `AssemblyDefinitionCache` stores each definition as STEP text;
+ every cache hit re-parses STEP and re-runs pcurve recovery. This is the 3 s no-change floor.
+- `FirmamentV2Parser.Parse` 13% (parsed repeatedly).
+- `FirmamentBuildAndExport.ExportSource` 10%: STEP is produced on every build.
+- Display tessellation 12% (torus faces 9%); `BSplineSurfaceWithKnots.Evaluate` 17% inclusive.
+
+### Root causes outside the kernel algorithms
+
+- Cache key (`AssemblyDefinitionCache.Key`) hashes the full `declarations` text including offsets,
+ so an edit anywhere invalidates nearly every definition.
+- The C#→JS boundary returns display meshes as JSON number arrays (17.5 MB for the guitar), which
+ the interpreter-mode runtime serializes and the worker parses on every build.
+
+## Rules for every milestone
+
+- **Determinism guard.** STEP DATA and display-mesh output for every showcase project stays
+ byte-identical to the M0 baseline *within a runtime*, or each difference is listed and justified
+ in that milestone's report. Native and WASM output are not byte-identical today (floating-point
+ drift; see BUILD-PERF-M0), so cross-runtime agreement is checked by tolerance, not bytes.
+- **Allocation is a target, not only time.** The browser penalty tracks allocation and GC
+ (bolt: 1.8 GB per build, 96× slower than native on the dev runtime). Exits state allocation too.
+- **Real path only.** Gains are measured through `Program.Invoke` and in the browser, never in a
+ side harness that skips work the editor does.
+- **Ratchet.** `Aetheris.Web.Perf showcase --check Aetheris.Web.Perf/build-perf-budgets.json` gates
+ hashes, response bytes, allocations and reuse; `--check-time` adds wall time on the recording
+ machine. Re-record with `--write-baseline` when a milestone lands.
+- Each milestone ends in Success, Meaningful progression or Honest stop (AGENTS.md convergence rule).
+
+## Ladder
+
+### M0 — Baseline and ratchet
+
+- Extend `Aetheris.Web.Perf` from helix fixtures to the showcase projects (multi-file
+ `projectDocuments`): cold, warm, no-change rebuild, single-leaf edit, comment edit; per-phase
+ `BuildPerfTrace` output aggregated by phase name; response size.
+- Instrument the uninstrumented assembly path (`AssemblyM1Pipeline.CompileParsed`,
+ `AssemblyDefinitionCache.Materialize`, SectionChain materialize/validate, STEP export/import).
+- Record browser timings for the dev runtime and the production AOT runtime on real hardware.
+- Commit budgets (`artifacts/local` for raw output; a small checked-in budget file) and a check
+ that fails on regression.
+
+Exit: baselines reproducible within ±10% across three runs; every phase above 2% of guitar time
+is named.
+
+**Result** ([BUILD-PERF-M0](../../../release/BUILD-PERF-M0.md)): meaningful progression. Native and
+dev-runtime browser baselines, instrumentation and the ratchet are in place. Open: AOT browser
+numbers (AOT link needs > 8 GB RAM), naming the bolt's part-compile interior.
+
+### M1 — Rebuild floor
+
+- Cache payload becomes the immutable materialized body (or Aetheris native binary form), cloned
+ on hit. No STEP parse on a cache hit.
+- STEP is produced only on `exportStep`, not on every build.
+- Per-document parse cache keyed by content hash (guitar parses Firmament 208 times per build).
+- Part path gets the same definition cache as assemblies (bolt no-change rebuild = full build).
+- Validation that cannot change when nothing changed is not re-run (datum seats: 1.24 s of the
+ guitar's 2.9 s no-change rebuild); cached bodies keep their display tessellation.
+- Cross-runtime tolerance comparator for STEP output (native vs WASM).
+
+Exit: guitar and bolt no-change rebuild < 100 ms native (from 2.9 s and 3.3 s); guitar no-change
+allocation < 50 MB (from 2.9 GB). STEP bytes unchanged per runtime.
+
+**Result** ([BUILD-PERF-M1](../../../release/BUILD-PERF-M1.md)): meaningful progression. The metric
+is now the *root comment edit* (source changed, geometry unchanged), stated as kernel time before
+response serialization. Guitar 2.61 s → 214 ms (2.75 GB → 145 MB), ATLAS 432 → 74 ms; hashes
+unchanged; rebuilds reproduce the cold build; native and WASM STEP proven equivalent. Bolt
+unchanged and moved to M4 (a single part is one definition). Guitar's remaining ~200 ms project
+parse and the Scene path move to M2.
+
+**Order after M1: M3 before M2.** In the browser, ATLAS' root-comment edit is 5.7 s of which only
+1.55 s is kernel; 4.1 s is the unchanged mesh's JSON round trip.
+
+
+### M2 — Invalidation granularity
+
+- Definition cache key = that definition's own dependency closure, not the whole declarations text.
+- Cached semantic evidence stores definition-relative spans, rebased on reuse.
+- Parse per definition instead of re-parsing the concatenated project on every edit (guitar
+ `assembly.parse-project` ~200 ms after M1).
+- Scene compilation uses the assembly session caches (house `web.scene-compile` 330 ms).
+
+Exit: the knob edit reuses ≥ 52 / 56 definitions and costs only the definitions it owns.
+Diagnostics, source maps and STEP match a clean build exactly.
+
+### M3 — Binary bridge
+
+- Display meshes cross the JS boundary as typed arrays (`JSExport` memory views → transferable
+ `ArrayBuffer`s to the page). JSON carries only tree, diagnostics and projections.
+
+Exit: guitar JSON response < 1 MB; mesh content hash identical; browser time between "build done
+in C#" and "mesh on GPU" measured and reported.
+
+### M4 — Kernel hotspots
+
+In order of measured share, re-profiled after M1–M3:
+
+1. SectionChain self-intersection validation: spatial index, and re-validate only changed chains.
+2. Pcurve construction and residual sampling (`BoundedPcurveBuilder`, `BrepPcurveRecovery.MaximumResidual`).
+3. `BSplineSurfaceWithKnots.Evaluate` allocation and basis reuse.
+4. Torus and trimmed-surface tessellation.
+5. Bolt maker-mark engraving: `PlanarCapEngraving.Engrave` verifies with a full
+ `BrepMassProperties.Evaluate` of the threaded body (41% of the part compile) and glyph profile
+ normalization (34%).
+
+Exit: guitar warm native build target set from M0 data (working target ≤ 5 s from 13.9 s); full
+`Aetheris.slnx` test lane green; STEP unchanged or justified.
+
+### M5 — First paint
+
+- Showcase projects ship a precomputed binary display mesh keyed by source hash; the editor shows
+ it immediately and replaces it with the authoritative build.
+- Per-definition cache persisted in IndexedDB by content hash, so a reload does not start cold.
+
+Exit: a showcase project shows geometry in < 1 s on open; the authoritative build replaces it with
+no visual difference.
+
+## Out of scope
+
+Kernel algorithm rewrites beyond the measured hotspots; changes to Firmament language semantics;
+Helios UI work (tracked separately).
diff --git a/docs/release/BUILD-PERF-M0.md b/docs/release/BUILD-PERF-M0.md
new file mode 100644
index 00000000..3b71ddbb
--- /dev/null
+++ b/docs/release/BUILD-PERF-M0.md
@@ -0,0 +1,108 @@
+# BUILD-PERF-M0 — Baseline and ratchet
+
+Ladder: [build-perf-ladder.md](../development/milestones/general/build-perf-ladder.md).
+
+**State: meaningful progression.** Native baseline, browser dev-runtime baseline and the ratchet
+are in place and reproducible. Two exit items are open: the AOT browser number (needs a machine
+with more than ~8 GB RAM to link) and naming the part-compile interior for the bolt.
+
+## What changed
+
+- **Instrumentation.** `BuildPerfTrace` phases at the boundaries the profiler identified:
+ assembly parse, route bindings, per-definition materialization, definition-cache key / hit
+ re-import / store re-import, M0 compile, execute, residual, interference and datum-seat
+ validation; SectionChain authoring compile, materialize, build-body and self-intersection
+ validation; bounded pcurve build; Firmament V2 parse; `Step242Importer.ImportBody`; web
+ assembly compile, STEP export and display-mesh export; web scene compile and display
+ projection. Phases are no-ops unless a request sets `performance`.
+- **`BuildPerfTrace` GC counts are now per build** (deltas since `Start`), not process totals.
+- **`Aetheris.Web.Perf showcase`** (native lane). Each showcase project runs in a fresh process
+ through `Aetheris.Web.Runtime.Program.Invoke`: cold, warm (new session), no-change rebuild,
+ leaf value edit (guitar knob radius), leaf comment edit, root comment edit. Records invoke and
+ rebuild time, response bytes, allocated bytes, reused definitions, per-phase exclusive time
+ and GC counts, plus STEP DATA and display-mesh hashes. `--runs N` reports medians and spread.
+- **`Aetheris.Web.Perf/build-perf-budgets.json`** and `--check`. Always gated:
+ STEP DATA hash and mesh hash (exact), response bytes (+1%), allocated bytes (+10%), reused
+ definitions (no fewer). Wall time is gated only with `--check-time` (default ×1.5) because it
+ is meaningful only on the recording machine. Verified: a fresh run passes; a run under heavy
+ CPU contention (time +25–45%) still passes because allocations stay within 10%; a tampered
+ budget fails with exit code 1.
+- **`HeliosCAD/scripts/measure-build-perf.mjs`** (browser lane). The same projects through the
+ public SDK in a Worker, on the interpreted dev runtime (`dev`) and/or the AOT runtime (`aot`),
+ appending to `artifacts/local/build-perf/browser.jsonl`; `--dump-step` writes the STEP.
+
+```powershell
+dotnet run --project Aetheris.Web.Perf -c Release -- showcase --runs 3 --check Aetheris.Web.Perf/build-perf-budgets.json
+node ../HeliosCAD/scripts/measure-build-perf.mjs --variants dev,aot --projects bracket,bolt
+```
+
+## Native baseline
+
+.NET 10.0.12 Release, 2-core Linux container, commit `2b3abbb`, median of 3 runs.
+
+| Project | Cold | Warm | No change | Leaf edit | Root comment | Response | Warm alloc |
+|---|---|---|---|---|---|---|---|
+| bracket | 683 ms | 34 ms | 31 ms | — | 31 ms | 51 KB | 3 MB |
+| bolt | 5.86 s | 3.86 s | 3.26 s | 3.31 s | 3.09 s | 13.3 MB | 1.76 GB |
+| atlas | 10.05 s | 3.98 s | 677 ms | 1.23 s (2/24 reused) | 456 ms | 3.3 MB | 3.36 GB |
+| guitar | 25.11 s | 14.98 s | 2.89 s | 5.77 s (4/56 reused) | 2.75 s | 17.2 MB | 9.48 GB |
+| house | 7.01 s | 2.46 s | 827 ms | 1.76 s | 679 ms | 5.1 MB | 718 MB |
+
+Spread across runs is under 10% for bolt, atlas and guitar. House varies 30–55% and bracket's
+sub-50 ms numbers are noise-dominated; neither affects the ratchet, which gates allocations.
+
+### Where the time goes (warm build, exclusive)
+
+| Project | Largest phases |
+|---|---|
+| guitar 15.0 s | SectionChain self-intersection validate 4.56 s (×4) · bounded pcurve build 2.96 s (×4) · Firmament parse 2.21 s (**×208**) · datum-seat validation 1.35 s · STEP import 0.87 s (×118) · tessellation 0.71 s · display-mesh export 0.56 s |
+| atlas 4.0 s | bounded pcurve build 1.54 s · SectionChain validate 0.62 s · Firmament parse 0.49 s (×88) · STEP import 0.34 s (×48) |
+| house 2.5 s | STEP import 0.89 s (×98) · Firmament parse 0.62 s (×196) · scene compile 0.35 s |
+| bolt 3.9 s | part compile interior 1.99 s (**not yet named**) · tessellation 1.64 s |
+
+### The no-change rebuild floor
+
+- **guitar 2.9 s:** datum-seat validation 1.24 s runs on every build even when nothing changed;
+ display-mesh export 0.50 s; all 56 cached bodies re-tessellated (0.31 s) and re-imported from
+ STEP text (0.27 s); assembly STEP export 0.22 s.
+- **bolt 3.3 s = a full build.** The part path has no definition cache: every rebuild recompiles.
+- **Invalidation:** the knob value edit reuses 4 of 56 definitions. A comment appended to
+ `CarvedMaple.firmament` reuses 55 of 56 but costs 7.6 s, because the one definition it owns is
+ the SectionChain body.
+
+## Browser baseline (interpreted dev runtime)
+
+Headless Chromium in the same container, plus the author's Windows desktop for the guitar.
+
+| Project | Cold | vs native | No change | vs native | GC gen0/1/2 (cold) |
+|---|---|---|---|---|---|
+| bracket | 1.26 s | 1.8× | 0.39 s | 13× | 1/0/0 |
+| bolt | 313 s | 53× | 313 s | 96× | 658/22/22 |
+| atlas | 333 s | 33× | 30.7 s | 45× | 807/16/16 |
+| house | 81 s | 12× | 33.6 s | 41× | 199/4/4 |
+| guitar (Windows desktop, `npm run dev`) | **870 s** | ~35× (different machines) | — | — | — |
+
+`npm run dev` always serves the interpreted runtime; production serves AOT. The penalty tracks
+allocation and GC more than raw interpretation (bolt, 1.8 GB per build, is the worst ratio),
+which makes allocation a first-class target for M1–M4, not only wall time.
+
+## Determinism
+
+- **Within a runtime:** STEP DATA and display-mesh hashes are identical across all native runs,
+ and the browser STEP is stable across browser runs.
+- **Across runtimes it is not byte-identical.** Bolt: 4 of 50,110 STEP lines differ, all in the
+ last printed digit (relative 3.9e-14). Atlas: the first difference is also a last digit, but
+ definition 0 is written with 6 fewer STEP entities under WASM, which shifts all later entity
+ ids; assembly structure, all 70 definitions, occurrences and the world bounding box agree
+ (`aetheris analyze assembly`). This points to a different B-spline representation produced
+ from floating-point drift. Equivalence within tolerance is **not yet established**.
+- Consequence for the ladder: the byte-exact guard is per runtime (native hashes for the native
+ ratchet). Cross-runtime equivalence needs a tolerance comparator — added to M1 as a gate.
+
+## Open items
+
+1. **AOT browser numbers.** Linking the AOT runtime OOMs at `wasm-opt -O2` (5.4 GB RSS) in an
+ 8 GB container even with `DisableParallelEmccCompile` and `DisableParallelAot`. Measure on a
+ larger machine with `npm run sdk:install:production` and the browser lane's `--variants aot`.
+2. **Name the part-compile interior** (bolt: 1.99 s of `web.compile-and-export` exclusive).
+3. **Cross-runtime tolerance comparator** (see Determinism).
diff --git a/docs/release/BUILD-PERF-M1.md b/docs/release/BUILD-PERF-M1.md
new file mode 100644
index 00000000..fa59a353
--- /dev/null
+++ b/docs/release/BUILD-PERF-M1.md
@@ -0,0 +1,123 @@
+# BUILD-PERF-M1 — Rebuild floor
+
+Ladder: [build-perf-ladder.md](../development/milestones/general/build-perf-ladder.md) ·
+previous: [BUILD-PERF-M0](BUILD-PERF-M0.md).
+
+**State: meaningful progression.** The assembly rebuild floor fell 5–12× with output unchanged:
+STEP and display-mesh hashes are identical to M0 for every showcase project, and rebuilds now
+provably reproduce the cold build. ATLAS meets the < 100 ms exit; the guitar stops at 214 ms on
+its project parse, which moves to M2. The bolt (a single part) is unchanged by design and moves to
+M4 with its hotspots named.
+
+## Metric correction
+
+M0 measured a rebuild with no source change. An IDE rarely rebuilds unchanged source, and a
+whole-result memo would make that number vanish without helping any edit. The floor every edit
+pays is a **root comment edit**: the source changed, so the build runs, but no geometry changed.
+M1 reports both, and states kernel time (before the response is serialized) separately from
+invoke time, because re-sending the unchanged mesh as JSON costs 107–141 ms natively on its own;
+that belongs to M3.
+
+## Changes
+
+1. **Definition cache stores bodies, not STEP text.** `BrepBody.Clone()` copies the topology,
+ geometry and binding stores (add-only dictionaries of immutable records; insertion order is
+ preserved, so downstream output is identical). The cache keeps a private clone and every hit
+ returns a fresh clone. No STEP parse or pcurve recovery on a hit.
+2. **Derived values keyed by definition input key.** Each cached definition carries the input key
+ the cache already used to decide reuse (`MaterializedAssemblyDefinition.InputKey`,
+ `AssemblyM1CompilationResult.DefinitionInputKeys`). A generational `DerivedValueCache` keeps
+ what one build used and drops the rest at the next build:
+ - **datum-seat queries** per world body (input key + exact transform bits), so seat contact
+ checks stop tessellating every instance body on every build;
+ - **prepared display-mesh definitions** (`FirmamentCompilationSession.ExportDisplayMesh`, used
+ by the web runtime);
+ - **published-port bindings** (`AssemblyPublishedPorts.BindAuthored`): a template
+ specialization's ports depend on identity, declarations and source name; a SectionChain
+ resource's on identity, path and loaded text. Diagnostics are recorded and replayed; only
+ bindings the definition cache can copy are kept, and reuse returns copies.
+ Keys are input keys, not STEP hashes: two bodies can export identical STEP and still differ in
+ state the tessellator reads.
+3. **Assembly STEP is written on request.** `AssemblyIrAp242Exporter.PrepareExport` runs every
+ structural check of `Export` during the build (a failure still fails the build); the AP242
+ writer runs on `exportStep` and produces the same text. **Contract note:** a failure inside the
+ writer itself now surfaces at export (`step-export-failed`) instead of failing the build.
+4. **Harness:** `rebuildStepMatchesCold` / `rebuildMeshMatchesCold` (a no-change rebuild must
+ reproduce the cold build; gated by budgets), revision-independent mesh hash, and
+ `Aetheris.Web.Perf compare-step` (cross-runtime equivalence, below).
+5. **Tests:** `BrepBodyCloneTests` (identical STEP and order; clone independence);
+ `IncrementalCompilationTests` gains session display-mesh equality with a fresh export, and a
+ check that mutating a body handed out by the cache cannot leak into the next build.
+
+## Results
+
+Native, median of 3 runs, same 2-core container as M0. Kernel = before response serialization.
+
+| Project | Scenario | M0 kernel | M1 kernel | M1 invoke | M0 alloc | M1 alloc | Reused |
+|---|---|---|---|---|---|---|---|
+| guitar | root comment edit | 2.61 s | **214 ms** | 353 ms | 2.75 GB | 145 MB | 56/56 |
+| guitar | no-change rebuild | 2.75 s | **108 ms** | 292 ms | 2.75 GB | 145 MB | 56/56 |
+| guitar | knob value edit | 5.64 s | 3.57 s | 3.71 s | 4.38 GB | 2.19 GB | 4/56 |
+| guitar | leaf comment edit (`CarvedMaple`) | 7.42 s | 5.70 s | 5.83 s | 5.20 GB | 3.99 GB | 55/56 |
+| guitar | warm build | 14.82 s | 12.87 s | 13.03 s | 9.48 GB | 8.89 GB | — |
+| atlas | root comment edit | 432 ms | **74 ms** | 100 ms | 374 MB | 36 MB | 24/24 |
+| atlas | no-change rebuild | 632 ms | **48 ms** | 90 ms | 375 MB | 36 MB | 24/24 |
+| house | root comment edit | 635 ms | 394 ms | 442 ms | 304 MB | 177 MB | — |
+| bolt | root comment edit | 3.00 s | 3.06 s | 3.15 s | 1.75 GB | 1.75 GB | — |
+
+All five projects: STEP DATA and display-mesh hashes equal to M0; stable across runs; no-change
+rebuild reproduces the cold build. Root-comment timings are noisy (spread 26–42%) because they
+are short; allocations are the gate.
+
+### What remains in the floor
+
+- **guitar 214 ms:** `assembly.parse-project` ~200 ms. Port binding is now reused; the rest is
+ `InstantiateAssemblyDefinition`, named-profile resolution and spelling normalization over the
+ concatenated project text, all re-run on every edit → **M2** (per-definition parse and
+ invalidation).
+- **house 394 ms:** `web.scene-compile` 330 ms; the Scene path does not use the assembly session
+ caches yet → M2.
+- **response 107–141 ms native:** the unchanged mesh re-sent as JSON → **M3**.
+
+### Bolt (M0 open item 2, named)
+
+74% of the bolt's part compile is the maker-mark engraving: `PlanarCapEngraving.Engrave` runs
+`BrepMassProperties.Evaluate` (41%: tessellates the whole threaded body to verify the engrave)
+and glyph profile normalization (34%). A single part is one definition, so a cache cannot help
+an edit. Moved to **M4**.
+
+## Browser (interpreted dev runtime)
+
+Headless Chromium, same container as M0, M1 runtime.
+
+| Project | Scenario | M0 | M1 | M1 kernel | M1 response (rest) |
+|---|---|---|---|---|---|
+| atlas | no-change rebuild | 30.7 s | **5.8 s** | — | — |
+| atlas | root comment edit | — | **5.7 s** | 1.55 s | **4.1 s (73%)** |
+| house | no-change rebuild | 33.6 s | 19.4 s | — | — |
+| house | root comment edit | — | 19.4 s | 12.3 s (scene compile 10.8 s) | 7.0 s |
+| atlas / house | cold | 333 s / 81 s | 328 s / 74 s | | |
+
+In the browser the unchanged mesh's JSON round trip, not the kernel, is now the larger part of the
+edit floor (natively it was 107–141 ms). **M3 moves ahead of M2.**
+
+## Cross-runtime determinism (M0 open item 3)
+
+`compare-step` imports two STEP files (product structure when present), matches definitions by
+name and occurrences by path, requires identical topology counts, and compares volume, area,
+centroid and bounds within a relative tolerance (default 1e-6) using `BrepMassProperties`.
+
+| Project | Native vs WASM (dev runtime) | Worst relative difference |
+|---|---|---|
+| bolt | equivalent | 1.9e-19 |
+| atlas (70 definitions, 112 occurrences) | equivalent | 0 |
+
+Atlas' 6-entity STEP difference is therefore entity sharing in the writer (point deduplication
+tripped by last-digit floating-point drift), not geometry. A sanity run (atlas vs bolt) reports
+184 differences.
+
+## Open items
+
+1. AOT browser numbers (M0 item 1) — still need a machine with > 8 GB RAM to link.
+2. Guitar project parse (~200 ms) and Scene compile → M2.
+3. Response serialization of unchanged meshes → M3, now next: it is 73% of ATLAS' browser edit floor.