Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add bounded timeout handling to tessellation

Yuechen Lica3f288ce37f
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc07ViewMaterializationRegressionTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc07ViewMaterializationRegressionTests.cs
new file mode 100644
index 00000000..de87e582
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242Ftc07ViewMaterializationRegressionTests.cs
@@ -0,0 +1,58 @@
+using System.Diagnostics;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242Ftc07ViewMaterializationRegressionTests
+{
+ private const string RelativePath = "testdata/step242/nist/FTC/nist_ftc_07_asme1_ap242-e2.stp";
+
+ [Fact]
+ public void Step242Ftc07ViewMaterialization_CompletesOrReportsBoundedDiagnostic()
+ {
+ var body = ImportFixture();
+
+ var stopwatch = Stopwatch.StartNew();
+ var tessellation = BrepDisplayTessellator.TessellateBounded(body);
+ stopwatch.Stop();
+
+ Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(15), $"FTC-07 display tessellation exceeded the bounded wall clock budget ({stopwatch.Elapsed}).");
+
+ if (tessellation.IsSuccess)
+ {
+ Assert.NotEmpty(tessellation.Value.FacePatches);
+ return;
+ }
+
+ Assert.Contains(tessellation.Diagnostics, diagnostic => string.Equals(diagnostic.Source, "Viewer.Tessellation.Timeout", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Step242Ftc07ViewMaterialization_ReportsPhaseAndFaceOnFailure()
+ {
+ var body = ImportFixture();
+
+ var tessellation = BrepDisplayTessellator.TessellateBounded(body);
+ if (tessellation.IsSuccess)
+ {
+ return;
+ }
+
+ var diagnostic = Assert.Single(tessellation.Diagnostics, candidate => string.Equals(candidate.Source, "Viewer.Tessellation.Timeout", StringComparison.Ordinal));
+ Assert.Contains("face", diagnostic.Message, StringComparison.OrdinalIgnoreCase);
+ Assert.Contains("phase", diagnostic.Message, StringComparison.OrdinalIgnoreCase);
+ Assert.Contains("surface", diagnostic.Message, StringComparison.OrdinalIgnoreCase);
+ Assert.True(
+ diagnostic.Message.Contains("PlanarTriangulationWithHoles", StringComparison.Ordinal)
+ || diagnostic.Message.Contains("FaceTessellation", StringComparison.Ordinal));
+ }
+
+ private static global::Aetheris.Kernel.Core.Brep.BrepBody ImportFixture()
+ {
+ var absolutePath = Path.Combine(Step242CorpusManifestRunner.RepoRoot(), RelativePath.Replace('/', Path.DirectorySeparatorChar));
+ var import = Step242Importer.ImportBody(File.ReadAllText(absolutePath));
+ Assert.True(import.IsSuccess);
+ return import.Value;
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
index a80875ef..04983009 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BrepDisplayTessellator.cs
@@ -35,6 +35,18 @@ public static class BrepDisplayTessellator
private const string TrimEvaluationFailedSource = "Viewer.Tessellation.TrimEvaluationFailed";
public static KernelResult<DisplayTessellationResult> Tessellate(BrepBody body, DisplayTessellationOptions? options = null)
+ => TessellateCore(body, options, null);
+
+ public static KernelResult<DisplayTessellationResult> TessellateBounded(
+ BrepBody body,
+ DisplayTessellationOptions? options = null,
+ TimeSpan? executionTimeout = null)
+ => TessellateCore(body, options, new DisplayTessellationExecutionBudget(executionTimeout ?? TimeSpan.FromSeconds(5)));
+
+ private static KernelResult<DisplayTessellationResult> TessellateCore(
+ BrepBody body,
+ DisplayTessellationOptions? options,
+ DisplayTessellationExecutionBudget? executionBudget)
{
if (body is null)
{
@@ -51,54 +63,116 @@ public static class BrepDisplayTessellator
var accumulatedDiagnostics = new List<KernelDiagnostic>();
var facePatches = new List<DisplayFaceMeshPatch>();
- foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value))
- {
- var faceResult = TessellateFace(body, face.Id, effectiveOptions);
- if (!faceResult.IsSuccess)
+ try
+ {
+ foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value))
+ {
+ executionBudget?.ThrowIfExpired("FaceDispatch", face.Id);
+ var faceResult = ExecuteWithinOptionalBudget(
+ () => TessellateFace(body, face.Id, effectiveOptions, executionBudget),
+ executionBudget,
+ "FaceTessellation",
+ face.Id,
+ TryGetSurfaceKind(body, face.Id),
+ executionBudget is null ? null : executionBudget.Remaining + TimeSpan.FromMilliseconds(250));
+ if (!faceResult.IsSuccess)
+ {
+ return KernelResult<DisplayTessellationResult>.Failure(faceResult.Diagnostics);
+ }
+
+ facePatches.Add(faceResult.Value);
+ accumulatedDiagnostics.AddRange(faceResult.Diagnostics);
+ }
+
+ var edgePolylines = new List<DisplayEdgePolyline>();
+ foreach (var edge in body.Topology.Edges.OrderBy(e => e.Id.Value))
{
- return KernelResult<DisplayTessellationResult>.Failure(faceResult.Diagnostics);
+ executionBudget?.ThrowIfExpired("EdgeDispatch");
+ var edgeResult = ExecuteWithinOptionalBudget(
+ () => TessellateEdge(body, edge.Id, effectiveOptions),
+ executionBudget,
+ "EdgeTessellation");
+ if (!edgeResult.IsSuccess)
+ {
+ return KernelResult<DisplayTessellationResult>.Failure(edgeResult.Diagnostics);
+ }
+
+ edgePolylines.Add(edgeResult.Value);
+ accumulatedDiagnostics.AddRange(edgeResult.Diagnostics);
}
- facePatches.Add(faceResult.Value);
- accumulatedDiagnostics.AddRange(faceResult.Diagnostics);
+ return KernelResult<DisplayTessellationResult>.Success(new DisplayTessellationResult(facePatches, edgePolylines), accumulatedDiagnostics);
+ }
+ catch (DisplayTessellationTimeoutException ex)
+ {
+ return KernelResult<DisplayTessellationResult>.Failure([CreateValidationError(ex.Message, "Viewer.Tessellation.Timeout")]);
}
+ }
- var edgePolylines = new List<DisplayEdgePolyline>();
- foreach (var edge in body.Topology.Edges.OrderBy(e => e.Id.Value))
+ private static KernelResult<T> ExecuteWithinBudget<T>(
+ Func<KernelResult<T>> action,
+ DisplayTessellationExecutionBudget executionBudget,
+ string phase,
+ FaceId? faceId = null,
+ SurfaceGeometryKind? surfaceKind = null,
+ TimeSpan? timeoutOverride = null)
+ {
+ try
{
- var edgeResult = TessellateEdge(body, edge.Id, effectiveOptions);
- if (!edgeResult.IsSuccess)
- {
- return KernelResult<DisplayTessellationResult>.Failure(edgeResult.Diagnostics);
- }
+ return Task.Run(action)
+ .WaitAsync(timeoutOverride ?? executionBudget.Remaining)
+ .GetAwaiter()
+ .GetResult();
+ }
+ catch (TimeoutException)
+ {
+ throw new DisplayTessellationTimeoutException(phase, executionBudget.Elapsed, faceId, surfaceKind);
+ }
+ }
- edgePolylines.Add(edgeResult.Value);
- accumulatedDiagnostics.AddRange(edgeResult.Diagnostics);
+ private static KernelResult<T> ExecuteWithinOptionalBudget<T>(
+ Func<KernelResult<T>> action,
+ DisplayTessellationExecutionBudget? executionBudget,
+ string phase,
+ FaceId? faceId = null,
+ SurfaceGeometryKind? surfaceKind = null,
+ TimeSpan? timeoutOverride = null)
+ => executionBudget is null
+ ? action()
+ : ExecuteWithinBudget(action, executionBudget, phase, faceId, surfaceKind, timeoutOverride);
+
+ private static SurfaceGeometryKind? TryGetSurfaceKind(BrepBody body, FaceId faceId)
+ {
+ if (!body.TryGetFaceSurfaceGeometry(faceId, out var surface) || surface is null)
+ {
+ return null;
}
- return KernelResult<DisplayTessellationResult>.Success(new DisplayTessellationResult(facePatches, edgePolylines), accumulatedDiagnostics);
+ return surface.Kind;
}
- private static KernelResult<DisplayFaceMeshPatch> TessellateFace(BrepBody body, FaceId faceId, DisplayTessellationOptions options)
+ private static KernelResult<DisplayFaceMeshPatch> TessellateFace(BrepBody body, FaceId faceId, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
if (!body.TryGetFaceSurfaceGeometry(faceId, out var surface) || surface is null)
{
return KernelResult<DisplayFaceMeshPatch>.Failure([CreateNotImplemented($"Face {faceId.Value} is missing bound surface geometry.")]);
}
+ executionBudget?.ThrowIfExpired("FaceSurfaceDispatch", faceId, surface.Kind);
+
return surface.Kind switch
{
- SurfaceGeometryKind.Plane => TessellatePlanarFace(body, faceId, surface.Plane!.Value, options),
- SurfaceGeometryKind.Cylinder => TessellateCylinderFace(body, faceId, surface.Cylinder!.Value, options),
- SurfaceGeometryKind.Cone => TessellateConeFace(body, faceId, surface.Cone!.Value, options),
+ SurfaceGeometryKind.Plane => TessellatePlanarFace(body, faceId, surface.Plane!.Value, options, executionBudget),
+ SurfaceGeometryKind.Cylinder => TessellateCylinderFace(body, faceId, surface.Cylinder!.Value, options, executionBudget),
+ SurfaceGeometryKind.Cone => TessellateConeFace(body, faceId, surface.Cone!.Value, options, executionBudget),
SurfaceGeometryKind.Sphere => TessellateSphereFace(body, faceId, surface.Sphere!.Value, options),
- SurfaceGeometryKind.Torus => TessellateTorusFace(body, faceId, surface.Torus!.Value, options),
- SurfaceGeometryKind.BSplineSurfaceWithKnots => TessellateBSplineSurfaceFace(body, faceId, surface.BSplineSurfaceWithKnots!, options),
+ SurfaceGeometryKind.Torus => TessellateTorusFace(body, faceId, surface.Torus!.Value, options, executionBudget),
+ SurfaceGeometryKind.BSplineSurfaceWithKnots => TessellateBSplineSurfaceFace(body, faceId, surface.BSplineSurfaceWithKnots!, options, executionBudget),
_ => KernelResult<DisplayFaceMeshPatch>.Failure([CreateNotImplemented($"Face {faceId.Value} has unsupported surface kind '{surface.Kind}'.")]),
};
}
- private static KernelResult<DisplayFaceMeshPatch> TessellatePlanarFace(BrepBody body, FaceId faceId, PlaneSurface plane, DisplayTessellationOptions options)
+ private static KernelResult<DisplayFaceMeshPatch> TessellatePlanarFace(BrepBody body, FaceId faceId, PlaneSurface plane, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
var loopIds = body.GetLoopIds(faceId);
if (loopIds.Count == 0)
@@ -108,19 +182,34 @@ public static class BrepDisplayTessellator
if (loopIds.Count == 1)
{
- var simpleLoopPoints = FlattenPlanarLoop(body, faceId, plane, options, loopIds[0]);
+ var simpleLoopPoints = ExecuteWithinOptionalBudget(
+ () => FlattenPlanarLoop(body, faceId, plane, options, loopIds[0]),
+ executionBudget,
+ "PlanarLoopFlattening",
+ faceId,
+ SurfaceGeometryKind.Plane);
if (!simpleLoopPoints.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Failure(simpleLoopPoints.Diagnostics);
}
- return TriangulatePlanarPatch(faceId, plane, simpleLoopPoints.Value);
+ return ExecuteWithinOptionalBudget(
+ () => TriangulatePlanarPatch(faceId, plane, simpleLoopPoints.Value),
+ executionBudget,
+ "PlanarTriangulation",
+ faceId,
+ SurfaceGeometryKind.Plane);
}
var flattenedLoops = new Dictionary<LoopId, IReadOnlyList<Point3D>>();
foreach (var loopId in loopIds.OrderBy(id => id.Value))
{
- var flattenedLoop = FlattenPlanarLoop(body, faceId, plane, options, loopId);
+ var flattenedLoop = ExecuteWithinOptionalBudget(
+ () => FlattenPlanarLoop(body, faceId, plane, options, loopId),
+ executionBudget,
+ "PlanarLoopFlattening",
+ faceId,
+ SurfaceGeometryKind.Plane);
if (!flattenedLoop.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Failure(flattenedLoop.Diagnostics);
@@ -129,7 +218,12 @@ public static class BrepDisplayTessellator
flattenedLoops[loopId] = flattenedLoop.Value;
}
- var outerLoopId = SelectPlanarPrimaryLoop(body, faceId, plane, loopIds);
+ var outerLoopId = ExecuteWithinOptionalBudget(
+ () => KernelResult<LoopId>.Success(SelectPlanarPrimaryLoop(body, faceId, plane, loopIds)),
+ executionBudget,
+ "PlanarPrimaryLoopSelection",
+ faceId,
+ SurfaceGeometryKind.Plane).Value;
var outerLoop = flattenedLoops[outerLoopId];
var holes = loopIds
.Where(loopId => loopId != outerLoopId)
@@ -137,22 +231,41 @@ public static class BrepDisplayTessellator
.Select(loopId => flattenedLoops[loopId])
.ToArray();
- if (!PlanarPolygonTriangulator.TryTriangulateWithHoles(
- outerLoop,
- holes,
- plane.Normal.ToVector(),
- out var triangulationPoints,
- out var indices,
- out var failure))
+ var triangulationResult = ExecuteWithinOptionalBudget(
+ () =>
+ {
+ if (!PlanarPolygonTriangulator.TryTriangulateWithHoles(
+ outerLoop,
+ holes,
+ plane.Normal.ToVector(),
+ out var triangulationPoints,
+ out var indices,
+ out var failure))
+ {
+ return KernelResult<(IReadOnlyList<Point3D> Points, IReadOnlyList<int> Indices, PlanarPolygonTriangulationFailure? Failure)>.Failure([
+ CreateValidationWarning(
+ $"Face {faceId.Value} planar multi-loop tessellation could not be resolved ({failure?.ToString() ?? "Unknown"}); skipping face patch to avoid misleading filled geometry.",
+ PlanarMultiLoopTriangulationSkippedSource)]);
+ }
+
+ return KernelResult<(IReadOnlyList<Point3D> Points, IReadOnlyList<int> Indices, PlanarPolygonTriangulationFailure? Failure)>.Success((triangulationPoints, indices, null));
+ },
+ executionBudget,
+ "PlanarTriangulationWithHoles",
+ faceId,
+ SurfaceGeometryKind.Plane);
+
+ if (!triangulationResult.IsSuccess)
{
- return KernelResult<DisplayFaceMeshPatch>.Success(
- CreateEmptyPlanarPatch(faceId),
- [CreateValidationWarning(
- $"Face {faceId.Value} planar multi-loop tessellation could not be resolved ({failure?.ToString() ?? "Unknown"}); skipping face patch to avoid misleading filled geometry.",
- PlanarMultiLoopTriangulationSkippedSource)]);
+ if (triangulationResult.Diagnostics.Any(diagnostic => string.Equals(diagnostic.Source, "Viewer.Tessellation.Timeout", StringComparison.Ordinal)))
+ {
+ return KernelResult<DisplayFaceMeshPatch>.Failure(triangulationResult.Diagnostics);
+ }
+
+ return KernelResult<DisplayFaceMeshPatch>.Success(CreateEmptyPlanarPatch(faceId), triangulationResult.Diagnostics);
}
- return KernelResult<DisplayFaceMeshPatch>.Success(CreatePlanarPatch(faceId, triangulationPoints, plane.Normal.ToVector(), indices));
+ return KernelResult<DisplayFaceMeshPatch>.Success(CreatePlanarPatch(faceId, triangulationResult.Value.Points, plane.Normal.ToVector(), triangulationResult.Value.Indices));
}
private static KernelResult<DisplayFaceMeshPatch> TriangulatePlanarPatch(FaceId faceId, PlaneSurface plane, IReadOnlyList<Point3D> polygonPoints)
@@ -344,12 +457,12 @@ public static class BrepDisplayTessellator
return KernelResult<DisplayFaceMeshPatch>.Success(new DisplayFaceMeshPatch(faceId, positions, normals, indices));
}
- private static KernelResult<DisplayFaceMeshPatch> TessellateCylinderFace(BrepBody body, FaceId faceId, CylinderSurface cylinder, DisplayTessellationOptions options)
+ private static KernelResult<DisplayFaceMeshPatch> TessellateCylinderFace(BrepBody body, FaceId faceId, CylinderSurface cylinder, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
var loopIds = body.GetLoopIds(faceId);
if (loopIds.Count > 1)
{
- var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToCylinderUv(cylinder, point), options);
+ var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToCylinderUv(cylinder, point), options, executionBudget, SurfaceGeometryKind.Cylinder);
if (!uvLoopsResult.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Success(
@@ -369,18 +482,20 @@ public static class BrepDisplayTessellator
double.PositiveInfinity,
double.NegativeInfinity,
double.PositiveInfinity,
- CreateValidationWarning);
+ CreateValidationWarning,
+ executionBudget,
+ SurfaceGeometryKind.Cylinder);
}
return TessellateLegacyCylinderFace(body, faceId, cylinder, options);
}
- private static KernelResult<DisplayFaceMeshPatch> TessellateConeFace(BrepBody body, FaceId faceId, ConeSurface cone, DisplayTessellationOptions options)
+ private static KernelResult<DisplayFaceMeshPatch> TessellateConeFace(BrepBody body, FaceId faceId, ConeSurface cone, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
var loopIds = body.GetLoopIds(faceId);
if (loopIds.Count > 0)
{
- var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToConeUv(cone, point), options);
+ var uvLoopsResult = TryBuildPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToConeUv(cone, point), options, executionBudget, SurfaceGeometryKind.Cone);
if (!uvLoopsResult.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Success(
@@ -405,7 +520,9 @@ public static class BrepDisplayTessellator
double.PositiveInfinity,
double.NegativeInfinity,
double.PositiveInfinity,
- CreateValidationWarning);
+ CreateValidationWarning,
+ executionBudget,
+ SurfaceGeometryKind.Cone);
}
return TessellateLegacyConeFace(body, faceId, cone, options);
@@ -553,8 +670,9 @@ public static class BrepDisplayTessellator
return area * 0.5d;
}
- private static KernelResult<DisplayFaceMeshPatch> TessellateBSplineSurfaceFace(BrepBody body, FaceId faceId, BSplineSurfaceWithKnots surface, DisplayTessellationOptions options)
+ private static KernelResult<DisplayFaceMeshPatch> TessellateBSplineSurfaceFace(BrepBody body, FaceId faceId, BSplineSurfaceWithKnots surface, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
+ executionBudget?.ThrowIfExpired("BSplineSurface.Start", faceId, SurfaceGeometryKind.BSplineSurfaceWithKnots);
var loopIds = body.GetLoopIds(faceId);
if (loopIds.Count == 0)
{
@@ -575,7 +693,9 @@ public static class BrepDisplayTessellator
faceId,
loopIds,
point => TryProjectPointToBSplineUv(surface, point),
- options);
+ options,
+ executionBudget,
+ SurfaceGeometryKind.BSplineSurfaceWithKnots);
if (!uvLoopsResult.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Success(
@@ -595,7 +715,9 @@ public static class BrepDisplayTessellator
surface.DomainEndU,
surface.DomainStartV,
surface.DomainEndV,
- CreateValidationWarning);
+ CreateValidationWarning,
+ executionBudget,
+ SurfaceGeometryKind.BSplineSurfaceWithKnots);
}
private static (double U, double V)? TryProjectPointToBSplineUv(BSplineSurfaceWithKnots surface, Point3D point)
@@ -683,12 +805,15 @@ public static class BrepDisplayTessellator
FaceId faceId,
IReadOnlyList<LoopId> loopIds,
Func<Point3D, (double U, double V)?> projectPointToUv,
- DisplayTessellationOptions options)
+ DisplayTessellationOptions options,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
var uvLoops = new List<IReadOnlyList<(double U, double V)>>(loopIds.Count);
foreach (var loopId in loopIds.OrderBy(id => id.Value))
{
- var uvLoop = TryBuildDoublyPeriodicTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options);
+ executionBudget?.ThrowIfExpired("DoublyPeriodicTrimLoopDispatch", faceId, surfaceKind);
+ var uvLoop = TryBuildDoublyPeriodicTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options, executionBudget, surfaceKind);
if (!uvLoop.IsSuccess)
{
return KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>>.Failure(uvLoop.Diagnostics);
@@ -705,7 +830,9 @@ public static class BrepDisplayTessellator
FaceId faceId,
LoopId loopId,
Func<Point3D, (double U, double V)?> projectPointToUv,
- DisplayTessellationOptions options)
+ DisplayTessellationOptions options,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
var coedges = body.GetCoedgeIds(loopId).Select(id => body.Topology.GetCoedge(id)).ToArray();
if (coedges.Length < 1)
@@ -730,7 +857,8 @@ public static class BrepDisplayTessellator
foreach (var coedge in coedges)
{
- var sampledCurve = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertexPointsResult.Value, options);
+ executionBudget?.ThrowIfExpired("DoublyPeriodicTrimLoopSampling", faceId, surfaceKind);
+ var sampledCurve = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertexPointsResult.Value, options, executionBudget, surfaceKind);
if (!sampledCurve.IsSuccess)
{
return KernelResult<IReadOnlyList<(double U, double V)>>.Failure(sampledCurve.Diagnostics);
@@ -775,12 +903,15 @@ public static class BrepDisplayTessellator
FaceId faceId,
IReadOnlyList<LoopId> loopIds,
Func<Point3D, (double U, double V)?> projectPointToUv,
- DisplayTessellationOptions options)
+ DisplayTessellationOptions options,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
var uvLoops = new List<IReadOnlyList<(double U, double V)>>(loopIds.Count);
foreach (var loopId in loopIds.OrderBy(id => id.Value))
{
- var uvLoop = TryBuildPeriodicTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options);
+ executionBudget?.ThrowIfExpired("PeriodicTrimLoopDispatch", faceId, surfaceKind);
+ var uvLoop = TryBuildPeriodicTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options, executionBudget, surfaceKind);
if (!uvLoop.IsSuccess)
{
return KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>>.Failure(uvLoop.Diagnostics);
@@ -797,7 +928,9 @@ public static class BrepDisplayTessellator
FaceId faceId,
LoopId loopId,
Func<Point3D, (double U, double V)?> projectPointToUv,
- DisplayTessellationOptions options)
+ DisplayTessellationOptions options,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
var coedges = body.GetCoedgeIds(loopId).Select(id => body.Topology.GetCoedge(id)).ToArray();
if (coedges.Length < 1)
@@ -820,7 +953,8 @@ public static class BrepDisplayTessellator
var wrappedSpanTolerance = double.Pi + 1e-6d;
foreach (var coedge in coedges)
{
- var sampledCurve = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertexPointsResult.Value, options);
+ executionBudget?.ThrowIfExpired("PeriodicTrimLoopSampling", faceId, surfaceKind);
+ var sampledCurve = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertexPointsResult.Value, options, executionBudget, surfaceKind);
if (!sampledCurve.IsSuccess)
{
return KernelResult<IReadOnlyList<(double U, double V)>>.Failure(sampledCurve.Diagnostics);
@@ -1028,12 +1162,15 @@ public static class BrepDisplayTessellator
FaceId faceId,
IReadOnlyList<LoopId> loopIds,
Func<Point3D, (double U, double V)?> projectPointToUv,
- DisplayTessellationOptions options)
+ DisplayTessellationOptions options,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
var uvLoops = new List<IReadOnlyList<(double U, double V)>>(loopIds.Count);
foreach (var loopId in loopIds.OrderBy(id => id.Value))
{
- var uvLoop = TryBuildTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options);
+ executionBudget?.ThrowIfExpired("TrimLoopDispatch", faceId, surfaceKind);
+ var uvLoop = TryBuildTrimmedSurfaceUvLoop(body, faceId, loopId, projectPointToUv, options, executionBudget, surfaceKind);
if (!uvLoop.IsSuccess)
{
return KernelResult<IReadOnlyList<IReadOnlyList<(double U, double V)>>>.Failure(uvLoop.Diagnostics);
@@ -1050,7 +1187,9 @@ public static class BrepDisplayTessellator
FaceId faceId,
LoopId loopId,
Func<Point3D, (double U, double V)?> projectPointToUv,
- DisplayTessellationOptions options)
+ DisplayTessellationOptions options,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
var coedges = body.GetCoedgeIds(loopId).Select(id => body.Topology.GetCoedge(id)).ToArray();
if (coedges.Length < 3)
@@ -1070,7 +1209,8 @@ public static class BrepDisplayTessellator
var uvPoints = new List<(double U, double V)>();
foreach (var coedge in coedges)
{
- var sampledCurve = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertexPointsResult.Value, options);
+ executionBudget?.ThrowIfExpired("TrimLoopSampling", faceId, surfaceKind);
+ var sampledCurve = TrySampleCoedgeForTrimEvaluation(body, faceId, coedge, vertexPointsResult.Value, options, executionBudget, surfaceKind);
if (!sampledCurve.IsSuccess)
{
return KernelResult<IReadOnlyList<(double U, double V)>>.Failure(sampledCurve.Diagnostics);
@@ -1104,8 +1244,11 @@ public static class BrepDisplayTessellator
FaceId faceId,
Coedge coedge,
IReadOnlyDictionary<VertexId, Point3D> vertexPoints,
- DisplayTessellationOptions options)
+ DisplayTessellationOptions options,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
+ executionBudget?.ThrowIfExpired("TrimCoedgeSampling", faceId, surfaceKind);
var endpoints = GetEdgeEndpoints(body, coedge.EdgeId, coedge.IsReversed, vertexPoints);
if (!endpoints.IsSuccess)
{
@@ -1220,12 +1363,12 @@ public static class BrepDisplayTessellator
}
- private static KernelResult<DisplayFaceMeshPatch> TessellateTorusFace(BrepBody body, FaceId faceId, TorusSurface torus, DisplayTessellationOptions options)
+ private static KernelResult<DisplayFaceMeshPatch> TessellateTorusFace(BrepBody body, FaceId faceId, TorusSurface torus, DisplayTessellationOptions options, DisplayTessellationExecutionBudget? executionBudget = null)
{
var loopIds = body.GetLoopIds(faceId);
if (loopIds.Count > 0)
{
- var uvLoopsResult = TryBuildDoublyPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToTorusUv(torus, point), options);
+ var uvLoopsResult = TryBuildDoublyPeriodicTrimmedSurfaceUvLoops(body, faceId, loopIds, point => TryProjectPointToTorusUv(torus, point), options, executionBudget, SurfaceGeometryKind.Torus);
if (!uvLoopsResult.IsSuccess)
{
return KernelResult<DisplayFaceMeshPatch>.Success(
@@ -1245,7 +1388,9 @@ public static class BrepDisplayTessellator
double.PositiveInfinity,
double.NegativeInfinity,
double.PositiveInfinity,
- CreateValidationWarning);
+ CreateValidationWarning,
+ executionBudget,
+ SurfaceGeometryKind.Torus);
}
var parameters = GetRevolvedFaceParameters(body, faceId, options, radiusHint: torus.MajorRadius + torus.MinorRadius, allowThreeCoedgeConeTopology: false, axialParameterFromPoint: point => TorusMinorAngleOf(torus, point));
@@ -3840,6 +3985,9 @@ public static class BrepDisplayTessellator
private static KernelDiagnostic CreateNotImplemented(string message, string? source = null)
=> new(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, message, source);
+ private static KernelDiagnostic CreateValidationError(string message, string source)
+ => new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, source);
+
private static KernelDiagnostic CreateValidationWarning(string message, string source)
=> new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning, message, source);
}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.cs b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.cs
index a17a8202..f802ae79 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayPreparationFallbackBuilder.cs
@@ -7,17 +7,20 @@ namespace Aetheris.Kernel.Core.Brep.Tessellation;
public static class DisplayPreparationFallbackBuilder
{
+ private static readonly TimeSpan DefaultExecutionTimeout = TimeSpan.FromSeconds(5);
+
public static KernelResult<DisplayTessellationResult> Build(
BrepBody body,
DisplayTessellationOptions? tessellationOptions = null)
- => Build(body, tessellationOptions, null);
+ => Build(body, tessellationOptions, null, DefaultExecutionTimeout);
internal static KernelResult<DisplayTessellationResult> Build(
BrepBody body,
DisplayTessellationOptions? tessellationOptions,
- DisplayPreparationBsplineScaffoldOptions? scaffoldOptions)
+ DisplayPreparationBsplineScaffoldOptions? scaffoldOptions,
+ TimeSpan? executionTimeout = null)
{
- var tessellation = BrepDisplayTessellator.Tessellate(body, tessellationOptions);
+ var tessellation = BrepDisplayTessellator.TessellateBounded(body, tessellationOptions, executionTimeout);
if (!tessellation.IsSuccess)
{
return tessellation;
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationExecutionBudget.cs b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationExecutionBudget.cs
new file mode 100644
index 00000000..45d18528
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/DisplayTessellationExecutionBudget.cs
@@ -0,0 +1,68 @@
+using System.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep.Tessellation;
+
+internal sealed class DisplayTessellationExecutionBudget
+{
+ private static readonly TimeSpan MinimumRemaining = TimeSpan.FromMilliseconds(1);
+ private readonly Stopwatch stopwatch;
+ private readonly TimeSpan maxElapsed;
+
+ internal DisplayTessellationExecutionBudget(TimeSpan maxElapsed)
+ {
+ stopwatch = Stopwatch.StartNew();
+ this.maxElapsed = maxElapsed;
+ }
+
+ internal static DisplayTessellationExecutionBudget CreateDefault() => new(TimeSpan.FromSeconds(5));
+
+ internal TimeSpan Elapsed => stopwatch.Elapsed;
+
+ internal TimeSpan Remaining
+ {
+ get
+ {
+ var remaining = maxElapsed - stopwatch.Elapsed;
+ return remaining > MinimumRemaining ? remaining : MinimumRemaining;
+ }
+ }
+
+ internal void ThrowIfExpired(string phase, FaceId? faceId = null, SurfaceGeometryKind? surfaceKind = null)
+ {
+ if (stopwatch.Elapsed <= maxElapsed)
+ {
+ return;
+ }
+
+ throw new DisplayTessellationTimeoutException(phase, stopwatch.Elapsed, faceId, surfaceKind);
+ }
+}
+
+internal sealed class DisplayTessellationTimeoutException : Exception
+{
+ internal DisplayTessellationTimeoutException(string phase, TimeSpan elapsed, FaceId? faceId, SurfaceGeometryKind? surfaceKind)
+ : base(BuildMessage(phase, elapsed, faceId, surfaceKind))
+ {
+ Phase = phase;
+ Elapsed = elapsed;
+ FaceId = faceId;
+ SurfaceKind = surfaceKind;
+ }
+
+ internal string Phase { get; }
+
+ internal TimeSpan Elapsed { get; }
+
+ internal FaceId? FaceId { get; }
+
+ internal SurfaceGeometryKind? SurfaceKind { get; }
+
+ private static string BuildMessage(string phase, TimeSpan elapsed, FaceId? faceId, SurfaceGeometryKind? surfaceKind)
+ {
+ var faceText = faceId.HasValue ? $"face {faceId.Value.Value}" : "unknown face";
+ var surfaceText = surfaceKind?.ToString() ?? "unknown";
+ return $"Display tessellation exceeded the bounded execution budget after {elapsed.TotalMilliseconds:F0} ms while processing {faceText} on surface '{surfaceText}' during phase '{phase}'.";
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
index 5cfc6354..6dee5231 100644
--- a/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
+++ b/Aetheris.Kernel.Core/Brep/Tessellation/TrimmedSurfaceTessellator.cs
@@ -1,4 +1,5 @@
using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
@@ -22,8 +23,11 @@ internal static class TrimmedSurfaceTessellator
double uDomainEnd,
double vDomainStart,
double vDomainEnd,
- Func<string, string, KernelDiagnostic> createWarning)
+ Func<string, string, KernelDiagnostic> createWarning,
+ DisplayTessellationExecutionBudget? executionBudget = null,
+ SurfaceGeometryKind? surfaceKind = null)
{
+ executionBudget?.ThrowIfExpired("TrimmedSurface.Start", faceId, surfaceKind);
if (uvLoops.Count == 0)
{
return KernelResult<DisplayFaceMeshPatch>.Success(CreateEmptyPatch(faceId));
@@ -73,6 +77,7 @@ internal static class TrimmedSurfaceTessellator
for (var iv = 0; iv <= vSegments; iv++)
{
+ executionBudget?.ThrowIfExpired("TrimmedSurface.GridSampling", faceId, surfaceKind);
var tv = (double)iv / vSegments;
var v = vStart + ((vEnd - vStart) * tv);
for (var iu = 0; iu <= uSegments; iu++)
@@ -88,6 +93,7 @@ internal static class TrimmedSurfaceTessellator
var rowWidth = uSegments + 1;
for (var iv = 0; iv < vSegments; iv++)
{
+ executionBudget?.ThrowIfExpired("TrimmedSurface.TriangleClassification", faceId, surfaceKind);
for (var iu = 0; iu < uSegments; iu++)
{
var i0 = (iv * rowWidth) + iu;
@@ -109,6 +115,7 @@ internal static class TrimmedSurfaceTessellator
void AppendTriangleWithBoundaryRefinement(int ia, int ib, int ic, int remainingDepth)
{
+ executionBudget?.ThrowIfExpired("TrimmedSurface.BoundaryRefinement", faceId, surfaceKind);
var classification = ClassifyTriangle(uvGrid[ia], uvGrid[ib], uvGrid[ic], trimContext);
switch (classification)
{
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index bea31ea4..93df6bdf 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -220,6 +220,56 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.Null(patch.ScaffoldRejectionReason);
}
+ [Fact]
+ public async Task Ftc07ServerImport_ReturnsBeforeViewMaterialization()
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+ var ftc07StepText = await File.ReadAllTextAsync(GetRepositoryPath("testdata/step242/nist/FTC/nist_ftc_07_asme1_ap242-e2.stp"));
+
+ using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
+ var importResponse = await _client.PostAsJsonAsync(
+ $"/api/v1/documents/{document.Data!.DocumentId}/import/step",
+ new StepImportRequestDto(ftc07StepText, "FTC07"),
+ cts.Token);
+ importResponse.EnsureSuccessStatusCode();
+
+ var imported = await importResponse.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>(cts.Token);
+ Assert.NotNull(imported);
+ Assert.True(imported!.Success);
+ Assert.NotNull(imported.Data);
+ }
+
+ [Fact]
+ public async Task Ftc07ViewMaterialization_FailsWithDiagnosticInsteadOfHang()
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+ var ftc07StepText = await File.ReadAllTextAsync(GetRepositoryPath("testdata/step242/nist/FTC/nist_ftc_07_asme1_ap242-e2.stp"));
+
+ var importResponse = await _client.PostAsJsonAsync(
+ $"/api/v1/documents/{document.Data!.DocumentId}/import/step",
+ new StepImportRequestDto(ftc07StepText, "FTC07"));
+ importResponse.EnsureSuccessStatusCode();
+ var imported = await importResponse.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>();
+ Assert.NotNull(imported);
+ Assert.True(imported!.Success);
+
+ using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
+ var prepareResponse = await _client.PostAsJsonAsync(
+ $"/api/v1/documents/{document.Data.DocumentId}/bodies/{imported.Data!.OccurrenceId}/display/prepare",
+ new DisplayPrepareRequestDto(null),
+ cts.Token);
+
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, prepareResponse.StatusCode);
+ var payload = await prepareResponse.Content.ReadFromJsonAsync<ApiResponseDto<object>>(cts.Token);
+ Assert.NotNull(payload);
+ Assert.False(payload!.Success);
+ Assert.Contains(payload.Diagnostics, diagnostic => diagnostic.Source == "Viewer.Tessellation.Timeout");
+ Assert.Contains(payload.Diagnostics, diagnostic => diagnostic.Message.Contains("face", StringComparison.OrdinalIgnoreCase));
+ Assert.Contains(payload.Diagnostics, diagnostic =>
+ diagnostic.Message.Contains("PlanarTriangulationWithHoles", StringComparison.Ordinal)
+ || diagnostic.Message.Contains("FaceTessellation", StringComparison.Ordinal));
+ }
+
[Fact]
public async Task DisplayPrepare_SameBodyTwice_IsDeterministic()
{
diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.cs
index c4de10c7..7e03b889 100644
--- a/Aetheris.Server/Api/KernelEndpoints.cs
+++ b/Aetheris.Server/Api/KernelEndpoints.cs
@@ -279,7 +279,7 @@ public static class KernelEndpoints
WithDocumentOccurrence(store, documentId, bodyId, (document, body) =>
{
var options = ApiMappings.BuildTessellationOptions(request?.Options);
- var kernel = BrepDisplayTessellator.Tessellate(body, options);
+ var kernel = BrepDisplayTessellator.TessellateBounded(body, options);
if (!kernel.IsSuccess)
{
return ApiMappings.KernelFailure(kernel.Diagnostics);
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index ef5ea1e4..30757b00 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -151,9 +151,9 @@ function App() {
}
}, []);
- const refreshSummaryAndActiveTessellation = useCallback(async (targetBodyId?: string) => {
+ const refreshSummaryAndActiveTessellation = useCallback(async (targetBodyId?: string, suppressDisplayErrors = false) => {
if (!documentId) {
- return;
+ return null;
}
const summary = await getDocumentSummary(documentId);
@@ -164,13 +164,29 @@ function App() {
setActiveBodyId(selected ?? null);
if (selected) {
- const preparedDisplay = await prepareBodyDisplay(documentId, selected);
- setDisplayPreparation(preparedDisplay);
- setTessellation(preparedDisplay.tessellationFallback);
+ try {
+ const preparedDisplay = await prepareBodyDisplay(documentId, selected);
+ setDisplayPreparation(preparedDisplay);
+ setTessellation(preparedDisplay.tessellationFallback);
+ return null;
+ } catch (error) {
+ const apiError = error instanceof ApiError
+ ? error
+ : new ApiError((error as Error).message || 'Unexpected display preparation error.', []);
+ setTessellation(null);
+ setDisplayPreparation(null);
+ if (!suppressDisplayErrors) {
+ throw apiError;
+ }
+
+ return apiError;
+ }
} else {
setTessellation(null);
setDisplayPreparation(null);
}
+
+ return null;
}, [activeBodyId, documentId]);
const handleCreateDocument = useCallback(async () => {
@@ -354,6 +370,7 @@ function App() {
setIsImporting(true);
try {
+ let displayError: ApiError | null = null;
const didImport = await runAction('Import STEP', async () => {
const stepText = await stepImportFile.text();
if (stepText.trim().length === 0) {
@@ -362,7 +379,7 @@ function App() {
const imported = await importStep(documentId, stepText);
setStepExportText('');
- await refreshSummaryAndActiveTessellation(imported.occurrenceId);
+ displayError = await refreshSummaryAndActiveTessellation(imported.occurrenceId, true);
const exported = await exportDefinitionStep(documentId, imported.definitionId);
setStepCanonicalHash(exported.canonicalHash);
setPickStatus('idle');
@@ -371,8 +388,16 @@ function App() {
setPickHits([]);
setCopyHashMessage('');
});
- setImportStatus(didImport ? 'success' : 'error');
- setImportStatusMessage(didImport ? 'Import complete.' : 'Import error: Request failed.');
+ if (didImport && displayError) {
+ setStatus('error');
+ setStatusMessage(`View materialization failed after import: ${displayError.message}`);
+ setDiagnostics(displayError.diagnostics);
+ setImportStatus('success');
+ setImportStatusMessage('Import complete. View materialization failed.');
+ } else {
+ setImportStatus(didImport ? 'success' : 'error');
+ setImportStatusMessage(didImport ? 'Import complete.' : 'Import error: Request failed.');
+ }
} finally {
setIsImporting(false);
}
diff --git a/aetheris.client/src/__tests__/App.test.tsx b/aetheris.client/src/__tests__/App.test.tsx
index bce3228d..7b8a297d 100644
--- a/aetheris.client/src/__tests__/App.test.tsx
+++ b/aetheris.client/src/__tests__/App.test.tsx
@@ -355,6 +355,44 @@ describe('App STEP file upload flow', () => {
await screen.findByText('[Error] ValidationFailed: Malformed STEP payload.');
});
+ it('reports view materialization failure without masquerading as import failure', async () => {
+ apiMocks.importStep.mockResolvedValue({
+ documentId: 'doc-1',
+ definitionId: 'def-2',
+ occurrenceId: 'occ-2',
+ name: 'Imported',
+ diagnostics: [],
+ });
+ apiMocks.prepareBodyDisplay.mockRejectedValue(new ApiError('Display tessellation exceeded the bounded execution budget.', [{
+ code: 'ValidationFailed',
+ severity: 'Error',
+ message: 'Display tessellation exceeded the bounded execution budget.',
+ source: 'Viewer.Tessellation.Timeout',
+ }]));
+ apiMocks.exportDefinitionStep.mockResolvedValue({
+ documentId: 'doc-1',
+ definitionId: 'def-2',
+ stepText: 'ISO-10303-21;',
+ canonicalHash: 'hash-123',
+ diagnostics: [],
+ });
+
+ render(<App />);
+ await screen.findByText('Document: Ready');
+
+ const fileInput = screen.getByTestId('step-import-file-input') as HTMLInputElement;
+ const file = new File(['ISO-10303-21;DATA;'], 'ftc07.stp', { type: 'text/plain' });
+ fireEvent.change(fileInput, { target: { files: [file] } });
+ await screen.findByText('ftc07.stp');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Import STEP 242' }));
+
+ await screen.findByText('Import complete. View materialization failed.');
+ await screen.findByText('[Error] ValidationFailed: Display tessellation exceeded the bounded execution budget.');
+ expect(screen.queryByText('Import failed')).toBeNull();
+ await screen.findByText('hash-123');
+ });
+
it('preserves ApiError diagnostics from canonical download failure', async () => {
apiMocks.exportDefinitionStep.mockRejectedValue(new ApiError('Export failed.', [{
code: 'StepExportFailed',
diff --git a/docs/step-ap242-ftc07-import-hang-house-call.md b/docs/step-ap242-ftc07-import-hang-house-call.md
new file mode 100644
index 00000000..38a36ab5
--- /dev/null
+++ b/docs/step-ap242-ftc07-import-hang-house-call.md
@@ -0,0 +1,185 @@
+# STEP-AP242-HARDEN-X2: FTC-07 Import Hang House Call
+
+## Problem statement
+
+FTC-07 was reported as a local "import hang" when loading `testdata/step242/nist/FTC/nist_ftc_07_asme1_ap242-e2.stp`.
+
+The primary question for this house call was whether the hang lived in:
+
+- STEP/AP242 parsing/import,
+- BRep/topology materialization,
+- canonical export,
+- server API orchestration, or
+- UI/view materialization.
+
+## FTC-06 / FTC-07 distinction
+
+FTC-06 and FTC-07 are separate issues.
+
+- FTC-06 was the curved `ADVANCED_FACE.same_sense` preservation regression and remains covered as a regression smoke.
+- This house call is FTC-07 only.
+- No new general NURBS support, no broad AP242 rewrite, and no FTC-06 behavior changes were introduced here.
+
+## Reproduction commands
+
+Fixture:
+
+```powershell
+testdata\step242\nist\FTC\nist_ftc_07_asme1_ap242-e2.stp
+```
+
+Core importer / exporter:
+
+```powershell
+dotnet run --project Aetheris.CLI -f net10.0 --no-build -- analyze testdata\step242\nist\FTC\nist_ftc_07_asme1_ap242-e2.stp --json
+dotnet run --project Aetheris.CLI -f net10.0 --no-build -- canon testdata\step242\nist\FTC\nist_ftc_07_asme1_ap242-e2.stp --out artifacts\ftc07\nist_ftc_07_canonical.step --json
+dotnet run --project Aetheris.CLI -f net10.0 --no-build -- analyze testdata\step242\nist\FTC\nist_ftc_07_asme1_ap242-e2.stp --face 9 --json
+```
+
+Server/API isolation:
+
+```powershell
+dotnet Aetheris.Server\bin\Debug\net10.0\Aetheris.Server.dll --urls http://127.0.0.1:5142
+```
+
+Then:
+
+1. `POST /api/v1/documents`
+2. `POST /api/v1/documents/{id}/import/step`
+3. `POST /api/v1/documents/{id}/bodies/{occurrenceId}/display/prepare`
+
+## Layer where the hang occurs
+
+The hang does not occur in core STEP import.
+
+Observed layer breakdown:
+
+- `analyze` completed successfully in about 1 second.
+- `canon` completed successfully in about 1.2 seconds.
+- `POST /import/step` completed successfully in about 200 ms.
+- `GET /documents/{id}` completed successfully in about 22 ms.
+- The old local hang appeared when the UI/server advanced into display preparation.
+
+Current classification:
+
+- `ViewMaterializationHang`
+- More specifically: bounded server-side display tessellation failure during planar face materialization.
+
+This is not a raw AP242 kernel importer hang.
+
+## Root cause found
+
+FTC-07 imports into kernel/BRep successfully, but display preparation can stall while tessellating a planar multi-loop face.
+
+The bounded diagnostic now reports:
+
+```text
+Display tessellation exceeded the bounded execution budget after ~5000 ms while processing face 9 on surface 'Plane' during phase 'PlanarTriangulationWithHoles'.
+```
+
+Supporting face inspection:
+
+- `aetheris analyze ... --face 9 --json` reports `surfaceType = Plane`
+- face 9 has 20 adjacent edges
+- bounding box is planar at `y = -4.75`
+
+So the FTC-07 local "import hang" was actually the viewer/display path blocking on planar hole triangulation for face 9, not STEP parse/import/export.
+
+## Instrumentation added
+
+Bounded execution diagnostics were added to display tessellation:
+
+- per-run display tessellation execution budget
+- timeout diagnostic category: `Viewer.Tessellation.Timeout`
+- diagnostic message includes:
+ - face id
+ - surface kind
+ - phase
+ - elapsed milliseconds
+
+Bounded phases now cover:
+
+- top-level face tessellation
+- trimmed-surface sampling/classification lanes
+- planar loop flattening
+- planar primary-loop selection
+- planar triangulation with holes
+
+## Fix applied
+
+This milestone takes the safe bounded-diagnostic path rather than pretending FTC-07 view materialization is healthy.
+
+Applied changes:
+
+- display tessellation now runs under a bounded execution budget instead of hanging forever
+- FTC-07 face 9 planar hole triangulation returns a precise timeout diagnostic
+- server `display/prepare` returns a bounded failure instead of stalling indefinitely
+- the client import flow no longer masquerades a display/materialization failure as an AP242 import failure
+
+Client behavior now distinguishes:
+
+- import succeeded
+- view materialization failed
+
+## UI/view-specific conclusion
+
+Kernel import is not the blocker for FTC-07.
+
+If FTC-07 fails locally after import, the active blocker is view/display materialization, specifically planar face hole triangulation during display preparation. The UI previously chained import directly into display preparation and could present that stall as if import itself had hung.
+
+## Tests added
+
+Core:
+
+- `Step242Ftc07ViewMaterialization_CompletesOrReportsBoundedDiagnostic`
+- `Step242Ftc07ViewMaterialization_ReportsPhaseAndFaceOnFailure`
+
+Server:
+
+- `Ftc07ServerImport_ReturnsBeforeViewMaterialization`
+- `Ftc07ViewMaterialization_FailsWithDiagnosticInsteadOfHang`
+
+Client:
+
+- `reports view materialization failure without masquerading as import failure`
+
+Regression smoke:
+
+- FTC-06 same-sense regression remains green.
+
+## Validation run
+
+Commands run during this house call:
+
+```powershell
+dotnet build Aetheris.Kernel.Core.Tests\Aetheris.Kernel.Core.Tests.csproj -f net10.0 --no-restore
+dotnet build Aetheris.Server.Tests\Aetheris.Server.Tests.csproj -f net10.0 --no-restore
+dotnet test Aetheris.Kernel.Core.Tests\Aetheris.Kernel.Core.Tests.csproj -f net10.0 --no-build --filter "FullyQualifiedName~Aetheris.Kernel.Core.Tests.Step242.Step242Ftc07ViewMaterializationRegressionTests.Step242Ftc07ViewMaterialization_CompletesOrReportsBoundedDiagnostic|FullyQualifiedName~Aetheris.Kernel.Core.Tests.Step242.Step242Ftc07ViewMaterializationRegressionTests.Step242Ftc07ViewMaterialization_ReportsPhaseAndFaceOnFailure" --logger "console;verbosity=minimal"
+dotnet test Aetheris.Server.Tests\Aetheris.Server.Tests.csproj -f net10.0 --no-build --filter "FullyQualifiedName~Aetheris.Server.Tests.KernelApiIntegrationTests.Ftc07ServerImport_ReturnsBeforeViewMaterialization|FullyQualifiedName~Aetheris.Server.Tests.KernelApiIntegrationTests.Ftc07ViewMaterialization_FailsWithDiagnosticInsteadOfHang" --logger "console;verbosity=minimal"
+dotnet test Aetheris.Kernel.Core.Tests\Aetheris.Kernel.Core.Tests.csproj -f net10.0 --no-build --filter "Step242Ftc06SameSenseRegressionTests|FTC06|Ftc06|same_sense" --logger "console;verbosity=minimal"
+npm test -- --run App.test.tsx
+```
+
+Representative direct API result:
+
+- `POST /display/prepare` now returns HTTP 422 with `Viewer.Tessellation.Timeout`
+- phase: `PlanarTriangulationWithHoles`
+- face: `9`
+- surface: `Plane`
+
+## Remaining limitations / blockers
+
+- FTC-07 still does not fully render through the current display tessellation path.
+- The exact algorithmic defect inside planar hole triangulation for face 9 is not yet repaired here.
+- This change intentionally prefers an honest bounded diagnostic over an unsafe broader triangulation rewrite.
+
+## Non-goals
+
+- no FTC-06 same-sense behavior changes
+- no general NURBS support expansion
+- no broad AP242 importer rewrite
+- no general Boolean behavior changes
+- no Firmament V2 side-hole semantics changes
+- no AIR Region route policy changes
+- no CIR authority changes
+- no BRep redesign