The CVL CORE Connection Lifecycle & Teardown Architecture governs the end-to-end state trajectory of network descriptors across the Connection Intake Gate, the Session Admission Controller, the Asymmetric Network Reactor, and the Authoritative Simulation Orchestrator. Engineered to sustain high-density 3D spatial tracking under adversarial load ("The Crucible") without leaking socket descriptors, ephemeral NetID tokens, or 64-byte C-memory strides, the subsystem pairs a 6-stage admission state machine with a 3-tier amortized teardown pipeline and continuous 1.0Hz mathematical conservation auditing.
To protect the deterministic 30Hz (33.3 ms) simulation loop from operating system I/O stalls, connection management is partitioned across isolated background socket workers and the single-threaded simulation orchestrator. Operating system socket descriptors are owned exclusively by the network subsystem, while entity state registries and memory slab leases are mutated strictly on the Main Thread.
Every inbound TCP connection progresses through a deterministic lifecycle managed by the Session Admission Controller using a slotted state structure (SessionState):
UNAUTHENTICATED (0): Initial socket acceptance at the Connection Intake Gate. The descriptor is configured with non-blocking OS flags (TCP_NODELAY = 1, SO_RCVBUF = 16384, SO_SNDBUF = 262144) and queued for registration before any identity payload is parsed.HANDSHAKING (1): The socket is registered with the Asymmetric Network Reactor in Phase 1 ASCII mode. The connection is held in the pending handshake registry subject to a strict 10.0-second AUTH_TIMEOUT (and a 3.0-second slow-loris staging cutoff) while awaiting the ATH:{cleanName}:{crcHash:X8}\n IEEE 802.3 CRC32 parity gate.QUEUED (3): If the server has reached its commercial entity capacity ceiling (MAX_SERVER_ENTITIES), validated non-privileged connections are parked in an ordered First-In, First-Out (FIFO) waiting room. Queued clients receive periodic OP_CONFIG (QUEUE:{pos}) telemetry pulses until a slot is reclaimed.STAGED (2): Upon passing the parity gate and securing a capacity slot, the Session Admission Controller leases an ephemeral 16-bit NetID (1 to 65535) and promotes the connection to the staged registry. The server dispatches Frame A (OP_CONFIG world dimensions), Frame B (OP_CONFIG permanent 16-byte EID assignment), and Frame C (OP_MAP_GEOMETRY static obstacle AABB stream).ACTIVE (4): Once the client constructs its local spatial collision volumes and returns the plaintext CHR\n (Client Hydration Ready) acknowledgment, the orchestrator calculates a safe spawn coordinate, leases a 64-byte slot in the Contiguous State Substrate, promotes the parser to Phase 2 Binary mode, and dispatches Frame D (OP_SET_POS spawn anchor), Frame E (OP_BUNDLE active world peer hydration), and a single-pass peer discovery broadcast.TEARDOWN (5): Terminal state triggered by graceful client logout (LOGOUT|{eid}\n), transport silence (FLATLINE_TIMEOUT), anti-cheat eviction (REASON_SPEEDHACK), or socket fault. The entity is atomically purged across all internal registries and its memory offset and NetID are recycled.The Connection Intake Gate and Asymmetric Network Reactor enforce multi-layered perimeter defenses prior to main-thread simulation ingress:
MAX_CONNS_PER_IP), automatically exempting configured local and private swarm subnets (127.0.0.1, ::1, localhost, 192.168.*, 10.*, 172.*) for synthetic load testing.3.0s) & ASCII Overflow Gate (1024B): Unauthenticated connections held in pending handshakes for greater than 3.0 seconds without completing the Phase 1 parity handshake are severed inline and unregistered from OS selectors as ERR_SLOW_LORIS_TIMEOUT (routing a slow_loris_eviction event to the security log). Furthermore, inbound Phase 1 buffers reaching >= 1024 bytes without a newline delimiter (\n) log an [ASCII OVERFLOW] diagnostic dump, record an immediate IP violation strike, and sever the descriptor.Thread boundary isolation is absolute: background network threads never hold, mutate, or pass live entity domain objects. All inter-thread signaling across Single-Producer Single-Consumer (SPSC) conduits utilizes immutable primitive tokens (net_id, temporary connection strings, raw byte buffers, or socket descriptors).
+-----------------------------------------------------------------------------------+| NETWORK INTAKE & REACTOR SUBSYSTEM || || [Connection Intake Gate] ---> (Passive Boot Gate & IP Ban Check) || | || +---> [TCP Admission Conduit] ======================================+ || | || [Asymmetric Network Reactor (OS Selector Loop - 0.5ms Poll)] | || |-- Step A: Drain Egress Command Conduit (REGISTER / PAYLOAD / DISCONNECT)| || |-- Step B: Opportunistic Non-Blocking Flush (1. Critical FIFO, 2. 15Hz) | || +-- Step C: Non-Blocking Read / Write-Stall Check (> 4.0s Auto-Sever) | || | | || +---> [Tier 1 Inline Sever] ---> (EOF / OSError / LOGOUT / Flood) | || | (Safe Socket Close + Buffer Purge) | |+----------------------|-------------------------------------------------------|----+ | ("DROP", eid, sock, ip, is_auth) | v v+-----------------------------------------------------------------------------------+| AUTHORITATIVE SIMULATION ORCHESTRATOR (30Hz) || || +-- PHASE 2: AMORTIZED FAST TEARDOWN (Tier 2 - Cap: 50 / Tick) || | |-- Drain Teardown Conduit & Teardown Set || | +-- Atomic Eviction Transaction: || | |-- Detach Mounted Passengers (Role 6/7 Vehicles -> OP_SET_POS) || | |-- Zero-Fill 64B Memory Slab & Return Offset to Pre-Warmed Pool || | |-- Recycle uint16 NetID & Purge 11 Internal State Registries || | +-- Enqueue OP_REMOVE (4B) Broadcast + NET_CMD_DISCONNECT || | || +-- PHASE 3: ADMISSIONS, REAPER & PARITY SENTINEL || |-- Drain Control Conduit (Bounded: 100 Frames / Time-Boxed) || |-- Process Admission Conduit & Waiting Room Promotions (Frame A -> E) || |-- [Tier 3 Async Reaper] ---> Sweep Auth (10s), Flatline (10s), Idle (300s)|| +-- [1.0Hz Parity Sentinel] -> Audit 4 Mathematical Conservation Laws |+-----------------------------------------------------------------------------------+The Asymmetric Network Reactor owns the operating system’s non-blocking I/O multiplexer and executes a continuous three-step cycle:
NET_CMD_REGISTER: Binds newly accepted sockets into the selector map for EVENT_READ monitoring and instantiates a zero-allocation stream handler.NET_CMD_PAYLOAD: Routes discrete control/state payloads into the entity’s Critical FIFO Buffer and 15Hz spatial broadcasts into the Keyed Spatial Conflation Buffer.NET_CMD_DISCONNECT: Executes idempotent descriptor closure and purges all per-entity reactor buffers.OP_REMOVE frame is always flushed to the wire ahead of the subsequent NET_CMD_DISCONNECT socket closure.EVENT_READ | EVENT_WRITE and records a stall timestamp. Once buffers flush, EVENT_WRITE is immediately unregistered. Any socket remaining write-stalled for > 4.0 seconds is severed inline and routed to the Teardown Eviction Conduit.To prevent mass disconnections (such as a 400-bot swarm termination) from spiking frame execution times on the 30Hz simulation thread, entity reclamation is distributed across three operational tiers:
OSError, a > 4.0s write stall, or an explicit LOGOUT|{eid}\n frame, it immediately unregisters the descriptor from the OS selector, closes the socket via isolated fault-absorbing wrappers, clears outbound conflation buffers, and pushes a single ("DROP", eid, sock, ip, is_authenticated) primitive tuple into the Teardown Eviction Conduit.MAX_TEARDOWNS_PER_TICK = 50 per frame. Surplus disconnections roll over cleanly to subsequent 33.3 ms ticks, guaranteeing deterministic frame budgets during catastrophic network drops.REAPER_INTERVAL) to evaluate up to 500 entities per chunk (REAPER_CHUNK_SIZE). The reaper identifies unauthenticated handshakes exceeding AUTH_TIMEOUT (10.0s), active connections exceeding FLATLINE_TIMEOUT (10.0s without OP_TELEMETRY or OP_PING), inactive operators or unpossessed vehicles exceeding IDLE_TIMEOUT (300.0s), and expired IP penalty box records, routing stale identities into the Phase-2 teardown queue with REASON_TIMEOUT (0x01).Every disconnection path—whether initiated by Tier 1 socket drops, Tier 2 anti-cheat strikes, Tier 3 reaper timeouts, or VIP human capacity preemption—converges on a single atomic eviction transaction executed on the Main Thread.
When the orchestrator evicts an entity, the Contiguous State Substrate executes an all-or-nothing reclamation sequence:
ROLE_MOBILE_GROUNDED = 6 or ROLE_MOBILE_AERIAL = 7), the transaction scans active entities for attached passengers (parent_net_id == evicting_net_id). Attached passengers are atomically unbound (parent_net_id = 0), flagged network-dirty, and immediately dispatched an authoritative 32-byte OP_SET_POS coordinate synchronization frame to prevent orphan transforms.offset to offset + 64) is overwritten with null bytes (64 zero bytes), scrubbing residual coordinates before returning the offset integer to the Pre-Warmed Offset Lease Pool.NetID & Registry Reclamation: The unsigned 16-bit NetID is cleared in the lookup index and returned to the recycled NetID pool. The entity is simultaneously purged across all 11 internal tracking registries (including pending handshakes, waiting room, staged entities, active dictionary, active iteration list, projectile list, socket-to-entity map, IP registry, and dirty sets).net_id > 0), the orchestrator packs a 4-byte OP_REMOVE envelope carrying the discrete 1-byte REASON_* code and broadcasts it to all remaining peers via the Critical FIFO Buffer.When an interactive human operator (ROLE_OPERATOR_HUMAN = 4) completes the Phase 1 handshake while the server is at 100% capacity with synthetic benchmark actors, the Session Admission Controller automatically executes VIP preemption. The controller selects the first active synthetic bot, executes an immediate atomic eviction (REASON_LOGOUT), and reallocates the freed 64-byte memory stride and NetID to the incoming human operator without routing them to the waiting room.
To mathematically prove zero resource leakage over multi-week Linux uptime windows, the Authoritative Simulation Orchestrator executes an inline conservation audit (Parity Sentinel) at 1.0Hz during Phase 3. The sentinel evaluates four strict set-conservation equations in O(1) time:
// Invariant C1 (Memory Slab Conservation)bool c1 = (activeEntitiesCount + availableOffsetsCount) == matrixCapacity;
// Invariant C2 (Iteration Cache Parity)bool c2 = activeEntitiesCount == activeEntityListCount;
// Invariant C3 (Socket Descriptor Conservation)bool c3 = socketToEntityMapCount == (activeBoundSocketsCount + stagedBoundSocketsCount);
// Invariant C4 (Ephemeral NetID Conservation)bool c4 = ((nextNetId - 1) - recycledNetIdsCount) == (activeEntitiesCount + stagedEntitiesCount + waitingRoomCount);If any of the four conservation laws evaluate to false, the sentinel trips registry_parity_ok = false, increments the discrepancy counter surfaced on the 1.0Hz administrative telemetry channel, and writes a symmetric set-difference diagnostic trace to the error log.
The lifecycle and reactor subsystems enforce strict operational guardrails to prevent thread contention, memory fragmentation, and client-side state desynchronization.
At server bootstrap—immediately following service instantiation and prior to igniting the 30Hz orchestration loop—the engine executes a full garbage collection sweep, freezes all static boot allocations into the permanent memory generation, and raises high-water collection thresholds. Furthermore, all socket and admission exception handlers explicitly sever local traceback reference cycles prior to returning, guaranteeing 0.00 ms of garbage collection pause time during high-frequency socket churn.
Toggling sockets into blocking mode or invoking synchronous network sends on either the server Main Thread or the Unity Main Thread is prohibited across the architecture. Multi-kilobyte Stage 2 obstacle geometry streams (OP_MAP_GEOMETRY) and peer discovery bundles (OP_BUNDLE) stream asynchronously through the Asymmetric Network Reactor via the per-entity Critical FIFO Buffer.
When a client enters an active simulation zone containing hundreds of peers, receiving a massive OP_BUNDLE payload can stall the client rendering thread if instantiated in a single frame. The CVL CORE Presentation Bridge time-slices inbound 64-byte bundle strides and 32-byte position overrides across frames, strictly bounded by MAX_SPAWNS_PER_FRAME = 4 and a 2.5 ms per-frame hydration budget (MAX_HYDRATION_BUDGET_MS). Local player activation is held behind the Staging Gate until the initial peer bundle finishes hydrating (or a 0.25-second safety timeout elapses), preventing the local operator from moving through an unpopulated world.
To ensure seamless session recycling without triggering false-positive security evictions, client integrations must observe three transport lifecycle rules:
LOGOUT|{eid}\n): Client applications disconnecting intentionally must invoke CVLEngineAPI.Disconnect() rather than abruptly dropping the TCP descriptor. This dispatches an inline logout control token that triggers Tier-1 server slot reclamation in under 45 ms.nextConnectTime) between successive connection attempts to prevent staging socket spam. Abruptly closing a TCP socket without a LOGOUT token and immediately reconnecting will collide with the prior session before the 10.0-second FLATLINE_TIMEOUT expires, triggering an automatic REASON_DUPLICATE_AUTH (0x03) preemption.OP_REMOVE: When CVLEngineAPI.OnEntityDespawned(eid, reasonCode) fires upon receipt of a 4-byte OP_REMOVE envelope, the Presentation Bridge automatically unbinds screen-space UI elements and returns the proxy instance to its pre-warmed PrefabCatalog pool stack. Event listeners should inspect the reasonCode strictly for telemetry or UI feedback and allow the SDK to manage proxy object lifecycles.Client applications monitor connection phase transitions, waiting room queue positions, and authoritative teardown reasons through CVLEngineAPI lifecycle delegates, while infrastructure operators configure timeout and capacity boundaries via cvlcore_engine_config.json.
cvlcore_engine_config.json)All admission ceilings, timeout thresholds, and socket defenses are hydrated at boot with fail-fast schema validation:
{ "BIND_IP": "0.0.0.0", "SERVER_PORT": 55555, "ADMIN_PORT": 55556, "DEFAULT_BOOT_MODE": "3", "MAX_SERVER_ENTITIES": 400, "MAX_CONNS_PER_IP": 8, "AUTH_TIMEOUT": 10.0, "FLATLINE_TIMEOUT": 10.0, "IDLE_TIMEOUT": 300.0, "REAPER_INTERVAL": 5.0, "REAPER_CHUNK_SIZE": 500, "MAX_TEARDOWNS_PER_TICK": 50}CVLEngineAPI.cs)The following C# integration pattern demonstrates tracking the 8-stage client connection state machine (EngineConnectionState), displaying live waiting room queue positions, and handling discrete server eviction reasons:
using UnityEngine;using CVLCore.SDK;
public class ConnectionLifecycleHandler : MonoBehaviour{ private void OnEnable() { CVLEngineAPI.OnNetworkStateChanged += HandleNetworkStateChanged; CVLEngineAPI.OnEntityDespawned += HandleEntityDespawned; CVLEngineAPI.OnPingUpdated += HandlePingUpdated; }
private void OnDisable() { CVLEngineAPI.OnNetworkStateChanged -= HandleNetworkStateChanged; CVLEngineAPI.OnEntityDespawned -= HandleEntityDespawned; CVLEngineAPI.OnPingUpdated -= HandlePingUpdated; }
public void InitiateCleanLogout() { // Transmits inline LOGOUT|{eid}\n for <45ms Tier-1 server slot reclamation CVLEngineAPI.Disconnect(); }
private void HandleNetworkStateChanged(EngineConnectionState state, string statusMessage) { switch (state) { case EngineConnectionState.Stage1_Config: Debug.Log("Phase 1 ASCII Handshake & CRC32 Parity Verified."); break;
case EngineConnectionState.InQueue: // Dispatched when server is at MAX_SERVER_ENTITIES capacity Debug.Log($"Waiting Room Active: {statusMessage}"); break;
case EngineConnectionState.Stage2_Hydrating: // Constructing static AABB colliders prior to emitting CHR\n Debug.Log("Hydrating World Geometry..."); break;
case EngineConnectionState.Stage3_Syncing: // Time-sliced OP_BUNDLE hydration (4 spawns / 2.5ms budget per frame) Debug.Log("Synchronizing Active World Peers..."); break;
case EngineConnectionState.ActiveGameplay: Debug.Log("Phase 2 Binary Stream Active (30Hz Telemetry / 15Hz Egress)."); break;
case EngineConnectionState.Disconnected: Debug.LogWarning($"Session Terminated: {statusMessage}"); break; } }
private void HandleEntityDespawned(string eid, byte reasonCode) { // Proxy GameObject is automatically returned to PrefabCatalog pool stack. // Inspect authoritative 1-byte eviction reason code: switch (reasonCode) { case ProtocolConstants.REASON_LOGOUT: Debug.Log($"Entity {eid} logged out gracefully (0x00)."); break; case ProtocolConstants.REASON_TIMEOUT: Debug.LogWarning($"Entity {eid} evicted: Transport Flatline / Idle Timeout (0x01)."); break; case ProtocolConstants.REASON_SPEEDHACK: Debug.LogError($"Entity {eid} evicted: Authoritative Kinematics Violation (0x02)."); break; case ProtocolConstants.REASON_DUPLICATE_AUTH: Debug.LogWarning($"Entity {eid} preempted by duplicate session login (0x03)."); break; case ProtocolConstants.REASON_SERVER_SHUTDOWN: Debug.LogWarning($"Server initiating deterministic shutdown (0x05)."); break; } }
private void HandlePingUpdated(float smoothedRttMs, float smoothedJitterMs) { // Driven by autonomous 1.0Hz OP_PING background loop; feeds 133ms interpolation floor }}EngineConnectionState enum and CVLEngineAPI lifecycle event surface, see Public Delegation Broker & Telemetry Controller.MAX_SERVER_ENTITIES, FLATLINE_TIMEOUT, and port bindings directly from the Unity Editor, see Setup Wizard & Server Config Hydration.