Table of Contents

Character System

View this file on GitHub

Short description: SceneServer subsystem for the full player character lifecycle — authentication-triggered loading, async database hydration with session claiming, prefab instantiation, scene validation, network spawning, periodic persistence, batched session lease refresh, teleportation, death/respawn, out-of-bounds correction, social data broadcast, and connection cleanup with save-then-release semantics and a retry queue that guarantees claims are never stranded.

Table of Contents

Overview

The Character system is the SceneServer authority for player character lifecycle management. It handles authentication-triggered character loading, async database hydration with session claiming, prefab instantiation, scene validation, FishNet network spawning/despawning, periodic persistence, teleportation across scenes, death/respawn logic, out-of-bounds correction, social data broadcasting, and connection cleanup with save-then-release semantics.

The implementation uses a split execution model:

  • Main thread: Unity/FishNet object lifecycle, map mutations, prefab instantiation, controller hydration, scene validation, network broadcasts, periodic out-of-bounds checks, and main-thread queue drain.
  • Async worker: database load/save/session operations (claim, release, lease refresh), social data fetches, and character persistence via EnqueueAsyncWork.
  • Main-thread queue: marshaling async completion actions back to Unity/FishNet-safe context via ICharacterSystemMainThreadQueueData.

Character sessions are explicitly claimed and released to prevent dual-server ownership. The session lifecycle uses TryClaimAsync during load, a batched RefreshSessionLeasesAsync on its own timer, and ReleaseAsync on disconnect, teleport, error, or deinitialize. All release paths follow save-then-release ordering to ensure data is persisted while the session lock is still held.

Two properties of that lifecycle are load-bearing for scene transfers and easy to regress:

  • A release is never dropped. The async worker pool is bounded and drops writes when full, and the session token is removed from SessionTokens before the release runs — so a lost work item would leave the character Online with nothing left in the process holding its token. Every release path routes through ReleaseSessionSafely, and anything that fails to enqueue or fails at the database lands on the pending-flush retry queue (also drained during OnDeinitialize). A stranded claim blocks the destination scene server from claiming the character and kicks the player repeatedly until the lease expires.
  • Lease liveness is independent of save throughput. Leases are refreshed by OnPeriodicSessionLeaseRefresh in a single batched statement, not per-character inside the sequential save loop. PersistAsync does not touch the lease at all.

Supported Platforms

Platform Supported Notes
Windows Yes
Linux Yes
WebGL N/A Server-only module
Unity 6.6 (6000.6.8f1) Yes Required engine version
IL2CPP Yes Supported scripting backend

