From 85508ef3e9a12d11ec889033b6a841768ee1b9d9 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 20 May 2026 12:57:44 -0400 Subject: [PATCH] Expand Ability-flow.md: error paths, delta sync, trigger ordering, cost atomicity, gotchas, JSON examples MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds six new sections: - §23 Failure/Error paths — all GameException codes with line refs, client error propagation behavior - §24 State version & delta sync — full vs delta push decision, client version gap handling, _fetch_state - §25 Trigger re-entrancy & ordering — no depth guard, iteration order, TriggerLimit as only loop protection - §26 Cost atomicity & rollback — costs-before-effects invariant, interactive pause semantics, no rollback - §27 Known caveats & gotchas — line drift, ActionGroup/Actions exclusivity, ChooserRole defaults, error opacity - §28 Minimal JSON examples — Active, Triggered with PendingTriggeredTarget, OR ActionGroup with chooser Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Ability-flow.md | 365 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 365 insertions(+) diff --git a/Ability-flow.md b/Ability-flow.md index c4d1b6f..5a2aa18 100644 --- a/Ability-flow.md +++ b/Ability-flow.md @@ -28,6 +28,12 @@ This document maps the full lifecycle of abilities in SOR, from data definition 20. [Client Visual Effects](#20-client-visual-effects) 21. [Resume Paths (Paused Abilities)](#21-resume-paths-paused-abilities) 22. [Key Cross-File Connections](#22-key-cross-file-connections) +23. [Failure and Error Paths](#23-failure-and-error-paths) +24. [State Version and Delta Sync](#24-state-version-and-delta-sync) +25. [Trigger Re-entrancy and Ordering](#25-trigger-re-entrancy-and-ordering) +26. [Cost Atomicity and Rollback Semantics](#26-cost-atomicity-and-rollback-semantics) +27. [Known Caveats and Gotchas](#27-known-caveats-and-gotchas) +28. [Minimal JSON Examples](#28-minimal-json-examples) --- @@ -902,3 +908,362 @@ AbilityContext (AbilityContext.cs) | `Client/origin-client/scenes/game/components/selection/ability_targeting.gd` | Full client targeting UI state machine | | `Client/origin-client/scenes/game/components/effects/ability_placeholder_fx.gd` | VFX for abilities without custom animations | | `Client/origin-client/scenes/collection/components/ability_row.gd` | UI row for displaying ability info in collection | + +--- + +## 23. Failure and Error Paths + +All server-side validation failures throw `GameException(string code)` — a plain `Exception` subclass defined in `GameEngine.cs:1740–1743` with an `ErrorCode` string property. + +### Exception propagation to client + +`GameException` propagates up through the handler into `NatsMessageRpcResponder.DispatchAsync` (line 206), which catches all exceptions generically and returns: + +```json +{ "errorCode": "INTERNAL_ERROR", "message": "An internal error occurred." } +``` + +**The specific `ErrorCode` is NOT forwarded to the client.** It is only logged server-side. The Gateway delivers this as `ServerMessage.Error(seq, errorCode, message)` over WebSocket. `GameActivateAbilityHandler` has no try/catch of its own — it relies entirely on this outer layer. + +### Active ability activation errors + +| Check | Line | Error Code | +|---|---|---| +| `source.IsExhausted` | 100–101 | `UNIT_EXHAUSTED` | +| `!source.CanUseAbility` | 103–104 | `UNIT_CANNOT_USE_ABILITY` | +| `abilityIndex` out of bounds | 107–108 | `ABILITY_INDEX_OUT_OF_RANGE` | +| `def.Type != Active` | 113 | `ABILITY_NOT_ACTIVE` | +| ability in `DisabledAbilities` | 116 | `ABILITY_DISABLED` | +| `AbilityUsesThisTurn >= UsesPerTurn` | 121 | `ABILITY_USES_EXHAUSTED` | +| source-level conditions not met | 127 | `ABILITY_CONDITION_NOT_MET` | + +### Target validation errors + +| Check | Line | Error Code | +|---|---|---| +| Client-picked target outside ability range | 2041 | `TARGET_OUT_OF_RANGE` | +| Not enough candidates after filtering | 2059 | `INSUFFICIENT_TARGETS` | +| Invalid tile for summon/placement effects | 231, 235, 245, 1315, 1364, 2901 | `INVALID_TILE` | + +### Resume handler errors (stale / mismatched RequestId) + +All resume methods follow the same guard pattern — check pending state exists, then check RequestId matches, then check actor identity: + +| Resume Method | Line | Error Codes (in order) | +|---|---|---| +| `ResumeTriggeredAbility` | 1880–1884 | `NO_PENDING_TRIGGER` → `REQUEST_ID_MISMATCH` → `NOT_YOUR_TRIGGER` | +| `ResumeTargetPick` | 1616–1626 | `NO_PENDING_TARGET_PICK` → `REQUEST_ID_MISMATCH` → `NOT_YOUR_TARGET_PICK` | +| `ResumeActionGroupPick` | 1087–1094 | `NO_PENDING_ACTION_GROUP_PICK` → `REQUEST_ID_MISMATCH` → `NOT_YOUR_ACTION_GROUP_PICK` | +| `ResumeCostPick` | 828–832 | `NO_PENDING_COST_PICK` → `REQUEST_ID_MISMATCH` | +| `ResumeCostGroupPick` | 692–696 | `NO_PENDING_COST_GROUP_PICK` → `REQUEST_ID_MISMATCH` | +| `ResumeBranchPick` | 939–943 | `NO_PENDING_BRANCH_PICK` → `REQUEST_ID_MISMATCH` | + +--- + +## 24. State Version and Delta Sync + +**File:** `Server/src/SOR.Game/Handlers/GameHandlerBase.cs` lines 78, 291–393 +**File:** `Client/origin-client/autoloads/Game.gd` lines 104, 717–755 + +### Sequence number + +Before every state save, the sequence number is incremented (`GameHandlerBase.cs:78`): + +```csharp +var seqNum = state.NextActionSequence++; +``` + +This is embedded in `stateVersion` on both full-state DTOs and delta payloads. + +### Full state vs delta decision — `PushStateToPlayersAsync` (line 291) + +`prevStateJson` is captured from `session.StateJson` **before** the engine call. After execution: + +``` +if prevStateJson != null: + GameStateDiffer.ComputeDelta(prevState, state, pid) per player + if ANY player's delta IsEmpty → push full game.state_update to ALL players + else → push per-player game.state_delta + +if prevStateJson == null (reconnect / initial connect): + always push full game.state_update +``` + +After the state push, `PushPendingPromptsAsync` is always called unconditionally (line 392) — this re-sends any `Pending*` pick requests to the correct player(s). + +### Acting player always gets full state + +`GameActivateAbilityHandler` sends the full `GameStateDto` back in the `game.activate_ability.ack` reply to the acting player. The opponent receives either a delta or a full push from `PushStateToPlayersAsync` depending on the differ result. + +### Client-side version tracking — `Game.gd` + +``` +_state_version tracked at line 104, initialized to -1 + +On game.state_update: replace entire state, update _state_version (lines 717–734) + +On game.state_delta: check delta.stateVersion vs _state_version (lines 739–755) + v <= _state_version → silently ignore (acting player already got full state in ACK) + v > _state_version+1 → version gap detected → call _fetch_state() for full resync + v == _state_version+1 → call _apply_delta(delta) +``` + +**`_fetch_state()`** (line 313): sends `game.get_state`, receives and applies a full state payload. + +### Paused ability flows and state pushes + +When execution pauses with a `Pending*` field set, `PushStateToPlayersAsync` still runs (with the paused state), and `PushPendingPromptsAsync` immediately pushes the interactive prompt. The client receives both the updated state (showing any effects already applied before the pause) and the pick request in the same handler cycle. + +--- + +## 25. Trigger Re-entrancy and Ordering + +**File:** `AbilitySystem.cs`, `FireTrigger` at line 256 + +### Re-entrancy + +`FireTrigger` is a plain synchronous static method with **no re-entry guard, no `_triggerDepth` counter, and no recursion limit**. It is called directly and synchronously from within: + +- `ApplyDamageToUnit` — which can be called from within `ExecuteActions` for a triggered ability's effects +- `KillUnit`, `SummonTokenEffect`, move effects, etc. + +This means **fully nested trigger chains are supported** by design. Example: `OnUnitDeath` trigger fires → its actions deal damage → `BeforeDamageApplied` and `OnDamageDealt` triggers fire → their actions can fire further triggers. + +### Ordering guarantees + +When multiple cards respond to the same event, `FireTrigger` iterates in this fixed order: + +1. Players — in `state.Players` dictionary insertion order +2. Per player — `Field` cards first, then `Hand`, `Discard`, `Deck` (lines 264–271) +3. Per card — ability array index order (ability 0 before ability 1) + +There is **no explicit priority system**. Trigger order is entirely determined by player order, then field position, then ability index. + +### Anti-loop protection + +The only protection against infinite trigger loops is the opt-in per-ability rate limiters: + +- **`TriggerLimitPerTurn`** — `_triggerCountsPerTurn` dict keyed by `(sourceInstanceId, abilityKey, turnNumber)`, checked at lines 323–332 +- **`TriggerLimitPerGame`** — `_triggerCountsPerGame` dict keyed by `(sessionId:sourceInstanceId, abilityKey)`, checked at lines 335–343 + +If a triggered ability definition has **neither limit set**, there is no hard loop guard. An ability that fires on `OnUnitDeath`, kills another unit, and has no `TriggerLimitPerTurn` could recurse indefinitely — protection is entirely a data/design responsibility. + +### One-at-a-time for client-pick triggers + +When any trigger needs a human target pick, `PendingTriggeredTarget` is set (line 364) and `FireTrigger` returns immediately (line 379). Only one pending trigger request can exist at a time — the rest of the trigger scan is abandoned and will not re-run when the pending trigger resumes. + +--- + +## 26. Cost Atomicity and Rollback Semantics + +**File:** `AbilitySystem.cs` lines 133–153 + +### Timing: costs always before effects + +```csharp +// line 133 — use-count increment first +source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; + +// line 139–150 — pay costs before ExecuteActions +if (def.CostGroup is { } cg) + PayCostGroup(cg, ctx, ...); +else if (def.Cost is { Length: > 0 }) + PayCosts(def.Cost, ctx, ...); + +// line 152 — effects only after costs are fully paid +ExecuteActions(effectiveActions, ctx, ...); +``` + +The use-count increment and all cost payments are applied before any ability effects execute. This is a strict invariant. + +### Interactive cost pause + +When a cost requires player input (e.g. `DiscardFromHand` with `SelfPick`), `PayCosts` stores `PendingCostPick` and returns early. At this point: + +- Any costs paid **before** the interactive cost in the same `CostEntry[]` are already applied and **cannot be undone** +- The interactive cost itself is not yet applied — it waits for `ResumeCostPick` +- `ExecuteActions` has not been called yet — no effects have fired + +When the player responds, `ResumeCostPick` (line 822) pays the remaining costs and then calls `ExecuteActions`. + +### No rollback + +There is **no rollback mechanism** in the codebase: + +- `PaySingleCost`, `PayCosts`, and `PayCostGroup` contain no exception handling +- There is no try/finally that un-pays costs on exception +- There is no "refund" path anywhere +- If `ExecuteActions` throws after costs are paid, the in-memory state is partially mutated — but `SaveStateAsync` at the handler level is not reached on exception, so the DB transaction is not committed. The in-memory session state may be inconsistent until the next full state push. + +**For QA / designers:** if an ability's cost-then-effect sequence is interrupted by an unhandled server error, costs are logically consumed but effects don't fire. This can only be observed as a transient state; the persisted state reverts to pre-activation. Test any ability with interactive costs carefully under network interruption conditions. + +--- + +## 27. Known Caveats and Gotchas + +### Line numbers drift + +Line numbers in this document reference `AbilitySystem.cs` as of 2026-05-20. `AbilitySystem.cs` is ~5500+ lines and actively developed — line numbers drift with every feature addition. When in doubt, search by method name rather than jumping to a line directly. + +### `ActionGroup` vs `Actions` — mutually exclusive + +`GetEffectiveActions()` (line 981–992) uses an **exclusive** check: + +```csharp +if (def.ActionGroup is { } ag) + return ResolveActionGroup(ag, ...); +return def.Actions; // only reached if ActionGroup is null +``` + +If `ActionGroup` is non-null, `def.Actions` is **completely ignored** — there is no merge or fallback. This means a card row that has both fields populated will silently discard `Actions`. The same exclusive logic applies in `GameHandlerBase.GetFirstAction` and `PreValidateClientTileTargets`. When migrating legacy cards to `ActionGroup`, ensure `Actions` is nulled out. + +### `ChooserRole` semantics in mixed branches + +In an OR/XOR `ActionGroup`, `ChooserRole` determines who picks the branch: + +- **`Random`** — server picks at random, **no client prompt**, execution continues synchronously +- **`Self`** — acting player's client receives `game.ability.action_group_pick_request`, execution pauses +- **`Opponent`** — opponent's client receives the request, execution pauses + +An OR group without `ChooserRole` set defaults to `null`, which the server treats as `Random`. This can be surprising if a player-choice was intended. + +### `TriggerLimitPerTurn` is the only loop guard + +As documented in §25, there is no hard recursion limit on trigger chains. A triggered ability with no `TriggerLimitPerTurn` set that can trigger its own event is a potential infinite loop. The limit must be set in the ability data. + +### Stale error codes never reach the client + +All `GameException` error codes (e.g. `UNIT_EXHAUSTED`, `REQUEST_ID_MISMATCH`) are swallowed by `NatsMessageRpcResponder` and replaced with the generic `"INTERNAL_ERROR"` code. The client has no way to distinguish failure reasons from the network layer alone. Server logs are the only source of the specific error code. + +### Cost interactivity can partially apply costs + +As documented in §26, costs in a `CostEntry[]` before an interactive cost entry are applied before the pause. If a designer places a non-interactive cost (e.g. SP deduction) before an interactive cost (e.g. `DiscardFromHand` with `SelfPick`) in the same `CostGroup`, the SP is spent before the player selects their discard. This is by design but can be counterintuitive. + +### `SourceZoneGate` is null-guarded as battlefield-only + +If `SourceZoneGate` is null on a Triggered ability, `FireTrigger` only scans `Field` (the battlefield). To allow a trigger to fire while the card is in Hand/Discard/Deck, `SourceZoneGate` must be explicitly set to those zone names. + +### Client `normalize_keys()` is mandatory + +The client's `ability_targeting.gd:normalize_keys()` (line 841) recursively lowercases all dictionary keys. This exists because server JSON serialization is not guaranteed to be consistent in casing across all code paths (some go through `JsonSerializerOptions` with camelCase, others with PascalCase). If a new action/effect type is added server-side and the client needs to read its JSON fields, those fields must be referenced in lowercase on the client side. + +--- + +## 28. Minimal JSON Examples + +All ability data is stored exclusively in the PostgreSQL database (managed via the Admin AbilityBuilder UI). No static JSON files exist on disk. The following examples use the canonical wire format — the same structure parsed by `AbilitySystem.ParseAbilities()`. + +### Simple Active ability (single SP cost, damages one enemy unit) + +```json +[{ + "Type": "Active", + "Name": "Searing Strike", + "Description": "Deal 3 damage to a target enemy unit.", + "UsesPerTurn": 1, + "Range": { "Min": 1, "Max": 3, "RequiresLos": true, "LinearOnly": false }, + "CostGroup": { + "LogicOp": "And", + "ChooserRole": "Self", + "Entries": [{ "Type": "SpiritPoints", "Amount": 2 }], + "Groups": [] + }, + "ActionGroup": { + "LogicOp": "And", + "ChooserRole": "Self", + "Actions": [{ + "Target": { + "Scope": "Battlefield", + "Type": "Unit", + "Ownership": "Enemy", + "Chooser": "Self", + "Count": { "N": 1 } + }, + "Effects": [{ "$type": "DealDamage", "Amount": { "Value": 3 }, "BypassDefense": false }] + }], + "Groups": [] + } +}] +``` + +### Triggered ability — fires on unit death, needs client target pick + +Triggers when any allied unit dies. The acting player must then choose one enemy unit to receive a buff. Because `Chooser: "Self"` with a non-trivial pool is used, `ActionNeedsClientTargets()` returns true and execution pauses with `PendingTriggeredTarget`. + +```json +[{ + "Type": "Triggered", + "Name": "Vengeful Surge", + "Description": "When an allied unit dies, give a target enemy unit -2 ATK until end of turn.", + "TriggerLimitPerTurn": 1, + "TriggerEvent": { + "$type": "OnUnitDeath", + "Ownership": "Ally" + }, + "ActionGroup": { + "LogicOp": "And", + "ChooserRole": "Self", + "Actions": [{ + "Target": { + "Scope": "Battlefield", + "Type": "Unit", + "Ownership": "Enemy", + "Chooser": "Self", + "Count": { "N": 1 } + }, + "Duration": { "Type": "UntilEndOfTurn" }, + "Effects": [{ + "$type": "ModifyDamage", + "Amount": { "Value": 2 }, + "Operator": "Subtract", + "StatTarget": "Current" + }] + }], + "Groups": [] + } +}] +``` + +### OR ActionGroup — Self chooser picks one branch (pauses for client input) + +The acting player is prompted to choose between two effects. Execution pauses with `PendingActionGroupPick` until they respond. The unchosen branch is discarded entirely. + +```json +[{ + "Type": "Active", + "Name": "Divergent Path", + "Description": "Choose: draw 2 cards, OR gain 3 SP.", + "UsesPerTurn": 1, + "CostGroup": { + "LogicOp": "And", + "ChooserRole": "Self", + "Entries": [{ "Type": "SpiritPoints", "Amount": 1 }], + "Groups": [] + }, + "ActionGroup": { + "LogicOp": "Or", + "ChooserRole": "Self", + "Actions": [], + "Groups": [ + { + "LogicOp": "And", + "ChooserRole": "Self", + "Actions": [{ + "Target": { "Scope": "Player", "Type": "Player", "Ownership": "Self", "Count": { "N": 1 } }, + "Effects": [{ "$type": "DrawCards", "Amount": { "Value": 2 } }] + }], + "Groups": [] + }, + { + "LogicOp": "And", + "ChooserRole": "Self", + "Actions": [{ + "Target": { "Scope": "Player", "Type": "Player", "Ownership": "Self", "Count": { "N": 1 } }, + "Effects": [{ "$type": "ModifySP", "Amount": { "Value": 3 }, "Operator": "Add" }] + }], + "Groups": [] + } + ] + } +}] +```