feat(runtime): first-entry conductor sequences local-player world entry

Cutover slice C3a: the resumable transaction that dissolves the C3
flip's circularity finding. RuntimeLocalPlayerFirstEntryState drives the
local player's complete entry in retail's own order — authored-mover
preparation (the makeObject/set_description shape analog, via a pure
no-submit extraction TryPrepareAuthoredMover), the publication chain's
off-canonical Prepare + atomic body Commit against the residence's exact
placement token, the Evaluate/CommitActivation enter-world analog, the
Place-receipt acknowledgement as that act's virtualized completion, and
only then the executor's FIFO drain (retail: enter_world at 93824
strictly precedes ProcessObjectNetBlobs at 93831). Five stages, eight
typed statuses, exactly-once per stage under retry, no second token
copies, and an acknowledge-stage discriminator that separates
not-yet-FIFO-head (retryable) from authority-moved (typed abandonment) —
a mid-flight delete can no longer strand a retry-forever entry.

The residence retirement notification becomes an ordered multicast
(snapshot-iterated per the event-stream precedent), the lifetime
constructs the conductor with a late-bind Publication seam (transactional
unbound failure — no mutation before the throw), deletion/reset converge
the conductor automatically through the same choke points as the
executor, and its active count is in the ownership snapshot and
IsConverged. Dormant: no production Advance caller; GameRuntime binding
is C3c's first act.

Reviewed: retail-conformance PASS (the stage order verified
step-for-step against retail's entry sequence; the live-controller-on-
abandonment invariant proven structurally enforced and retail-correct —
retail has no entry-flow rollback) + architecture/adversarial PASS after
one fix round (acknowledge-stage authority discrimination; the wiring
fold; two prescribed pre-C3c hardenings). Runtime 948/948; complete
Release solution green across all nine projects.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-02 09:43:15 +02:00
parent 874d94bf34
commit 960373df2e
6 changed files with 1816 additions and 29 deletions

View file

