Scene runtime and crdt

From decentraland/unity-explorer · View interactive version

Scene runtime and crdt is an AI agent skill from the GitHub repository decentraland/unity-explorer. Scene runtime internals — V8/ClearScript engine, CRDT protocol, JS module system, scene lifecycle, and threading. Use when implementing or modifying scene runtime modules (require/wrapper/API pattern), working with CRDTProtocol or CRDTWorldSynchronizer, handling MultiThreadSync for ECS access, debug

How to use this skill

Skill file

Scene Runtime & CRDT

Sources


Scene Lifecycle State Machine

File: Explorer/Assets/DCL/Infrastructure/SceneRunner/Scene/SceneState.cs

public enum SceneState : byte
{
    NotStarted,      // Created but not started
    Running,         // Active update loop
    EngineError,     // Scene communication broken (exception tolerance exceeded)
    EcsError,        // ECS World execution error
    JavaScriptError, // JS code error (tolerance exceeded)
    Disposing,       // Signaled for disposal
    Disposed,        // Fully disposed
}

Transitions:

ISceneStateProvider exposes Atomic<SceneState> State, TickNumber, IsCurrent, and EngineStartInfo. The Atomic<T> wrapper provides thread-safe reads/writes since state is mutated from background threads.

IsNotRunningState() returns true for Disposing, Disposed, JavaScriptError, or EngineError -- used as a guard to break the update loop.


Threading Model (CRITICAL)

See docs/scene-runtime.md -- "the scene lifecycle is thread agnostic and executes in a separate thread."

No thread affinity. Each scene runs on the thread pool. After every await, the continuation may resume on a different thread. You cannot assume thread consistency.

MultiThreadSync -- Mutex for ECS Access

File: Explorer/Assets/DCL/PerformanceAndDiagnostics/Optimization/Multithreading/MultiThreadSync.cs

Arch ECS is not thread-safe. All ECS reads and writes must be serialized through MultiThreadSync:

// Acquire a scope before touching ECS state (from any thread)
using MultiThreadSync.Scope mutex = multiThreadSync.GetScope(syncOwner);

// Now safe to call crdtWorldSynchronizer.ApplySyncCommandBuffer(...)
// or any World read/write

SyncedGroup -- Automatic System Synchronization

File: Explorer/Assets/DCL/Infrastructure/ECS/Groups/SyncedGroup.cs

Systems in scene worlds use SyncedGroup subclasses (SyncedSimulationSystemGroup, etc.) that guard Update/BeforeUpdate/AfterUpdate behind a SceneState.Running check. This prevents systems from running during disposal:

public override void Update(in float t, bool throttle)
{
    if (sceneStateProvider.State != SceneState.Running)
        return;
    UpdateInternal(in t, throttle);
}

When Explicit Mutex Is Needed


Module Implementation Pattern

See docs/scene-runtime.md -- "How to Implement a Module"

Each JS API module follows a 4-file pattern:

1. Interface

Defines the C# contract. Example: IEngineApi

2. Implementation

Core logic, thread-agnostic. Example: EngineAPIImplementation -- receives CRDT bytes, deserializes, reconciles, syncs to ECS, serializes outgoing messages.

3. JsApiWrapper

Bridges JS calls to C#. Extends JsApiWrapper<TApi> which holds the API impl and a CancellationTokenSource for disposal. The wrapper catches exceptions and routes them through ISceneExceptionsHandler:

// From EngineApiWrapper.cs (condensed)
public class EngineApiWrapper : JsApiWrapper<IEngineApi>
{
    public PoolableByteArray CrdtSendToRenderer(ITypedArray<byte> data)
    {
        if (disposeCts.IsCancellationRequested)
            return PoolableByteArray.EMPTY;
        try
        {
            instancePoolsProvider.RenewCrdtRawDataPoolFromScriptArray(data, ref lastInput);
            return api.CrdtSendToRenderer(lastInput.Memory);
        }
        catch (Exception e)
        {
            if (!disposeCts.IsCancellationRequested)
                exceptionsHandler.OnEngineException(e);
            return PoolableByteArray.EMPTY;
        }
    }
}

4. JS Module + Registration


CRDT Protocol Internals

File: Explorer/Assets/DCL/Infrastructure/CRDT/Protocol/CRDTProtocol.cs

LWW vs GOVS Processing

ProcessMessage dispatches by CRDTMessageType:

Zero-Allocation Design

State Structure

internal struct State
{
    // Entity Number -> deleted Entity Version
    internal readonly PooledDictionary<int, int> deletedEntities;
    // ComponentId -> (CRDTEntity -> EntityComponentData) for LWW
    internal readonly PooledDictionary<int, PooledDictionary<CRDTEntity, EntityComponentData>> lwwComponents;
    // ComponentId -> (CRDTEntity -> list of EntityComponentData) for APPEND
    internal readonly PooledDictionary<int, PooledDictionary<CRDTEntity, PooledList<EntityComponentData>>> appendComponents;
    internal int messagesCount;
}

ECS-CRDT Bridge

Inbound: Scene -> ECS

File: Explorer/Assets/DCL/Infrastructure/CrdtEcsBridge/JsModulesImplementation/EngineAPIImplementation.cs

The flow in CrdtSendToRenderer (called from background thread):

  1. Deserialize -- crdtDeserializer.DeserializeBatch into List<CRDTMessage>
  2. Reconcile -- Each message through crdtProtocol.ProcessMessage
  3. Buffer -- worldSyncBuffer.SyncCRDTMessage prepares ECS mutations
  4. Apply -- ApplySyncCommandBuffer acquires MultiThreadSync scope, then crdtWorldSynchronizer.ApplySyncCommandBuffer writes to ECS World
  5. Respond -- SerializeOutgoingCRDTMessages returns buffered outgoing data

ICRDTWorldSynchronizer

File: Explorer/Assets/DCL/Infrastructure/CrdtEcsBridge/WorldSynchronizer/CrdtEcsSynchronizer.cs

Outbound: ECS -> Scene

Systems write to IECSToCRDTWriter (PutMessage, AppendMessage, DeleteMessage). These are collected by IOutgoingCRDTMessagesProvider and serialized back to the scene in EngineAPIImplementation.SerializeOutgoingCRDTMessages. Outgoing LWW messages are also synced into the local CRDTProtocol state via EnforceLWWState to keep timestamps correct.


Gotchas


Cross-References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.