acdream/tests/AcDream.App.Tests/World/RuntimeEntityOwnershipTests.cs
Erik 6dc7ba51ee feat(physics): C4 route 4b-3 — remote teleport + cell-less through the canonical placement
Flips the last remote classification (SetPosition: teleport-advanced and
cell-less) onto 4b-1's RuntimeRemotePlacementDriveController, runs retail's
teleport_hook before the placement, and deletes the legacy remote-teleport
machinery. Contract: docs/research/2026-08-04-c4-route-4b-3-contract.md.

Retail: MoveOrTeleport @0x00516330's branch @0x00516386 -> teleport_hook
@0x005163EF -> SetFlags(0x1012) @0x00516414 -> SetPosition @0x00516420 ->
return 1 @0x00516438. The hook @0x00514ED0 runs BEFORE the placement and
regardless of its outcome. Retail places this branch unconditionally, at any
distance and any contact state (arg4 is read only @0x0051638E, after the
branch) — which is what retires AP-137's cell-less enqueue-vs-place delta.

D1 — the classifier's cell-less input is now the PRE-merge committed cell.
Retail's predicate is `this_1->cell == 0`, the BODY's own cell at
MoveOrTeleport entry (this_1 is assigned from this @0x00516334). acdream fed
the POST-merge canonical.FullCellId, which RefreshSnapshot ->
RefreshDerivedState -> SetFullCell has already stamped with the accepted wire
cell; a zero wire cell fails validation into RejectedData first. The shipped
remote cell-less predicate was therefore dead code, not merely different from
remotePlacementRequired. Threaded via a builder overload; route 1's overload
is untouched. The graphical !IsSpatiallyVisible arm of
projectionRequiresTeleportHook is deleted — a presentation predicate with no
retail analogue that fired the teleport machinery on a routine hot path.

Deleted: RemoteTeleportController (605), RemoteTeleportPlacement (85),
RemoteShadowPlacementSynchronizer (49), their 1,709 lines of tests, the
remotePlacementRequired predicate, the TeleportHookRequired plumbing, the
legacy pre-operation ConstrainTo fallback, and the player arm's legacy
!IsGrounded fallback. Net -2,030 lines.

Structural fix (two independent Opus reviews, round 1 FAIL/FAIL): three of the
four MAJORs were one defect — OnPosition carried two parallel inline copies of
the routing tail (player-guid, NPC-guid) that had drifted. Extracted
RunRemoteArmTail (3 call sites) and ApplyWireAirborneLeftoverBookkeeping (2),
both branches now share one implementation.

  A1  ToConstraintArm mapped AirborneSnap -> AirborneNoOperation, so the NPC
      arm armed ConstrainTo ZERO times for an out-of-contact wire-grounded
      creature — a regression this slice introduced while closing a
      structurally identical hole. Now maps to NearInterpolate; switch made
      total with a throwing default proven unreachable.
  R1  D2's write-nothing shape existed on the player arm only; NPC packets
      fell through and wrote the body. Retail makes no player/NPC distinction.
  R2  report_collision_end(this,1) @0x00514F31 was bound to
      ShadowObjects.Suspend, a port of a DIFFERENT retail function
      (remove_shadows_from_cells) that teleport_hook never calls. Now routes
      to RuntimeCollisionReportingState.LeaveWorld, which wraps the private
      ForceEnd in an admission-blocking transaction so a DoCollisionEnd
      callback cannot recreate the contact table.
  R3/A2 A teleported NPC synthesized ServerVelocity from the teleport distance
      (~1,000+ m/s) and planned a run cycle from it. Both the install and
      RemoteServerControlledVelocityCycle.Apply now gate on !isTeleportRoute.

BISECT HAZARD — A1's fix is correct only BECAUSE R1 landed. AirborneSnap is
reachable wire-airborne on the NPC arm only while D2's shape is missing there.
Reverting R1 alone silently inverts A1 into the opposite divergence: arming
where retail returns 0. Revert both or neither.

Also in the velocity hunk: the NPC block's two !IsPlayerGuid(update.Guid)
guards were dropped when it was wrapped in `if (!isTeleportRoute)`. Safe — all
five exit paths of the enclosing IsPlayerGuid block return, so the predicate is
unconditionally false below it — but it was unremarked by both reviews.

Register: AP-137 REWRITTEN (not deleted) to the surviving acdream-only
divergences — null classification during the login window and Rejected*
through UnroutedCatchUp keep a row. AD-42's RemoteTeleportController citation
retired; AP-136/AP-138 writer lists corrected to the two surviving non-Position
rebucket writers; AP-138 gains the teleport arm as a second producer of the
visible-without-collision residual (retirement path remains #309). AP-135 is
untouched and its two airborne bookkeeping writes are preserved on both arms.
AP-131 does not retire; #276 does not close.

Proof obligation 1: ParkCollisionResidents' overlap throw stays unreachable —
the teleport arm adds packets to the same TryBeginExclusiveAuthoredPlacement
one-operation-per-key machinery the far arm uses, opens no new operation shape,
and every DeferredCell outcome cancels synchronously with
restoreCancelledPark: true. The guarded property remains
HasOldPrefixPlacementDebt's stall, not a throw (4b-1's B2 caveat stands).