@ -4,6 +4,7 @@ using AcDream.Core.Items;
using AcDream.Core.Net;
using AcDream.Core.Net.Messages;
using AcDream.Core.Physics;
using AcDream.Runtime.Gameplay;
using AcDream.Runtime.Physics;
namespace AcDream.Runtime.Entities;
@ -56,7 +57,14 @@ public readonly record struct RuntimeEntityObjectOwnershipSnapshot(
/// SAME underlying receipt stream - unlike ReplayFailureCount above,
/// this is NOT a diagnostic-only counter.
/// </summary>
int PendingCompletionReceiptCount = 0)
int PendingCompletionReceiptCount = 0,
/// <summary>
/// C3a/F2: outstanding <c>AcDream.Runtime.Gameplay.RuntimeLocalPlayerFirstEntryState</c>
/// tracked keys - dormant (no production caller of its own
/// <c>Advance</c>), but fully constructed/wired like every other owner
/// here, so its own ownership must converge to zero the same way.
/// </summary>
int LocalPlayerFirstEntryActiveCount = 0)
{
public bool IsConverged =>
IsDisposed
@ -78,6 +86,7 @@ public readonly record struct RuntimeEntityObjectOwnershipSnapshot(
&& InitialCreateResidenceLeaseCount == 0
&& InitialCreateExecutorProgressCount == 0
&& PendingCompletionReceiptCount == 0
&& LocalPlayerFirstEntryActiveCount == 0
&& StreamSubscriberCount == 0
&& PlacementStreamSubscriberCount == 0
&& PendingDispatchCount == 0
@ -157,6 +166,16 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
RegisterEntityWithInitialResidence(spawn, isLocalPlayer),
(canonical, version, spawn, replaceGeneration) =>
ApplyAcceptedSpawn(canonical, version, spawn, replaceGeneration));
// C3a/F2: dormant - no production caller of its own Advance - but
// constructed and wired exactly like the executor above so its
// ownership converges the same way. RuntimeLocalPlayerPhysicsPublicationState
// does not exist yet at this point (GameRuntime builds
// RuntimeLocalPlayerMovementState, then attaches its publication,
// only after this lifetime); BindPublication supplies it later.
LocalPlayerFirstEntry = new RuntimeLocalPlayerFirstEntryState(
InitialCreateResidences,
InitialCreateExecution,
Physics);
// Round 3 B3: every residence retirement path - not only the
// executor's own DiscardProgress calls - must converge the
// executor's progress AND its separately-tracked pending
@ -165,6 +184,12 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
// residence state referencing the executor type directly.
InitialCreateResidences.BindRetirementNotification(
key => InitialCreateExecution.DiscardProgress(key));
// C3a/F2: the SAME multicast retirement notification also reaps the
// first-entry conductor's tracked progress - see
// RuntimeInitialCreateResidenceState.BindRetirementNotification's
// updated doc comment for why this is now multicast.
InitialCreateResidences.BindRetirementNotification(
key => LocalPlayerFirstEntry.Forget(key));
// F2: reaps the executor's completion-receipt correlation entry
// exactly when a host acknowledges the ExecutorCompleted receipt it
// correlates - mirrors the residence-retirement binding immediately
@ -210,6 +235,16 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
RegisterEntityWithInitialResidence(spawn, isLocalPlayer),
(canonical, version, spawn, replaceGeneration) =>
ApplyAcceptedSpawn(canonical, version, spawn, replaceGeneration));
// C3a/F2: dormant - no production caller of its own Advance - but
// constructed and wired exactly like the executor above so its
// ownership converges the same way. RuntimeLocalPlayerPhysicsPublicationState
// does not exist yet at this point (GameRuntime builds
// RuntimeLocalPlayerMovementState, then attaches its publication,
// only after this lifetime); BindPublication supplies it later.
LocalPlayerFirstEntry = new RuntimeLocalPlayerFirstEntryState(
InitialCreateResidences,
InitialCreateExecution,
Physics);
// Round 3 B3: every residence retirement path - not only the
// executor's own DiscardProgress calls - must converge the
// executor's progress AND its separately-tracked pending
@ -218,6 +253,12 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
// residence state referencing the executor type directly.
InitialCreateResidences.BindRetirementNotification(
key => InitialCreateExecution.DiscardProgress(key));
// C3a/F2: the SAME multicast retirement notification also reaps the
// first-entry conductor's tracked progress - see
// RuntimeInitialCreateResidenceState.BindRetirementNotification's
// updated doc comment for why this is now multicast.
InitialCreateResidences.BindRetirementNotification(
key => LocalPlayerFirstEntry.Forget(key));
// F2: reaps the executor's completion-receipt correlation entry
// exactly when a host acknowledges the ExecutorCompleted receipt it
// correlates - mirrors the residence-retirement binding immediately
@ -263,6 +304,16 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
RegisterEntityWithInitialResidence(spawn, isLocalPlayer),
(canonical, version, spawn, replaceGeneration) =>
ApplyAcceptedSpawn(canonical, version, spawn, replaceGeneration));
// C3a/F2: dormant - no production caller of its own Advance - but
// constructed and wired exactly like the executor above so its
// ownership converges the same way. RuntimeLocalPlayerPhysicsPublicationState
// does not exist yet at this point (GameRuntime builds
// RuntimeLocalPlayerMovementState, then attaches its publication,
// only after this lifetime); BindPublication supplies it later.
LocalPlayerFirstEntry = new RuntimeLocalPlayerFirstEntryState(
InitialCreateResidences,
InitialCreateExecution,
Physics);
// Round 3 B3: every residence retirement path - not only the
// executor's own DiscardProgress calls - must converge the
// executor's progress AND its separately-tracked pending
@ -271,6 +322,12 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
// residence state referencing the executor type directly.
InitialCreateResidences.BindRetirementNotification(
key => InitialCreateExecution.DiscardProgress(key));
// C3a/F2: the SAME multicast retirement notification also reaps the
// first-entry conductor's tracked progress - see
// RuntimeInitialCreateResidenceState.BindRetirementNotification's
// updated doc comment for why this is now multicast.
InitialCreateResidences.BindRetirementNotification(
key => LocalPlayerFirstEntry.Forget(key));
// F2: reaps the executor's completion-receipt correlation entry
// exactly when a host acknowledges the ExecutorCompleted receipt it
// correlates - mirrors the residence-retirement binding immediately
@ -295,6 +352,7 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
{ get; }
internal RuntimeInitialCreateContinuationExecutor InitialCreateExecution
{ get; }
internal RuntimeLocalPlayerFirstEntryState LocalPlayerFirstEntry { get; }
public RuntimeEntityObjectOwnershipSnapshot CaptureOwnership()
{
@ -330,7 +388,8 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
parents.DeferredAcceptedRelationCount,
InitialCreateExecution.ReplayFailureCount,
InitialCreateExecution.LastReplayFailure is not null,
InitialCreateExecution.PendingCompletionReceiptCount);
InitialCreateExecution.PendingCompletionReceiptCount,
LocalPlayerFirstEntry.CaptureOwnership().ActiveCount);
}
public void BindEventContext(
@ -1674,6 +1733,7 @@ public sealed class RuntimeEntityObjectLifetime : IDisposable
RuntimeEntityRecord[] active = Entities.ActiveRecords.ToArray();
InitialCreateResidences.Clear();
InitialCreateExecution.DiscardAll();
LocalPlayerFirstEntry.DiscardAll();
Physics.CollisionReports.LeaveWorldBatch(active);
Physics.ResetSessionPhysics();
Entities.BeginSessionClear();

View file

@ -489,7 +489,7 @@ internal sealed class RuntimeInitialCreateResidenceState
private readonly Dictionary<RuntimeEntityKey, Entry> _entries = [];
private readonly Dictionary<RuntimeEntityKey, CompletedEntry> _completed = [];
private Func<RuntimeGenerationToken>? _generation;
private Action<RuntimeEntityKey>? _retirementNotification;
private readonly List<Action<RuntimeEntityKey>> _retirementNotifications = [];
private ulong _nextLeaseId;
internal RuntimeInitialCreateResidenceState(
@ -524,17 +524,36 @@ internal sealed class RuntimeInitialCreateResidenceState
/// leave the executor's progress AND its separately-tracked pending
/// continuation placement token orphaned - this class owns no reference
/// to the executor type, so the lifetime binds a plain delegate here
/// instead.
/// instead. Multicast (ordered invocation list, registration order) so a
/// second independent per-key owner (e.g. the local-player first-entry
/// conductor) can subscribe to the SAME retirements the executor already
/// does, without either overwriting the other's binding.
/// </summary>
internal void BindRetirementNotification(Action<RuntimeEntityKey> notify)
{
ArgumentNullException.ThrowIfNull(notify);
if (_retirementNotification is not null)
{
throw new InvalidOperationException(
"The initial Create residence retirement notification is already bound.");
}
_retirementNotification = notify;
_retirementNotifications.Add(notify);
}
/// <summary>
/// H1: snapshots the subscriber list before invoking anything, mirroring
/// <see cref="RuntimeEntityObjectEventStream"/>'s own copy-on-write
/// dispatch precedent. A subscriber binding a NEW notification from
/// inside a retirement callback it is itself receiving (e.g. a future
/// third, runtime-bound subscriber added at C3c) must not corrupt or be
/// skipped by THIS iteration - <c>_retirementNotifications</c> is a
/// plain <see cref="List{T}"/>, so iterating it directly while
/// <see cref="BindRetirementNotification"/> appends to it mid-loop would
/// throw <see cref="InvalidOperationException"/> ("Collection was
/// modified"). <c>ToArray()</c> is the right granularity here (unlike
/// the event stream's <see cref="Volatile"/>-guarded array swap) because
/// binding only ever happens a handful of times at construction, never
/// on a hot per-frame path.
/// </summary>
private void NotifyRetirement(RuntimeEntityKey key)
{
foreach (Action<RuntimeEntityKey> notify in _retirementNotifications.ToArray())
notify(key);
}
internal bool CanAcceptCreate(WorldSession.EntitySpawn incoming)
@ -1003,7 +1022,7 @@ internal sealed class RuntimeInitialCreateResidenceState
lease = entry.Lease;
cancellation = _setPosition.ForgetExactPlacement(
lease.Placement);
_retirementNotification?.Invoke(key);
NotifyRetirement(key);
return true;
}
if (record.Key is { } completedKey
@ -1016,7 +1035,7 @@ internal sealed class RuntimeInitialCreateResidenceState
lease = completed.Lease;
cancellation = _setPosition.ForgetExactPlacement(
lease.Placement);
_retirementNotification?.Invoke(completedKey);
NotifyRetirement(completedKey);
return true;
}
lease = default;
@ -1052,13 +1071,10 @@ internal sealed class RuntimeInitialCreateResidenceState
{
_setPosition.PublishCancellation(cancellations[index]);
}
if (_retirementNotification is { } notify)
{
foreach (Entry entry in active)
notify(entry.Lease.Token.Entity);
foreach (CompletedEntry entry in completed)
notify(entry.Receipt.Token.Entity);
}
foreach (Entry entry in active)
NotifyRetirement(entry.Lease.Token.Entity);
foreach (CompletedEntry entry in completed)
NotifyRetirement(entry.Receipt.Token.Entity);
}
internal RuntimeInitialCreateResidenceOwnershipSnapshot CaptureOwnership() =>
@ -1245,7 +1261,7 @@ internal sealed class RuntimeInitialCreateResidenceState
RuntimePlacementCancellationReceipt cancellation =
_setPosition.ForgetExactPlacement(entry.Lease.Placement);
_setPosition.PublishCancellation(cancellation);
_retirementNotification?.Invoke(key);
NotifyRetirement(key);
}
private void Retire(CompletedEntry entry)
@ -1255,6 +1271,6 @@ internal sealed class RuntimeInitialCreateResidenceState
RuntimePlacementCancellationReceipt cancellation =
_setPosition.ForgetExactPlacement(entry.Lease.Placement);
_setPosition.PublishCancellation(cancellation);
_retirementNotification?.Invoke(key);
NotifyRetirement(key);
}
}

