Skip to content
CVL COREEngine

Connection Lifecycle, Network Reactor & Deterministic Teardown

[SPECIFICATION] Connection Lifecycle & Teardown Invariant

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.


[SEC 01.0] Executive Architecture & Subsystem Topology

Section titled “[SEC 01.0] Executive Architecture & Subsystem Topology”

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.

[LIFECYCLE] The 6-Stage Session State Machine
Section titled “[LIFECYCLE] The 6-Stage Session State Machine”

Every inbound TCP connection progresses through a deterministic lifecycle managed by the Session Admission Controller using a slotted state structure (SessionState):

  1. 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.
  2. 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.
  3. 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.
  4. 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).
  5. 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.
  6. 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.
[DEFENSE] Reactor Flood Defenses, Slow-Loris Cutoff & IP Penalty Box
Section titled “[DEFENSE] Reactor Flood Defenses, Slow-Loris Cutoff & IP Penalty Box”

The Connection Intake Gate and Asymmetric Network Reactor enforce multi-layered perimeter defenses prior to main-thread simulation ingress:

  • Passive Boot Gate: The intake listener refuses incoming TCP handshakes at the OS level until static world geometry is fully compiled and cached in memory.
  • Per-IP Connection Ceilings: Concurrent sockets from a single remote IP address are strictly bounded (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.
  • Slow-Loris Staging Cutoff (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.
  • Reactor Strike Governor & 60-Second IP Ban Box: In Phase 2 binary mode, inbound telemetry exceeding 45Hz is dropped inline, while telemetry exceeding 60Hz or control packets exceeding 10 packets/sec increment per-connection flood strikes. Reaching the strike ceiling (25 strikes) immediately severs the socket and records an IP strike. Accumulating 3 IP strikes within a 30.0-second sliding window blacklists the remote IP address in the IP Penalty Box for 60.0 seconds.

[SEC 02.0] Concurrency & State Ownership / Lifecycle

Section titled “[SEC 02.0] Concurrency & State Ownership / Lifecycle”

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).

Architecture: 6-Stage Admission & 3-Tier Deterministic Teardown Pipeline
+-----------------------------------------------------------------------------------+
| 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 |
+-----------------------------------------------------------------------------------+
[REACTOR] The 3-Step Asymmetric Reactor Loop
Section titled “[REACTOR] The 3-Step Asymmetric Reactor Loop”

The Asymmetric Network Reactor owns the operating system’s non-blocking I/O multiplexer and executes a continuous three-step cycle:

  • Step A (Egress Command Drain): Drains symbolic command tuples from the Master Egress Queue:
    • 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.
  • Step B (Opportunistic Non-Blocking Flush): Iterates across dirty egress targets and executes non-blocking socket writes. The reactor flushes the Critical FIFO Buffer to completion before transmitting the Keyed Spatial Conflation Buffer. This ordering guarantees that an outgoing 4-byte OP_REMOVE frame is always flushed to the wire ahead of the subsequent NET_CMD_DISCONNECT socket closure.
  • Step C (Selector Poll & Write-Stall Enforcement): Polls the OS selector with a 0.5 ms timeout. If a non-blocking send encounters write backpressure, the reactor dynamically upgrades the socket registration to 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.
[TEARDOWN] The 3-Tier Deterministic Teardown Pipeline
Section titled “[TEARDOWN] The 3-Tier Deterministic Teardown Pipeline”

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:

  • Tier 1 — Inline Reactor Severing: When the Asymmetric Network Reactor detects a 0-byte EOF, a fatal socket 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.
  • Tier 2 — Phase-2 Amortized Fast Teardown: During Phase 2 of every 30Hz tick, the Authoritative Simulation Orchestrator drains the Teardown Eviction Conduit and the internal teardown queue. Reclamations are strictly capped at 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.
  • Tier 3 — Asynchronous Reaper Sweeps: A background maintenance daemon wakes on a 5.0-second cadence (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).

[SEC 03.0] Atomic Eviction, Passenger Detachment & Parity Auditing

Section titled “[SEC 03.0] Atomic Eviction, Passenger Detachment & Parity Auditing”

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.

[TRANSACTION] The Atomic Eviction Transaction
Section titled “[TRANSACTION] The Atomic Eviction Transaction”

When the orchestrator evicts an entity, the Contiguous State Substrate executes an all-or-nothing reclamation sequence:

  1. De-Jitter Ring Purge: Clears any unprocessed kinematic telemetry frames remaining in the entity’s 3-slot staging buffer.
  2. Hierarchical Passenger Detachment: If the evicting entity is a multi-passenger vehicle or mobile platform (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.
  3. 64-Byte Memory Slab Zero-Fill: The entity’s leased 64-byte slice within the Contiguous State Substrate (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.
  4. 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).
  5. Peer Notification Broadcast: If the evicted entity was active in the simulation (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.

[SENTINEL] 1.0Hz Conservation Parity Sentinel
Section titled “[SENTINEL] 1.0Hz Conservation Parity Sentinel”

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:

Verification: 1.0Hz Parity Sentinel Conservation Equations
// 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.


[SEC 04.0] Architectural Invariants & Guardrails

Section titled “[SEC 04.0] Architectural Invariants & Guardrails”

The lifecycle and reactor subsystems enforce strict operational guardrails to prevent thread contention, memory fragmentation, and client-side state desynchronization.

[GUARDRAIL] Permanent Heap Isolation & Exception Cycle Severing
Section titled “[GUARDRAIL] Permanent Heap Isolation & Exception Cycle Severing”

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.

[GUARDRAIL] Prohibition of Synchronous Socket Operations
Section titled “[GUARDRAIL] Prohibition of Synchronous Socket Operations”

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.

[GUARDRAIL] Time-Sliced Client Hydration Gate
Section titled “[GUARDRAIL] Time-Sliced Client Hydration Gate”

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.

[GUARDRAIL] Client Disconnection & Reconnection Hygiene
Section titled “[GUARDRAIL] Client Disconnection & Reconnection Hygiene”

To ensure seamless session recycling without triggering false-positive security evictions, client integrations must observe three transport lifecycle rules:

  • Graceful Logout Dispatch (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.
  • Mandatory 3.0-Second Reconnection Backoff: The client transport gateway enforces a 3.0-second cooldown (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.
  • Non-Destructive Proxy Pooling on 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.

[SEC 05.0] Configuration Schema & Client Lifecycle Integration

Section titled “[SEC 05.0] Configuration Schema & Client Lifecycle Integration”

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.

[CONFIG] Lifecycle & Capacity Configuration Schema (cvlcore_engine_config.json)
Section titled “[CONFIG] Lifecycle & Capacity Configuration Schema (cvlcore_engine_config.json)”

All admission ceilings, timeout thresholds, and socket defenses are hydrated at boot with fail-fast schema validation:

config/cvlcore_engine_config.json
{
"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
}
[IMPLEMENTATION] Client Connection Lifecycle & Eviction Integration (CVLEngineAPI.cs)
Section titled “[IMPLEMENTATION] Client Connection Lifecycle & Eviction Integration (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:

Assets/CVL_CORE_SDK/API/ConnectionLifecycleHandler.cs
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
}
}
Section titled “[RELATED SPECS] Cross-Category Subsystem Links”