Correction to an earlier claim: LiveEntityPresentationController's
_activePlacementOwners was NOT write-never at HEAD —
remotePlacementRequired -> BeginPlacement -> Begin -> BeginAuthoritativePlacement
was a live writer chain. It becomes write-never BECAUSE this slice deletes that
chain, which is why deleting the dead half is behaviour-preserving.

Probe: ACDREAM_PROBE_REMOTE_TELEPORT=1 emits one [remote-teleport] line per
routed arm (guid, cause, hook-ran, placement status). TEMPORARY, strip with the
probe family.

Carried, disclosed not fixed: no dedicated bidirectional collision-partner test
for R2 (the wiring, not LeaveWorld itself, is what lacks coverage); the
stress test's teleport step drives hand-written field assignments rather than
the canonical arm; the per-packet runTeleportHook closure allocation (network
path, not the resolve path Slice I's 0 B discipline governs — file before
route 5 adds a fourth call site). B2: IRuntimeCollisionReportObserver has zero
production implementations, so retail's bidirectional DoCollisionEnd half still
reaches no gameplay consumer — this fix closes the wrong-function binding, not
that nobody listens.

Complete Release suite MEASURED at 11,013 passed / 4 skipped / 0 failed
(baseline 11,027/4/0; net -14 = ~33 deleted test cases against ~19 added).
Neither known flake fired (#302 PortalProjectionTests GC-allocation, #308
NakEmissionTests wall-clock).

STILL OWED: the two-client connected gate, which MUST use an NPC/creature
teleport target. Both round-1 MAJORs lived on the NPC arm and the velocity
cycle early-returns for 0x50xxxxxx guids, so a player target structurally
cannot observe A1, A2, or R3.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-04 16:00:10 +02:00

350 lines
13 KiB
C#