View file

@ -0,0 +1,690 @@
using AcDream.Content;
using AcDream.Runtime.Entities;
using AcDream.Runtime.Physics;
namespace AcDream.Runtime.Gameplay;
/// <summary>
/// Typed yields for <see cref="RuntimeLocalPlayerFirstEntryState.Advance"/>.
/// Mirrors the executor's own <c>RuntimeInitialCreateExecutionStatus</c>
/// shape (terminal Completed/RejectedToken/RejectedAuthority plus named
/// retryable yields) rather than inventing a parallel vocabulary.
/// </summary>
internal enum RuntimeLocalPlayerFirstEntryStatus : byte
{
/// <summary>
/// The underlying <see cref="RuntimeInitialCreateContinuationExecutor.Execute"/>
/// call reported <c>Completed</c>: residence consumed, initial tail and
/// FIFO drained, ExecutorCompleted receipt dispatched on the placement
/// stream. Terminal; the conductor's own progress entry is removed.
/// </summary>
Completed,
/// <summary>
/// The authored-mover Setup read
/// (<see cref="RuntimeSetPositionState.TryPrepareAuthoredMover"/>) is not
/// yet available (<c>RetrySetupUnavailable</c>) — the prepared-asset
/// package has not landed. Retry <see cref="RuntimeLocalPlayerFirstEntryState.Advance"/>
/// with the same arguments once it has; no Runtime state changed.
/// </summary>
AwaitingCollisionSource,
/// <summary>
/// <see cref="RuntimeLocalPlayerPhysicsPublicationState.EvaluateActivation"/>
/// or <see cref="RuntimeLocalPlayerPhysicsPublicationState.CommitActivation"/>
/// yielded <c>DeferredCell</c> or a retryable <c>RejectedPlacement</c> —
/// the destination cell's collision generation is not ready, or the
/// placement needs re-evaluation after some other change. Retry later
/// (e.g. on a collision-generation wake); the dormant activation lease
/// itself remains intact and is re-driven from the same stage.
/// </summary>
AwaitingActivation,
/// <summary>
/// The activation committed but its <c>Place</c> projection has not been
/// acknowledged yet — either <see cref="RuntimeSetPositionState.AcknowledgeProjection"/>
/// was not (yet) the exact FIFO head, or the subsequent
/// <see cref="RuntimeInitialCreateContinuationExecutor.Execute"/> call
/// still observed <c>PendingPlacement</c> from
/// <see cref="RuntimeInitialCreateResidenceState.Complete"/>. Retry the
/// same stage.
/// </summary>
AwaitingReceiptAcknowledgement,
/// <summary>
/// Passthrough of the executor's own <c>AwaitingContinuationPlacement</c>
/// — a later FIFO continuation (a Position update accepted while this
/// entity's initial placement was in flight) needs its own authored
/// placement prepared/submitted/acknowledged before the drain can
/// finish. Entirely the executor's own concern from this point forward;
/// the conductor's job (residence -> publication -> Execute) is done as
/// soon as it reaches this yield.
/// </summary>
AwaitingContinuationPlacement,
/// <summary>
/// A reentrant <see cref="RuntimeLocalPlayerFirstEntryState.Advance"/>
/// call for the SAME entity arrived while an outer call for it was still
/// on the stack (mirrors the executor's own <c>_executing</c> fail-closed
/// guard). Not a Runtime-state rejection — retry once the outer call has
/// returned.
/// </summary>
Contention,
/// <summary>The residence/placement token no longer matches anything tracked.</summary>
RejectedToken,
/// <summary>
/// An authority-shaped failure (stale epoch/session/identity, deleted or
/// replaced record, GUID reuse, disposed identity, or an inner
/// currency check failing during a reentrant callback). Abandoned: the
/// conductor's own in-flight publication candidate/activation (if any)
/// is discarded through the shared choke points and its progress entry
/// is removed. The caller must begin a fresh first-entry sequence
/// (a new residence lease) rather than retry this exact call.
/// </summary>
RejectedAuthority,
}
internal readonly record struct RuntimeLocalPlayerFirstEntryOwnershipSnapshot(
int ActiveCount)
{
internal bool IsConverged => ActiveCount == 0;
}
/// <summary>
/// The dormant, resumable Runtime transaction that dissolves C3's Finding B:
/// the local player's initial residence lease opens its SetPosition operation
/// at Create time, but nothing wires the mover-preparation ->
/// <see cref="RuntimeLocalPlayerPhysicsPublicationState"/> body/controller
/// attach -> placement acknowledgement -> FIFO drain sequence together into
/// one driveable state machine. This class ORCHESTRATES the existing,
/// already-tested residence
/// (<see cref="RuntimeInitialCreateResidenceState"/>), publication
/// (<see cref="RuntimeLocalPlayerPhysicsPublicationState"/>), mover
/// (<see cref="RuntimeSetPositionState.TryPrepareAuthoredMover"/>), and
/// executor (<see cref="RuntimeInitialCreateContinuationExecutor"/>)
/// machinery — it reimplements none of their validation and bypasses none of
/// their staged semantics.
///
/// Required order (campaign handoff route-1,
/// docs/research/2026-07-31-remaining-physics-campaign-handoff.md:280-292):
/// residence Begin (already done at registration, before this class is ever
/// invoked) -&gt; authored-mover preparation (Setup read + PrepareMover, which
/// MUST precede publication Prepare —
/// <see cref="RuntimeLocalPlayerPhysicsPublicationState.Prepare"/>'s own
/// <c>CanPrepare</c> gate requires
/// <see cref="RuntimeSetPositionState.IsExactPreparedPlacementCurrent"/> to
/// already be true) -&gt; publication Prepare -&gt; publication Commit (the
/// <see cref="RuntimeSetPositionState.PrepareDormantLocalActivationOwnership"/>
/// seam attaches the body) -&gt; activation Evaluate/Commit/Finalize -&gt;
/// Place-receipt acknowledgement -&gt; <see cref="RuntimeInitialCreateContinuationExecutor.Execute"/>
/// (FIFO drain) -&gt; ExecutorCompleted receipt.
///
/// Once <see cref="RuntimeSetPositionState.PrepareDormantLocalActivationOwnership"/>
/// sets an operation's <c>DormantLocalActivation</c> flag,
/// <see cref="RuntimeSetPositionState.SubmitPreparedPlacement"/> (and the
/// fused <see cref="RuntimeSetPositionState.TryPrepareAndSubmitAuthoredPlacement"/>)
/// must never be called against it again — see <c>RetryDeferred</c>'s "must
/// never bypass that path through the ordinary remote CommitCanonical tail"
/// comment — so this class calls the mover-only
/// <see cref="RuntimeSetPositionState.TryPrepareAuthoredMover"/> half instead
/// and never the fused method.
///
/// Dormant by design: <see cref="RuntimeEntityObjectLifetime"/> fully
/// constructs and wires this class (construction, publication binding,
/// retirement fan-out, bulk session-clear cleanup, ownership fold) exactly
/// like every other owner it builds, but nothing calls
/// <see cref="Advance"/> in production — a later slice wires a host to drive
/// it.
/// </summary>
internal sealed class RuntimeLocalPlayerFirstEntryState
{
private enum Stage : byte
{
/// <summary>No progress yet, or the mover has not been prepared.</summary>
AwaitingMoverPreparation,
/// <summary>Mover command in hand; publication Prepare+Commit not run yet.</summary>
MoverPrepared,
/// <summary>
/// Publication Prepare+Commit succeeded (the body/controller are
/// attached to the canonical record); Evaluate+CommitActivation not
/// yet reached <c>Committed</c>. Also the retry point for
/// <c>DeferredCell</c>/<c>RejectedPlacement</c>.
/// </summary>
PublicationCommitted,
/// <summary>
/// CommitActivation reached <c>Committed</c>; the Place projection is
/// known but not yet acknowledged.
/// </summary>
ActivationCommitted,
/// <summary>
/// The Place projection has been acknowledged. Only
/// <see cref="RuntimeInitialCreateContinuationExecutor.Execute"/>
/// remains; re-acknowledging the same (already-consumed) token would
/// fail, so this stage is never re-entered by the acknowledgement
/// step.
/// </summary>
Acknowledged,
}
private sealed class Progress
{
internal required ulong LeaseId { get; init; }
internal Stage Stage { get; set; } = Stage.AwaitingMoverPreparation;
internal RuntimeSetPositionCommand PreparedCommand { get; set; }
internal RuntimeLocalPlayerPhysicsPublicationToken PublicationToken
{ get; set; }
internal RuntimeLocalPlayerPhysicsActivationToken ActivationToken
{ get; set; }
internal RuntimePlacementProjectionToken Projection { get; set; }
}
private readonly RuntimeInitialCreateResidenceState _residences;
private readonly RuntimeInitialCreateContinuationExecutor _executor;
private readonly RuntimePhysicsState _physics;
private RuntimeLocalPlayerPhysicsPublicationState? _publication;
private readonly Dictionary<RuntimeEntityKey, Progress> _progress = [];
private readonly HashSet<RuntimeEntityKey> _executing = [];
/// <summary>
/// F2: <see cref="RuntimeEntityObjectLifetime"/> constructs this class
/// (alongside the residence and executor it also owns) BEFORE
/// <see cref="RuntimeLocalPlayerPhysicsPublicationState"/> exists —
/// <c>GameRuntime</c> creates <c>RuntimeLocalPlayerMovementState</c> and
/// attaches its physics publication only after the entity-object lifetime
/// is already built. This mirrors the SAME late-bind pattern already
/// used throughout this class family (<c>BindGeneration</c>,
/// <c>BindRetirementNotification</c>, <c>BindLiveInputs</c>,
/// <c>RuntimeLocalPlayerMovementState.PhysicsPublication</c>'s own
/// throws-if-unbound accessor) rather than requiring the caller to
/// construct things out of their natural order.
/// </summary>
internal RuntimeLocalPlayerFirstEntryState(
RuntimeInitialCreateResidenceState residences,
RuntimeInitialCreateContinuationExecutor executor,
RuntimePhysicsState physics)
{
_residences = residences
?? throw new ArgumentNullException(nameof(residences));
_executor = executor
?? throw new ArgumentNullException(nameof(executor));
_physics = physics
?? throw new ArgumentNullException(nameof(physics));
}
internal void BindPublication(
RuntimeLocalPlayerPhysicsPublicationState publication)
{
ArgumentNullException.ThrowIfNull(publication);
if (_publication is not null)
{
throw new InvalidOperationException(
"The local-player first-entry conductor's publication owner is already bound.");
}
_publication = publication;
}
private RuntimeLocalPlayerPhysicsPublicationState Publication =>
_publication ?? throw new InvalidOperationException(
"The local-player first-entry conductor's publication owner is not yet bound.");
/// <summary>
/// One resumable step. Callers pass the SAME arguments on every retry;
/// this method re-reads currency from the owning states on every entry
/// rather than trusting anything cached beyond its own stage cursor and
/// the exact token/receipt/projection structs each owning method itself
/// requires as arguments — there is no other source for those; they are
/// the "exact keys" this class carries, not a second copy of any owning
/// state's internal record.
/// </summary>
internal RuntimeLocalPlayerFirstEntryStatus Advance(
RuntimeEntityRecord record,
in RuntimeInitialCreateResidenceToken residenceToken,
PlayerMovementConstructionOptions options,
in RuntimeLocalPlayerPhysicsActivationPreparation activationPreparation,
IPreparedCollisionSource collisionSource,
double gameTime,
in RuntimeInitialCreateExecutionInputs inputs,
out RuntimeInitialCreateExecutionReceipt receipt)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(collisionSource);
receipt = default;
if (!residenceToken.IsValid || record.Key is not { } key)
return RuntimeLocalPlayerFirstEntryStatus.RejectedToken;
// Mirrors RuntimeInitialCreateContinuationExecutor.Execute's own
// _executing.Add(key) guard: a synchronous reentrant call for the
// SAME entity (e.g. from a collision-report/placement observer
// invoked mid-Advance) fails closed rather than interleaving two
// drains of the same stage machine.
if (!_executing.Add(key))
return RuntimeLocalPlayerFirstEntryStatus.Contention;
try
{
return AdvanceCore(
record,
residenceToken,
options,
activationPreparation,
collisionSource,
gameTime,
inputs,
key,
out receipt);
}
finally
{
_executing.Remove(key);
}
}
private RuntimeLocalPlayerFirstEntryStatus AdvanceCore(
RuntimeEntityRecord record,
in RuntimeInitialCreateResidenceToken residenceToken,
PlayerMovementConstructionOptions options,
in RuntimeLocalPlayerPhysicsActivationPreparation activationPreparation,
IPreparedCollisionSource collisionSource,
double gameTime,
in RuntimeInitialCreateExecutionInputs inputs,
RuntimeEntityKey key,
out RuntimeInitialCreateExecutionReceipt receipt)
{
receipt = default;
// H2: fail transactionally, before any state mutation, if
// Publication has not been bound yet. Without this upfront check,
// an unbound call could still get as far as authored-mover
// preparation (which mutates RuntimeSetPositionState's own
// _preparedMovers) and creating THIS class's own Progress entry
// (stored into _progress) before the first Publication dereference
// (inside the MoverPrepared stage below) throws — leaving a
// poisoned Progress entry that a later, unrelated Discard/DiscardAll
// call (from a retirement notification or session-clear fan-out)
// would ALSO throw on. Referencing the accessor here throws
// immediately with nothing yet mutated.
_ = Publication;
_progress.TryGetValue(key, out Progress? progress);
// ABA/GUID-reuse guard, exactly like the executor's own Progress
// reconciliation: an existing entry for a DIFFERENT (older or
// reused) lease id can never be resumed by this call.
if (progress is not null && progress.LeaseId != residenceToken.LeaseId)
{
Discard(key);
progress = null;
}
if (progress is null || progress.Stage is Stage.AwaitingMoverPreparation)
{
if (!_residences.TryGetCurrent(
record,
out RuntimeInitialCreateResidenceLease lease)
|| lease.Token != residenceToken)
{
// No progress was ever tracked for this key under this exact
// lease — mirrors RuntimeInitialCreateResidenceState.Complete's
// own convention (a token matching neither its active nor its
// completed table is RejectedToken, not RejectedAuthority).
// Only abandon (RejectedAuthority) when THIS class was
// actually tracking in-flight publication/activation state
// that must now be discarded.
if (progress is null)
return RuntimeLocalPlayerFirstEntryStatus.RejectedToken;
Discard(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
if (!lease.Route.PerformsSetPosition)
{
// Parented/PickedUp residence — never true for a real
// login, but kept for structural completeness: no
// SetPosition operation exists at all, so there is nothing
// for the publication chain to attach a body to. Skip
// straight to Execute (idempotent/retryable on its own).
progress ??= new Progress { LeaseId = residenceToken.LeaseId };
progress.Stage = Stage.Acknowledged;
_progress[key] = progress;
return RunExecute(record, residenceToken, inputs, key, out receipt);
}
RuntimeSetPositionMoverPreparationStatus moverStatus = _physics
.SetPosition.TryPrepareAuthoredMover(
record,
lease.Placement,
lease.Route.OperationKind,
lease.Route.SetPositionFlags,
collisionSource,
gameTime,
out RuntimeSetPositionCommand command);
if (moverStatus
== RuntimeSetPositionMoverPreparationStatus.RetrySetupUnavailable)
{
return RuntimeLocalPlayerFirstEntryStatus
.AwaitingCollisionSource;
}
if (moverStatus != RuntimeSetPositionMoverPreparationStatus.Prepared)
{
if (progress is not null)
Discard(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
progress ??= new Progress { LeaseId = residenceToken.LeaseId };
progress.PreparedCommand = command;
progress.Stage = Stage.MoverPrepared;
_progress[key] = progress;
}
if (progress.Stage is Stage.MoverPrepared)
{
if (!_residences.TryGetCurrent(
record,
out RuntimeInitialCreateResidenceLease lease)
|| lease.Token != residenceToken)
{
Discard(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
RuntimeLocalPlayerPhysicsPublicationStatus prepareStatus =
Publication.Prepare(
record,
lease.Placement,
progress.PreparedCommand,
options,
activationPreparation,
out RuntimeLocalPlayerPhysicsPublicationToken pubToken);
if (prepareStatus
!= RuntimeLocalPlayerPhysicsPublicationStatus.Prepared)
{
// Prepare mutates nothing canonical on rejection (its own
// second CanPrepare recheck discards any just-built
// candidate itself); there is nothing further for this
// class to undo beyond dropping its own progress entry.
Discard(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
progress.PublicationToken = pubToken;
RuntimeLocalPlayerPhysicsPublicationStatus commitStatus =
Publication.Commit(
pubToken,
out RuntimeLocalPlayerPhysicsActivationToken activationToken);
if (commitStatus != RuntimeLocalPlayerPhysicsPublicationStatus.Committed)
{
Discard(key);
return commitStatus
is RuntimeLocalPlayerPhysicsPublicationStatus.RejectedToken
? RuntimeLocalPlayerFirstEntryStatus.RejectedToken
: RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
progress.ActivationToken = activationToken;
progress.Stage = Stage.PublicationCommitted;
}
if (progress.Stage is Stage.PublicationCommitted)
{
// A single combined retry point for Evaluate+CommitActivation.
// Every publication test that hits DeferredCell/RejectedPlacement
// WITHOUT an intervening CommitActivation call chains both calls
// together and retries both together; running EvaluateActivation
// again before every CommitActivation retry is safe even for
// CommitActivation's own internal AwaitingFinalShadowPreparation
// resumption (its top-of-method check re-validates
// activation.Receipt == receipt, which a fresh Evaluate call
// satisfies, before consulting the untouched stored
// PendingFinalCommit).
//
// EvaluateActivation's DeferredCell status is overloaded: once a
// PRIOR CommitActivation call has already registered this lease
// as awaiting a specific cell/collision generation
// (IsDormantLocalActivationAwaitingCell), a REPEATED
// EvaluateActivation call that is still not ready returns
// DeferredCell WITHOUT ever populating receipt (it stays
// default/invalid) — see
// DeferredCommitWaitsThenRearmsSameLeaseAfterExactGenerationWake
// in the publication test suite, which asserts exactly
// `waiting.IsValid == false` on that repeat call and never feeds
// it to CommitActivation. Calling CommitActivation with that
// invalid receipt would hit its own `!receipt.IsValid` guard and
// incorrectly report RejectedAuthority instead of "still
// waiting" — so this class must check validity first and simply
// yield AwaitingActivation again without calling CommitActivation
// at all in that case.
RuntimeLocalPlayerPhysicsActivationStatus evalStatus =
Publication.EvaluateActivation(
progress.ActivationToken,
out RuntimeLocalPlayerPhysicsActivationReceipt evalReceipt);
if (evalStatus is
RuntimeLocalPlayerPhysicsActivationStatus.RejectedToken
or RuntimeLocalPlayerPhysicsActivationStatus.RejectedAuthority)
{
Discard(key);
return evalStatus
is RuntimeLocalPlayerPhysicsActivationStatus.RejectedToken
? RuntimeLocalPlayerFirstEntryStatus.RejectedToken
: RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
if (!evalReceipt.IsValid)
{
// DeferredCell with nothing to commit — the destination
// cell/collision generation genuinely is not resolvable yet.
return RuntimeLocalPlayerFirstEntryStatus.AwaitingActivation;
}
RuntimeDormantSetPositionCommitStatus commitActivationStatus =
Publication.CommitActivation(
evalReceipt,
out RuntimePlacementProjectionToken projection);
switch (commitActivationStatus)
{
case RuntimeDormantSetPositionCommitStatus.Committed:
progress.Projection = projection;
progress.Stage = Stage.ActivationCommitted;
break;
case RuntimeDormantSetPositionCommitStatus.DeferredCell:
case RuntimeDormantSetPositionCommitStatus.RejectedPlacement:
// Stage stays PublicationCommitted — retry re-runs both
// EvaluateActivation and CommitActivation next Advance.
return RuntimeLocalPlayerFirstEntryStatus.AwaitingActivation;
default:
Discard(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
}
if (progress.Stage is Stage.ActivationCommitted)
{
if (!_physics.SetPosition.AcknowledgeProjection(
progress.Projection))
{
// A failed acknowledge is retryable ONLY while nothing has
// moved authority out from under this exact projection — a
// genuinely later entity simply sitting ahead of ours in the
// FIFO. It is NOT automatically retryable: a mid-flight
// delete (TryAcceptDelete -> CompleteProjectionRetirement ->
// Physics.SetPosition.Forget -> CancelCoreDeferred) rewrites
// the SAME pending slot from Place to Discard with a bumped
// Revision, so the exact struct this class cached in
// progress.Projection can never match the FIFO head again —
// without this check, AcknowledgeProjection would fail
// forever and this progress entry would never converge.
if (!IsAcknowledgementStillPending(
record, residenceToken, progress.Projection))
{
Discard(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
return RuntimeLocalPlayerFirstEntryStatus
.AwaitingReceiptAcknowledgement;
}
progress.Stage = Stage.Acknowledged;
}
return RunExecute(record, residenceToken, inputs, key, out receipt);
}
/// <summary>
/// Re-validates authority after a failed acknowledge. Two independent
/// checks, either of which failing means authority moved and this class
/// must abandon rather than keep retrying forever: (1) the residence
/// lease this whole sequence began under must still be exactly current
/// (mirrors the stage0/stage1 checks — a delete or reset retires it);
/// (2) if the FIFO head belongs to THIS entity at all, it must still be
/// the exact Place projection this class is holding — a head that
/// belongs to us but is no longer that exact token (rewritten to
/// Discard, or to a later revision) means our specific placement was
/// superseded even if the residence lookup transiently still resolves.
/// A head belonging to a DIFFERENT entity is the genuine "not yet our
/// turn" case and must stay retryable. This reads the Runtime-internal
/// <see cref="RuntimeSetPositionState.TryPeekProjection"/> directly
/// rather than through the public, generation-gated
/// <see cref="RuntimePlacementProjectionChannel"/> — this class is part
/// of Runtime, not an external host crossing that boundary, exactly like
/// its existing direct <see cref="RuntimeSetPositionState.AcknowledgeProjection"/>
/// call above.
/// </summary>
private bool IsAcknowledgementStillPending(
RuntimeEntityRecord record,
in RuntimeInitialCreateResidenceToken residenceToken,
in RuntimePlacementProjectionToken expected)
{
if (!_residences.TryGetCurrent(
record,
out RuntimeInitialCreateResidenceLease lease)
|| lease.Token != residenceToken)
{
return false;
}
if (_physics.SetPosition.TryPeekProjection(
out RuntimePlacementProjectionSnapshot head)
&& head.Token.Entity == expected.Entity
&& (head.Kind is not RuntimePlacementProjectionKind.Place
|| head.Token != expected))
{
return false;
}
return true;
}
private RuntimeLocalPlayerFirstEntryStatus RunExecute(
RuntimeEntityRecord record,
in RuntimeInitialCreateResidenceToken residenceToken,
in RuntimeInitialCreateExecutionInputs inputs,
RuntimeEntityKey key,
out RuntimeInitialCreateExecutionReceipt receipt)
{
RuntimeInitialCreateExecutionStatus executeStatus = _executor.Execute(
record, residenceToken, inputs, out receipt);
switch (executeStatus)
{
case RuntimeInitialCreateExecutionStatus.Completed:
_progress.Remove(key);
return RuntimeLocalPlayerFirstEntryStatus.Completed;
case RuntimeInitialCreateExecutionStatus.PendingPlacement:
return RuntimeLocalPlayerFirstEntryStatus
.AwaitingReceiptAcknowledgement;
case RuntimeInitialCreateExecutionStatus.AwaitingContinuationPlacement:
return RuntimeLocalPlayerFirstEntryStatus
.AwaitingContinuationPlacement;
case RuntimeInitialCreateExecutionStatus.RejectedToken:
_progress.Remove(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedToken;
default:
_progress.Remove(key);
return RuntimeLocalPlayerFirstEntryStatus.RejectedAuthority;
}
}
/// <summary>
/// Discards any in-flight publication candidate/activation this class
/// owns for <paramref name="key"/> and drops its own progress entry.
/// Safe to call at every stage: <see cref="RuntimeLocalPlayerPhysicsPublicationState.Discard"/>
/// and <see cref="RuntimeLocalPlayerPhysicsPublicationState.DiscardActivation"/>
/// are both no-ops against a default/invalid token (an unreached stage's
/// token field holds exactly that) AND against a token whose activation
/// has already reached <c>FinalizeActivation</c>'s terminal success path
/// — <c>FinalizeActivation</c> itself nulls the publication's own
/// tracked activation the instant the commit succeeds, because the
/// controller is now genuinely live/published, not a discardable
/// in-progress candidate. Calling this once <see cref="Stage.ActivationCommitted"/>
/// (or later) has been reached is therefore correctly a no-op on the
/// controller/body — an abandoned Place acknowledgement never
/// retroactively un-publishes an already-live entity; that is ordinary
/// entity teardown's job (the SAME path any other live entity's delete
/// already runs), not this class's. The residence and executor own
/// their own convergence independently (their existing retirement/reset
/// paths are untouched by this class).
/// </summary>
private void Discard(RuntimeEntityKey key)
{
if (!_progress.TryGetValue(key, out Progress? progress))
return;
_progress.Remove(key);
// H2: post-H2, a Progress entry can only exist at all if Advance's
// own upfront check already found Publication bound — this should
// therefore be structurally unreachable. Guarded anyway
// (belt-and-suspenders) so a future caller shape can never turn an
// already-surfaced Advance failure into a SECOND throw from inside
// an unrelated retirement/session-clear teardown fan-out.
if (_publication is null)
return;
Publication.Discard(progress.PublicationToken);
Publication.DiscardActivation(progress.ActivationToken);
}
/// <summary>
/// Cleanup for one key this class is tracking. <see cref="RuntimeEntityObjectLifetime"/>
/// binds this into <see cref="RuntimeInitialCreateResidenceState"/>'s
/// multicast retirement notification (alongside the executor's own
/// <c>DiscardProgress</c>), so any residence retirement path — delete,
/// reset, generation replacement, a host discovering staleness — reaps
/// this class's progress automatically. The notification always carries
/// the exact <see cref="RuntimeEntityKey"/> the residence itself tracked
/// internally, so it converges correctly even after
/// <see cref="RuntimeEntityRecord.Key"/> has gone null (e.g. post-delete
/// teardown released the local id) — unlike re-deriving a key from the
/// record, which <see cref="Advance"/> cannot do once that happens.
/// Still exposed directly for a caller that captured a key before a
/// teardown this class was not notified about (e.g. constructed
/// standalone in a test without the lifetime's fan-out).
/// </summary>
internal void Forget(RuntimeEntityKey key) => Discard(key);
/// <summary>
/// Bulk cleanup mirroring <see cref="RuntimeInitialCreateContinuationExecutor.DiscardAll"/>
/// — wired into the same session-clear sequence
/// (<see cref="RuntimeEntityObjectLifetime.BeginSessionClear"/>). Discards
/// every tracked key's in-flight publication candidate/activation before
/// dropping the whole progress table, exactly like a per-key
/// <see cref="Forget"/> for each entry.
/// </summary>
internal void DiscardAll()
{
// H2: same belt-and-suspenders tolerance as Discard above — a
// structurally unreachable case post-H2, guarded so bulk session
// clear can never throw from an unbound Publication either.
if (_publication is not null)
{
foreach (Progress progress in _progress.Values)
{
Publication.Discard(progress.PublicationToken);
Publication.DiscardActivation(progress.ActivationToken);
}
}
_progress.Clear();
}
internal RuntimeLocalPlayerFirstEntryOwnershipSnapshot CaptureOwnership() =>
new(_progress.Count);
}

View file

@ -1576,11 +1576,69 @@ internal sealed class RuntimeSetPositionState : IDisposable
uint scatterAttempts = 0u,
float shadowWorldOffsetX = 0f,
float shadowWorldOffsetY = 0f)
{
outcome = default;
RuntimeSetPositionMoverPreparationStatus status =
TryPrepareAuthoredMover(
record,
token,
operationKind,
flags,
collisionSource,
gameTime,
out RuntimeSetPositionCommand command,
placementClass,
portal,
line,
scatterRadiusX,
scatterRadiusY,
scatterAttempts,
shadowWorldOffsetX,
shadowWorldOffsetY);
if (status != RuntimeSetPositionMoverPreparationStatus.Prepared)
return status;
outcome = SubmitPreparedPlacement(token, command);
return RuntimeSetPositionMoverPreparationStatus.Prepared;
}
/// <summary>
/// C3a: the exact-Setup-read + <see cref="PrepareMover"/> half of
/// <see cref="TryPrepareAndSubmitAuthoredPlacement"/>, extracted (pure
/// refactor, byte-identical behavior for the existing caller above) so
/// the dormant local-player first-entry conductor
/// (<c>AcDream.Runtime.Gameplay.RuntimeLocalPlayerFirstEntryState</c>)
/// can obtain a prepared <see cref="RuntimeSetPositionCommand"/> WITHOUT
/// the trailing <see cref="SubmitPreparedPlacement"/> call. Submission
/// through the ordinary tail is exactly what an operation with
/// <c>DormantLocalActivation</c> set must never receive — see
/// <see cref="RetryDeferred"/>'s "must never bypass that path through the
/// ordinary remote CommitCanonical tail" comment; the dormant chain's own
/// Evaluate/Commit/FinalizeActivation methods are the sole substitute for
/// submission on that path.
/// </summary>
internal RuntimeSetPositionMoverPreparationStatus TryPrepareAuthoredMover(
RuntimeEntityRecord record,
in RuntimeEntityPlacementToken token,
RuntimeSetPositionOperationKind operationKind,
PhysicsSetPositionFlags flags,
IPreparedCollisionSource collisionSource,
double gameTime,
out RuntimeSetPositionCommand command,
PhysicsPlacementClass placementClass = PhysicsPlacementClass.Ordinary,
RuntimePortalPlacementAuthority portal = default,
Vector3 line = default,
float scatterRadiusX = 0f,
float scatterRadiusY = 0f,
uint scatterAttempts = 0u,
float shadowWorldOffsetX = 0f,
float shadowWorldOffsetY = 0f)
{
EnsureNotDisposed();
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(collisionSource);
outcome = default;
command = default;
uint setupTableId = CanonicalSetupTableId(record);
RuntimeSetPositionMoverSetup setup;
@ -1615,13 +1673,7 @@ internal sealed class RuntimeSetPositionState : IDisposable
shadowWorldOffsetX,
shadowWorldOffsetY,
portal);
RuntimeSetPositionMoverPreparationStatus status = PrepareMover(
token, preparation, out RuntimeSetPositionCommand command);
if (status != RuntimeSetPositionMoverPreparationStatus.Prepared)
return status;
outcome = SubmitPreparedPlacement(token, command);
return RuntimeSetPositionMoverPreparationStatus.Prepared;
return PrepareMover(token, preparation, out command);
}
internal bool IsExactPreparedPlacementCurrent(