acdream/tests/AcDream.App.Tests/Rendering/Issue181CameraParkStabilityTests.cs
Erik a7529a975a test(app): serialize the classes sharing camera/render process globals (#252)
A full Release App run failed once at Issue181WallPressEquilibriumTests
.Diagnostic_WallPressedCamera_EyeWanderAndViewerCellStability. It passed in
isolation and did not recur across five further whole-suite runs, and the diff
under test touched only the world texture-creation stack -- nothing in camera,
visibility or physics. A cross-class parallelism race was the only plausible
mechanism, not a regression.

Ten App test classes share three process-global mutable statics, and xUnit runs
distinct test classes in parallel by default:

  - CameraDiagnostics: AlignToSlope, CollideCamera, TranslationStiffness,
    RotationStiffness, UseRetailChaseCamera. These are not merely written, they
    are written AWAY from their defaults -- RetailChaseCameraTests sets
    AlignToSlope and CollideCamera to false, and three classes set
    UseRetailChaseCamera to false -- while RetailChaseCamera.Update,
    CameraController.Active, CameraFrameController, WorldRenderFrameBuilder and
    MouseLookController read them.
  - RenderingDiagnostics.ProbeFlapEnabled, written by CornerFloodReplayTests
    and Issue181WallPressEquilibriumTests.
  - System.Console.Out, redirected by those same two classes to capture probe
    output.

Every one of these classes already saved and restored in try/finally. That is
correct within a class and remains necessary, but it was never sufficient. A
finally bounds a mutation in TIME along its own thread; it cannot stop another
class from reading the static inside that window. Worse, two overlapping
save/restore pairs can interleave so the second restore writes back the FIRST
one's temporary value, leaving the global permanently wrong for the rest of the
run. The Console.Out case is the sharpest instance: an interleaved restore can
install a DISPOSED StringWriter as the process-wide Console.Out, which then
throws in unrelated tests. Serializing the sharers is what makes each class's
existing finally sufficient.

The fix is a marker CollectionDefinition applied to the ten sharing classes,
following the WorldEnvironmentControllerCollection precedent. No collection
fixture: several members are [Theory] cases that need different knob values per
case, so a fixture cannot own the save/restore without rewriting every member's
internals, and it would not help the read side at all. Because every member
references the same compile-time const for the collection name, the grouping
cannot silently drift via a typo.

Membership is deliberately narrow. It covers the eight writers plus two classes
that drive production code which READS a knob another member moves off its
default (HouseExitWalkReplayTests and CameraFrameControllerTests both run
RetailChaseCamera.Update and assert on the resulting eye). Classes that merely
construct a CameraController without a retail chase camera are NOT members --
their reads fall through the null branch and are insensitive.

No production code changed; no assertion was weakened, and no retry, sleep or
tolerance was added.

Verification. Base commit f6275f45 measured empirically at 3,763 passed / 3
skipped. Post-fix: 136 whole-suite Release runs. Every failure observed was in
the pre-existing zero-allocation family tracked as #250 (an Expected 0 / Actual
N bytes assertion), and none was in any collection member. A matched 55-run
baseline at f6275f45 reproduced that same family, confirming it predates this
change. Serialization cost is inside run-to-run noise: the suite is ~3 s of a
~4.5 s wall-clock dotnet test, and the ten serialized classes are a small
fraction of it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 18:46:43 +02:00

101 lines
4.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Numerics;
using AcDream.App.Rendering;
using AcDream.Core.Rendering;
using Xunit;
using Xunit.Abstractions;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// #181 excitation probe — the live parked camera wanders ~0.9 mm/frame
/// (launch-176-leakfix.log [flap-sweep]: 19,889 distinct sought values in 20k
/// parked sweeps), which keeps the portal flood's knife-edge admissions
/// flapping. Retail's parked viewer is a bit-exact fixed point (UpdateCamera
/// dead-band `return viewer`).
///
/// This test drives RetailChaseCamera.Update with BIT-IDENTICAL inputs at the
/// live frame rate: if the camera parks bit-stable here, the live wobble comes
/// from its INPUTS (player position/yaw jitter out of GameWindow); if it
/// wobbles here, the camera loop itself fails to reach the fixed point.
/// </summary>
[Collection(CameraDiagnosticsCollection.Name)]
public class Issue181CameraParkStabilityTests
{
private readonly ITestOutputHelper _out;
public Issue181CameraParkStabilityTests(ITestOutputHelper output) => _out = output;
private sealed class PassthroughProbe : ICameraCollisionProbe
{
public CameraSweepResult SweepEye(Vector3 pivot, Vector3 desiredEye, uint cellId, uint selfEntityId, Vector3 playerPos)
=> new(desiredEye, cellId);
}
[Fact]
public void ParkedCamera_StaticInputs_ReachesBitStableFixedPoint()
{
bool savedAlign = CameraDiagnostics.AlignToSlope;
bool savedColl = CameraDiagnostics.CollideCamera;
float savedT = CameraDiagnostics.TranslationStiffness;
float savedR = CameraDiagnostics.RotationStiffness;
try
{
CameraDiagnostics.AlignToSlope = true; // production default
CameraDiagnostics.CollideCamera = true;
CameraDiagnostics.TranslationStiffness = 0.45f;
CameraDiagnostics.RotationStiffness = 0.45f;
var cam = new RetailChaseCamera { CollisionProbe = new PassthroughProbe() };
// Live-like parked pose: static player, static yaw, zero velocity,
// grounded on a flat contact plane, ~1500 fps.
var playerPos = new Vector3(49.5f, -39.9f, -5.9f);
float yaw = 1.83f;
float dt = 1f / 1500f;
void Step() => cam.Update(
playerPosition: playerPos,
playerYaw: yaw,
playerVelocity: Vector3.Zero,
isOnGround: true,
contactPlaneNormal: Vector3.UnitZ,
dt: dt,
cellId: 0x8A020142u,
selfEntityId: 0x5);
// Converge: at α≈0.003/frame the boom needs a few thousand frames
// to settle from the init pose into the dead-band.
for (int i = 0; i < 20000; i++) Step();
Vector3 a = cam.Position;
var fwdA = cam.View; // full view matrix — includes the forward half
// 2000 further frames with bit-identical inputs: every one must be
// the exact fixed point (retail parks verbatim).
float maxDelta = 0f;
Vector3 prev = a;
bool viewChanged = false;
for (int i = 0; i < 2000; i++)
{
Step();
maxDelta = MathF.Max(maxDelta, Vector3.Distance(cam.Position, prev));
prev = cam.Position;
if (cam.View != fwdA) viewChanged = true;
}
_out.WriteLine(FormattableString.Invariant(
$"post-convergence maxConsecDelta={maxDelta * 1e6f:F2}um viewChanged={viewChanged} pos=({cam.Position.X:F7},{cam.Position.Y:F7},{cam.Position.Z:F7})"));
Assert.True(maxDelta == 0f,
$"parked camera must be a bit-exact fixed point, wandered up to {maxDelta * 1e6f:F1}um/frame");
Assert.False(viewChanged, "view matrix must be frozen at park");
}
finally
{
CameraDiagnostics.AlignToSlope = savedAlign;
CameraDiagnostics.CollideCamera = savedColl;
CameraDiagnostics.TranslationStiffness = savedT;
CameraDiagnostics.RotationStiffness = savedR;
}
}
}