Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
surface mesh IR fix.
Yuechen Li7dcb782bfef2
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.csindex 193ce408..cabf72dc 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs@@ -171,11 +171,22 @@ public sealed class SurfaceMeshIrTestsAssert.True(SurfaceMeshIrTessellator.TryBuild(body.Value, SurfaceMeshPolicy.FromDisplayOptions(DisplayTessellationOptions.Default), out var document));var caps = document.Patches.Where(patch => patch.Support.Kind == SurfaceMeshSupportKind.Plane && patch.TrimLoops.Count == 2).ToArray();Assert.Equal(2, caps.Length);- Assert.Equal(90, caps.Sum(cap => cap.Cells.Count));+ // The two caps are mirror images, so their decompositions must agree structurally. A pinned+ // total used to stand in for that and could not tell a real regression from a one-cell tie in+ // the greedy remainder merge - it went 90 -> 87 when one cap silently lost its bridge.Assert.All(caps, cap =>{var plan = Assert.IsType<PlanarFeatureDecompositionPlan>(cap.PlanarFeaturePlan);Assert.False(plan.UsedM6Fallback, plan.FallbackReason);+ // Outer runs counter-clockwise and every hole runs clockwise in the plane-local frame.+ // Without this a hole can arrive wound as material, which no planner can bridge.+ Assert.All(cap.TrimLoopData!, loop => Assert.Equal(loop.IsInner ? -1 : 1, double.Sign(loop.SignedArea)));+ // Each hole is joined to the outer boundary, which is what makes the remainder simply connected.+ Assert.Equal(cap.TrimLoopData!.Count(loop => loop.IsInner), plan.Bridges.Count);+ Assert.Equal(29, plan.FeatureBandCellCount);+ Assert.Equal(2, plan.BridgeCellCount);+ Assert.Equal(10, plan.ResidualTransitionCellCount);+ Assert.InRange(plan.CoarseRemainderCellCount, 3, 4);Assert.Contains(cap.Cells, cell => cell.Provenance == SurfaceMeshCellProvenance.FeatureBand);Assert.Contains(cap.Cells, cell => cell.Provenance == SurfaceMeshCellProvenance.CoarseRemainder);var incidence = cap.Cells.SelectMany(cell => Enumerable.Range(0, cell.VertexIds.Count)diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.csindex 61646cac..4d016943 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs@@ -674,6 +674,28 @@ public static class SurfaceMeshIrTessellatorreturn worst;}+ /// <summary>+ /// Reverses a trim loop when its measured winding contradicts the outer-CCW / inner-CW convention.+ /// Reversal is purely a traversal change: the same vertices bound the same region.+ /// </summary>+ private static SurfaceMeshTrimLoop NormalizeTraversal(SurfaceMeshTrimLoop loop)+ {+ var wanted = loop.IsInner ? -1d : 1d;+ if (loop.SignedArea == 0d || double.Sign(loop.SignedArea) == wanted) return loop;+ // Reverse the cycle about its own base point: [a,b,c,d] becomes [a,d,c,b], not [d,c,b,a].+ // Loop index 0 seeds guide construction and bridge candidate ordering, so moving it would make+ // two mirror-image faces decompose differently for no geometric reason.+ static T[] ReverseCycle<T>(IReadOnlyList<T> items) =>+ items.Take(1).Concat(items.Skip(1).Reverse()).ToArray();+ var ids = ReverseCycle(loop.VertexIds);+ var local = ReverseCycle(loop.LocalCoordinates);+ var spans = loop.BoundarySpans?+ .Reverse()+ .Select(span => span with { StartVertexId = span.EndVertexId, EndVertexId = span.StartVertexId })+ .ToArray();+ return loop with { VertexIds = ids, LocalCoordinates = local, SignedArea = -loop.SignedArea, BoundarySpans = spans };+ }+private static SurfacePatch? TryBuildPlanePatch(BrepBody body, FaceId faceId, bool sameSense, PlaneSurface plane, IReadOnlyDictionary<EdgeId, SharedEdgeSamplePlan> plans, List<SurfaceMeshVertex> vertices, ref int nextVertexId){var loops = body.GetLoopIds(faceId);@@ -692,7 +714,20 @@ public static class SurfaceMeshIrTessellatorvar outer = loopData.OrderByDescending(loop => double.Abs(loop.SignedArea)).First();var inners = loopData.Where(loop => loop.LoopId != outer.LoopId).ToArray();- var annotatedLoops = loopData.Select(loop => loop with { IsInner = loop.LoopId != outer.LoopId }).ToArray();+ // A trimmed planar face has exactly one valid traversal convention: the outer loop runs+ // counter-clockwise in the plane-local frame and every inner loop runs clockwise. The source+ // topology does not guarantee it - a box's two caps carry their outer loops in the same 3D+ // direction even though their normals oppose, so one cap arrives mirrored and, on a face with+ // a hole, outer and inner can even agree in sign, which is geometrically impossible. Cell+ // winding does not depend on this (every emitted cell is re-oriented by its own signed area),+ // so the decomposition planners below were the first consumers to actually trust the traversal+ // direction, and they silently produced a different, poorer decomposition when it was wrong.+ // Normalize once, here, rather than teaching each planner to accept both handednesses.+ var annotatedLoops = loopData+ .Select(loop => NormalizeTraversal(loop with { IsInner = loop.LoopId != outer.LoopId }))+ .ToArray();+ outer = annotatedLoops.Single(loop => loop.LoopId == outer.LoopId);+ inners = annotatedLoops.Where(loop => loop.LoopId != outer.LoopId).ToArray();if (inners.Length == 0){var coedges = body.GetCoedgeIds(outer.LoopId).Select(body.Topology.GetCoedge).ToArray();diff --git a/docs/development/test-suite-performance.md b/docs/development/test-suite-performance.mdnew file mode 100644index 00000000..81256313--- /dev/null+++ b/docs/development/test-suite-performance.md@@ -0,0 +1,137 @@+# Test-suite performance profile — 2026-09-24++Measured on the Cowork Linux VM (`nproc` = 2), Release, `dotnet test` with a TRX logger.+Wall-clock numbers are therefore parallelism-bound on this box and will differ on the+dev machine. **CPU time is the machine-independent number and is what the analysis below+uses.**++| suite | tests | wall | sum of test durations |+|---|---|---|---|+| Aetheris.Kernel.Core.Tests | 1092 | 58-61s | 117s |+| Aetheris.Kernel.Firmament.Tests | 1624 | 37-43s | 76s |+| Aetheris.Server.Tests | 59 | 9s | - |++## 1. Kernel.Core is a STEP-import benchmark wearing a unit-test costume++By namespace: **Step242 84.1% (98.2s), Brep 15.4% (18.0s), everything else 0.5%.**+Roughly 200 tests account for all 117s; the other ~890 cost under 20ms combined.++Top classes:++| CPU | tests | class |+|---|---|---|+| 17.8s | 25 | Step242LoopRoleNormalizationRegressionTests |+| 11.4s | 18 | NistDisplayCorpusRegressionTests |+| 9.4s | 21 | Step242NistAuditHarnessTests |+| 8.8s | 9 | Step242PeriodicBoundaryOrientationTests |+| 8.7s | 21 | Step242RationalSurfaceReductionTests |+| 8.6s | 18 | Step242ConicalSurfaceRegressionTests |+| 8.5s | 11 | Step242BSplineSurfaceWithKnotsTests |++The cause is structural, not algorithmic: there are **203 `Step242Importer.ImportBody`+call sites** and **52 `File.ReadAllText` sites** across the test project, against **48+distinct corpus files**. Every test re-reads and re-imports from scratch.++Measured cost of importing *every* corpus file exactly once (117 files, 40MB):++```+read = 550ms parse = 957ms import (incl. parse) = 10.3s+```++So the suite spends ~98s doing work whose irreducible content is ~10s. **About 90% of+Kernel.Core's CPU is redundant re-import.** Parse caching alone is worth only ~9% - the+cost is in topology construction and geometry binding, not tokenizing.++### Recommendation++A memoized corpus fixture: `Step242Corpus.Text(relativePath)` and+`Step242Corpus.Body(relativePath)`, both `ConcurrentDictionary<string, Lazy<...>>` so they+are safe under xunit's parallel collections. `BrepBody` and everything it exposes is+get-only, so sharing one instance across tests is safe for read-only consumers.++Two categories cannot share a body and should still share the *text*:++- tests using `Step242Importer.CaptureLoopRoleXDiagnostics(...)` scopes, which collect+ during import and therefore need a real import (this is most of the 17.8s in+ `Step242LoopRoleNormalizationRegressionTests`);+- tests using `Step242Importer.PreserveRationalSurfaces()`, which changes import behaviour.++For the capture-based group the deeper win is a single import that collects *all*+diagnostic families at once, shared by the tests that each want one family. That is a+larger refactor and should be costed separately.++## 2. A one-face torus costs a quarter of a second to import++Not a test problem - this is shipping importer behaviour, and it shows up in the corpus+timings as tiny files with absurd costs:++```+m10g2-torus.step 1KB 499ms+torus_basic.step 1KB 262ms+toroid.step 3KB 243ms+nist_ctc_01_asme1_ap242-e1.stp 387KB 551ms+```++`m10g2-torus.step` contains one `TOROIDAL_SURFACE`, one `ADVANCED_FACE`, two `CIRCLE`s and+two `EDGE_CURVE`s. Instrumenting `ProjectLoopToTorus` shows its loops arrive with+**513 samples each**.++That comes from `ComputeAdaptiveCircleSegmentCount`, whose `maxSegmentAngle` is+`pi / 64` - 2.8 degrees, so 128 segments per full circle regardless of radius or of how+coarse a *classification* polygon actually needs to be. The method's own comment says the+polygon is for classification only and that the constant was raised from a two-chord+quarter arc because that "falsely rejected close polynomial inner trims" - a fix that+overshot. The 513-point loops then feed helpers that are pairwise in the sample count+(`CountUniquePoints`, `SimplifyClosedPolygon`, per-point containment against the loop),+so the cost is quadratic in a constant nobody intended to be large.++I did **not** change it. Lowering it risks re-introducing exactly the false rejection it+was raised to fix, so it needs its own pass with the NIST corpus as the oracle. Candidate+approaches: make the count adaptive on sagitta relative to part size rather than on a+fixed angle, cap total samples per loop, or make the pairwise helpers use a spatial hash.++Ruled out by measurement: `TryRecoverToroidalProjectionFromCyclicUnwrap` - which *is*+O(n^2) by construction, re-projecting the whole loop once per rotation with no early exit -+is never called for these files (`unwrapCalls = 0`). It remains a latent hazard for any+file that does hit the degenerate-projection path.++## 3. Firmament has no structural hotspot++76s over 1624 tests with a flat distribution: the largest class is 12.3% and the slowest+single test is 5.9s. This is real geometry work - sweeps, coil meshing, gear lowering -+not repeated I/O. Caching buys little here. The realistic lever is the same corpus-sharing+idea applied to the `.firmament` fixtures, which is a much smaller prize.++## 4. Parallelism is already saturated *on this box*++117s CPU / 58s wall = 1.9x on 2 cores. There is no headroom here, but there may be plenty+on the dev machine: xunit parallelizes across collections, and a suite whose time is+concentrated in a handful of large classes parallelizes poorly no matter how many cores+are available. Splitting the big Step242 classes into more collections is worth trying on+real hardware before anything else, because it is free.++`[CollectionDefinition(..., DisableParallelization = true)]` on `StorageGateMeshing` in+the Firmament tests serializes that collection; worth confirming it still needs to.++## 5. The fast lane already exists and is under-used++`[Trait("Category", "SlowCorpus")]` is applied 29 times in Kernel.Core and 7 times in+Firmament.++```+dotnet test Aetheris.Kernel.Core.Tests --filter "Category!=SlowCorpus"+ -> 981 tests, 28s (vs 1092 tests, 58s)+```++111 tests cost 33s of the 61. Extending the trait to the rest of the corpus-driven classes+would bring the inner-loop suite under ~15s without touching coverage, provided the full+lane still runs before commit. This is the cheapest immediate win and needs no code change+beyond attributes.++## Suggested order++1. Extend `SlowCorpus` and document the two-lane workflow. Free, today.+2. Memoized corpus fixture (text + body). Targets ~90% of Kernel.Core CPU.+3. Split the large Step242 classes into separate collections; measure on real hardware.+4. The torus classification-sampling constant, as its own investigation.+5. Unify diagnostic capture so one import serves several capture-based tests.