Features

  • Authentication-triggered character load with per-account rate limiting (AuthCallbackCooldownSeconds = 2.0s). A refused callback disconnects with DisconnectNoticeReason.RateLimited rather than returning silently — this callback is the only thing that starts a character load, so a quiet return left the client authenticated, in no map, and watched by nothing
  • Async database fetch of character and 14 sub-entity data sets within a single Unit of Work for a consistent snapshot. Items are one fetch now: inventory, bank and equipment are rows in character_item distinguished by a container column, not three tables
  • The load aborts on any sub-entity fetch failure. A character used to spawn with whatever had loaded, and the next item snapshot then pruned every row a null item list did not vouch for — a transient database fault on login destroyed an inventory. A refused login costs the player a retry
  • Early session claim (TryClaimAsync) before sub-entity hydration to fail fast if another server owns the character, with a bounded retry (5 attempts, ~1.5s) that absorbs the hand-off window during a scene transfer instead of kicking
  • Authoritative re-read of the character row after the claim succeeds, so a transfer cannot load a snapshot that predates the source server's final save
  • Race-template-based prefab instantiation from the FishNet object pool
  • Full controller hydration from pre-fetched DTOs: items (inventory, bank, equipment), attributes, abilities, known abilities, achievements, waypoints, friends, guild, party, hotkeys, buffs, factions, archetypes, quests
  • Equipment attribute modifier application during load (item.Equippable.Equip)
  • Buff restoration with tick-based expiry/next-tick recalculation from remaining time
  • Scene validation and FishNet scene loading for both world scenes and instances
  • Two-phase client scene handshake: SceneManager_OnClientLoadedStartScenes → ClientValidatedSceneBroadcast → OnClientValidatedSceneBroadcastReceived
  • Network spawning with physics scene assignment for stacked scene support
  • Immortality toggling during teleport (immortal) and scene entry (mortal)
  • IsLoaded flag management to prevent controller actions before the character is fully in the world
  • Immediate non-DB payload broadcast after spawn: known abilities, known ability events, achievements, inventory, bank, hotkeys
  • Async social payload broadcast after spawn: guild members, party members, friend online status
  • Targeted broadcast helpers by character name (case-insensitive) or character ID
  • Periodic save with configurable interval, main-thread DTO snapshot, async persistence, and an atomic processing guard to prevent overlapping save cycles
  • Batched session lease refresh on an independent timer (sessionLeaseRefreshRate, default 20s), one statement for the whole resident population
  • Pending-flush retry queue for saves and releases that could not be enqueued or failed at the database, with linear backoff and a bounded attempt count
  • Periodic out-of-bounds check with respawn point teleportation for characters outside scene boundaries
  • Teleport flow: teleporter validation, scene unload, immortality, position/scene update, instance flag removal, save-then-release with reconnect through world routing
  • Transfer watchdog: a connection whose character has been handed off is force-disconnected after TransferDisconnectGrace (15s) if the client never reports its scene unload, so a crashed or modified client cannot idle on a server that no longer holds its character
  • Residency watchdog: a connection that authenticated but still has no character after CharacterResidencyTimeout (60s) is disconnected with ServerError, bounding every load path that can fail without delivering its own disconnect
  • Scene-handshake watchdog: a character parked in WaitingSceneLoadCharacters that never acknowledges its scene within the scene-load watchdog (120 s without a progress heartbeat, SceneLoadStallTimeoutSeconds; 900 s at most, SceneLoadMaxSeconds) is disconnected with SceneHandshakeTimedOut, so its session claim is released instead of being held for the life of the socket
  • Death/respawn: player marked IsDead, death dialog shown on client. Player chooses Respawn (teleport to bind + revive) or waits for Resurrect (revive at corpse location). A respawn into a different scene follows the same ordering as the teleporter path, so OnDisconnect subscribers see the scene being left rather than the one being entered. Reconnect-while-dead re-shows the death dialog. NPC despawn with corpse decay timer; pet killed event with immediate despawn
  • Connection disconnect cleanup: waiting-scene-load character pool return with session release, spawned character mapping removal with save-then-despawn
  • Graceful deinitialize: main-thread DTO snapshot of all characters, async persist all, release all sessions (spawned + waiting-to-load)
  • A dead owner's pet is never captured as out (IsPetOut): death dismisses the pet, but the pet system's kill handler runs after this one, which finalises a combat-logout body killed while its owner was away — and used to save it with its pet still out
  • Buffs saved as one set with the character row (CharacterData.Buffs, captured by BuildCharacterData → CaptureBuffSet), so the stored buffs are exactly the current ones — see Buffs are one set, written with the row
  • Sub-entity persistence captured in one SubEntitySnapshot — attributes, abilities, pets, achievements, waypoints, factions, archetypes, known abilities — and handed to the persistence lane by EnqueueSubEntitySaves. One type rather than eight parallel lists threaded through five save paths, which is how factions went unsaved for the life of the project: fetched on login, never written back
  • Every sub-entity row is written under the session claim it was captured with (SubEntitySnapshot.Claims, the services' PersistOwnedAsync), so it lands only while that claim is still held — see Session claims are binding on writes. A character with no claim is not captured at all
  • Dirty marks cleared only by a write that actually landed (MarkAttributesPersisted and friends), and only when BulkWriteReporting.MayClearDirtyMarks says so: a successful write with Filtered == 0. A row the service declined to attempt never reached the database — including one the ownership gate refused (BulkWriteResult.Unowned, counted as filtered) — so retiring its value would lose it
  • Item persistence handed off, not duplicated: the logout item flush is captured by ICharacterInventorySystem.CaptureDespawnFlush while the character is still resident and awaited inside save-and-release, before the release
  • The hotkey bar is folded in the same way: every departure capture (AppendDepartureSubEntities — logout, transfer, a linger's end or reattach, the shutdown flush) takes the character's whole live bar (IHotkeySystemRuntimeData.TakeDepartingBar) into its SubEntitySnapshot, written before the release under the claim. The hotkey system no longer writes on OnDisconnect or from its own teardown
  • No release overtakes a write already queued for the character: releases and pending-flush retries run on the character's ordered lane, and the shutdown flush waits (briefly) for that lane before each release — see Every other system's writes are gated too
  • Characters pool out of the world scene (PersistentPool) on every despawn — logout, transfer, a lingering body, an eviction — so an instance scene that unloads after its last occupant leaves no longer destroys pooled characters the pool still counts
  • Verified client target reports (TargetSelectionBroadcast), which feed the observer-streaming target pin
  • Verified client buff dismissal (DismissBuffBroadcast): resolved against the sender's own character and its own buff container, refused for debuffs, and rate-limited on the same ingress guard as respawn and target reports
  • Optimistic concurrency via character.Version++ on every save
  • Runtime mapping caches for fast lookups: by ID, by lowercase name, by world, by connection, waiting-scene-load, session tokens
  • Lifecycle events for cross-system coordination: OnBeforeLoadCharacter, OnAfterLoadCharacter, OnConnect, OnDisconnect, OnSpawnCharacter, OnDespawnCharacter, OnPetKilled
  • Per-system main-thread queue isolation with configurable drain cap per frame
  • Async worker backpressure via EnqueueAsyncWork with entity-key-based consistent routing and diagnostic caller names

Prerequisites

  • Unity 6.6 (6000.6.8f1)
  • FishNetworking — networking framework (ServerManager, SceneManager, NetworkObject, NetworkConnection, object pooling)
  • FishMMO Server Core — provides ServerBehaviour, ICharacterSystem, ICharacterMappingData, ICharacterSystemRuntimeData, ICharacterSystemMainThreadQueueData, ISceneServerSystem, ISceneServerRuntimeData, IAsyncWorkerData, CharacterSessionInfo, SceneServerAuthenticator, broadcast types (ClientValidatedSceneBroadcast, ClientScenesUnloadedBroadcast, GuildAddBroadcast, GuildAddMultipleBroadcast, PartyAddBroadcast, PartyAddMultipleBroadcast, FriendAddBroadcast, FriendAddMultipleBroadcast, KnownAbilityAddBroadcast, KnownAbilityAddMultipleBroadcast, KnownAbilityEventAddBroadcast, KnownAbilityEventAddMultipleBroadcast, AchievementUpdateBroadcast, AchievementUpdateMultipleBroadcast, InventorySetItemBroadcast, InventorySetMultipleItemsBroadcast, BankSetItemBroadcast, BankSetMultipleItemsBroadcast, HotkeySetBroadcast, HotkeySetMultipleBroadcast), WorldSceneDetails, SceneTeleporterDetails, CharacterRespawnPositionDetails, and IPeriodicUpdateSystem
  • FishMMO Database — provides ICharacterService, IUnitOfWorkService, ICharacterSessionOwnershipService, ICharacterItemService, ICharacterAttributeService, ICharacterAbilityService, ICharacterKnownAbilityService, ICharacterAchievementService, ICharacterWaypointService, ICharacterFriendService, ICharacterGuildService, ICharacterPartyService, IPartyService, ICharacterHotkeyService, ICharacterBuffService, ICharacterFactionService, ICharacterArchetypeService, ICharacterQuestService, CharacterData, BulkWriteResult, and all sub-entity data DTOs
  • FishMMO Shared — provides IPlayerCharacter, ICharacterDamageController, ICharacterAttributeController, IAbilityController, IAchievementController, IInventoryController, IBankController, IEquipmentController, IFriendController, IGuildController, IPartyController, IBuffController, IFactionController, RaceTemplate, CharacterFlags, AccessLevel, Item, Ability, Buff, Faction, Achievement, HotkeyData

Installation / Build

This is an integrated module within FishMMO. It is included as part of the server-side scene-server implementation and does not require separate installation. Ensure the FishMMO Server Core and its dependencies are properly configured in your Unity project.

Quick Start Guides

  1. Ensure CharacterSystem is present on the scene server GameObject (it inherits from ServerBehaviour and implements ICharacterSystem<NetworkConnection, Scene>). The asset is created via Create > FishMMO > Server > SceneServer > Character System.
  2. Verify that the following data containers are registered in DataContainerRegistry:
    • CharacterMappingData → ICharacterMappingData<NetworkConnection>
    • CharacterSystemRuntimeData → ICharacterSystemRuntimeData
    • CharacterSystemMainThreadQueueData → ICharacterSystemMainThreadQueueData
    • AsyncWorkerData (shared async work queue)
  3. Verify that ISceneServerSystem<NetworkConnection> is registered in BehaviourRegistry for scene loading and validation.
  4. Verify that SceneServerAuthenticator exists in the scene for authentication event subscription.
  5. Verify that ICharacterService and all sub-entity services are registered in Database.ServiceRegistry.
  6. Adjust inspector parameters (saveRate, sessionLeaseRefreshRate, outOfBoundsCheckRate, maxMainThreadActionsPerFrame) as needed.
  7. On initialize, CharacterSystem registers the authenticator callback, broadcast handlers (ClientValidatedSceneBroadcast, ClientScenesUnloadedBroadcast, RespawnAtBindPointBroadcast, ResurrectAcceptBroadcast), scene manager events, connection state events, character events (IPlayerCharacter.OnTeleport, ICharacterDamageController.OnKilled), and periodic callbacks for save, session lease refresh, pending-flush retry, transfer watchdog, out-of-bounds checks, and respawn/resurrect guard sweep.
  8. On deinitialize, it unregisters all event handlers, snapshots and persists all character data, drains the pending-flush retry queue, and releases all claimed sessions.

Configuration

Inspector Parameters

Parameter Type Default Description
maxMainThreadActionsPerFrame int 200 Max character-system actions drained from main-thread queue per frame
saveRate float 30.0 Interval in seconds between periodic character saves (min 1.0)
sessionLeaseRefreshRate float 20.0 Interval in seconds between batched session lease refreshes (min 1.0). Must stay well under the 2-minute lease duration so a few missed passes cannot let a live character's claim lapse.
outOfBoundsCheckRate float 2.5 Interval in seconds between out-of-bounds checks (min 0.1)

Constants

Constant Value Description
AuthCallbackCooldownSeconds 2.0 Minimum seconds between auth-callback character load requests per account. Exceeding it disconnects with RateLimited
ValidatedSceneBroadcastCooldownSeconds 2.0 Minimum seconds between validated-scene broadcasts per connection
PendingFlushRetryIntervalSeconds 3.0 Interval between pending save/release retry passes
MaxPendingFlushAttempts 12 Attempts before abandoning a pending flush (spans past the 2-minute lease, after which the claim frees itself)
TransferDisconnectGrace 15s Grace period for a handed-off client to disconnect on its own before the watchdog forces it
TransferDisconnectSweepIntervalSeconds 5.0 Interval between transfer watchdog sweeps
CharacterResidencyTimeout 60s How long an authenticated connection may go without a character before the residency watchdog disconnects it
CharacterResidencySweepIntervalSeconds 10.0 Interval between residency watchdog sweeps
SceneLoadStallTimeoutSeconds / SceneLoadMaxSeconds (cfg) 120 s / 900 s How long a character in WaitingSceneLoadCharacters may go without a load-progress heartbeat, and the absolute cap on acknowledging its scene load
SceneLoadTimeoutSweepIntervalSeconds 10.0 Interval between scene-handshake watchdog sweeps
DefaultSessionLeaseDuration 2 min Database-side lease duration (CharacterService), the backstop that frees a claim held by a dead server

Required Data Containers

Attribute Container Type Purpose
[RequiresDataContainer] CharacterMappingData Runtime mapping caches (connection, ID, name, world, waiting load, session tokens)
[RequiresDataContainer] CharacterSystemRuntimeData Periodic save processing guard (atomic begin/end save)
[RequiresDataContainer] CharacterSystemMainThreadQueueData Per-system main-thread queue for marshaling async completions
[RequiresDataContainer] AsyncWorkerData Shared async work queue with entity-key routing

Runtime Mapping Model

CharacterMappingData maintains synchronized runtime indices:

Map Key → Value Purpose
CharactersByID characterID → IPlayerCharacter Fast lookup by character ID
CharactersByLowerCaseName lowercase name → IPlayerCharacter Case-insensitive name lookup
CharactersByWorld worldID → (characterID → IPlayerCharacter) Per-world character grouping
ConnectionCharacters connection → IPlayerCharacter Active spawned character per connection
WaitingSceneLoadCharacters connection → IPlayerCharacter Character loaded from DB but not yet scene-validated
SessionTokens characterID → CharacterSessionInfo Claimed session ownership (Token + ServerID)

Threading Model

Thread Responsibilities
Main thread Unity/FishNet object lifecycle, prefab instantiation, controller hydration, map mutations, scene validation, broadcasts, out-of-bounds checks, main-thread queue drain
Async worker DB load/save/session operations (claim, release, lease refresh), social data fetches, character and sub-entity persistence, and the item flush handed over by ICharacterInventorySystem.CaptureDespawnFlush

Usage Examples

Registered Broadcasts

CharacterSystem registers the following server-side broadcast handlers on initialize:

Broadcast Handler Purpose
ClientValidatedSceneBroadcast OnClientValidatedSceneBroadcastReceived Client confirms scene loaded; server spawns character and sends initial payloads
ClientScenesUnloadedBroadcast OnClientScenesUnloadedBroadcastReceived Client confirms scene unloaded; server disconnects if no character is loaded
RespawnAtBindPointBroadcast OnClientRespawnAtBindPointBroadcastReceived Dead player asks to respawn at their bind point
ResurrectAcceptBroadcast OnClientResurrectAcceptBroadcastReceived Dead player accepts a recorded resurrect offer
RequestLeaveInstanceBroadcast OnClientRequestLeaveInstanceBroadcastReceived Leave the current instance
RequestInstanceDetailsBroadcast OnClientRequestInstanceDetailsBroadcastReceived Instance panel readout
InstanceKickBroadcast OnClientInstanceKickBroadcastReceived Party leader removes a member from the run
InstancePrivacyBroadcast OnClientInstancePrivacyBroadcastReceived Party leader changes the run's listing
TargetSelectionBroadcast OnClientTargetSelectionBroadcastReceived Client reports its selected target; verified, then installed on ITargetController
DismissBuffBroadcast OnClientDismissBuffBroadcastReceived Player clicks a buff off their own HUD strip; verified against the sender's own buffs, then removed

DismissBuffBroadcast carries a template ID and nothing else, and is debounced per connection (BuffDismissOperation = 8, BuffDismissDebounceMs = 100). It resolves the sender's own character and that character's own buff container — a request can never name someone else's buff — and refuses anything BaseBuffTemplate.CanBeDismissedByPlayer rejects, which is every debuff. The removal then rides the existing reconcile: BuffController.Remove marks the snapshot dirty and the owner's RestoreFromReconcile fires OnRemoveBuff, so there is no second message and no client-side optimistic removal. See the buff system's README for the client half.

TargetSelectionBroadcast is debounced per connection (TargetSelectionOperation = 7, TargetSelectionDebounceMs = 50). Verification is the whole job: the value feeds the observer-streaming target pin, so a non-zero id must resolve to a spawned character in the sender's own scene or an unverified id would let a modified client pin arbitrary objects into its own observer budget. Anything that fails to resolve is stored as no-target rather than dropped, so a bad report cannot leave a stale pin standing. Range is deliberately not checked at receipt — the pin bounds it at use, where the live distance is already in hand, and rejecting on a moving value would flap.

Subscribed Events

Event Source Event Handler Purpose
SceneServerAuthenticator OnClientAuthenticationResult Authenticator_OnClientAuthenticationResult Entry point for character loading after authentication
SceneManager OnClientLoadedStartScenes SceneManager_OnClientLoadedStartScenes Validates character scene and sends ClientValidatedSceneBroadcast
IPlayerCharacter OnTeleport IPlayerCharacter_OnTeleport Handles teleportation between scenes
ICharacterDamageController OnKilled CharacterDamageController_OnKilled Handles player death, NPC despawn, pet death
RespawnAtBindPointBroadcast Client broadcast OnClientRespawnAtBindPointBroadcastReceived Handles dead player respawn at bind point
ResurrectAcceptBroadcast Client broadcast OnClientResurrectAcceptBroadcastReceived Handles dead player accepting a resurrect
Connection state Remote connection stopped OnRemoteConnectionStopped Cleans up auth rate-limit tracking and character mappings

Exposed Lifecycle Events

CharacterSystem exposes the following events for cross-system coordination:

Event Signature When Fired
OnBeforeLoadCharacter Action<NetworkConnection, long> Before character is loaded from the database
OnAfterLoadCharacter Action<NetworkConnection, IPlayerCharacter> After character is successfully loaded and scene load initiated
OnConnect Action<NetworkConnection, IPlayerCharacter> After character is added to active connection mapping (post-spawn)
OnDisconnect Action<NetworkConnection, IPlayerCharacter> After character is removed from active mapping (disconnect or teleport)
OnSpawnCharacter Action<NetworkConnection, IPlayerCharacter, Scene> After character is spawned in the scene via ServerManager.Spawn
OnDespawnCharacter Action<NetworkConnection, IPlayerCharacter> After character is despawned during save-and-despawn
OnPetKilled Action<NetworkConnection, IPlayerCharacter> After a pet owned by a player character is killed

Every one of these events is raised through DispatchCharacterEvent, which invokes each subscriber independently and logs anything that throws. They all fire part-way through a teardown, with the save, the session release or the despawn still to come on the line after them — so a plain ?.Invoke let one exception in a social system abandon both the rest of the invocation list and the caller, leaving a character removed from every mapping but never saved and never released, or its NetworkObject spawned in the world with no owner. Losing one subscriber's bookkeeping is recoverable; losing the teardown is not.

It also exposes one command, SuppressCombatLingerOnDisconnect(conn). It marks the next disconnect on that connection as something the server is doing on purpose rather than a player walking out of a fight, which suppresses the combat-logout linger for it. Callers that transfer a character through the ordinary disconnect pipeline need it — SceneChannelSystem and the dungeon finder both do — and so does KickRequestSystem: an operator kick is a removal, not a departure, and lingering there keeps the kicked character's body in the world holding its session claim, which makes a kick the opposite of a remedy for a character that is stuck. IPlayerCharacter_OnTeleport and the cross-scene bind-point respawn instead release the character themselves before disconnecting, so they never reach the linger check. A transfer that lingered would leave the body and its session claim on the source server while the client arrived at the destination, which could then not claim the character and would kick it on every retry until the linger expired.

Combat-Logout Linger

A character whose owner disconnects mid-combat keeps its body in the world instead of being despawned, so closing the client is not a way to win a losing fight. TryBeginCombatLinger removes ownership (which is what stops FishNet despawning the object with its connection), flags the row IsCombatLogged, puts the body back into the scene's population count, and persists a snapshot immediately — the body can be damaged and killed from here with nothing attached to it, so a crash mid-linger must not roll that back.

It also cancels any activation in progress. A despawn would have done this for free — FishNet's ResetState calls AbilityController.Cancel() — but a lingering body is by definition not despawned, so an in-flight cast simply carried on: the server keeps ticking OnReplicate for an unowned object, and a tick with no input re-asserts IsHeld from the replicated flags rather than clearing it. A channelled or charged ability therefore held indefinitely and a plain cast ran to completion and fired, spawning projectiles and raising ECA events on behalf of a player who was no longer connected and could not aim, retarget or stop them. Cancel() also unlocks any consumable inventory slot the activation had reserved, which would otherwise follow the character into its next session — the linger's snapshot is what the reattach reloads.

The linger ends on whichever comes first: the character leaving combat, dying, its owner reconnecting (TryReattachLingeringCharacter), or combatLogoutLingerSeconds elapsing. That last one is the guarantee that an attacker cannot pin a player in the world indefinitely by refusing to let their combat timer lapse.

Character Load Pipeline

Step 1 — Authentication callback (Authenticator_OnClientAuthenticationResult):

  1. Arms the residency watchdog (CharacterResidencyTimeout) before any branch below can return.
  2. Rate-limits per-account auth callbacks (AuthCallbackCooldownSeconds); a refusal disconnects with RateLimited.
  3. Validates: connection not already loading, authenticated, account name resolved, ISceneServerSystem available, ICharacterService available, server ID valid.
  4. Hands off to TryReattachLingeringCharacter when this account left a combat-logout body on this server, which carries the existing claim into the load instead of contending with it.
  5. Enqueues LoadCharacterAsync to the async worker.

Step 2 — Async DB snapshot + session claim (LoadCharacterAsync):

  1. Fetches the selected character for the account, with its staff lock, in one read via ICharacterService.FetchSelectedWithLockAsync, to resolve its ID and refuse a locked character (terminally) before the claim. A failed read refuses this attempt only (ServerError).
  2. Claims the session via ClaimCharacterSessionAsync → TryClaimAsync(characterID, serverID), before heavy hydration, so contention fails before 14 sub-entity fetches. Contention (InvalidOperation) is retried up to 5 times with linear backoff (~1.5s total); any other error fails immediately. This runs outside the Unit of Work — retrying inside an open transaction would hold it for the whole backoff.
  3. Re-reads the character row now that the claim is held, and verifies the selected character did not change. The pre-claim read is unsynchronised and on a scene transfer can predate the source server's final save; loading it would put the player back where they started.
  4. Begins IUnitOfWork for a consistent sub-entity snapshot. If this fails, the already-committed claim is released explicitly (there is no transaction to roll it back).
  5. Fetches 14 sub-entity datasets sequentially within the UoW: items, attributes, abilities, known abilities, achievements, waypoints, friends, guild, party (plus a party lookup when one is set), hotkeys, buffs, factions, archetypes, quests. Any one of them failing abandons the load: AbandonLoadAfterFetchFailure logs, releases the held session, and disconnects with ServerError. There is no partial load.
  6. Commits the read-only transaction.
  7. Bundles all data into CharacterLoadContext and marshals to main thread.
  8. On failure after claim: releases session and kicks connection.

Step 3 — Main-thread instantiate + hydrate (InstantiateAndLoadCharacter):

  1. Validates connection is still active; releases session if not.
  2. Validates character is not already loaded.
  3. Fires OnBeforeLoadCharacter.
  4. Looks up RaceTemplate and instantiates prefab from FishNet object pool.
  5. Populates base character fields from CharacterData (ID, name, account, world, scene, bind point, instance, race, flags, etc.).
  6. Hydrates all controllers from pre-fetched DTOs: attributes (resource vs regular), items routed to inventory/bank/equipment by their container column (with Equippable.Equip), abilities, known abilities, achievements, waypoints, friends, guild, party, hotkeys, buffs (with tick recalculation), factions, archetypes, quests.
  7. Resolves scene (world or instance) and attempts scene load via ISceneServerSystem.TryLoadSceneForConnection.
  8. On success: fires OnAfterLoadCharacter, stores session token, moves character to WaitingSceneLoadCharacters.
  9. On failure: releases session, pools prefab, disconnects.

Step 4 — Scene validation + spawn (SceneManager_OnClientLoadedStartScenes → OnClientValidatedSceneBroadcastReceived):

  1. SceneManager_OnClientLoadedStartScenes: verifies character exists in WaitingSceneLoadCharacters, validates scene is loaded and valid, sends ClientValidatedSceneBroadcast to client.
  2. OnClientValidatedSceneBroadcastReceived: promotes character from WaitingSceneLoadCharacters into all active maps (ConnectionCharacters, CharactersByID, CharactersByLowerCaseName, CharactersByWorld), sets physics scene, toggles mortal, activates GameObject, enables IsLoaded flag, spawns via ServerManager.Spawn, fires OnSpawnCharacter and OnConnect, sends non-DB payloads, enqueues async social data fetch.

Initial Payloads After Spawn

Immediate non-DB payloads (SendNonDbCharacterData):

Payload Broadcast Type
Known base abilities KnownAbilityAddMultipleBroadcast
Known ability events KnownAbilityEventAddMultipleBroadcast
Achievements AchievementUpdateMultipleBroadcast
Inventory items InventorySetMultipleItemsBroadcast
Bank items BankSetMultipleItemsBroadcast
Hotkeys HotkeySetMultipleBroadcast

Module payloads. Friends, party and guild rosters are sent by the Social module's systems, each to a spawned player, not by CharacterSystem (see Assets/FishMMO/Modules/Social).

Session Ownership and Release

Character sessions are explicitly claimed/released to prevent dual-server ownership:

Operation Method When
Claim TryClaimAsync(characterID, serverID) During LoadCharacterAsync, before sub-entity hydration. Succeeds only when the row is Offline or its lease has expired. Skipped when a combat-logout reattach hands the load a claim this server already holds.
Lease refresh RefreshSessionLeasesAsync(leases) OnPeriodicSessionLeaseRefresh, batched across every held session in one statement
Release ReleaseAsync(characterID, serverID, token) On disconnect, teleport, bind-point respawn into another scene, load failure, scene validation failure, deinitialize

Claim, release and lease refresh all verify the full ownership triple (character, owner server, owner token), so a stale server can neither free nor extend a claim it no longer holds.

A claim handed to LoadCharacterAsync by a combat-logout reattach is tracked from the method's first line, alongside the character ID it belongs to, so the abandon paths that run before any character row has been read still have something to give back — and so a reattach whose account no longer selects that character is refused rather than installing the token under the wrong ID. The final hand-off to the main thread is checked too: it is the only step that installs the claim in SessionTokens, so a rejected enqueue releases instead of stranding it.

All release paths follow save-then-release ordering via SaveAndReleaseCharacterAsync to ensure data is persisted while the session lock is still held. The character row, its sub-entity rows and the item flush all travel in that one work item. The sub-entity writes used to be enqueued separately, on a different worker lane than the save-and-release, and the item snapshot was enqueued from the despawn event onto the character's ordered lane while the save-and-release ran unkeyed on another — so the release could land, the destination scene server could claim and load, and the item snapshot would then be refused by the ownership assertion or land too late for the load that had already read the rows.

The item half is captured, not enqueued: ICharacterInventorySystem.CaptureDespawnFlush(character, sessionInfo) builds the batch while the character is still resident and returns a Func<Task<ItemWriteOutcome>> that is awaited before the release, and whose outcome decides it: a flush that still reports Retry after its bounded attempts keeps the claim and goes to the pending-flush queue, which runs it again and releases only once it lands (NotOwned stops everything; Rejected is logged as lost and released). The lease is passed explicitly for the same reason the caller takes the token out of SessionTokens first. TryExtractAndReleaseSession is used for non-save release paths (waiting-to-load characters, scene validation failures), and every path ultimately routes through ReleaseSessionSafely.

The release happens even if the row save fails (the item flush is the exception above). Holding the claim back because a write failed strands the character far more visibly than losing one save: the destination scene server cannot claim it and kicks the player. A failed save is retried separately by the pending-flush queue, where the version guard drops it if the next owner has already written something newer.

Pending flush retry

QueuePendingFlush records any save, item flush and/or release that could not be completed on its first attempt — because EnqueueAsyncWork returned false (AsyncWorkerData refuses admission once maxOutstandingItems accepted-but-unfinished items are in flight; work runs concurrently behind a SemaphoreSlim capped at maxConcurrency, ordered per entity key by OrderedLane) or because the database call failed. OnPeriodicPendingFlushRetry drains it every PendingFlushRetryIntervalSeconds with linear backoff up to MaxPendingFlushAttempts, and DrainPendingFlushes flushes whatever remains during OnDeinitialize. Each attempt runs on the character's ordered lane (keyed by its id), as ReleaseSessionSafely's release does: every write another system queued for the character before its departure quotes the claim an attempt hands back, and is refused once it is released, so the release must come after them — which it does on the lane and did not off it, exactly when the lane was backed up enough to send the departure here.

Terminal outcomes are not retried: a release that reports InvalidOperation/NotFound means the session is no longer ours, a save rejected as StaleState means newer state is already persisted, and DUPLICATE_REPLAY means the save already landed. The release waits for the entry's item flush and its sub-entity rows: a departure whose save-and-release could not be enqueued (SaveAndDespawnCharacter, a failed reattach) hands its SubEntitySnapshot to the entry rather than to a lane of its own, because those rows are ownership-gated and would be refused, not merely late, if they landed after the release. A merge into an entry builds a new snapshot rather than extending the one an attempt may be writing. Each entry is locked while it is merged into and while an attempt reads and clears its work, and an entry is retired as it is removed, so a merge can never land in an entry on its way out.

Note that a character queued for release has already been removed from SessionTokens, so the lease refresher no longer covers it — if every retry fails, the claim still frees itself when the lease expires.

Periodic Save

OnPeriodicSave(deltaTime) fires at saveRate intervals:

  1. Validates initialization, and returns only when CharactersByID and LingeringCharacterCount are both zero — a combat-logout body has no connection, so it is absent from the map but still resident and still accumulating state worth writing.
  2. Acquires atomic processing guard via TryBeginSave.
  3. Snapshots character DTOs on the main thread via BuildCharacterData (increments character.Version for optimistic concurrency, and captures the buff set that rides the row), pairing each with the CharacterSessionInfo this server holds so the write can prove ownership, and appends every dirty sub-entity row of that character into one SubEntitySnapshot via AppendSubEntities.
  4. AppendLingeringCharacterSnapshots adds the combat-logout bodies to both lists.
  5. Enqueues SaveAllCharactersAsync, which writes the rows through ICharacterService.PersistManyAsync — one transaction per 500 characters, with the single-row save's version and ownership checks per row and an outcome per row (a lost claim evicts that character alone) — and releases the processing guard in finally.
  6. EnqueueSubEntitySaves hands every non-empty list of the snapshot to the persistence lane independently: attributes (one statement for the whole pass), abilities, pets, achievements, waypoints, factions, archetypes, known abilities. An attribute a trade is settling (CharacterAttribute.IsSettling) is left dirty for the pass after the trade's outcome; see the trade system's README.

A character whose capture throws is skipped for that pass and reported through a RepeatingFaultLog; the processing guard is released in a finally on every exit that did not hand it to SaveAllCharactersAsync. (It used to latch on the first exception and stop periodic saves until restart.)

SubEntitySnapshot is one type rather than eight parallel lists threaded through five save paths. Each new sub-entity had to be added to every one of those paths by hand, and factions were simply missed for the life of the project — fetched on login, never written back. With the capture and the saves in one place there is one list to extend and no path that can forget a table.

A dirty mark is cleared only by a write that landed. Each SaveXAsync clears its marks (MarkAttributesPersisted, MarkAbilitiesPersisted, MarkKnowledgePersisted; a persistence participant such as achievements, factions or archetypes clears its own in its SaveAsync) back on the main thread, and only when BulkWriteReporting.MayClearDirtyMarks holds: the write succeeded and reports Filtered == 0. Rows the ownership gate refused are filtered (Unowned), and a batch it refused whole is a Forbidden failure, so a refused write never clears a mark. Every mark resolves lingering bodies as well as connected characters (TryGetResidentCharacter); abilities used to look only in CharactersByID, so a lingering body's abilities were rewritten every pass. A failed write leaves everything marked so the next pass carries it — the periodic path has no other retry. Filtered rows are why the outcome matters rather than the boolean alone: a row the service declined to attempt never reached the database, and clearing it would retire a value that was never stored. Superseded rows are the opposite and safe to clear, because the database already holds something newer.

Saving does not touch session leases. PersistAsync previously extended the lease for any row whose session was Online without checking which server was writing, which let a stale save from a released character extend the new owner's lease.

Periodic Session Lease Refresh

OnPeriodicSessionLeaseRefresh(deltaTime) fires at sessionLeaseRefreshRate intervals, independently of the save cycle:

  1. Snapshots every entry in SessionTokens into CharacterSessionLeaseData triples on the main thread.
  2. Enqueues a single batched ICharacterService.RefreshSessionLeasesAsync call (chunked at 500 rows per statement).
  3. Logs a warning when fewer rows were refreshed than sent — that means at least one claim is no longer owned by this server, the signature of the split-brain window the lease exists to bound.

This is deliberately decoupled from saveRate, so a claim's liveness never depends on how long a save pass takes: a pass stretched by a slow database or a backed-up worker (or skipped at the processing guard) must not let a live character's 2-minute lease lapse and become claimable while it is still online.

Periodic Out-of-Bounds Check

OnPeriodicOutOfBoundsCheck(deltaTime) fires at outOfBoundsCheckRate intervals:

  1. Iterates all ConnectionCharacters.
  2. Resolves scene name (instance or world).
  3. Checks character position against WorldSceneDetails.Boundaries.
  4. If out of bounds: selects a random respawn position and teleports the character.

Teleport Flow

IPlayerCharacter_OnTeleport(character):

  1. Validates character exists and IsTeleporting.
  2. Resolves current scene from WorldSceneDetailsCache.
  3. Validates teleporter exists in scene details. A refusal goes through CancelTeleport(character, reason, playerText, severity), which clears TeleporterName and sends the owner a ToastBroadcast — the refusal used to be logged server-side only, leaving the player standing on a teleporter with no explanation.
  4. Tells connection to unload current world scene.
  5. Sets character immortal.
  6. Fires OnDisconnect early (requires current scene context).
  7. Updates SceneName and position/rotation to teleporter destination.
  8. Removes instance and loaded flags.
  9. Calls RemoveCharacterConnectionMapping with skipOnDisconnect: true — triggers save-then-release, forcing reconnect through world routing.
  10. Arms the transfer watchdog via ArmTransferDisconnect(owner).

Nothing in this flow disconnects the client directly. The transfer depends on the client reporting its scene unload (ClientScenesUnloadedBroadcast), which is what sends it back to the world server. Two safeguards keep that from becoming a hang:

  • OnClientScenesUnloadedBroadcastReceived checks for a loaded character before consulting its rate limiter. A client unloads scenes on the way in as well as on the way out, so stamping the limiter on the benign entry-time broadcast would swallow a teleport broadcast arriving within the next five seconds — which teleporters placed near a spawn point hit every time.
  • OnPeriodicTransferDisconnectSweep force-disconnects any armed connection still present after TransferDisconnectGrace, skipping connections that have since acquired a character (FishNet recycles ClientIds).

Death/Respawn Flow

CharacterDamageController_OnKilled(killer, defender):

  1. Removes all buffs from the defender.
  2. Player character:
    • Sets IsDead flag, sends DeathBroadcast to client to show death dialog.
    • Player chooses: "Respawn at Bind Point" (teleports to bind + revives) or waits for "Resurrect" from another player (revives at corpse location).
    • Reconnect-while-dead: IsDead flag is persisted; DeathBroadcast re-sent after scene load so dialog reappears.
  3. NPC: calls npc.Despawn() which enters corpse state for CorpseDecayDuration seconds before returning to the object pool.
  4. Pet: calls pet.Despawn() which returns to pool immediately (no corpse timer).

Client-side death handlers:

  • RespawnAtBindPointBroadcast → OnClientRespawnAtBindPointBroadcastReceived: revives character, teleports to bind.
  • ResurrectAcceptBroadcast → OnClientResurrectAcceptBroadcastReceived: revives character at current position (no teleport).

When the bind point is in a different scene, respawning is a scene-server transfer and follows the same ordering as the teleporter path: fire OnDisconnect while the character still knows the scene it is in, then apply the bind scene/position, then RemoveCharacterConnectionMapping(skipOnDisconnect: true) to save and release, then disconnect. Deferring the save and release to the connection-stopped handler instead meant SceneName had already been overwritten with BindScene by the time OnDisconnect ran, so party, guild and per-scene bookkeeping were told the player left the scene they were respawning into rather than the one they died in.

Targeted Broadcasts

Method Lookup Returns
SendBroadcastToCharacter<T>(string characterName, T msg) CharactersByLowerCaseName (case-insensitive) true if sent
SendBroadcastToCharacter<T>(long characterID, T msg) CharactersByID true if sent

Disconnect Cleanup

OnRemoteConnectionStopped(conn):

  1. Removes the transfer watchdog entry, the residency and scene-handshake deadlines, and scene-unload and validated-scene rate-limit tracking for the connection.
  2. Removes auth callback rate-limit tracking for the account.
  3. Consumes any SuppressCombatLingerOnDisconnect marker for the connection.
  4. Calls RemoveCharacterConnectionMapping(conn, allowCombatLinger: <not a server-initiated disconnect>).

RemoveCharacterConnectionMapping(conn, skipOnDisconnect):

  1. Checks for waiting-scene-load character: removes from map, extracts and releases session, fires OnDisconnect, pools prefab.
  2. Checks for spawned character: removes from all mapping dictionaries (ConnectionCharacters, CharactersByID, CharactersByLowerCaseName, CharactersByWorld).
  3. Fires OnDisconnect (unless skipOnDisconnect).
  4. Extracts session info from SessionTokens.
  5. Calls SaveAndDespawnCharacter: disables IsLoaded, snapshots DTO on main thread, enqueues SaveAndReleaseCharacterAsync, despawns immediately.

Deinitialize

OnDeinitialize:

  1. Unregisters all event handlers (authenticator, broadcasts, scene manager, connection state, character events, periodic callbacks).
  2. Clears every per-connection watchdog and rate-limit map. This behaviour is a ScriptableObject, so its fields outlive a play-session restart in the editor while FishNet reissues ClientIds from zero — a stale entry whose id is reissued would be read as the new connection's state, and for a deadline map one that expired long ago.
  3. Captures all session tokens (spawned, lingering, waiting-to-load).
  4. Snapshots every connected character and every lingering body on the main thread (row, sub-entities, item flush) — lingering bodies directly, not through FinalizeCombatLinger, whose async save used to be raced by this method's own release of the same token — and takes over whatever the pending-flush queue holds.
  5. Synchronously runs FlushForShutdownAsync (bounded by shutdownFlushTimeoutMs, and by what remains of the server's 8 s teardown budget): releases the claims with nothing to write in one statement; writes every row through PersistManyAsync; writes every sub-entity table once for everyone; then, in parallel lanes, each character's item flush followed straight away by that character's release. A character is released only after all of its own writes have finished, so when the deadline cuts the flush short the characters already done are free and the rest keep their claims (their writes may still be in flight) until the lease expires. It used to save everyone in series and release nobody until the end, so a slow database released nobody at all. Before each release the flush also waits for the character's ordered lane to drain (DrainCharacterLaneAsync, at most ShutdownLaneDrainTimeoutMs = 1.5 s): this flush runs off the lanes, and a quest turn-in, grant or dismissal still queued there when the claim is handed back would be refused by the ownership gate. A lane that does not drain in time — typically one waiting on the main thread this flush is blocking — is released anyway, with a warning, rather than holding the player out for the lease.

Failure Semantics

  • Auth rate-limited connections are disconnected with RateLimited (timestamp not updated). They are not silently skipped: the auth callback is the only entry point to a character load, and every other watchdog on this server is armed downstream of it, so a quiet return left the connection authenticated, in no map, driven by nothing, and behind a client-side loading screen until the player killed the process.
  • A connection that authenticates but never ends up in WaitingSceneLoadCharacters or ConnectionCharacters is disconnected by the residency watchdog after CharacterResidencyTimeout. This is the backstop for load paths whose own failure branch is delivered through TryEnqueueMainThread, which is bounded and drops work when saturated — precisely when the load has also failed.
  • Invalid authentication state results in Kick(UnusualActivity).
  • TryClaimAsync contention is retried up to 5 times before kicking; non-contention errors kick immediately. No sub-entity data is fetched in either case.
  • A selected character that changes between the pre-claim and post-claim reads releases the claim and kicks.
  • Connection dying between async load and main-thread marshal triggers session release without kick.
  • Duplicate character load attempts are detected via CharactersByID and result in session release + kick.
  • Failed scene load releases session, pools prefab, and disconnects.
  • Scene validation failures after WaitingSceneLoadCharacters release session, pool prefab, and kick.
  • A release that cannot be enqueued or that fails at the database is queued for retry rather than dropped; if every attempt fails, the 2-minute database lease is the backstop.
  • Failed EnqueueAsyncWork logs a warning; critical paths (load, save-and-despawn) also take fallback action.
  • SaveAllCharactersAsync acts on per-row outcomes, so one character's lost claim or stale row does not affect another's; it does not touch session leases at all.
  • A sub-entity fetch that fails during load abandons the load rather than spawning a partially hydrated character.
  • Deinitialize catches per-character snapshot/save/release failures independently.

Operational Checks

Check How to Verify
Initialization success Confirm CharacterSystem logs "Initialized (SaveRate=30s, OutOfBoundsCheckRate=2.5s)" without errors on server startup
Data containers available Verify ICharacterMappingData, ICharacterSystemRuntimeData, ICharacterSystemMainThreadQueueData, and IAsyncWorkerData all resolve from DataContainerRegistry
Scene server system available Verify ISceneServerSystem<NetworkConnection> resolves from BehaviourRegistry
Authenticator found Verify SceneServerAuthenticator exists in the scene and OnClientAuthenticationResult is subscribed
Character service available Verify ICharacterService resolves from Database.ServiceRegistry
Auth rate limiting Send rapid repeated auth callbacks from the same account; confirm excess requests are logged as rate-limited and disconnected with a RateLimited notice rather than left hanging
Residency watchdog Force a character load to fail without disconnecting (e.g. saturate the main-thread queue); confirm the connection is dropped within CharacterResidencyTimeout and the client returns to world routing
Character load Authenticate a client with a selected character; confirm character is loaded, hydrated, and placed in WaitingSceneLoadCharacters
Session claim During load, confirm TryClaimAsync succeeds and session token is stored in SessionTokens
Session claim conflict Attempt to load a character already claimed by another server; confirm TryClaimAsync fails and connection is kicked
Sub-entity hydration After load, confirm all 14 sub-entity datasets are populated on the character's controllers
Fetch failure aborts the load Fail one sub-entity fetch (e.g. drop the connection mid-load); confirm the session is released, the client is disconnected with ServerError, and nothing is written over the unloaded state
Sub-entity persistence Change a faction, waypoint, archetype and known ability; wait for saveRate; confirm each list is enqueued and its dirty marks cleared only on a write with Filtered == 0
Sub-entity ownership gate Capture a periodic pass, release the character before its attribute write runs (or quote a stale claim); confirm the write reports FORBIDDEN or Unowned rows, the stored values are unchanged, and no dirty mark is cleared
Buff set Apply two buffs, save, let one expire and dismiss the other, save, relog; confirm neither comes back and character_buffs holds no rows for the character
Permanent buffs Stand in weather that applies an exposure buff, save, relog; confirm character_buffs holds no row for it and the buff returns from the weather, not from the database
Item flush ordering Disconnect a character; confirm CaptureDespawnFlush is awaited inside the save-and-release work item, before the session release
Target selection Send TargetSelectionBroadcast naming an object in another scene; confirm it is stored as no-target rather than pinned
Buff dismissal Send DismissBuffBroadcast for a debuff on the sender's own character; confirm nothing is removed and no error is raised. Then repeat for an ordinary buff and confirm the icon leaves the owner's strip on the next reconcile
Scene validation Confirm SceneManager_OnClientLoadedStartScenes validates the scene and sends ClientValidatedSceneBroadcast
Character spawn Confirm OnClientValidatedSceneBroadcastReceived promotes character into active maps, spawns network object, and fires OnSpawnCharacter
Non-DB payload broadcast After spawn, confirm client receives known abilities, achievements, inventory, bank, and hotkeys broadcasts
Social payload broadcast After spawn, confirm client receives guild members, party members, and friend online status broadcasts
Periodic save Wait for saveRate interval; confirm OnPeriodicSave fires and characters are persisted through PersistManyAsync (500 rows per batch), and that no session lease is touched
Save processing guard Trigger overlapping save cycles; confirm only one executes at a time via TryBeginSave
Session lease refresh Confirm OnPeriodicSessionLeaseRefresh batches every held session into one RefreshSessionLeasesAsync call on its own timer, and that the save path never touches a lease
Out-of-bounds check Move a character outside scene boundaries; confirm OnPeriodicOutOfBoundsCheck teleports them to a respawn point
Teleport flow Trigger a valid teleporter; confirm scene unload, immortality, position update, and save-then-release with reconnect
Invalid teleporter Trigger a non-existent teleporter name; confirm it is logged and no mutation occurs
Player death (same scene) Kill a player character whose bind scene matches current scene; confirm full heal and respawn at bind position
Player death (cross-scene) Kill a player character whose bind scene differs; confirm scene/position update, flag removal, and disconnect
NPC death Kill an NPC; confirm Despawn() is called
Pet death Kill a pet; confirm OnPetKilled is fired for the pet owner
Disconnect cleanup Disconnect a client; confirm character is saved, despawned, session released, and all mappings removed
Waiting character disconnect Disconnect a client with a character in WaitingSceneLoadCharacters; confirm session released and prefab pooled
Deinitialize Trigger server deinitialize; confirm all characters are saved, all sessions released, and all handlers unregistered
Optimistic concurrency Save a character; confirm character.Version is incremented in the persisted CharacterData
Main-thread queue drain Confirm queued async results are dispatched on the main thread within maxMainThreadActionsPerFrame per frame
Async backpressure Saturate async worker queue; confirm new work is rejected with a logged warning
Connection dead after async Kill a connection during async load; confirm session is released without kick on main-thread marshal
Duplicate load prevention Attempt to load an already-loaded character; confirm session release and kick

Flow Diagram

High-Level Overview

flowchart LR
    Spawn[Character spawn request] --> Sys[CharacterSystem]
    Sys -->|load state| DB[(PostgreSQL Characters)]
    Sys -->|instantiate| Scene[Scene world]
    Scene -->|tick / state changes| Sys
    Sys -->|persist diffs| DB
    Sys -->|broadcast updates| Clients[Nearby Clients]

Character Load Pipeline

Authenticator_OnClientAuthenticationResult(conn, authenticated)
│
├─ 1. Arm residency watchdog (CharacterResidencyTimeout)
├─ 2. Rate-limit check (AuthCallbackCooldownSeconds) → DisconnectWithNotice(RateLimited)
├─ 3. Validate: not already loading, authenticated, account name, dependencies
├─ 4. Resolve serverID on main thread
├─ 5. TryReattachLingeringCharacter (combat-logout body on this server)
└─ 6. EnqueueAsyncWork → LoadCharacterAsync
       │
       ├─ ICharacterService.FetchSelectedWithLockAsync(accountName) (row + staff lock)
       ├─ ICharacterService.TryClaimAsync(characterID, serverID) → sessionToken
       │    (outside any transaction; retried on contention)
       ├─ Re-read the character row now the claim is held
       ├─ IUnitOfWorkService.BeginAsync → UoW
       ├─ Fetch 14 sub-entity datasets within UoW (any failure →
       │    AbandonLoadAfterFetchFailure: release + ServerError):
       │    items, attributes, abilities, knownAbilities,
       │    achievements, waypoints, friends, guild, party,
       │    hotkeys, buffs, factions, archetypes, quests
       ├─ UoW.CommitAsync (read-only)
       └─ TryEnqueueMainThread → InstantiateAndLoadCharacter(CharacterLoadContext)
              │
              ├─ Validate connection still active
              ├─ Validate character not already loaded
              ├─ OnBeforeLoadCharacter(conn, characterID)
              ├─ RaceTemplate.Get → Instantiate prefab from pool
              ├─ Populate base character fields from CharacterData
              ├─ Hydrate controllers: attributes, items routed by
              │    container (+Equip), abilities, knownAbilities,
              │    achievements, waypoints, friends, guild, party,
              │    hotkeys, buffs (tick recalc), factions,
              │    archetypes, quests
              ├─ TryLoadSceneForConnection(conn, instance)
              ├─ OnAfterLoadCharacter(conn, character)
              ├─ Store SessionTokens[characterID]
              └─ WaitingSceneLoadCharacters.Add(conn, character)

Scene Validation + Spawn

SceneManager_OnClientLoadedStartScenes(conn, asServer)
│
├─ Validate character in WaitingSceneLoadCharacters
├─ Validate scene is loaded and valid
└─ Broadcast ClientValidatedSceneBroadcast to conn

OnClientValidatedSceneBroadcastReceived(conn, msg, channel)
│
├─ Remove from WaitingSceneLoadCharacters
├─ Add to ConnectionCharacters, CharactersByID,
│    CharactersByLowerCaseName, CharactersByWorld
├─ Set physics scene (stacked scene support)
├─ Set mortal, activate GameObject, enable IsLoaded
├─ ServerManager.Spawn(nob, conn, scene)
├─ OnSpawnCharacter(conn, character, scene)
├─ OnConnect(conn, character)
└─ SendNonDbCharacterData (immediate, main thread):
     knownAbilities, knownAbilityEvents, achievements,
     inventory, bank, hotkeys
   (module systems answer OnSpawnCharacter with their own payloads:
    friends, party and guild rosters, quests, …)

Disconnect + Save

OnRemoteConnectionStopped(conn)
│
├─ Remove auth rate-limit tracking, residency + scene-handshake deadlines
└─ RemoveCharacterConnectionMapping(conn)
       │
       ├─ [Waiting character] Remove from WaitingSceneLoadCharacters
       │    ├─ TryExtractAndReleaseSession
       │    ├─ OnDisconnect(conn, character)
       │    └─ Pool prefab
       │
       └─ [Spawned character] Remove from all mappings
            ├─ OnDisconnect(conn, character)
            ├─ Extract SessionTokens entry
            └─ SaveAndDespawnCharacter(conn, character, sessionInfo)
                   │
                   ├─ DisableFlags(IsLoaded)
                   ├─ BuildCharacterData (Version++) + AppendDepartureSubEntities
                   ├─ ICharacterInventorySystem.CaptureDespawnFlush(character, lease)
                   ├─ EnqueueAsyncWork (character's lane) → SaveAndReleaseCharacterAsync
                   │    ├─ SaveCharacterOutcomeAsync (persist while holding lock)
                   │    ├─ await itemFlush() (bounded retry) [same work item, before the release]
                   │    ├─ SaveSubEntitiesSequentiallyAsync (hotkey bar included)
                   │    ├─ [item flush still Retry] → QueuePendingFlush, claim kept
                   │    └─ ReleaseCharacterSessionAsync (Online → Offline)
                   ├─ OnDespawnCharacter(conn, character)
                   └─ PersistentPool.Despawn (pooled out of the world scene)

Teleport

IPlayerCharacter_OnTeleport(character)
│
├─ Validate character exists and IsTeleporting
├─ Resolve current scene from WorldSceneDetailsCache
├─ Validate teleporter in SceneTeleporterDetails
├─ UnloadSceneForConnection(conn, currentScene)
├─ Set immortal
├─ OnDisconnect(conn, character) [early, needs current scene]
├─ Update SceneName, position, rotation to destination
├─ DisableFlags(IsInInstance, IsLoaded)
└─ RemoveCharacterConnectionMapping(conn, skipOnDisconnect: true)
       └─ Save-then-release → reconnect via world routing

Death/Respawn

CharacterDamageController_OnKilled(killer, defender)
│
├─ RemoveAll buffs
├─ [Player + different bind scene]
│    ├─ Heal(999999)
│    ├─ Update SceneName/position to bind point
│    ├─ DisableFlags(IsInInstance, IsLoaded)
│    └─ Disconnect → reconnect via world server
├─ [Player + same bind scene]
│    ├─ Heal(999999)
│    └─ SetPositionAndRotationAndVelocity(bindPosition)
├─ [NPC] → Despawn()
└─ [Pet] → OnPetKilled(petOwner.conn, petOwner)

Periodic Save

OnPeriodicSave(deltaTime)
│
├─ Validate initialized; CharactersByID or LingeringCharacterCount non-zero
├─ TryBeginSave (atomic guard)
├─ Snapshot all CharacterData DTOs on main thread (Version++, buff set),
│    each paired with the CharacterSessionInfo held for it
├─ AppendSubEntities → one SubEntitySnapshot
├─ AppendLingeringCharacterSnapshots (combat-logout bodies)
├─ EnqueueAsyncWork → SaveAllCharactersAsync
│      ├─ Per 500 characters: ICharacterService.PersistManyAsync (one transaction, per-row outcomes;
│      │    each written row's buff set replaced in the same transaction)
│      └─ finally: EndSave (release guard)
└─ EnqueueSubEntitySaves (one lane per non-empty list)
       ├─ SaveAttributesAsync   ├─ SaveAbilitiesAsync    ├─ SavePetsAsync
       ├─ SaveKnownAbilitiesAsync                       ├─ SaveHotkeysAsync
       ├─ each CharacterPersistenceParticipant.SaveAsync (achievements, and the modules':
       │    factions, archetypes, waypoints, …)
       └─ each: written && Filtered == 0 → MarkXPersisted on the main thread

Project Structure

Directory Tree

Character/
├── CharacterSystem.cs                    # Core lifecycle: initialization, deinitialize, update, main-thread queue, async work helpers
├── CharacterSystem.Connection.cs         # Partial: disconnect handling, teleportation, out-of-bounds checks, death/respawn
├── CharacterSystem.Loading.cs            # Partial: auth callback, async DB fetch, prefab instantiation, scene validation, spawn
├── CharacterSystem.Saving.cs             # Partial: periodic save, save-and-despawn, session claim/release, BuildCharacterData
├── CharacterSystem.Social.cs             # Partial: async guild/party/friend fetch, non-DB payload broadcast, targeted broadcasts
├── CharacterSystem.Instance.cs           # Partial: instance readout, party-leader kick and visibility, difficulty death rules
├── CharacterSystem.CombatLogout.cs       # Partial: combat-logout linger, reattach, linger sweep and finalisation
├── CharacterSystem.Unstuck.cs            # Partial: the /unstuck (/stuck) chat command and its per-character cooldown
├── CharacterMappingData.cs               # Runtime mapping caches (connection, ID, name, world, waiting load, session tokens)
├── CharacterSystemRuntimeData.cs         # Runtime state: atomic save processing guard (TryBeginSave/EndSave)
├── CharacterSystemMainThreadQueueData.cs # Per-system main-thread queue container
└── README.md
Server/Core/World/SceneServer/Character/
├── ICharacterSystem.cs
├── ICharacterMappingData.cs
├── ICharacterSystemMainThreadQueueData.cs
├── ICharacterSystemRuntimeData.cs
└── CharacterSessionInfo.cs

Server/Core/RuntimeData/
├── IAsyncWorkerData.cs
└── IMainThreadQueueData.cs

Inheritance Hierarchy

Behaviour:

ServerBehaviour
└── CharacterSystem : ICharacterSystem<NetworkConnection, Scene>
        Partial classes:
        ├── CharacterSystem.Connection.cs
        ├── CharacterSystem.Loading.cs
        ├── CharacterSystem.Saving.cs
        ├── CharacterSystem.Social.cs
        ├── CharacterSystem.Instance.cs
        ├── CharacterSystem.CombatLogout.cs
        └── CharacterSystem.Unstuck.cs

Runtime Data Containers:

RuntimeDataContainer
├── CharacterMappingData : ICharacterMappingData<NetworkConnection>
├── CharacterSystemRuntimeData : ICharacterSystemRuntimeData
└── SystemMainThreadQueueData (abstract)
    └── CharacterSystemMainThreadQueueData : ICharacterSystemMainThreadQueueData

License

This module is part of the FishMMO project and is subject to the FishMMO project license.

Session claims are binding on writes

TryClaimAsync / ReleaseAsync / RefreshSessionLeasesAsync gate who may load a character. Until recently nothing gated who may write one: PersistAsync was guarded only by the monotonic Version, which does not identify the writer.

That made a lease lapse corrupting rather than untidy. A scene server whose lease expired while it was still running (a database outage or async-worker saturation lasting past the two-minute lease) kept simulating and saving characters another server had legitimately claimed — and reliably won, because its version counter had been climbing all session while the new owner restarted from the persisted row. Every periodic save overwrote the live session.

Two changes close it:

  • ICharacterService.PersistOwnedAsync puts the ownership triple in the same UPDATE as the write, so there is no check-then-write window. A displaced server gets DatabaseErrorCodes.Forbidden, checked before the version comparison — a displaced server usually looks version-stale too, and reporting that as a benign stale write is what let it retry forever. Every save path that holds a claim uses it: periodic save, save-and-release, combat-linger snapshot, linger reattach, pending-flush retry, and the shutdown flush.
  • ICharacterService.FetchUnownedSessionsAsync resolves which claims were lost when the batched lease refresh reports a short count, so eviction happens within one refresh interval (~20 s) rather than waiting for a save to be refused.

Lost-claim eviction

EvictLostCharacter removes a character this server no longer owns. It deliberately does not save and does not release:

  • not save, because the other server has been authoritative since it loaded — writing this server's diverged snapshot would overwrite the live session's progress, which loses strictly more than discarding it;
  • not release, because the row's owner token belongs to somebody else.

It logs at Error with the character ID, name and discarded version, removes the mappings, fires OnDisconnect so scene counts and social systems stay in step, despawns, and disconnects the client — which reconnects through the world server and reloads the authoritative row.

Sub-entity writes are gated too

Everything this system writes for a character besides its row — attributes, abilities, known abilities, achievements, factions, archetypes, and the pet row, pet attributes and pet buffs — goes through the services' PersistOwnedAsync, quoting the claim the rows were captured under (AppendSubEntities records it in SubEntitySnapshot.Claims; the departure paths pass it explicitly because they take it out of SessionTokens first). The database's CharacterWriteGate share-locks every such character, in ascending id order, while it is still Online under exactly that triple, and writes only those characters' rows:

  • A write captured by a session released a moment later cannot land. Before, a periodic pass still on the worker, or a retry, could land after the release — over an offline tax debit, over a trade's last settlement, or over the next owner's first save, whose versions restart from the rows it loaded and so lost to ours.
  • A release never races a write. A write in flight holds its share lock until it commits, and the release (an UPDATE of the row) waits behind it; a release that commits first is seen by the waiting write, which is then refused.
  • A refused row clears nothing. Rows of a character whose claim is gone are counted as BulkWriteResult.Unowned (part of Filtered), and a write that could touch none of its characters fails as Forbidden; either way MayClearDirtyMarks is false. Eviction is still the row save's and the lease refresh's job; the refusal only says what the tables lost.
  • The departure's own rows are never refused for being late, because they are written in the save-and-release work item, or in the pending entry, before the release they belong to.

Items were already gated by AssertOwnershipAsync inside the item transaction, but every call accepted an unclaimed row, which is exactly what a just-released character is; the item layer now accepts one only for a write that carries no claim at all (AllowsUnclaimedItemWrite). Waypoint pages are an OR-merge and stay ungated: a late merge can only add a place the character really discovered.

Validated against a throwaway PostgreSQL through the real services: a normal save; a write quoting a released claim (refused, value untouched); an offline debit that survives the late write, with the ungated write as the control that does overwrite it; a reclaimed character; a batch with one owned and one released character; a release that waits behind a write in flight; a write that waits for an uncommitted release and is refused when it commits (and admitted when it rolls back, or when the in-flight update is only a lease refresh); the same races for items and a pet table; and a stress run of gated writers against the row save, the lease refresh and release/re-claim churn with no deadlock.

Every other system's writes are gated too

Everything else a scene server writes for a resident character goes through the same gate, quoting the claim captured from SessionTokens with the request, on the main thread (ServerBehaviour.TryCaptureSessionClaim) and carried with the write — looked up later on the worker it could be a later session's claim. The single-row owned variants are ICharacterAbilityService.PersistOwnedAsync(row, claim) and DeleteAbilityOwnedAsync, and ICharacterQuestService.DeleteQuestOwnedAsync; the rest use the batched PersistOwnedAsync with one row.

Writer Write
AbilitySystem the crafted/purchased grant, its revoke, a forget
QuestSystem every quest update, turn-in and abandon
HotkeySystem the pump's bar (the departing bar rides the save-and-release — above)
InteractableSystem merchant, loot, mail and craft currency rows (TryPersistCharacterAttributes); a purchased known ability
AchievementSystem a known-ability reward
SceneServerSystem (operator economy) /admin setgold, givegold, takegold, setattr
GuildSystem the creation fee and its refund
HousingSystem a land purchase, and the tax charged to an owner online here
PetSystem a dismissal (release, owner's death, pet's death)

Refused before, not after. A request whose character has no claim here is refused before anything changes — a grant is not built, a purchase not charged, an operator's balance change not made — with the answer the request already had for a write that could not be made (a forget answers PersistFailed, a purchase Unavailable, a currency spend refunds). A resident always holds a claim, so this is a character that is leaving or being evicted.

What the player sees when a write is refused later (the claim was lost between the request and the write, which only a lapsed lease does): the same answer as any failed write — a grant fails and nothing is charged, a forget reports PersistFailed — and then, within one lease-refresh interval, the eviction that a lost claim always brings (EvictLostCharacter: disconnected with SessionSuperseded, reconnected to whichever server owns the character, whose state is what they see). The refused write is logged; it never reports success and never clears a dirty mark. A refusal does not request the eviction itself: the row save and the lease refresh already do, and a refusal for a claim that has since been replaced by a new session of the same character would evict the wrong session.

The grant's revoke is the one compensating write: a player who logs out inside the grant's round trip is released on its lane before the settlement finds them gone, so the revoke that removes the unpaid row always arrives after the release. It is admitted under the grant's claim or while the character holds no claim at all (DeleteAbilityOwnedAsync(..., admitReleased: true), CharacterWriteGate.AdmitOwnOrReleasedAsync), and refused only once another session has claimed — and loaded — the character.

Deliberately never gated: dialogue choices and waypoint pages (OR-merges: a late merge can only add something the character really did), and friends, party, guild membership and mail (social tables written for characters who are not resident, by design). The offline tax debit (HousingSystem.TryChargeWonPeriodFromRowAsync) writes a character NO server holds, inside a unit of work whose ownership assertion proves exactly that under the row lock; it carries no claim and keeps the ungated write.

Validated against a throwaway PostgreSQL through the real services: a grant under a live claim, under a released one (refused, nothing written) and for a missing character (NOT_FOUND); a forget under the previous session's claim (refused) and the current one (removed; a repeat succeeds); a revoke with and without admitReleased after the release, and after another server's claim (refused); a quest turn-in under a released claim (refused, quest stands) and the current one (deleted; a repeat succeeds; the version guard still applies); a grant, a quest delete and a revoke each waiting on an uncommitted release or claim, refused when it commits and admitted when it rolls back; a release waiting behind a gated write's share lock; and the one-row batches the other sites use (hotkey bar, known ability, pet dismissal) landing under the claim and refused after the release.

Buffs are one set, written with the row

character_buffs used to be upserted one row per buff and never deleted except with the character, AppendBuffData wrote nothing once a character had no buffs, and the load restores every row. A buff that expired, was dismissed or was stripped on death after it had first been saved therefore came back at the next login.

Now BuildCharacterData captures the character's complete buff set (CaptureBuffSet) into CharacterData.Buffs, and ICharacterService writes it in the same transaction as the row — PersistOwnedAsync, PersistAsync, and each row of PersistManyAsync — and only when the row's own UPDATE wrote (CharacterBuffService.ReplaceSetsAsync): rows the set does not name are deleted, the rest upserted. An empty set is the instruction that deletes; a null set (a fetched row, the world server's flag edits, a snapshot taken without a time manager) leaves the stored buffs untouched.

Why the row's version, and not a delete per buff. A delete must be safe against two saves landing out of order: an older save must never delete a buff a newer one wrote, nor re-add one a newer one dropped. Per-buff versions cannot give that: a buff re-applied after it ended is a new instance whose counter restarts (so its saves were refused as stale against its own dead predecessor's row), and a set that became empty leaves no row to carry a version, so an older save landing after it could re-insert what it dropped. The character row's version < incoming check (plus the ownership triple) already orders every save of a character, and running the set replacement behind it in the same transaction makes the set exactly as ordered as the row — a refused row writes no set. Buff.Version is gone; every row is stamped with the snapshot's version for inspection only. It also puts buffs behind the row's own ownership gate; the other sub-entity tables now have theirs (see Sub-entity writes are gated too).

Validated against a throwaway PostgreSQL through the real services: expire-then-save, dismiss-all-then-save, an older save landing after a newer one (including after a newer EMPTY set on a character with no rows), a lost claim, a replay, legacy rows with high per-buff versions, the batched path, 200 randomly overlapping pairs, and both queue orders behind a held row lock. Remaining time is frozen while offline, exactly as before.

Permanent buffs are not saved (IsPersistedBuff). They are the weather-exposure buffs, which the exposure system applies from where the character stands, every tick; a saved one had no expiry to record and came back as a buff that expired on its first tick. Leaving them out of the set deletes their old rows at the next save, and the load skips any it still finds. Pets follow the same rule.

Rows written before this change are replaced by the first save after it; a character's first login after deploying still restores whatever stale rows it had.

Death, respawn and resurrect

CharacterDamageController_OnKilled flags IsDead first, before any side-effecting call. CharacterDamageController.Kill guards re-entry on that flag but never sets it — this handler does, and it is invoked at the very end of Kill. Anything side-effecting that ran before the flag was set executed inside a window where a second Kill would sail past the guard and recurse; buff removal, which invokes each buff's removal effects, is exactly such a call.

The handler never revives, teleports, or moves the character. Bind-point movement happens only in OnClientRespawnAtBindPointBroadcastReceived, in response to an explicit client request.

Resurrect offers

ApplyReviveAction offers a resurrect to a player rather than applying one — the revive happens only if they accept. It previously called Revive and then sent the offer, which made the prompt meaningless and left the target with health restored but IsDead still set, because only the accept handler cleared it. A player who ignored the prompt stayed in that contradictory state indefinitely.

Offers are recorded server-side (pendingResurrectOffers: who offered, how much, 30 s expiry) and raised through ICharacterDamageController.OnResurrectOffered, so the shared ECA action does not need to reference server types.

OnClientResurrectAcceptBroadcastReceived requires a matching, unexpired recorded offer. Previously it only checked that the named resurrector existed and shared the scene — not that they had offered anything — so a dead player could revive themselves at full health at will by naming any nearby character. The accept now applies the offer's configured amount, credited to the actual resurrector so their ECA resurrect triggers fire, instead of a blanket full heal. Choosing bind-point respawn declines any outstanding offer; unanswered offers expire on the existing respawn/resurrect sweep.

Reconnecting while dead

Death survives a disconnect intact: combat-logout linger declines a dead character, the save preserves IsDead (only IsInCombat is masked), and health persists at zero. On reload the flag and health are restored, scene entry re-sends DeathBroadcast, and Immortal is cleared. The character cannot regenerate, be healed, be damaged further, move, or cast. CharacterAnimationController re-applies the death pose when the animator appears, because death is an Animator trigger — a one-shot with nothing to restore — so a character that arrives already dead would otherwise stand and idle.

Instance Control

An instance belongs to a party, not to whoever opened it. The scene row records both, and the party is the durable half: it survives its creator leaving, logging out, or handing leadership on. ResolveInstanceAuthority derives, for one viewer, who leads and whether that viewer is them.

  • The viewer's own authority comes from their own party rank, never from finding the leader in the roster walk. A leader standing outside the instance — they opened it and stepped out, or have not arrived yet — must not silently lose control of it, and a member must not silently gain control because the leader is momentarily unresolvable.
  • Identifying the leader is a separate, best-effort question. The roster walk can only see characters this scene server holds, so a leader elsewhere yields no ID and LeaderCharacterID is zero. The client is told there is a leader it cannot name rather than that there is none — "no leader" is a state the party system actively repairs, and displaying it for a run that has one would be alarming and wrong. The ID is the whole answer the wire carries: InstanceAuthority no longer resolves a LeaderName, which was a second lookup that could only succeed where the ID had already been found, and put a name on the wire the client resolves better itself through its own naming system.
  • A run opened by an ungrouped character has no party, and there its owner is its leader. That is the only case where the two differ, and also the one where they cannot disagree.

Leadership therefore moves the moment the party's does, with nothing here needing to know a promotion happened — the panel refreshes on its own timer and reports the new answer.

Kick and visibility are both re-authorised through the same helper when the request arrives; the client's ViewerIsLeader only decides what is drawn. SetInstancePrivacyAsync additionally re-asserts ownership inside the UPDATE itself, so an authorisation that went stale between the roster read and the write updates zero rows rather than flipping another party's dungeon.

Instance Death Rules

instanceDeathCounts tracks deaths per run, not per character: leaving and coming back starts over, which is what makes a one-death rule a rule about this attempt. It is cleared by TryLeaveInstance and by RemoveCharacterConnectionMapping, so every route out of the instance and off this server forgets it — without the second the map would grow by one entry per character the process has ever hosted, and a character reconnecting into the same instance would resume a count from a run it had already left.

Spending the last life removes only the character who died, through the ordinary leave-instance transfer rather than a disconnect. Ending a group's run over one member's mistake is a much harsher rule than any dungeon is trying to express, and it would make a hardcore run something any one member could end for everybody. AllowResurrection is checked at the offer and at the accept: the offer check stops a pointless prompt appearing, and the accept check is the enforcement, because an offer recorded a moment before the character walked into the instance would otherwise still be redeemable inside it.