Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add bounded semantic through-hole rematerializer wiring

Yuechen Lic93816dc1fbd
diff --git a/Aetheris.Kernel.Firmament.Tests/FrepSemanticRecoveryRematerializerTests.cs b/Aetheris.Kernel.Firmament.Tests/FrepSemanticRecoveryRematerializerTests.cs
new file mode 100644
index 00000000..450a4554
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FrepSemanticRecoveryRematerializerTests.cs
@@ -0,0 +1,75 @@
+using Aetheris.Kernel.Core.Cir;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Execution;
+using Aetheris.Kernel.Firmament.Lowering;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FrepSemanticRecoveryRematerializerTests
+{
+ [Fact]
+ public void SemanticRecovery_BoxCylinder_ProducesBRepBody()
+ {
+ var root = new CirSubtractNode(new CirBoxNode(20d, 10d, 8d), new CirCylinderNode(2d, 20d));
+ var result = FrepSemanticRecoveryRematerializer.TryRecover(root);
+
+ Assert.True(result.Succeeded);
+ Assert.NotNull(result.Body);
+ Assert.Equal(nameof(ThroughHoleRecoveryPolicy), result.SelectedPolicy);
+ Assert.Contains(result.Diagnostics, d => d.Contains("planner ran", StringComparison.Ordinal));
+ Assert.Contains(result.Diagnostics, d => d.Contains("executor succeeded", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void SemanticRecovery_TranslatedBoxCylinder_ProducesBRepBody()
+ {
+ var root = new CirSubtractNode(
+ new CirTransformNode(new CirBoxNode(20d, 20d, 10d), Transform3D.CreateTranslation(new Vector3D(5d, 2d, 4d))),
+ new CirTransformNode(new CirCylinderNode(3d, 16d), Transform3D.CreateTranslation(new Vector3D(4d, 1d, 4d))));
+
+ var result = FrepSemanticRecoveryRematerializer.TryRecover(root);
+
+ Assert.True(result.Succeeded);
+ Assert.NotNull(result.Body);
+ Assert.Equal(nameof(ThroughHoleRecoveryPolicy), result.SelectedPolicy);
+ }
+
+ [Fact]
+ public void SemanticRecovery_UnsupportedBoxSphere_FallsBackOrRejectsCleanly()
+ {
+ var root = new CirSubtractNode(new CirBoxNode(20d, 10d, 8d), new CirSphereNode(2d));
+ var result = FrepSemanticRecoveryRematerializer.TryRecover(root);
+
+ Assert.False(result.Succeeded);
+ Assert.Null(result.Body);
+ Assert.Equal(FrepMaterializerDecisionStatus.NoAdmissiblePolicy, result.Decision.Status);
+ Assert.Contains(result.Diagnostics, d => d.Contains("no admissible policy", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Rematerializer_CirOnlyBoxCylinder_TransitionsToBRepActive_UsingSemanticRecovery()
+ {
+ var plan = BuildBoxMinusCylinderPlan();
+ var state = new NativeGeometryState(NativeGeometryExecutionMode.CirOnly, NativeGeometryMaterializationAuthority.PendingRematerialization, null, "hole", BuildReplay("cylinder"), [], new NativeGeometryCirMirrorState(CirMirrorStatus.NotAttempted, null, []));
+
+ var remat = NativeGeometryRematerializer.TryRematerialize(plan, state);
+
+ Assert.True(remat.IsSuccess, string.Join(" | ", remat.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(NativeGeometryExecutionMode.BRepActive, remat.Value.ExecutionMode);
+ Assert.Contains(remat.Value.TransitionEvents, e => e.Message.Contains("semantic recovery policy", StringComparison.Ordinal));
+ }
+
+ private static NativeGeometryReplayLog BuildReplay(string toolKind)
+ => new([
+ new NativeGeometryReplayOperation(0, "base", "primitive:box", null, null, null, null, new NativeGeometryResolvedPlacement(NativeGeometryPlacementKind.None, null, null, Vector3D.Zero, Vector3D.Zero, true, null), null),
+ new NativeGeometryReplayOperation(1, "cut", "boolean:subtract", "base", toolKind, "tool", null, new NativeGeometryResolvedPlacement(NativeGeometryPlacementKind.None, null, null, Vector3D.Zero, Vector3D.Zero, true, null), null)
+ ]);
+
+ private static FirmamentPrimitiveLoweringPlan BuildBoxMinusCylinderPlan()
+ {
+ var primitives = new[] { new FirmamentLoweredPrimitive(0, "base", FirmamentLoweredPrimitiveKind.Box, new FirmamentLoweredBoxParameters(20, 20, 10), null) };
+ var booleans = new[] { new FirmamentLoweredBoolean(1, "hole", FirmamentLoweredBooleanKind.Subtract, "from", "base", new FirmamentLoweredToolOp("cylinder", new Dictionary<string, string> { { "op", "cylinder" }, { "radius", "3" }, { "height", "20" } }, "op cylinder radius=3 height=20"), null) };
+ return new FirmamentPrimitiveLoweringPlan(primitives, booleans, []);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Materializer/FrepSemanticRecoveryRematerializer.cs b/Aetheris.Kernel.Firmament/Materializer/FrepSemanticRecoveryRematerializer.cs
new file mode 100644
index 00000000..02c58d5a
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Materializer/FrepSemanticRecoveryRematerializer.cs
@@ -0,0 +1,65 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Cir;
+using Aetheris.Kernel.Firmament.Execution;
+
+namespace Aetheris.Kernel.Firmament.Materializer;
+
+internal sealed record FrepSemanticRecoveryResult(
+ bool Attempted,
+ bool Succeeded,
+ string? SelectedPolicy,
+ ThroughHoleRecoveryPlan? Plan,
+ ThroughHoleRecoveryExecutionStatus ExecutionStatus,
+ BrepBody? Body,
+ IReadOnlyList<string> Diagnostics,
+ FrepMaterializerDecision Decision);
+
+internal static class FrepSemanticRecoveryRematerializer
+{
+ private static readonly ThroughHoleRecoveryPolicy ThroughHolePolicy = new();
+
+ internal static FrepSemanticRecoveryResult TryRecover(
+ CirNode root,
+ NativeGeometryReplayLog? replayLog = null,
+ string? sourceLabel = null)
+ {
+ ArgumentNullException.ThrowIfNull(root);
+
+ var diagnostics = new List<string> { "semantic recovery attempted", "planner ran" };
+ var decision = FrepMaterializerPlanner.Decide(new FrepMaterializerContext(root, replayLog, sourceLabel), [ThroughHolePolicy]);
+ diagnostics.AddRange(decision.Diagnostics);
+
+ if (decision.Status != FrepMaterializerDecisionStatus.Selected)
+ {
+ diagnostics.Add("no admissible policy");
+ return new(true, false, null, null, ThroughHoleRecoveryExecutionStatus.Failed, null, diagnostics, decision);
+ }
+
+ diagnostics.Add($"selected policy: {decision.SelectedPolicyName}");
+ if (!string.Equals(decision.SelectedPolicyName, nameof(ThroughHoleRecoveryPolicy), StringComparison.Ordinal))
+ {
+ diagnostics.Add("selected policy was not ThroughHoleRecoveryPolicy");
+ return new(true, false, decision.SelectedPolicyName, null, ThroughHoleRecoveryExecutionStatus.Failed, null, diagnostics, decision);
+ }
+
+ var selectedEval = decision.Evaluations.Single(e => string.Equals(e.PolicyName, decision.SelectedPolicyName, StringComparison.Ordinal));
+ if (selectedEval.Plan is not ThroughHoleRecoveryPlan plan)
+ {
+ diagnostics.Add("selected policy did not provide through-hole plan");
+ return new(true, false, decision.SelectedPolicyName, null, ThroughHoleRecoveryExecutionStatus.Failed, null, diagnostics, decision);
+ }
+
+ diagnostics.Add("through-hole plan extracted");
+ var execution = ThroughHoleRecoveryExecutor.Execute(plan);
+ diagnostics.AddRange(execution.Diagnostics);
+ if (execution.Status != ThroughHoleRecoveryExecutionStatus.Succeeded || execution.Body is null)
+ {
+ diagnostics.Add("executor failed");
+ return new(true, false, decision.SelectedPolicyName, plan, execution.Status, null, diagnostics, decision);
+ }
+
+ diagnostics.Add("executor succeeded");
+ diagnostics.Add("brep body recovered");
+ return new(true, true, decision.SelectedPolicyName, plan, execution.Status, execution.Body, diagnostics, decision);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Materializer/NativeGeometryRematerializer.cs b/Aetheris.Kernel.Firmament/Materializer/NativeGeometryRematerializer.cs
index e844988c..5edbcf49 100644
--- a/Aetheris.Kernel.Firmament/Materializer/NativeGeometryRematerializer.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/NativeGeometryRematerializer.cs
@@ -24,12 +24,31 @@ internal static class NativeGeometryRematerializer
return KernelResult<NativeGeometryState>.Failure(lowered.Diagnostics);
}
+ var semanticRecovery = FrepSemanticRecoveryRematerializer.TryRecover(lowered.Value.Root, state.ReplayLog, state.CirIntentRootReference);
+ if (semanticRecovery.Succeeded && semanticRecovery.Body is not null)
+ {
+ return KernelResult<NativeGeometryState>.Success(state with
+ {
+ ExecutionMode = NativeGeometryExecutionMode.BRepActive,
+ MaterializationAuthority = NativeGeometryMaterializationAuthority.BRepAuthoritative,
+ MaterializedBody = semanticRecovery.Body,
+ TransitionEvents =
+ [
+ .. state.TransitionEvents,
+ new NativeGeometryTransitionEvent(NativeGeometryExecutionMode.CirOnly, NativeGeometryExecutionMode.BRepActive, state.CirIntentRootReference, null, NativeGeometryTransitionReasonCategory.MaterializationUnsupported, $"CIR rematerialized via semantic recovery policy '{semanticRecovery.SelectedPolicy}'.")
+ ]
+ });
+ }
+
var materialized = CirBrepMaterializer.TryMaterialize(new CirBrepMaterializer.CirBrepMaterializerContext(lowered.Value.Root, state.ReplayLog));
if (!materialized.IsSuccess || materialized.Body is null)
{
+ var semanticSummary = semanticRecovery.Attempted
+ ? $" Semantic recovery fallback used: selectedPolicy='{semanticRecovery.SelectedPolicy ?? "none"}', executionStatus='{semanticRecovery.ExecutionStatus}'."
+ : string.Empty;
var diagnostics = materialized.Diagnostics.Count > 0
? materialized.Diagnostics
- : [new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, $"CIR rematerialization unsupported for pattern '{materialized.PatternName}': {materialized.Message}", "Firmament.CirRematerializer")];
+ : [new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, $"CIR rematerialization unsupported for pattern '{materialized.PatternName}': {materialized.Message}.{semanticSummary}", "Firmament.CirRematerializer")];
return KernelResult<NativeGeometryState>.Failure(diagnostics);
}
diff --git a/docs/cir-recovery-v4-semantic-rematerializer-wiring.md b/docs/cir-recovery-v4-semantic-rematerializer-wiring.md
new file mode 100644
index 00000000..98d95e36
--- /dev/null
+++ b/docs/cir-recovery-v4-semantic-rematerializer-wiring.md
@@ -0,0 +1,75 @@
+# CIR-RECOVERY-V4: controlled rematerializer/fall-forward wiring for ThroughHoleRecoveryPolicy
+
+## Integration point selected
+
+Chosen: **Option A (`NativeGeometryRematerializer`)**.
+
+Why this is least disruptive:
+- `FirmamentStepExporter` already routes `CirOnly` export attempts through `NativeGeometryRematerializer.TryRematerialize(...)`.
+- This keeps STEP exporter behavior unchanged.
+- Existing `CirBrepMaterializer` registry remains intact as a bounded fallback path.
+- Semantic policy/executor wiring is gated at the rematerialization boundary where root CIR and replay log are both available.
+
+## Semantic recovery gates
+
+Semantic recovery is attempted only when:
+1. rematerializer is invoked for `CirOnly`,
+2. CIR root is lowered successfully,
+3. `FrepMaterializerPlanner` selects `ThroughHoleRecoveryPolicy`,
+4. selected evaluation contains a valid `ThroughHoleRecoveryPlan`,
+5. `ThroughHoleRecoveryExecutor` succeeds with non-null `BrepBody`.
+
+If any gate fails, rematerializer falls back to existing `CirBrepMaterializer` behavior.
+
+## Fallback behavior
+
+- No admissible semantic policy: fallback to existing replay-guided strategy registry (`CirBrepMaterializer`).
+- Policy selected but no usable plan: fallback to registry.
+- Executor fails or null body: fallback to registry.
+- If both semantic route and existing registry fail, failure remains explicit and diagnostics include semantic attempt summary.
+
+## State transition behavior
+
+On semantic success:
+- `ExecutionMode`: `CirOnly -> BRepActive`
+- `MaterializationAuthority`: `PendingRematerialization -> BRepAuthoritative`
+- transition event message identifies semantic recovery policy.
+
+On semantic non-success:
+- transition semantics are unchanged and governed by pre-existing fallback route.
+
+## Export behavior
+
+No STEP exporter logic changes were made.
+
+`FirmamentStepExporter` still:
+- selects export body,
+- asks rematerializer for `CirOnly` states,
+- exports through existing `Step242Exporter.ExportBody(...)`.
+
+This milestone only enables additional `CirOnly` recoverability through the rematerializer branch.
+
+## Diagnostics
+
+Semantic helper emits explicit diagnostics for:
+- attempt start,
+- planner run,
+- selected policy,
+- no admissible policy,
+- plan extraction,
+- executor success/failure,
+- BRep recovered.
+
+Rematerializer failure now appends semantic attempt summary when it had been attempted before falling back/ending in failure.
+
+## Non-goals preserved
+
+- No broad materializer replacement.
+- No generic boolean recovery.
+- No generic through-hole recovery.
+- No STEP exporter behavior change.
+- No topology naming expansion (SEM-A0 preserved).
+
+## Recommended CIR-RECOVERY-V5
+
+Add a bounded multi-policy semantic recovery catalog (still planner-driven) with explicit precedence/diagnostics, plus richer propagation of semantic diagnostics into export result metadata without changing public export APIs.