using System.Reflection;
using AcDream.App.Physics;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Scene;
using AcDream.App.Rendering.Vfx;
using AcDream.App.Rendering.Wb;
using AcDream.App.Runtime;
using AcDream.App.Streaming;
using AcDream.App.World;
using AcDream.Core.Items;
using AcDream.Runtime;
using AcDream.Runtime.Entities;
namespace AcDream.App.Tests.World;
public sealed class RuntimeEntityOwnershipTests
{
[Fact]
public void LiveEntityRuntime_BorrowsCanonicalRuntimeDirectory()
{
var lifetime = new RuntimeEntityObjectLifetime();
var runtime = new LiveEntityRuntime(
new GpuWorldState(),
new DelegateLiveEntityResourceLifecycle(
static _ => { },
static _ => { }),
lifetime);
FieldInfo owner = typeof(LiveEntityRuntime).GetField(
"_entityObjects",
BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException("Missing Runtime lifetime root.");
FieldInfo directory = typeof(LiveEntityRuntime).GetField(
"_directory",
BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException("Missing canonical entity directory.");
FieldInfo sidecars = typeof(LiveEntityRuntime).GetField(
"_projections",
BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException("Missing App projection sidecar store.");
Assert.Equal(typeof(RuntimeEntityDirectory), directory.FieldType);
Assert.Same(lifetime, owner.GetValue(runtime));
Assert.Same(lifetime.Entities, directory.GetValue(runtime));
Assert.Equal(typeof(LiveEntityProjectionStore), sidecars.FieldType);
}
[Fact]
public void ProductionComposition_HasOneRuntimeEntityObjectConstructionRoot()
{
string root = FindRepositoryRoot();
string appRoot = Path.Combine(root, "src", "AcDream.App");
string runtimeRoot = Path.Combine(root, "src", "AcDream.Runtime");
string[] appSources = Directory.GetFiles(
appRoot,
"*.cs",
SearchOption.AllDirectories);
string[] runtimeSources = Directory.GetFiles(
runtimeRoot,
"*.cs",
SearchOption.AllDirectories);
string[] appObjectAllocators = appSources
.Where(path => !path.Contains(
$"{Path.DirectorySeparatorChar}Studio{Path.DirectorySeparatorChar}",
StringComparison.OrdinalIgnoreCase))
.Where(path => File.ReadAllText(path).Contains(
"new ClientObjectTable",
StringComparison.Ordinal))
.ToArray();
string[] appDirectoryAllocators = appSources
.Where(path => File.ReadAllText(path).Contains(
"new RuntimeEntityDirectory",
StringComparison.Ordinal))
.ToArray();
string[] runtimeObjectAllocators = runtimeSources
.Where(path => File.ReadAllText(path).Contains(
"new ClientObjectTable",
StringComparison.Ordinal))
.Select(path => Path.GetFileName(path)!)
.ToArray();
string[] runtimeDirectoryAllocators = runtimeSources
.Where(path => File.ReadAllText(path).Contains(
"new RuntimeEntityDirectory",
StringComparison.Ordinal))
.Select(path => Path.GetFileName(path)!)
.ToArray();
Assert.Empty(appObjectAllocators);
Assert.Empty(appDirectoryAllocators);
Assert.Equal(
["RuntimeEntityObjectLifetime.cs"],
runtimeObjectAllocators);
Assert.Equal(
["RuntimeEntityObjectLifetime.cs"],
runtimeDirectoryAllocators);
}
[Fact]
public void AppProjectionOwners_UseExactRuntimeKeysAndNoGuidDictionary()
{
FieldInfo[] runtimeFields = typeof(LiveEntityRuntime).GetFields(
BindingFlags.Instance | BindingFlags.NonPublic);
Assert.DoesNotContain(runtimeFields, IsGuidDictionary);
FieldInfo[] storeFields = typeof(LiveEntityProjectionStore).GetFields(
BindingFlags.Instance | BindingFlags.NonPublic);
FieldInfo[] exactStores = storeFields
.Where(field => IsDictionaryWithKey(field, typeof(RuntimeEntityKey)))
.ToArray();
Assert.NotEmpty(exactStores);
Assert.All(
exactStores,
field => Assert.Equal(
typeof(LiveEntityRecord),
field.FieldType.GetGenericArguments()[1]));
Assert.DoesNotContain(storeFields, IsGuidDictionary);
}
[Fact]
public void MaterializedPresentationWorksets_AreExactKeyed()
{
AssertExactKeyFields(
typeof(LiveEntityPresentationController),
"_readyOwners",
"_suspendedShadowOwners");
AssertExactKeyFields(typeof(LiveRenderProjectionJournal), "_byKey");
AssertExactKeyFields(
typeof(EntityEffectController),
"_liveProfiles",
"_readyLiveOwners");
AssertExactKeyFields(
typeof(LiveEntityLightController),
"_trackedOwners",
"_presentOwners");
AssertExactKeyFields(
typeof(EquippedChildRenderController),
"_attachedByChild",
"_pendingUnparentByChild",
"_pendingOrdinaryRemovalByRoot",
"_pendingDetachedRemovalByChild",
"_pendingReparentRemovalByChild",
"_pendingPoseLossRemovalByChild",
"_pendingOrphanRemovalByChild");
AssertExactKeyFields(typeof(LiveEntityAnimationScheduler), "_schedules");
AssertExactKeyFields(typeof(EntitySpawnAdapter), "_ownersByKey");
AssertExactKeyFields(
typeof(LiveEntityLivenessTracker),
"_deadlines",
"_present");
AssertExactKeyFields(
typeof(RemoteMovementObservationTracker),
"_lastMove");
AssertExactKeyFields(
typeof(GpuWorldState),
"_liveProjectionByKey",
"_visibleLiveProjectionCounts",
"_visibilityBeforeMutation");
}
[Fact]
public void AppAssembly_HasNoGuidKeyedLiveEntityRecordDictionary()
{
FieldInfo[] forbidden = typeof(LiveEntityRuntime).Assembly
.GetTypes()
.SelectMany(type => type.GetFields(
BindingFlags.Instance
| BindingFlags.Static
| BindingFlags.Public
| BindingFlags.NonPublic))
.Where(field =>
IsDictionaryWithKey(field, typeof(uint))
&& field.FieldType.GetGenericArguments()[1]
== typeof(LiveEntityRecord))
.ToArray();
Assert.Empty(forbidden);
}
[Fact]
public void ExactOwners_HaveNoRetainedGuidIndex()
{
Type[] exactOwnerTypes =
[
typeof(LiveEntityProjectionStore),
typeof(LiveEntityPresentationController),
typeof(LiveRenderProjectionJournal),
typeof(LiveEntityLightController),
typeof(EquippedChildRenderController),
typeof(LiveEntityAnimationScheduler),
typeof(EntitySpawnAdapter),
typeof(LiveEntityLivenessTracker),
typeof(RemoteMovementObservationTracker),
];
FieldInfo[] forbidden = exactOwnerTypes
.SelectMany(type => type.GetFields(
BindingFlags.Instance
| BindingFlags.NonPublic))
.Where(field =>
field.Name.Contains("Guid", StringComparison.OrdinalIgnoreCase))
.ToArray();
Assert.Empty(forbidden);
}
[Fact]
public void CanonicalRuntimeRecord_HasNoProjectionOrBackendSurface()
{
string[] forbiddenPropertyNames =
[
"WorldEntity",
"AnimationRuntime",
"RemoteMotionRuntime",
"ProjectileRuntime",
"EffectProfile",
"ResourcesRegistered",
"IsSpatiallyProjected",
"IsSpatiallyVisible",
];
PropertyInfo[] properties = typeof(RuntimeEntityRecord).GetProperties(
BindingFlags.Instance | BindingFlags.Public);
Assert.DoesNotContain(
properties,
property => forbiddenPropertyNames.Contains(
property.Name,
StringComparer.Ordinal));
Assert.DoesNotContain(
properties,
property => IsPresentationType(property.PropertyType));
}
[Fact]
public void CurrentRuntimeAdapters_DoNotRetainEntityOrInventoryMirrors()
{
FieldInfo[] adapterFields = typeof(CurrentGameRuntimeAdapter)
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
Assert.Contains(
adapterFields,
field => field.FieldType == typeof(GameRuntime));
Assert.DoesNotContain(
adapterFields,
field => field.FieldType == typeof(LiveEntityRuntime)
|| field.FieldType == typeof(ClientObjectTable)
|| field.FieldType == typeof(IRuntimeEntityView)
|| field.FieldType == typeof(IRuntimeInventoryView)
|| field.FieldType == typeof(RuntimeEntityObjectLifetime));
string root = FindRepositoryRoot();
string liveSource = File.ReadAllText(Path.Combine(
root,
"src",
"AcDream.App",
"World",
"LiveEntityRuntime.cs"));
Assert.DoesNotContain("_entityObjects.PublishEntity", liveSource);
Assert.DoesNotContain("_directory.TryApply", liveSource);
Assert.DoesNotContain("_directory.RemoveActive", liveSource);
string appRuntimeRoot = Path.Combine(
root,
"src",
"AcDream.App",
"Runtime");
Assert.False(File.Exists(Path.Combine(
appRuntimeRoot,
"CurrentGameRuntimeViewAdapter.cs")));
Assert.False(File.Exists(Path.Combine(
appRuntimeRoot,
"CurrentGameRuntimeEventAdapter.cs")));
string rootSource = File.ReadAllText(Path.Combine(
root,
"src",
"AcDream.Runtime",
"GameRuntime.cs"));
Assert.Contains(
"public RuntimeEntityObjectLifetime EntityObjects",
rootSource,
StringComparison.Ordinal);
Assert.Contains(
"public IRuntimeEntityView Entities => EntityObjects.EntityView;",
rootSource,
StringComparison.Ordinal);
Assert.Contains(
"public IRuntimeInventoryView Inventory => EntityObjects.InventoryView;",
rootSource,
StringComparison.Ordinal);
}
private static bool IsPresentationType(Type type)
{
string? ns = type.Namespace;
return ns?.StartsWith("AcDream.App", StringComparison.Ordinal) == true
|| ns?.StartsWith("AcDream.UI", StringComparison.Ordinal) == true
|| ns?.StartsWith("Silk.NET", StringComparison.Ordinal) == true;
}
private static bool IsGuidDictionary(FieldInfo field) =>
IsDictionaryWithKey(field, typeof(uint));
private static void AssertExactKeyFields(
Type owner,
params string[] fieldNames)
{
foreach (string fieldName in fieldNames)
{
FieldInfo field = owner.GetField(
fieldName,
BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException(
$"{owner.Name}.{fieldName} is missing.");
Assert.True(
IsCollectionWithKey(field, typeof(RuntimeEntityKey)),
$"{owner.Name}.{fieldName} must be keyed by RuntimeEntityKey, "
+ $"but was {field.FieldType}.");
}
}
private static bool IsCollectionWithKey(FieldInfo field, Type keyType)
{
if (!field.FieldType.IsGenericType)
return false;
Type generic = field.FieldType.GetGenericTypeDefinition();
return (generic == typeof(Dictionary<,>)
|| generic == typeof(HashSet<>))
&& field.FieldType.GetGenericArguments()[0] == keyType;
}
private static bool IsDictionaryWithKey(FieldInfo field, Type keyType) =>
field.FieldType.IsGenericType
&& field.FieldType.GetGenericTypeDefinition() == typeof(Dictionary<,>)
&& field.FieldType.GetGenericArguments()[0] == keyType;
private static string FindRepositoryRoot()
{
DirectoryInfo? directory = new(AppContext.BaseDirectory);
while (directory is not null)
{
if (File.Exists(Path.Combine(directory.FullName, "AcDream.slnx")))
return directory.FullName;
directory = directory.Parent;
}
throw new DirectoryNotFoundException(
$"Could not find AcDream.slnx above {AppContext.BaseDirectory}.");
}
}