Refocus Delta-updates plan on full cutover of current delta system

This commit is contained in:
Shard
2026-03-27 12:27:44 +00:00
parent bd640c1eee
commit f07ea4135a
+122 -166
View File
@@ -2,213 +2,169 @@
## Context
Current `game.state_delta` infrastructure was designed around a 2-player worldview (viewer + one opponent). That assumption now leaks in custom lobbies with 3+ players and will become more problematic with larger sessions and spectators.
Current `game.state_delta` is structurally 2-player (viewer + one opponent). In 3+ player sessions this causes partial updates (e.g., tile updates arrive, but a third player's ArchSpirit/unit visual lags until another action).
Observed symptom in 3-player custom game:
- Client 3 places ArchSpirit.
- Other clients see tile occupancy update immediately.
- ArchSpirit visual/unit state does not appear until a later action triggers another state update.
This is a data-shape mismatch, not just a rendering issue.
Because we're still in dev with no active production players, this plan is a **direct cutover** of the existing delta system (no v1/v2 dual-run, no compatibility scaffolding).
---
## Current design structure
## Current system constraints (what must change)
### Message contract (server → client)
`Server/src/SOR.Game/GameMessages.cs`
### Contract constraints (`GameMessages.cs`)
Current `GameStateDelta` includes single-opponent fields:
- `OpponentHandCount`, `OpponentDeckCount`
- `OwnArchSpiritDelta`, `OpponentArchSpiritDelta`
- `OwnStatsDelta`, `OpponentStatsDelta`
`GameStateDelta` currently includes (abridged):
- `ChangedTiles`
- `AddedUnits` / `RemovedUnitIds` / `ChangedUnits`
- `HandAdded` / `HandRemovedIds` / `DiscardAdded`
- `OpponentHandCount` / `OpponentDeckCount`
- `OwnArchSpiritDelta` / `OpponentArchSpiritDelta`
- `OwnStatsDelta` / `OpponentStatsDelta`
- `MetaDelta`
These fields cannot represent N-player state.
This schema encodes exactly one “opponent lane”.
### Differ constraints (`GameStateDiffer.cs`)
`ComputeDelta(prev, next, viewerAccountId)` chooses one opponent via `FirstOrDefault(...)`, so only one non-viewer player can be represented in several categories.
### Differ logic
`Server/src/SOR.Game/GameStateDiffer.cs`
### Push constraints (`GameHandlerBase.cs`)
P1/P2 receive deltas while seats 3+ receive full state, causing mixed consistency and harder debugging.
`ComputeDelta(prev, next, viewerAccountId)` selects one opponent via:
- `FirstOrDefault(p => p.AccountId != viewerAccountId)`
So for N-player sessions, only one non-viewer player is represented in opponent fields.
### Push strategy
`Server/src/SOR.Game/Handlers/GameHandlerBase.cs`
Current approach after action:
- P1/P2 receive `game.state_delta` (viewer-specific deltas).
- Additional players (seats 3+) receive full `game.state_update`.
- Spectators receive delta/full based on branch and emptiness checks.
This creates inconsistent data fidelity across participants in >2-player sessions.
### Client delta application
`Client/origin-client/autoloads/Game.gd`
`_apply_delta()` applies:
- own arch via `ownArchSpiritDelta` to local player
- opponent arch via `opponentArchSpiritDelta` to `get_opponent()` (first opponent)
So multi-opponent updates are inherently lossy under current contract.
### Client constraints (`Client/autoloads/Game.gd`)
Delta apply path assumes only local + one opponent (`get_opponent()` / own vs opponent fields).
---
## Why this will degrade at scale
## Full cutover target (replace current delta contract)
As player count and spectator count increase:
- A single-opponent delta shape cannot represent all relevant changes.
- Clients drift into “partially updated” state until a full-state sync occurs.
- UX appears nondeterministic (tiles updated, units missing, stale HUD numbers).
- Complexity increases in client-side heuristics trying to infer ownership/placement.
Replace the **existing** `GameStateDelta` payload shape with an account-scoped, multi-entity schema.
The root issue is contract shape, not patchable with isolated client fixes.
## New `GameStateDelta` shape (post-cutover)
- `StateVersion: int`
- `ChangedTiles: TileDelta[]?`
- `UnitsAdded: UnitSnapshot[]?` (must include `ownerAccountId`)
- `UnitsRemoved: string[]?` (instance IDs)
- `UnitsChanged: UnitDelta[]?` (instance ID keyed)
- `ArchSpiritByAccount: Dictionary<string, UnitDeltaOrSnapshot>?`
- `PlayerStatsByAccount: Dictionary<string, PlayerStatsDelta>?`
- `PublicCountsByAccount: Dictionary<string, PublicCountsDelta>?`
- `handCount`, `deckCount`, `discardCount` (optional as needed)
- `PrivateByViewer: PrivateViewerDelta?`
- `HandAdded`, `HandRemovedIds`, `DiscardAdded`
- `MetaDelta: GameMetaDelta?`
### Design rules
- No `own/opponent` naming anywhere in wire payload.
- All public/player state keyed by `accountId`.
- Private info strictly isolated under `PrivateByViewer`.
- Delta remains sparse (null = no change).
---
## Proposed revision
## Component-by-component change list
## 1) Introduce a normalized multi-entity delta schema
## 1) `Server/src/SOR.Game/GameMessages.cs`
Add a v2 payload (`game.state_delta_v2`) with per-entity maps/lists keyed by accountId or instanceId.
### Required edits
1. Replace current `GameStateDelta` record fields with new account-scoped fields.
2. Add/rename DTOs:
- `UnitSnapshot` (for new units with owner context)
- `PublicCountsDelta`
- `PrivateViewerDelta`
3. Keep `TileDelta`, `UnitDelta`, `PlayerStatsDelta`, `GameMetaDelta` where reusable.
### Proposed `GameStateDeltaV2`
- `StateVersion`
- `ChangedTiles: TileDelta[]`
- `UnitsAdded: UnitSnapshot[]` (includes ownerAccountId)
- `UnitsRemoved: string[]` (instanceIds)
- `UnitsChanged: UnitDelta[]` (instanceId keyed)
- `ArchSpiritByAccount: Dictionary<string, UnitDeltaOrSnapshot>`
- `PlayerStatsByAccount: Dictionary<string, PlayerStatsDelta>`
- `PrivateByViewer` (viewer-only zones):
- `HandAdded`
- `HandRemovedIds`
- `DiscardAdded`
- `PublicCountsByAccount`: `{ handCount, deckCount, discardCount? }`
- `MetaDelta`
Notes:
- Separate private and public sections to preserve hidden-information rules.
- Remove “own/opponent” field naming from wire format.
## 2) Make generation player-count aware
In `GameHandlerBase`:
- If `playerCount == 2` and both clients support v2: send `state_delta_v2`.
- If `playerCount > 2`: prefer v2 to all players.
- If client does not advertise v2 capability: fallback to full `game.state_update`.
Do **not** mix “delta for some seats, full-state for other seats” in same session generation path except compatibility fallback.
## 3) Add explicit capability negotiation
Client declares capabilities on `game.ready` (or equivalent session-init message), e.g.:
- `clientCapabilities: ["state_delta_v2"]`
Server records per-connection capability and chooses push format accordingly.
## 4) Client application path changes
In `Client/origin-client/autoloads/Game.gd`:
- Add `_apply_delta_v2()`.
- Resolve players by `accountId` directly (no `get_opponent()` assumptions).
- Apply arch/unit/stats updates from account-keyed structures.
- Keep existing `_apply_delta()` only for legacy format.
## 5) Spectator model
Spectators should receive one consistent public v2 stream:
- No private hand card identities.
- Public counts/states for all players.
- Full board/unit/arch state transitions for all players.
This avoids extra spectator-specific shape forks over time.
### Acceptance check
- JSON payload for `game.state_delta` can represent updates for any number of players in one push.
---
## Migration plan
## 2) `Server/src/SOR.Game/GameStateDiffer.cs`
### Phase 0: Safety + diagnostics
- Add telemetry counters:
- push type used (full, delta v1, delta v2)
- out-of-order or version-gap resync rate
- client-requested full sync frequency
- Add logging guardrails around state-version discontinuities.
### Required edits
1. Rewrite `ComputeDelta(prev, next, viewerAccountId)` to:
- Diff all players by `accountId`.
- Build per-account maps for archspirit/stats/public counts.
- Build `PrivateByViewer` only from viewer's own hidden zones.
2. Replace single-opponent logic (`FirstOrDefault`) entirely.
3. Ensure `UnitsAdded` carries ownership deterministically.
4. Update spectator computation to use same core diff machinery with no private section.
### Phase 1: Add v2 in parallel
- Implement v2 DTOs and differ logic (`ComputeDeltaV2`).
- Keep existing v1 unchanged.
- Add capability handshake path.
### Phase 2: Dual-serve with fallback
- Serve v2 to capable clients.
- Serve full-state to non-capable clients in >2-player sessions.
- Keep v1 only for 2-player legacy clients.
### Phase 3: Client rollout
- Implement `_on_server_push("game.state_delta_v2")` and `_apply_delta_v2()`.
- Add strict validation and soft-fallback to `request_sync()` if malformed payload.
### Phase 4: Default shift
- Make v2 default for all sessions where both ends support it.
- Remove v1-specific assumptions from gameplay UI code (`get_opponent()`-only paths).
### Phase 5: Decommission v1
- After adoption threshold and soak period, retire v1 delta contract.
### Acceptance check
- In 3+ player test fixtures, a single delta includes all changed players' arch/unit/stat transitions.
---
## Validation strategy
## 3) `Server/src/SOR.Game/Handlers/GameHandlerBase.cs`
### Deterministic scenario tests
1. 2-player baseline: parity with existing behavior.
2. 3-player FFA: each player places ArchSpirit in sequence.
3. 4+ player game: multiple simultaneous board/unit changes.
4. Spectator joins mid-match and remains consistent through turns.
### Required edits
1. Remove split strategy (delta for seats 1/2, full-state for seats 3+).
2. For normal action updates, send `game.state_delta` to **all session players**.
3. Build each player's delta from same prev/next snapshots but viewer-specific private section.
4. Spectators receive public-only delta (same message type, private section omitted/null).
5. Keep full `game.state_update` for bootstrap/reconnect/missed-version recovery only.
### Invariants to assert
- For each `stateVersion`, all clients converge to same public board/unit state.
- No missing unit/arch meshes after an acknowledged action.
- No client remains stale without either next delta or explicit resync.
### Tooling
- Add golden JSON fixtures for prev/next snapshots and expected v2 deltas.
- Add replay harness to feed ordered/unordered pushes and verify convergence.
### Acceptance check
- All active participants receive delta path uniformly for same stateVersion progression.
---
## Risks and mitigations
## 4) `Client/origin-client/autoloads/Game.gd`
- **Risk:** Payload size growth in large sessions.
- **Mitigation:** Keep delta sparse; only changed entities; optional compression at transport layer.
### Required edits
1. Replace `_apply_delta()` implementation to consume the new `GameStateDelta` shape.
2. Remove assumptions based on `get_opponent()` for delta application.
3. Apply updates by account map:
- locate player in `state.players` by `accountId`
- apply arch stats/unit updates per-account
- apply viewer private hand/discard updates only from `PrivateByViewer`
4. Keep state-version guards and full-sync fallback on gap/malformed payload.
5. Update helper methods as needed (e.g., utility to get player dict by account id quickly).
- **Risk:** Capability mismatch during deploy.
- **Mitigation:** Explicit negotiation + conservative full-state fallback.
- **Risk:** Hidden-information leakage.
- **Mitigation:** Strict separation of `PrivateByViewer` and public account-scoped counts.
- **Risk:** Complex migration bugs.
- **Mitigation:** Parallel-run v1/v2 in staging with differential checks.
### Acceptance check
- Any opponent (not just “first opponent”) placing ArchSpirit appears immediately on all clients after one delta.
---
## Recommended immediate hotfix (before v2 lands)
## 5) `Client/origin-client/scenes/game/game_screen.gd`
For sessions where `playerCount > 2`:
- Send full `game.state_update` to **all** players (including seats 1 and 2).
### Required edits
1. Audit for any implicit “single opponent” rendering assumptions tied to delta-fed data.
2. Ensure ownership/highlight lists are rebuilt from full `state.players` each update (already mostly true).
3. Verify no UI panel relies on old opponent-only count fields.
This removes the current inconsistency immediately while v2 is implemented.
### Acceptance check
- 3+ player HUD and board visuals remain consistent after each delta without waiting for secondary actions.
---
## Success criteria
## 6) Tests and fixtures
- No delayed appearance of ArchSpirits/units in 3+ player sessions.
- Reduced full-resync requests during active games.
- Spectator views remain consistent without bespoke patch logic.
- Delta contract no longer encodes 1-opponent assumptions.
### Server tests
- Add golden prev/next snapshots for:
1. 2-player baseline action
2. 3-player arch placements in sequence
3. 4-player mixed action turn
4. spectator-visible transitions
- Assert delta JSON contains correct account-scoped maps and no hidden-info leaks.
### Client tests (or scripted replay harness)
- Feed ordered deltas and verify convergence.
- Feed version gaps/out-of-order and verify fallback `request_sync()` behavior.
### Acceptance check
- No repro of delayed ArchSpirit/unit appearance in 3+ session replay.
---
## Implementation order (cutover)
1. Update DTO contract (`GameMessages.cs`).
2. Update differ generation (`GameStateDiffer.cs`).
3. Update push fanout (`GameHandlerBase.cs`).
4. Update client delta apply (`Game.gd`).
5. Run fixture + replay validation.
6. Remove obsolete code paths/fields referencing own-vs-opponent deltas.
---
## Done criteria
- `game.state_delta` natively supports N-player + spectators.
- No own/opponent delta fields remain.
- No mixed per-seat push strategy in active sessions.
- 3+ player ArchSpirit/unit updates are immediate and deterministic on all clients.