From 47effec8d6252803ec7d65d92e69848b4df7fb1b Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 20 May 2026 17:23:50 -0400 Subject: [PATCH] =?UTF-8?q?Add=20=C2=A714=20Known=20Issues=20to=20Delta-Sy?= =?UTF-8?q?nc-flow.md:=20bugs=20and=20planned=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Issue 1: SpectatorRegistryService is in-memory per-process; spectators miss updates in scaled deployments due to load-balancer routing mismatch. Fix: move registry to Redis. - Issue 2: get_unit_by_id null crash when arch is null (not absent) on player disconnect. Fix: use 'is Dictionary' guard instead of .get({}). - Issue 3: ChangedTiles must only include actually-changed tiles; fix is server-side only. - Issue 4: modelUrl/art2dUrl sent in every UnitDelta; strip from delta, derive from card definition; iOS Safari: cache on first sight. - Issue 5: iOS Safari memory crash from unbounded asset cache; layered fix: scoped loading, lazy load, disk cache for non-iOS, evict on removal. - Issue 6: _fetch_state() race on version gap; fix with _syncing flag. - §12: clarified IsEmpty should never fire in practice (MP always regenerates). Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Delta-Sync-flow.md | 101 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-) diff --git a/Delta-Sync-flow.md b/Delta-Sync-flow.md index 91b2c23..d065ea0 100644 --- a/Delta-Sync-flow.md +++ b/Delta-Sync-flow.md @@ -21,6 +21,7 @@ serialisation, transport, and final application on the client. 11. [Client -- Unit Merge (_merge_unit_delta)](#11-client----unit-merge-mergeunitdelta-) 12. [Fallback and Resync Paths](#12-fallback-and-resync-paths-) 13. [Design Invariants](#13-design-invariants-) +14. [Known Issues & Planned Fixes](#14-known-issues--planned-fixes) --- @@ -580,7 +581,7 @@ The `ud.has(k) and ud[k] != null` pattern distinguishes JSON `null` (no change) | Trigger | Behaviour | |---|---| | `prevStateJson == null` passed to handler | Full `game.state_update` pushed to all players (initial connect, reconnect, timer expiry). | -| Any player's delta `IsEmpty()` | All players receive full `game.state_update` instead of deltas. | +| Any player's delta `IsEmpty()` | All players receive full `game.state_update` instead of deltas. In practice this should never fire: every turn-start regenerates MP for all units, meaning every player always has at least one stat change. If it does fire it indicates a diff bug, not a valid "no change" case. | | Spectator | Always receives full `game.state_update` (public DTO, no private data, no delta). | | Client: `v <= _state_version` | Delta dropped -- acting player already received the new state in their ACK reply. | | Client: `v > _state_version + 1` | Gap in sequence -- client calls `_fetch_state()` which sends `game.get_state`; server replies with full state. | @@ -611,3 +612,101 @@ The `ud.has(k) and ud[k] != null` pattern distinguishes JSON `null` (no change) 7. **IsEmpty check excludes `ActiveEffects`.** Comment at `GameHandlerBase.cs:313`: `ActiveEffects` is always populated (even when it is an empty list), so including it in the emptiness check would always trigger the full-state fallback. +--- + +## 14. Known Issues & Planned Fixes + +--- + +### Issue 1 — Spectators miss updates: `SpectatorRegistryService` is in-memory per process (High) + +**Root cause:** `SpectatorRegistryService` (`SpectatorRegistryService.cs:11`) is registered as an in-memory singleton with a static `Instance` reference set in its constructor. Action handlers access it via `SpectatorRegistryService.Instance` (a static field). + +In a horizontally scaled deployment (multiple server pods / load balancer), a spectator's `game.spectate` request is handled by pod A, which registers them in pod A's in-memory map. The next game action may be routed to pod B — pod B's `SpectatorRegistryService` has an empty map. `GetSpectators(sessionId)` returns empty, the spectator push is silently skipped. Only when the load balancer happens to route both the `game.spectate` and the subsequent action to the same pod does the spectator receive updates — explaining why leaving and rejoining several times eventually "works". + +Additionally, even within a single pod: `Instance` is only set when the DI container first resolves `SpectatorRegistryService`, which happens lazily on the first request to `GameSpectateHandler`. If no spectator has ever called `game.spectate` since the pod started, `Instance` is null and `PushStateToPlayersAsync` silently skips the `if (registry != null)` guard. + +**Planned fix:** Move spectator registration into Redis (the same pub/sub layer already used for player pushes). Replace the in-memory `_map` with a Redis set keyed by `spectators:{sessionId}`. `Register`/`Unregister` become `SADD`/`SREM`; `GetSpectators` becomes `SMEMBERS`. This makes spectator state shared across all pods with no per-process affinity requirement. + +--- + +### Issue 2 — `get_unit_by_id` crashes when a player's arch spirit is null on disconnect (High) + +**Root cause:** `Game.gd — get_unit_by_id` + +```gdscript +var arch: Dictionary = p.get("archSpirit", {}) +if arch.get("instanceId", "") == instance_id: + return arch +``` + +In GDScript, `Dictionary.get(key, default)` returns the default only when the **key is absent**. If the key exists with a `null` value — which happens when a player leaves and their arch spirit is cleared — `p.get("archSpirit", {})` returns `null`. The following `.get("instanceId", "")` call on `null` crashes: `Invalid call. Nonexistent function 'get' in base 'Nil'`. + +**Planned fix:** + +```gdscript +var arch_val: Variant = p.get("archSpirit") +if arch_val is Dictionary and not arch_val.is_empty(): + if arch_val.get("instanceId", "") == instance_id: + return arch_val +``` + +This pattern should be applied everywhere in the client that reads a dict value that could be null rather than absent (i.e. `dict.get(key)` followed by an `is Dictionary` guard, not `dict.get(key, {})`). + +--- + +### Issue 3 — `ChangedTiles` should only contain tiles that actually changed (Medium) + +**Location:** `GameStateDiffer.cs — DiffTiles` + +The delta's `ChangedTiles` array must only include tiles where at least one field (`base1`, `base2`, `resolvedAffinity`, `occupantId`, `ruinId`, etc.) actually differs between `prev` and `next`. Sending unchanged tiles wastes bandwidth and forces the client to process unnecessary entries. + +Verify that `DiffTiles` performs a field-by-field equality check before emitting a `TileDelta`, and emits `null` (no entry) for unchanged tiles. If any path exists where all tiles are included unconditionally, that is the bug. The fix is entirely server-side — the client already applies only what it receives; no client changes are needed. + +--- + +### Issue 4 — `modelUrl` / `art2dUrl` sent in `UnitDelta` on every unit change (Low / Bandwidth) + +**Location:** `GameStateDiffer.cs — DiffUnit`, `_merge_unit_delta` lines 571-572 + +`modelUrl` and `art2dUrl` are CDN URL strings that are fixed for the lifetime of a card definition. They are set once when the unit is first added (via `UnitSnapshot` in `UnitsAdded`). Sending them again in every subsequent `UnitDelta` is pure waste. The casing inconsistency (`art2dUrl`, `Art2dUrl`, `modelUrl`, `ModelUrl`, `modelurl` all checked on the client) also indicates the server is not emitting these consistently. + +**Planned fix:** +- Strip `modelUrl` and `art2dUrl` from `UnitDelta` entirely. They should only ever appear in the initial `UnitSnapshot`. +- Longer term: derive asset URLs from the card definition stored on the client (each card's `definitionId` is already in the unit snapshot). The client card catalog holds the canonical URLs, so no URL transmission is needed at all. +- **iOS Safari exception:** because iOS Safari applies strict per-origin memory limits, asset URLs should be sent once on first sight (via `UnitSnapshot`) and held in a scoped cache keyed by `definitionId`. Subsequent units using the same definition reuse the cached URL rather than re-fetching. See Issue 5 for the broader iOS memory strategy. + +--- + +### Issue 5 — iOS Safari crashes from unbounded asset cache (High / Mobile) + +iOS Safari enforces a hard per-tab memory ceiling (~300 MB). The client currently loads and retains all card art, 3D models, and assets as the game progresses, never evicting them. As more distinct cards are seen, memory climbs until the tab is killed. + +**Planned fix (layered):** + +1. **Detect iOS Safari** via `OS.get_name() == "Web"` plus a user-agent check for Safari on iOS. Apply a separate asset management path for this client. + +2. **Scope asset loading to visible scene only.** Only load model/art assets for cards currently on the board or in the local player's hand. Unload assets when cards leave these zones (moved to discard, removed, etc.). + +3. **Lazy load on demand.** Trigger asset loads when a unit enters the viewport, not on game-state receipt. Cards in hand that are not being hovered or inspected do not need their 3D model resident. + +4. **Disk cache for non-iOS clients.** Desktop browsers and Android Chrome support the Cache API and IndexedDB with generous quotas — use these to persist card assets across sessions. Scope this to non-iOS Safari only; Safari's IndexedDB quota is small and unreliable. + +5. **Drop invisible assets.** When a unit is removed from the board (captured, discarded) and is not in hand, release its model and art resources immediately rather than waiting for scene transition. + +--- + +### Issue 6 — `_fetch_state()` race: multiple concurrent full-sync requests on version gap (Low) + +**Location:** `Game.gd` — version gap handler + +```gdscript +if _state_version >= 0 and v > _state_version + 1: + _fetch_state() + return +``` + +There is no in-flight guard. On poor connections, multiple consecutive deltas can arrive with gaps, triggering multiple `_fetch_state()` calls simultaneously. Each causes a full state response; the last one wins, but the intermediate responses can briefly corrupt `_state_version`. + +**Planned fix:** Add `var _syncing: bool = false`. Check `if _syncing: return` at the top of the gap branch. Set `_syncing = true` before `_fetch_state()`. Reset to `false` in the `game.state_update` handler after applying the full state. +