Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
BUILD-PERF-M2 (part 1): content-keyed derived caches, scene reuse, placement index
Claude99101c90a965
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.csindex ae6b7675..13445533 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs@@ -59,6 +59,42 @@ public sealed class IncrementalCompilationTestsAssert.Equal(expected, AssemblyDisplayMeshExporter.Serialize(session.ExportDisplayMesh(second)));}+ [Fact]+ public void SourceOnlyEditRebuildsTheDefinitionButReusesItsUnchangedDisplayMesh()+ {+ // BUILD-PERF-M2: derived values are keyed by definition content (identity, canonical STEP,+ // retained CIR), not by source text, so a comment in the declarations re-materializes the+ // definition but keeps the prepared mesh object (the web runtime retains it by reference).+ using var session = new FirmamentCompilationSession();+ var first = Good(session.Compile(Source()));+ var firstMesh = session.ExportDisplayMesh(first);+ var commented = Source().Replace("Struct Pad {", "Struct Pad {\n // declarations comment", StringComparison.Ordinal);+ var second = Good(session.Compile(commented));+ Assert.Equal(1, second.Reuse!.RebuiltDefinitions);+ var secondMesh = session.ExportDisplayMesh(second);+ Assert.Same(firstMesh.Definitions.Single(), secondMesh.Definitions.Single());+ var baseline = Good(new AssemblyM1Pipeline().Compile(commented));+ Assert.Equal(AssemblyDisplayMeshExporter.Serialize(AssemblyDisplayMeshExporter.Export(baseline)), AssemblyDisplayMeshExporter.Serialize(secondMesh));+ var taller = Good(session.Compile(Source(height: "3mm")));+ Assert.NotSame(firstMesh.Definitions.Single(), session.ExportDisplayMesh(taller).Definitions.Single());+ }++ [Fact]+ public void SceneRebuildReusesItsDisplayDefinitions()+ {+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Scene/WarmModernHouse/house.firmament");+ using var session = new Aetheris.Kernel.Firmament.Scene.FirmamentSceneSession();+ var first = session.CompileFile(path);+ Assert.True(first.IsSuccess, string.Join("\n", first.Diagnostics.Select(d => d.Message)));+ var second = session.CompileFile(path);+ Assert.True(second.IsSuccess);+ var fresh = new Aetheris.Kernel.Firmament.Scene.FirmamentSceneSession().CompileFile(path);+ Assert.Equal(first.Scene!.Display.Definitions.Count, second.Scene!.Display.Definitions.Count);+ Assert.All(first.Scene.Display.Definitions.Zip(second.Scene.Display.Definitions), pair => Assert.Same(pair.First, pair.Second));+ Assert.All(DisplayProjection.Project(first.Scene).Definitions.Zip(DisplayProjection.Project(second.Scene).Definitions), pair => Assert.Same(pair.First, pair.Second));+ Assert.Equal(AssemblyDisplayMeshExporter.Serialize(DisplayProjection.Project(fresh.Scene!)), AssemblyDisplayMeshExporter.Serialize(DisplayProjection.Project(second.Scene)));+ }+[Fact]public void MutatingAReusedBodyCannotLeakIntoTheNextBuild(){diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.csindex 77efa1ab..d4c9ca89 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs@@ -328,12 +328,27 @@ public sealed class AssemblyM0CompilerList<AssemblyDiagnostic> diagnostics){var result = new List<PlacementConstraintIr>();+ // BUILD-PERF-M2: instances do not change while constraints lower; index their semantic values+ // once (first occurrence wins, as FirstOrDefault did; the unique index throws on a duplicate+ // exactly where ToDictionary did) instead of flattening every instance per role and requirement.+ Dictionary<string, SemanticValue>? firstById = null, uniqueById = null;+ SemanticValue? FirstById(string id)+ {+ if (firstById is null)+ {+ firstById = new(StringComparer.Ordinal);+ foreach (var value in Flatten(instances.Select(instance => instance.SemanticRoot))) firstById.TryAdd(value.StableIdentity, value);+ }+ return firstById.GetValueOrDefault(id);+ }+ Dictionary<string, SemanticValue> UniqueById() =>+ uniqueById ??= Flatten(instances.Select(instance => instance.SemanticRoot)).ToDictionary(value => value.StableIdentity, StringComparer.Ordinal);foreach (var mate in mates){var definition = interfaces.Values.Single(x => x.StableId == mate.InterfaceStableId);var frameRevolute = definition.Family == MechanicalInterfaceFamily.Revolute && mate.Roles.Count == 2- && mate.Roles.All(role => Flatten(instances.Select(instance => instance.SemanticRoot))- .FirstOrDefault(value => value.StableIdentity == role.ParticipantSemanticValueId)?+ && mate.Roles.All(role => (role.ParticipantSemanticValueId is { } participant ? FirstById(participant)+ : Flatten(instances.Select(instance => instance.SemanticRoot)).FirstOrDefault(value => value.StableIdentity == role.ParticipantSemanticValueId))?.TryBinding<ExactDatumFrameBinding>(out _) == true);var authoredFrame = definition.Requirements.Count == 1&& definition.Requirements[0].Kind == PlacementConstraintKind.FrameCoincident;@@ -361,7 +376,7 @@ public sealed class AssemblyM0Compiler{ diagnostics.Add(new(InvalidParticipant, $"Interface '{definition.Name}' requirement '{requirement.Kind}' cannot resolve exposed members '{requirement.FirstMember}'/'{requirement.SecondMember}'.")); continue; }if (requirement.Kind == PlacementConstraintKind.FrameCoincident){- var values = Flatten(instances.Select(instance => instance.SemanticRoot)).ToDictionary(value => value.StableIdentity, StringComparer.Ordinal);+ var values = UniqueById();if (!values[firstId].TryBinding<ExactDatumFrameBinding>(out var firstFrame) || !values[secondId].TryBinding<ExactDatumFrameBinding>(out var secondFrame)){diagnostics.Add(new("assembly-interface-missing-frame", $"Interface '{definition.Name}' Mate '{mate.Name}' requires an exact DatumFrame on both participants."));@@ -489,6 +504,9 @@ public sealed class AssemblyM0Compilerif (anchor is null) diagnostics.Add(new("assembly-anchor-invalid", $"Anchor '{source.Anchor}' is outside the Assembly tree."));var known = new Dictionary<string, AssemblyTransform>(StringComparer.Ordinal);var overconstrained = new HashSet<string>(StringComparer.Ordinal);+ Dictionary<string, SemanticValue>? valueIndex = null;+ IReadOnlyDictionary<string, SemanticValue> ValueIndex() =>+ valueIndex ??= Flatten(instances.Select(x => x.SemanticRoot)).ToDictionary(x => x.StableIdentity, StringComparer.Ordinal);var root = instances.Single(instance => instance.ParentStableId is null);known[root.StableId] = AssemblyTransform.Identity;if (anchor is not null) known[anchor.StableId] = AssemblyTransform.Identity;@@ -527,7 +545,7 @@ public sealed class AssemblyM0Compiler{var target = owners.Single(x => x.StableId != moving.StableId);var oriented = Orient(mateConstraints, moving, instances);- var candidate = CandidateTransform(oriented, instances, known[target.StableId]);+ var candidate = CandidateTransform(oriented, ValueIndex, known[target.StableId]);if (TransformDistance(candidate, known[moving.StableId]) > 1e-7 && overconstrained.Add(moving.StableId))diagnostics.Add(new(Overconstrained, $"Instance '{moving.Path}' receives a conflicting placement from Mate '{mate.Name}'; transform residual exceeds 1e-7."));}@@ -537,7 +555,7 @@ public sealed class AssemblyM0Compilervar targetInstance = firstKnown ? owners[0] : owners[1];var orientedConstraints = Orient(mateConstraints, movingInstance, instances);var frameCandidates = orientedConstraints.Where(x => x.Kind == PlacementConstraintKind.FrameCoincident)- .Select(x => CandidateTransform([x], instances, known[targetInstance.StableId])).ToArray();+ .Select(x => CandidateTransform([x], ValueIndex, known[targetInstance.StableId])).ToArray();if (frameCandidates.Length > 1 && frameCandidates.Skip(1).Any(x => TransformDistance(frameCandidates[0], x) > 1e-7)){overconstrained.Add(movingInstance.StableId);@@ -545,14 +563,14 @@ public sealed class AssemblyM0Compilercontinue;}var axisCandidates = orientedConstraints.Where(x => x.Kind == PlacementConstraintKind.AxisCoincident)- .Select(x => CandidateTransform([x], instances, known[targetInstance.StableId])).ToArray();+ .Select(x => CandidateTransform([x], ValueIndex, known[targetInstance.StableId])).ToArray();if (axisCandidates.Length > 1 && axisCandidates.Skip(1).Any(x => TransformDistance(axisCandidates[0], x) > 1e-7)){overconstrained.Add(movingInstance.StableId);diagnostics.Add(new(Overconstrained, $"Instance '{movingInstance.Path}' receives incompatible constraints from Mate '{mate.Name}'; transform residual exceeds 1e-7."));continue;}- known[movingInstance.StableId] = CandidateTransform(orientedConstraints, instances, known[targetInstance.StableId]);+ known[movingInstance.StableId] = CandidateTransform(orientedConstraints, ValueIndex, known[targetInstance.StableId]);progress = true;}}@@ -626,9 +644,11 @@ public sealed class AssemblyM0Compilerreturn Math.Sqrt(Enumerable.Range(0, 16).Sum(i => Math.Pow(a.Matrix[i] - b.Matrix[i], 2)));}- private static AssemblyTransform CandidateTransform(IReadOnlyList<PlacementConstraintIr> constraints, IReadOnlyList<AssemblyInstanceIr> instances, AssemblyTransform? targetWorld = null)+ // BUILD-PERF-M2: the caller supplies the semantic-value index of its (unchanging) instances, built+ // once per placement solve instead of once per candidate (it was rebuilt for every constraint).+ private static AssemblyTransform CandidateTransform(IReadOnlyList<PlacementConstraintIr> constraints, Func<IReadOnlyDictionary<string, SemanticValue>> valueIndex, AssemblyTransform? targetWorld = null){- var values = Flatten(instances.Select(x => x.SemanticRoot)).ToDictionary(x => x.StableIdentity, StringComparer.Ordinal);+ var values = valueIndex();var frameConstraint = constraints.FirstOrDefault(x => x.Kind == PlacementConstraintKind.FrameCoincident);if (frameConstraint is not null&& values[frameConstraint.FirstSemanticValueId].TryBinding<ExactDatumFrameBinding>(out var sourceFrame)diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex 968918af..38696ea4 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -1,3 +1,4 @@+using Aetheris.Kernel.Core.Results;using Aetheris.Kernel.Core.Diagnostics;using System.Security.Cryptography;using System.Diagnostics;@@ -70,8 +71,12 @@ internal sealed record MaterializedAssemblyDefinition(/// </summary>internal static class AssemblyDefinitionMaterializer{- public static MaterializedAssemblyDefinition? TryMaterialize(string definitionIdentity, string? definitionSource, string sourceIdentity, List<AssemblyDiagnostic> diagnostics, FirmamentProjectSnapshot? project = null)+ public static MaterializedAssemblyDefinition? TryMaterialize(string definitionIdentity, string? definitionSource, string sourceIdentity, List<AssemblyDiagnostic> diagnostics, FirmamentProjectSnapshot? project = null,+ Func<string, KernelResult<BrepBody>>? importBody = null){+ // BUILD-PERF-M2: a session supplies an importer that returns a clone of a body it already+ // imported from the identical canonical STEP text (the importer is deterministic).+ importBody ??= stepText => Step242Importer.ImportBody(stepText);if (!string.IsNullOrWhiteSpace(definitionSource)){// Keep the authored SectionChain in its own source document so sibling@@ -136,7 +141,7 @@ internal static class AssemblyDefinitionMaterializerdiagnostics.Add(new("assembly-definition-materialization-failed", $"SectionChain source '{sectionPath}' STEP export failed: {diagnostic.Message}"));return null;}- var sectionImport = Step242Importer.ImportBody(sectionStep.Value);+ var sectionImport = importBody(sectionStep.Value);if (!sectionImport.IsSuccess || sectionImport.Value is null){foreach (var diagnostic in sectionImport.Diagnostics)@@ -250,7 +255,7 @@ internal static class AssemblyDefinitionMaterializerdiagnostics.Add(new("assembly-definition-materialization-failed", $"Definition '{definitionIdentity}' failed ordinary Firmament materialization: {diagnostic.Message}"));return null;}- var import = Step242Importer.ImportBody(build.Value.StepText);+ var import = importBody(build.Value.StepText);if (!import.IsSuccess || import.Value is null){foreach (var diagnostic in import.Diagnostics)@@ -395,7 +400,7 @@ public sealed class AssemblyM1Pipeline.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, cache.ImportCanonical)); }).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) };@@ -421,7 +426,8 @@ public sealed class AssemblyM1Pipeline}private static MaterializedAssemblyDefinition? Materialize(string identity, string? declarations, string sourceIdentity,- List<AssemblyDiagnostic> diagnostics, AssemblyPartMaterializer? domainMaterializer, FirmamentProjectSnapshot? project)+ List<AssemblyDiagnostic> diagnostics, AssemblyPartMaterializer? domainMaterializer, FirmamentProjectSnapshot? project,+ Func<string, KernelResult<BrepBody>>? importBody = null){if (domainMaterializer?.Invoke(identity, declarations, sourceIdentity, diagnostics) is { } supplied){@@ -435,7 +441,7 @@ public sealed class AssemblyM1Pipelinereturn 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);+ return AssemblyDefinitionMaterializer.TryMaterialize(identity, declarations, sourceIdentity, diagnostics, project, importBody);}private static AssemblyMemberSource Enrich(AssemblyMemberSource member, IReadOnlyDictionary<string, MaterializedAssemblyDefinition> definitions)diff --git a/Aetheris.Kernel.Firmament/Assembly/DisplayProjection.cs b/Aetheris.Kernel.Firmament/Assembly/DisplayProjection.csindex a98ef546..ebf75ee9 100644--- a/Aetheris.Kernel.Firmament/Assembly/DisplayProjection.cs+++ b/Aetheris.Kernel.Firmament/Assembly/DisplayProjection.cs@@ -18,7 +18,9 @@ public static class DisplayProjectionvar nodes = scene.Nodes.ToDictionary(n => n.Path, StringComparer.Ordinal);return display with{- Definitions = display.Definitions.Select(d => d with { Shader = d.Shader ?? CirShaderArtifactProvider.Resolve(d.Cir) }).ToArray(),+ // A definition that already carries its shader is passed through as the same object (BUILD-PERF-M2:+ // the web runtime retains unchanged definitions by reference identity).+ Definitions = display.Definitions.Select(d => d.Shader is null ? d with { Shader = CirShaderArtifactProvider.Resolve(d.Cir) } : d).ToArray(),Occurrences = display.Occurrences.Select(o => o with{Material = Material(scene.Appearances.GetValueOrDefault(o.Id)) ?? o.Material,diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.csindex f37fecd5..a6d49821 100644--- a/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs@@ -1,3 +1,5 @@+using Aetheris.Kernel.Core.Results;+using System.Text.Json;using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Queries;@@ -98,8 +100,12 @@ internal sealed class AssemblyDefinitionCache(int capacity)// 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.)+ // BUILD-PERF-M2: an entry also carries the definition's content key (identity, canonical STEP,+ // retained CIR). Everything derived downstream (display mesh, seat queries) is a function of+ // exactly those, so a definition rebuilt from changed source text but producing the same+ // geometry reuses them; an input-key change alone no longer re-tessellates.private sealed record Entry(string Key, MaterializedAssemblyDefinition Metadata,- IReadOnlyList<AssemblyDiagnostic> Diagnostics);+ IReadOnlyList<AssemblyDiagnostic> Diagnostics, string ContentKey);private readonly Dictionary<string, Entry> entries = new(StringComparer.Ordinal);private readonly Queue<string> insertionOrder = new();internal List<AssemblyDefinitionReuse> Evidence { get; } = [];@@ -125,7 +131,7 @@ internal sealed class AssemblyDefinitionCache(int capacity)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 };+ return CopyMetadata(entry.Metadata) with { Body = body, InputKey = entry.ContentKey };}}var diagnosticStart = diagnostics.Count;@@ -155,8 +161,27 @@ internal sealed class AssemblyDefinitionCache(int capacity)while (entries.Count >= capacity) entries.Remove(insertionOrder.Dequeue());insertionOrder.Enqueue(identity);}- entries[identity] = new(key, metadata, diagnostics.Skip(diagnosticStart).ToArray());- return result with { InputKey = key };+ var contentKey = ContentKey(result);+ entries[identity] = new(key, metadata, diagnostics.Skip(diagnosticStart).ToArray(), contentKey);+ return result with { InputKey = contentKey };+ }++ private static string ContentKey(MaterializedAssemblyDefinition definition) =>+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("assembly-definition-content-v1\0"+ + definition.DefinitionIdentity + "\0" + definition.CanonicalStep + "\0"+ + (definition.Cir is null ? "" : JsonSerializer.Serialize(definition.Cir)))));++ /// <summary>The body of canonical STEP text: a clone of a cached definition imported from the+ /// identical text, otherwise a fresh import. The importer is deterministic, so both are equal.</summary>+ internal KernelResult<BrepBody> ImportCanonical(string stepText)+ {+ foreach (var entry in entries.Values)+ if (entry.Metadata.CanonicalStep is { } step && step.Length == stepText.Length && string.Equals(step, stepText, StringComparison.Ordinal))+ {+ using (BuildPerfTrace.Phase("assembly.cache-import-clone"))+ return KernelResult<BrepBody>.Success(entry.Metadata.Body.Clone());+ }+ return Step242Importer.ImportBody(stepText);}private static string? Key(string identity, string? declarations, string sourceIdentity, FirmamentProjectSnapshot? project)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex e67a8718..dc1d79ae 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -308,6 +308,41 @@ public static class FirmamentV2Parser{using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("firmament.v2-parse");ArgumentNullException.ThrowIfNull(sourceText);+ // BUILD-PERF-M2: one compilation parses the same text several times (an assembly definition+ // four times). The parser is a pure function of its text and directory, and its result is+ // immutable records, except InlineStep, which reads a STEP file; those, and parses with a+ // concept catalog, always run.+ if (conceptCatalog is not null || sourceText.Contains("InlineStep", StringComparison.OrdinalIgnoreCase))+ return ParseUncached(sourceText, sourceDirectory, conceptCatalog);+ var key = (sourceDirectory ?? string.Empty) + "\0" + sourceText;+ lock (RecentParses)+ {+ var index = RecentParses.FindIndex(entry => string.Equals(entry.Key, key, StringComparison.Ordinal));+ if (index >= 0)+ {+ var hit = RecentParses[index];+ RecentParses.RemoveAt(index);+ RecentParses.Add(hit);+ return hit.Result;+ }+ }+ var result = ParseUncached(sourceText, sourceDirectory, conceptCatalog);+ lock (RecentParses)+ {+ RecentParses.Add((key, result));+ if (RecentParses.Count > RecentParseCapacity) RecentParses.RemoveAt(0);+ }+ return result;+ }++ private const int RecentParseCapacity = 8;+ private static readonly List<(string Key, FirmamentV2ParseResult Result)> RecentParses = [];++ private static FirmamentV2ParseResult ParseUncached(+ string sourceText,+ string? sourceDirectory,+ FirmamentV2ForgeConceptCatalog? conceptCatalog)+ {sourceText = FirmamentSourceSpelling.Normalize(sourceText);sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);var diagnostics = new List<string> { "firmament-v2-parser-invoked" };diff --git a/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs b/Aetheris.Kernel.Firmament/Scene/SceneCompilation.csindex c0dd2904..2d30d957 100644--- a/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs+++ b/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs@@ -29,6 +29,12 @@ public sealed class FirmamentSceneSession : IDisposableprivate readonly object gate = new();private readonly AssemblyDefinitionCache parts = new(256);private readonly Dictionary<string,FirmamentCompilationSession> assemblies = new(StringComparer.OrdinalIgnoreCase);+ // BUILD-PERF-M2: display definitions are pure functions of their inputs (a box of its key; a+ // part of its content key and id; an assembly-derived definition of the assembly session's+ // prepared definition and its scene id), so a rebuild reuses the same objects. Reference+ // identity is what lets the web runtime send unchanged definitions as retained stubs.+ private readonly DerivedValueCache<AssemblyDisplayMeshDefinition> sceneDefinitions = new();+ private readonly DerivedValueCache<(AssemblyDisplayMeshDefinition Source,AssemblyDisplayMeshDefinition Derived)> assemblyDefinitions = new();private bool disposed;public SceneCompilationResult CompileFile(string path) => Compile(File.ReadAllText(path),Path.GetFullPath(path));public SceneCompilationResult CompileProject(FirmamentProjectSnapshot project) => project.TryResolve(project.RootDocument, out var source)@@ -41,7 +47,7 @@ public sealed class FirmamentSceneSession : IDisposableObjectDisposedException.ThrowIf(disposed,this);var watch = Stopwatch.StartNew(); var parsed = SceneAuthoring.Parse(source,sourceIdentity);if (!parsed.IsSuccess) return new(null,parsed.Diagnostics);- var bindMs=watch.Elapsed.TotalMilliseconds; watch.Restart(); parts.BeginBuild();+ var bindMs=watch.Elapsed.TotalMilliseconds; watch.Restart(); parts.BeginBuild(); sceneDefinitions.BeginBuild(); assemblyDefinitions.BeginBuild();var s=parsed.Source!; var diagnostics=parsed.Diagnostics.ToList();var definitions=new Dictionary<string,AssemblyDisplayMeshDefinition>(StringComparer.Ordinal);var occurrences=new List<AssemblyDisplayMeshOccurrence>(); var nodes=new List<SceneNode>();@@ -120,7 +126,7 @@ public sealed class FirmamentSceneSession : IDisposableforeach (var panel in Panels(room,boundary.Kind,s.Openings.Where(o => o.Boundary == boundary.Path).ToArray())){var key="scene-box:"+string.Join(":",panel.Size.Select(F)); var id=Id(key);- if (!definitions.ContainsKey(id)) definitions.Add(id,Box(id,key,panel.Size));+ if (!definitions.ContainsKey(id)) definitions.Add(id,sceneDefinitions.GetOrAdd(id,() => WithShader(Box(id,key,panel.Size))));var panelPath=wallPath+".panel"+panel.Index;var world=Transform3D.CreateTranslation(new(panel.At[0],panel.At[1],panel.At[2]))*transform;AddNode(panelPath,"EnvironmentPanel",key,wallPath,world.ToRowMajor(),id,room.Span);@@ -135,7 +141,7 @@ public sealed class FirmamentSceneSession : IDisposableforeach (var piece in WindowPieces(opening,room.ThicknessMm,boundary.Kind)){var key="scene-box:"+string.Join(":",piece.Size.Select(F)); var id=Id(key);- if (!definitions.ContainsKey(id)) definitions.Add(id,Box(id,key,piece.Size));+ if (!definitions.ContainsKey(id)) definitions.Add(id,sceneDefinitions.GetOrAdd(id,() => WithShader(Box(id,key,piece.Size))));var path=openingPath+"."+piece.Name;var world=Transform3D.CreateTranslation(new(piece.At[0],piece.At[1],piece.At[2]))*aperture;AddNode(path,"WindowFinish",key,openingPath,world.ToRowMajor(),id,opening.Span);@@ -162,7 +168,12 @@ public sealed class FirmamentSceneSession : IDisposableif (item.From != "Origin") { Error("scene-part-source-frame-unsupported","X0 Part Scene placement starts at Origin; assembly published source frames are supported."); continue; }var part=materializedParts[item.Definition]; var id=Id("part:"+item.Definition);if (!definitions.ContainsKey(id))- { var preparation=Stopwatch.StartNew(); definitions.Add(id,AssemblyDisplayMeshExporter.PrepareDefinition(id,item.Definition,part.Body, externalStep: part.Artifact.Provenance.Any(p => p.Stage == "imported-step-definition")) with { Cir = part.Cir is null ? null : part.Cir with { DefinitionId = id }, GeometryRevision = part.Artifact.StepSha256 }); displayMs+=preparation.Elapsed.TotalMilliseconds; }+ {+ var preparation=Stopwatch.StartNew();+ AssemblyDisplayMeshDefinition Prepare() => AssemblyDisplayMeshExporter.PrepareDefinition(id,item.Definition,part.Body, externalStep: part.Artifact.Provenance.Any(p => p.Stage == "imported-step-definition")) with { Cir = part.Cir is null ? null : part.Cir with { DefinitionId = id }, GeometryRevision = part.Artifact.StepSha256 };+ definitions.Add(id,part.InputKey is { } contentKey ? sceneDefinitions.GetOrAdd("part|"+contentKey+"|"+id,() => WithShader(Prepare())) : Prepare());+ displayMs+=preparation.Elapsed.TotalMilliseconds;+ }AddNode(item.Path,"Part",item.Definition,parent,world.ToRowMajor(),id,item.Span,item.PatternKey); ApplyLook(item.Path,item.Appearance);}else@@ -171,7 +182,7 @@ public sealed class FirmamentSceneSession : IDisposablevar path=AssemblyPathFor(match.Groups["path"].Value)!;var assembly=compiledAssemblies[path];if (!preparedAssemblies.TryGetValue(path,out var mesh))- { var preparation=Stopwatch.StartNew(); preparedAssemblies[path]=mesh=AssemblyDisplayMeshExporter.Export(assembly); displayMs+=preparation.Elapsed.TotalMilliseconds; }+ { var preparation=Stopwatch.StartNew(); preparedAssemblies[path]=mesh=assemblies[path].ExportDisplayMesh(assembly); displayMs+=preparation.Elapsed.TotalMilliseconds; }if (item.From != "Origin"){var root=assembly.Ir!.Instances.Single(i => i.ParentStableId is null);@@ -184,7 +195,10 @@ public sealed class FirmamentSceneSession : IDisposableforeach (var d in mesh.Definitions){var id=prefix+":"+d.Id;- if (!definitions.ContainsKey(id)) definitions.Add(id,d with { Id=id, Identity=path+"::"+d.Identity, Cir = d.Cir is null ? null : d.Cir with { DefinitionId = id } });+ if (definitions.ContainsKey(id)) continue;+ var derived=assemblyDefinitions.GetOrAdd(id,() => (d,Derive(d,id,path)));+ if (!ReferenceEquals(derived.Source,d)) { assemblyDefinitions.Forget(id); derived=assemblyDefinitions.GetOrAdd(id,() => (d,Derive(d,id,path))); }+ definitions.Add(id,derived.Derived);}foreach (var o in mesh.Occurrences){@@ -220,6 +234,8 @@ public sealed class FirmamentSceneSession : IDisposableyield return new(path,room.Name,kind,world.ToRowMajor(),width,height,s.Openings.Where(o => o.Boundary == path).Select(o => o.Name).ToArray());}}+ AssemblyDisplayMeshDefinition Derive(AssemblyDisplayMeshDefinition d,string id,string path) =>+ d with { Id=id, Identity=path+"::"+d.Identity, Cir = d.Cir is null ? null : d.Cir with { DefinitionId = id } };void Error(string code,string message) => diagnostics.Add(new(code,message));string? AssemblyPathFor(string relative){@@ -237,7 +253,10 @@ public sealed class FirmamentSceneSession : IDisposable{ if (look is not null) looks[Id(path)]=new("","",look,s.Looks.Appearances[look].Preview,"scene-appearance"); }}}- public void Dispose() { lock(gate) { foreach (var session in assemblies.Values) session.Dispose(); assemblies.Clear(); parts.Clear(); disposed=true; } }+ public void Dispose() { lock(gate) { foreach (var session in assemblies.Values) session.Dispose(); assemblies.Clear(); parts.Clear(); sceneDefinitions.Clear(); assemblyDefinitions.Clear(); disposed=true; } }+ // The shader DisplayProjection would attach; attached once here so the cached object is final.+ private static AssemblyDisplayMeshDefinition WithShader(AssemblyDisplayMeshDefinition d) =>+ d.Shader is null ? d with { Shader = CirShaderArtifactProvider.Resolve(d.Cir) } : d;private static string F(double value) => value.ToString("R",CultureInfo.InvariantCulture);private static string Id(string value) => "scene:"+Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)))[..24];private sealed record Panel(int Index,double[] At,double[] Size);diff --git a/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj b/Aetheris.Web.Perf/Aetheris.Web.Perf.csprojindex c330b88e..00592b5f 100644--- a/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj+++ b/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj@@ -16,5 +16,6 @@<Compile Include="ShowcasePerf.cs" /><Compile Include="CompareStep.cs" /><Compile Include="VerifyBridge.cs" />+ <Compile Include="VerifyIncremental.cs" /></ItemGroup></Project>diff --git a/Aetheris.Web.Perf/PerfProgram.cs b/Aetheris.Web.Perf/PerfProgram.csindex 4afd579e..4bd808b2 100644--- a/Aetheris.Web.Perf/PerfProgram.cs+++ b/Aetheris.Web.Perf/PerfProgram.cs@@ -11,6 +11,7 @@ public static class PerfProgramif (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 > 0 && args[0] == "verify-bridge") return VerifyBridge.Run(args[1..]);+ if (args.Length > 0 && args[0] == "verify-incremental") return VerifyIncremental.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)),diff --git a/Aetheris.Web.Perf/VerifyBridge.cs b/Aetheris.Web.Perf/VerifyBridge.csindex a7cfbaa8..cdb1ffe4 100644--- a/Aetheris.Web.Perf/VerifyBridge.cs+++ b/Aetheris.Web.Perf/VerifyBridge.cs@@ -6,7 +6,7 @@ namespace Aetheris.Web.Perf;/// <summary>/// BUILD-PERF-M3: the bridge (binary arrays + retained definitions) must deliver exactly what the/// legacy JSON response delivers. A legacy session and a bridged session build the same project-/// through cold build, no-change rebuild and root-comment edit; each bridged model is+/// through cold build, no-change rebuild, root-comment edit and (for projects) an include-comment edit; each bridged model is/// reconstructed the way the SDK does it and compared with the legacy model./// </summary>internal static class VerifyBridge@@ -25,12 +25,16 @@ internal static class VerifyBridge("no-change rebuild", _ => new { operation = "rebuild" }),("root comment edit", _ => new { operation = "rebuild" }),};+ // BUILD-PERF-M2: an included document's comment changes definition input keys but no geometry;+ // content-keyed display definitions must still be retained, and still equal legacy.+ var include = documents.Keys.Where(key => key != root).Order(StringComparer.Ordinal).FirstOrDefault();+ if (include is not null) steps = [.. steps, ("include comment edit", _ => new { operation = "rebuild" })];var current = new Dictionary<string, string>(documents, StringComparer.Ordinal);foreach (var (name, request) in steps){- if (name == "root comment edit")+ if (name is "root comment edit" or "include comment edit"){- current[root] += "\n// verify-bridge\n";+ current[name == "root comment edit" ? root : include!] += "\n// verify-bridge\n";foreach (var session in new[] { legacySession, bridgedSession })Call(new { operation = "setSource", sessionId = session!.GetValue<string>(), source = current[root], sourceName = root, projectDocuments = current.Count > 1 ? current : null }, bridged: false);}@@ -41,7 +45,7 @@ internal static class VerifyBridgebridgedSession ??= bridged["result"]!["model"]!["id"]!.DeepClone();var expected = Comparable(legacy); var actual = Comparable(bridged);var equal = JsonNode.DeepEquals(expected, actual);- Console.WriteLine($"{name,-18} legacy {Size(legacy.ToJsonString())} · bridged {Size(bridgedRaw.ToJsonString())} JSON + {Size(binary.Length)} binary · " ++ Console.WriteLine($"{name,-20} legacy {Size(legacy.ToJsonString())} · bridged {Size(bridgedRaw.ToJsonString())} JSON + {Size(binary.Length)} binary · " +$"{binaryArrays} binary arrays · {retained} retained definitions · {(equal ? "identical" : "DIFFERENT")}");if (!equal) { failures++; Report(expected, actual, "model"); }previousBridged = bridged["result"]!["model"]!.AsObject();diff --git a/Aetheris.Web.Perf/VerifyIncremental.cs b/Aetheris.Web.Perf/VerifyIncremental.csnew file mode 100644index 00000000..c360ab1b--- /dev/null+++ b/Aetheris.Web.Perf/VerifyIncremental.cs@@ -0,0 +1,162 @@+using System.Diagnostics;+using System.Text.Json;+using System.Text.Json.Nodes;+using System.Text.RegularExpressions;++namespace Aetheris.Web.Perf;++/// <summary>+/// BUILD-PERF-M2 safety net: an incremental rebuild must equal a from-scratch build. Edits are applied+/// to a live session (comment appended, line inserted at the top of a document so every later offset+/// shifts, first numeric literal changed); after each edit the session's model is compared with a+/// fresh compile of the edited project, and after reverting it with the original model. Geometry,+/// mesh, tree, properties, projections, diagnostics and every source span must be identical.+/// </summary>+internal static class VerifyIncremental+{+ private sealed record Edit(string Name, string Document, Func<string, string?> Apply);++ public static int Run(string[] args)+ {+ if (args.Length < 2) { Console.Error.WriteLine("Usage: Aetheris.Web.Perf verify-incremental <project-directory|file> <root> [--documents N]"); return 2; }+ var maximumDocuments = 6;+ for (var i = 2; i < args.Length; i++)+ if (args[i] == "--documents" && i + 1 < args.Length) maximumDocuments = int.Parse(args[++i]);+ var (documents, root) = Load(args[0], args[1]);+ var edits = Edits(documents, root, maximumDocuments);+ var baseline = Fresh(documents, root);+ var session = Compile(documents, root, out var sessionResult);+ var failures = 0;+ failures += Compare("initial build", baseline, sessionResult);+ foreach (var edit in edits)+ {+ var text = edit.Apply(documents[edit.Document]);+ if (text is null || text == documents[edit.Document]) continue;+ var edited = new Dictionary<string, string>(documents, StringComparer.Ordinal) { [edit.Document] = text };+ var started = Stopwatch.GetTimestamp();+ var incremental = SetSourceAndRebuild(session, edited, root);+ var incrementalMs = Stopwatch.GetElapsedTime(started).TotalMilliseconds;+ started = Stopwatch.GetTimestamp();+ var fresh = Fresh(edited, root);+ var freshMs = Stopwatch.GetElapsedTime(started).TotalMilliseconds;+ failures += Compare($"{edit.Name} ({incrementalMs:0} ms vs fresh {freshMs:0} ms, {Reused(incremental)})", fresh, incremental);+ failures += Compare($" revert {edit.Name}", baseline, SetSourceAndRebuild(session, documents, root));+ }+ Console.WriteLine(failures == 0 ? "Every incremental rebuild equals a fresh build." : $"{failures} comparison(s) differ.");+ return failures == 0 ? 0 : 1;+ }++ private static IReadOnlyList<Edit> Edits(Dictionary<string, string> documents, string root, int maximumDocuments)+ {+ var names = documents.Keys.Order(StringComparer.Ordinal).ToList();+ // A deterministic spread over the project, always including the root.+ var picked = names.Count <= maximumDocuments ? names+ : Enumerable.Range(0, maximumDocuments).Select(i => names[i * names.Count / maximumDocuments]).Append(root).Distinct().ToList();+ var edits = new List<Edit>();+ foreach (var name in picked)+ {+ edits.Add(new($"{name}: comment appended", name, text => text + "\n// verify-incremental\n"));+ edits.Add(new($"{name}: line inserted at top", name, text => "// verify-incremental: shifts every offset\n" + text));+ edits.Add(new($"{name}: first value changed", name, text =>+ {+ var match = Regex.Match(text, @"(?<![\w.])(\d+(?:\.\d+)?)(mm)\b");+ if (!match.Success) return null;+ var value = double.Parse(match.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);+ var changed = (value * 1.05 + 0.1).ToString("0.###", System.Globalization.CultureInfo.InvariantCulture);+ return text[..match.Index] + changed + text[(match.Index + match.Groups[1].Length)..];+ }));+ }+ if (documents.TryGetValue("knob.firmament", out var knob) && knob.Contains("R:9mm,H:9mm", StringComparison.Ordinal))+ edits.Add(new("knob.firmament: knob radius", "knob.firmament", text => text.Replace("R:9mm,H:9mm", "R:9.5mm,H:9mm", StringComparison.Ordinal)));+ return edits;+ }++ private static (Dictionary<string, string>, string) Load(string path, string root)+ {+ if (File.Exists(path)) return (new(StringComparer.Ordinal) { [root] = File.ReadAllText(path).Replace("\r\n", "\n") }, root);+ return (Directory.GetFiles(path).Where(f => f.EndsWith(".firmament", StringComparison.Ordinal) || f.EndsWith(".firmasm", StringComparison.Ordinal))+ .ToDictionary(Path.GetFileName, f => File.ReadAllText(f).Replace("\r\n", "\n"), StringComparer.Ordinal)!, root);+ }++ private static JsonObject Invoke(object request)+ {+ var response = JsonNode.Parse(Aetheris.Web.Runtime.Program.Invoke(JsonSerializer.Serialize(request)))!.AsObject();+ if (response["ok"]?.GetValue<bool>() != true) throw new InvalidOperationException(response.ToJsonString());+ return response["result"]!.AsObject();+ }++ private static string Compile(Dictionary<string, string> documents, string root, out JsonObject result)+ {+ result = Invoke(new { operation = "compile", source = documents[root], sourceName = root, projectDocuments = documents.Count > 1 ? documents : null });+ return result["model"]?["id"]?.GetValue<string>() ?? throw new InvalidOperationException("The original project does not build.");+ }++ private static JsonObject Fresh(Dictionary<string, string> documents, string root)+ {+ var result = Invoke(new { operation = "compile", source = documents[root], sourceName = root, projectDocuments = documents.Count > 1 ? documents : null });+ if (result["model"]?["id"]?.GetValue<string>() is { } id) Invoke(new { operation = "disposeSession", sessionId = id });+ return result;+ }++ private static JsonObject SetSourceAndRebuild(string session, Dictionary<string, string> documents, string root)+ {+ Invoke(new { operation = "setSource", sessionId = session, source = documents[root], sourceName = root, projectDocuments = documents.Count > 1 ? documents : null });+ return Invoke(new { operation = "rebuild", sessionId = session });+ }++ private static string Reused(JsonObject result) =>+ result["model"]?["timings"]?["reuse"]?["definitions"] is JsonArray reuse+ ? $"{reuse.Count(item => item?["reused"]?.GetValue<bool>() == true)}/{reuse.Count} reused" : "no definition cache";++ /// <summary>A failed build compares by its diagnostics; a successful one by its whole model,+ /// without the session id, build revision, timings and change set (which legitimately differ).</summary>+ private static int Compare(string label, JsonObject expected, JsonObject actual)+ {+ var a = Comparable(expected); var b = Comparable(actual);+ var equal = JsonNode.DeepEquals(a, b);+ Console.WriteLine($"{(equal ? "ok " : "DIFF")} {label}");+ if (!equal) Report(a, b, "");+ return equal ? 0 : 1;+ }++ private static JsonNode Comparable(JsonObject result)+ {+ if (result["success"]?.GetValue<bool>() != true)+ return new JsonObject { ["failed"] = true, ["diagnostics"] = result["diagnostics"]?.DeepClone() };+ var model = result["model"]!.DeepClone().AsObject();+ var session = model["id"]!.GetValue<string>();+ foreach (var key in new[] { "id", "revision", "timings", "changes" }) model.Remove(key);+ var text = Regex.Replace(model.ToJsonString(), $@"(?<![\w-]){Regex.Escape(session)}(?!\d)", "<session>");+ return WithoutRevisions(JsonNode.Parse(text)!);+ }++ 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 void Report(JsonNode? expected, JsonNode? actual, string path, int budget = 6)+ {+ if (JsonNode.DeepEquals(expected, actual)) return;+ if (expected is JsonObject a && actual is JsonObject b)+ {+ foreach (var key in a.Select(p => p.Key).Union(b.Select(p => p.Key)))+ if (!JsonNode.DeepEquals(a[key], b[key]) && budget-- > 0) Report(a[key], b[key], $"{path}.{key}", 2);+ return;+ }+ if (expected is JsonArray x && actual is JsonArray y && x.Count == y.Count)+ {+ for (var i = 0; i < x.Count && budget > 0; i++) if (!JsonNode.DeepEquals(x[i], y[i])) { Report(x[i], y[i], $"{path}[{i}]", 1); budget--; }+ return;+ }+ Console.Error.WriteLine($" {path}: fresh {Short(expected)} · incremental {Short(actual)}");+ }++ private static string Short(JsonNode? node) { var text = node?.ToJsonString() ?? "null"; return text.Length > 140 ? text[..140] + "…" : text; }+}